[SERVER-33925] Queries that are known to return no results at plan time should optimize to EOF plan Created: 16/Mar/18  Updated: 06/Dec/22

Status: Backlog
Project: Core Server
Component/s: Querying
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Ian Whalen (Inactive) Assignee: Backlog - Query Optimization
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to SERVER-33642 Alert client when parsing a query exp... Closed
is related to SERVER-65049 Optimize away { $expr : true } in $ma... Closed
Assigned Teams:
Query Optimization
Participants:

 Description   

Due to auto-generation of queries or user error, it is possible to issue a query to the server which cannot possibly return any results. One such query is

db.foo.find({$expr:{$eq:["a","b"]}});

as described by related ticket SERVER-33642. Since the constant string "a" is never equal to the constant string "b", this query can never match any documents. In fact, the server optimizes this expression to be a constant of false. However, it still runs a collection scan, filtering out each of the documents that do not match one by one:

> db.foo.drop();
> db.foo.insert([{}, {}, {}]);
> db.foo.find({$expr:{$eq:["a","b"]}}).explain("executionStats");
{
	"queryPlanner" : {
		"plannerVersion" : 1,
		"namespace" : "test.foo",
		"indexFilterSet" : false,
		"parsedQuery" : {
			"$expr" : {
				"$const" : false
			}
		},
		"winningPlan" : {
			"stage" : "COLLSCAN",
			"filter" : {
				"$expr" : {
					"$const" : false
				}
			},
			"direction" : "forward"
		},
		"rejectedPlans" : [ ]
	},
	"executionStats" : {
		"executionSuccess" : true,
		"nReturned" : 0,
		"executionTimeMillis" : 0,
		"totalKeysExamined" : 0,
		"totalDocsExamined" : 3,
		"executionStages" : {
			"stage" : "COLLSCAN",
			"filter" : {
				"$expr" : {
					"$const" : false
				}
			},
			"nReturned" : 0,
			"executionTimeMillisEstimate" : 0,
			"works" : 5,
			"advanced" : 0,
			"needTime" : 4,
			"needYield" : 0,
			"saveState" : 0,
			"restoreState" : 0,
			"isEOF" : 1,
			"invalidates" : 0,
			"direction" : "forward",
			"docsExamined" : 3
		}
	},
	"serverInfo" : {
		"host" : "storchbox",
		"port" : 27017,
		"version" : "0.0.0",
		"gitVersion" : "unknown"
	},
	"ok" : 1
}

Instead, the planner could notice that the plan is guaranteed to return no documents, and replace the entire execution tree with an EOF plan. EOF plans simply immediately return end-of-stream, without doing any wasteful query execution work.


Generated at Thu Feb 08 04:35:00 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.