(function() { const st = new ShardingTest({shards: 2}); assert.commandWorked(st.s.adminCommand({enableSharding: 'test'})); st.ensurePrimaryShard("test", st.shard0.shardName); assert.commandWorked(st.s.adminCommand({shardCollection: 'test.user', key: {_id: 1}})); const mongosDB = st.s.getDB('test'); const coll = mongosDB.user; coll.insert({_id: 1}); coll.insert({_id: -1}); var res = assert.commandWorked(mongosDB.runCommand({ aggregate: coll.getName(), pipeline: [], exchange: {policy: 'broadcast', consumers: NumberInt(5), bufferSize: NumberInt(1024)}, cursor: {batchSize: 0} })); st.stop(); })();
This test will trip this invariant.
The situation is that we have an aggregation targeting 1 shard, but the request sent to the shard says there are 5 consumers, so the shard will open 5 cursors. On mongos, establishCursors() will return 5 cursors, leading to the invariant failing.