// // Copyright 2025 DXOS.org // import { Order, Query } from '@dxos/echo'; import { QueryAST } from '@dxos/echo-protocol'; import { invariant } from '@dxos/invariant'; import { DXN, type URI } from '@dxos/keys'; import { QueryError } from './errors.ts'; import { QueryPlan } from './plan.ts'; /** * Creates a QueryError with "Query too complex" message and includes the prettified query in the context. */ const queryTooComplexError = (query: QueryAST.Query | null): QueryError => { if (query === null) { return new QueryError({ message: 'Query too complex', context: { query: null }, }); } const prettyQuery = Query.pretty(Query.fromAst(query)); return new QueryError({ message: `Query too complex: ${prettyQuery}`, context: { query, prettyQuery }, }); }; export type QueryPlannerOptions = { defaultTextSearchKind: QueryPlan.TextSearchKind; /** * When true, downgrade index-backed selectors to WildcardSelector + FilterStep. * Use when executing against an in-memory working set without SQL index access. * TextSelector and TimestampSelector remain as-is so the caller can detect them and bail. */ noIndexes?: boolean; }; const DEFAULT_OPTIONS: QueryPlannerOptions = { defaultTextSearchKind: 'full-text', }; /** * Constructs an optimized query plan. */ // TODO(dmaretskyi): Implement inefficient versions of complex queries. export class QueryPlanner { private readonly _options: QueryPlannerOptions; constructor(options?: Partial) { this._options = { ...DEFAULT_OPTIONS, ...options, }; } /** The uncompiled steps. Pure, so the SQL compiler recurses through it for `in-query` subqueries. */ createPlan(query: QueryAST.Query): QueryPlan.Plan { this._validateQueryScoped(query); this._validateAggregatePlacement(query); const selectsChanges = queryContainsChanges(query); if (selectsChanges) { this._validateChangesFilters(query); } let plan = this._generate(query, { ...DEFAULT_CONTEXT, originalQuery: query }); plan = this._optimizeEmptyFilters(plan); plan = this._optimizeSoloUnions(plan); plan = this._ensureOrderStep(plan); if (selectsChanges) { return this._routeChanges(plan, query); } plan = this._optimizeLimits(plan); plan = this._optimizeBareAggregate(plan); return plan; } private _validateChangesFilters(query: QueryAST.Query): void { QueryAST.visit(query, (node) => { if ( (node.type === 'filter' && filterContainsChanges(node.filter)) || (node.type === 'select' && node.filter.type !== 'changes' && filterContainsChanges(node.filter)) ) { throw new QueryError({ message: 'Filter.changes() cannot be combined with other filters, traversals or unions.', context: { query: Query.pretty(Query.fromAst(query)) }, }); } }); } private _routeChanges(plan: QueryPlan.Plan, query: QueryAST.Query): QueryPlan.Plan { const fail = (message: string): never => { throw new QueryError({ message, context: { query: Query.pretty(Query.fromAst(query)) } }); }; const [select, ...rest] = plan.steps; if (select?._tag !== 'SelectStep' || select.selector._tag !== 'ChangesSelector') { return fail('Filter.changes() cannot be combined with other filters, traversals or unions.'); } if (!select.scope.every((scope) => scope._tag === 'space')) { return fail('Filter.changes() selects from spaces, not feeds.'); } for (const step of rest) { switch (step._tag) { case 'LimitStep': case 'SkipStep': break; case 'OrderStep': if (!step.order.every((order) => order.kind === 'natural' || order.kind === 'property')) { return fail('Changes can only be ordered by a property or naturally (by time).'); } break; case 'AggregateStep': { const unsupported = step.aggregates.find( (aggregate) => aggregate.kind === 'items' || aggregate.kind === 'type' || aggregate.kind === 'timestamp', ); if (unsupported) { const name = unsupported.kind === 'timestamp' ? unsupported.field === 'updatedAt' ? 'updated' : 'created' : unsupported.kind; return fail(`Aggregate.${name}() does not apply to changes.`); } break; } default: return fail('Filter.changes() cannot be combined with other filters, traversals or unions.'); } } const indexAnswers = activityIndexAnswers(rest); if (!indexAnswers && select.selector.targets === undefined) { return fail( "A space-wide Filter.changes() query must aggregate with only Aggregate.time('time', …), " + "Aggregate.group('source'), Aggregate.count() and Aggregate.sum('ops'); pass targets to Filter.changes() " + 'for anything else.', ); } return QueryPlan.Plan.make([ { ...select, selector: { ...select.selector, source: indexAnswers ? 'index' : 'replay' } }, ...rest, ]); } /** * Marks the select of a plan that only counts objects by index fields as {@link QueryPlan.SelectStep.bare}, * so the executor groups index rows instead of loading documents. Eligible shape: a space-scoped * wildcard, type or timestamp select, then deleted handling, a plain typename re-check and natural * ordering in any order, ending in an aggregate of `count`, `type` and `timestamp` only. */ private _optimizeBareAggregate(plan: QueryPlan.Plan): QueryPlan.Plan { if (this._options.noIndexes) { return plan; } const [select, ...rest] = plan.steps; const aggregate = rest.at(-1); if ( select?._tag !== 'SelectStep' || aggregate?._tag !== 'AggregateStep' || select.limit !== undefined || select.feedCursorRange !== undefined || !select.scope.every((scope) => scope._tag === 'space' && !scope.includeAllFeeds) || (select.selector._tag !== 'WildcardSelector' && select.selector._tag !== 'TimestampSelector' && (select.selector._tag !== 'TypeSelector' || select.selector.inverted)) || !aggregate.aggregates.every( (entry) => entry.kind === 'count' || entry.kind === 'type' || entry.kind === 'timestamp', ) ) { return plan; } const readsOnlyIndexFields = rest.slice(0, -1).every( (step) => step._tag === 'FilterDeletedStep' || // A metadata predicate reads keys an index row does not carry, so it has to load documents. (step._tag === 'FilterStep' && isTrivialTypenameFilter(step.filter) && step.filter.type === 'object' && step.filter.metaKey === undefined) || (step._tag === 'OrderStep' && step.limit === undefined && step.order.every((order) => order.kind === 'natural')), ); if (!readsOnlyIndexFields) { return plan; } return QueryPlan.Plan.make([{ ...select, bare: true }, ...rest]); } private _generate(query: QueryAST.Query, context: GenerationContext): QueryPlan.Plan { switch (query.type) { case 'options': return this._generateOptionsClause(query, context); case 'select': return this._generateSelectClause(query, context); case 'filter': return this._generateFilterClause(query, context); case 'incoming-references': return this._generateIncomingReferencesClause(query, context); case 'relation': return this._generateRelationClause(query, context); case 'relation-traversal': return this._generateRelationTraversalClause(query, context); case 'reference-traversal': return this._generateReferenceTraversalClause(query, context); case 'hierarchy-traversal': return this._generateHierarchyTraversalClause(query, context); case 'union': return this._generateUnionClause(query, context); case 'set-difference': return this._generateSetDifferenceClause(query, context); case 'order': return this._generateOrderClause(query, context); case 'limit': return this._generateLimitClause(query, context); case 'skip': return this._generateSkipClause(query, context); case 'aggregate': return this._generateAggregateClause(query, context); case 'from': return this._generateFromClause(query, context); default: throw new QueryError({ message: `Unsupported query type: ${(query as any).type}`, context: { query: context.originalQuery }, }); } } private _generateOptionsClause(query: QueryAST.QueryOptionsClause, context: GenerationContext): QueryPlan.Plan { const newContext = { ...context, }; if (query.options.deleted) { newContext.deletedHandling = query.options.deleted; } return this._generate(query.query, newContext); } private _generateFromClause(query: QueryAST.QueryFromClause, context: GenerationContext): QueryPlan.Plan { if (query.from._tag === 'scope') { return this._generate(query.query, { ...context, scope: query.from.scopes }); } // Subquery from: flatten by rewriting the outer query's leaf select into a filter on the subquery. const subquery = query.from.query; const rewritten = QueryAST.map(query.query, (node) => node.type === 'select' ? { type: 'filter', selection: subquery, filter: node.filter } : node, ); return this._generate(rewritten, context); } private _generateSelectClause(query: QueryAST.QuerySelectClause, context: GenerationContext): QueryPlan.Plan { return this._generateSelectionFromFilter(query.filter, context); } // TODO(dmaretskyi): This can be rewritten as a function of (filter[]) -> (selection ? undefined, rest: filter[]) that recurses onto itself. // TODO(dmaretskyi): If the tip of the query ast is a [select, ...filter] shape we can reorder the filters so the query is most efficient. private _generateSelectionFromFilter(filter: QueryAST.Filter, context: GenerationContext): QueryPlan.Plan { // A feed cursor bounds the scan rather than describing an object, so it is lifted out of the // filter tree and onto the select step it bounds; what remains plans exactly as it would // without it. const { range, rest } = _splitFeedCursor(filter, context); if (range !== undefined) { // Checked here rather than where the bound is applied, so the start sentinel — which bounds // nothing and so reaches no window — is refused over a space's documents just the same. An // automerge object has no position for any cursor to name. if (!context.scope.every((scope) => scope._tag === 'feed')) { throw new QueryError({ message: 'A feed cursor filter can only be used with a feed scope.', context: { query: context.originalQuery }, }); } const plan = this._generateSelectionFromFilter(rest ?? { type: 'object', typename: null, props: {} }, context); const selectIdx = plan.steps.findIndex((step) => step._tag === 'SelectStep'); invariant(selectIdx !== -1, 'expected a select step to bound'); const steps = [...plan.steps]; steps[selectIdx] = { ...(steps[selectIdx] as QueryPlan.SelectStep), feedCursorRange: range }; return QueryPlan.Plan.make(steps); } switch (filter.type) { // Props case 'object': { if ( context.selectionInverted && filter.id === undefined && filter.typename === null && Object.keys(filter.props).length === 0 ) { // filter of nothing -> clear working set. return QueryPlan.Plan.make([ { _tag: 'ClearWorkingSetStep', }, ...this._generateDeletedHandlingSteps(context), ]); } if (context.selectionInverted && isTrivialTypenameFilter(filter)) { invariant(filter.typename !== null); // Negated plain type filter (e.g. `Filter.not(Filter.type(Foo))`) — mirrors the trivial-OR // handling below: select via an inverted TypeSelector when indexed, or a WildcardSelector // when working from the in-memory set, then re-check the negation in the FilterStep. const selector: QueryPlan.Selector = this._options.noIndexes ? { _tag: 'WildcardSelector' } : { _tag: 'TypeSelector', typename: [filter.typename], inverted: true }; return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: { type: 'not', filter: { ...filter } }, }, ]); } if (context.selectionInverted) { throw queryTooComplexError(context.originalQuery); } // Try to utilize indexes during selection, prioritizing selecting by id, then by typename. // After selection, filter out using the remaining predicates. if (filter.id && filter.id?.length > 0) { return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'IdSelector', objectIds: filter.id, }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: { ...filter, id: undefined }, }, ]); } else if (filter.typename) { // When noIndexes is set, use WildcardSelector so all loaded cores are scanned; // the type predicate is enforced by the FilterStep that already follows. const selector: QueryPlan.Selector = this._options.noIndexes ? { _tag: 'WildcardSelector' } : { _tag: 'TypeSelector', typename: [filter.typename], inverted: false }; return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector, }, ...this._generateDeletedHandlingSteps(context), // TODO(dmaretskyi): Normally we could skip filtering by typename here, but since the index does not separate schema versions, we need to do additional filter to only select the correct version. { _tag: 'FilterStep', filter: { ...filter }, }, ]); } else { return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector', }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: { ...filter }, }, ]); } } // Tag case 'tag': { return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector', }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: { ...filter }, }, ]); } // Text case 'text-search': { return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'TextSelector', text: filter.text, searchKind: filter.searchKind ?? this._options.defaultTextSearchKind, typename: null, }, }, ...this._generateDeletedHandlingSteps(context), ]); } // Feed cursor — always lifted out above, so reaching here means the tree changed shape. case 'feed-cursor': throw queryTooComplexError(context.originalQuery); // Timestamp case 'timestamp': { if (context.selectionInverted) { throw new QueryError({ message: 'Negated timestamp filters are not supported. Use Filter.updated/Filter.created with the inverted range instead.', context: { query: context.originalQuery }, }); } return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: _timestampFilterToSelector(filter), }, ...this._generateDeletedHandlingSteps(context), ]); } // ChildOf case 'child-of': { return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector', }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: { ...filter }, }, ]); } case 'changes': { if (context.selectionInverted) { throw queryTooComplexError(context.originalQuery); } return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'ChangesSelector', targets: filter.targets, source: 'replay' }, }, ]); } // Mnemonic and annotation — local predicates on the object's own id or meta, so they run as a // filter step over a wildcard select. Inversion cannot fold into the value, so it is re-wrapped as `not`. case 'annotation': case 'mnemonic': { const planned: QueryAST.Filter = context.selectionInverted ? { type: 'not', filter } : filter; return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector', }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: planned, }, ]); } // HasParent — a local predicate on the object's own parent slot, so inversion folds into // the value rather than costing a negated plan. case 'has-parent': { const planned: QueryAST.Filter = context.selectionInverted ? { ...filter, value: !filter.value } : { ...filter }; return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector', }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: planned, }, ]); } // Compare case 'compare': throw queryTooComplexError(context.originalQuery); case 'in': throw queryTooComplexError(context.originalQuery); case 'in-query': throw queryTooComplexError(context.originalQuery); case 'range': throw queryTooComplexError(context.originalQuery); // Boolean case 'not': return this._generateSelectionFromFilter(filter.filter, { ...context, selectionInverted: !context.selectionInverted, }); case 'and': { const flatFilters = _flattenAnd(filter.filters); const timestampFilters = flatFilters.filter((f): f is QueryAST.FilterTimestamp => f.type === 'timestamp'); const childOfFilters = flatFilters.filter((f): f is QueryAST.FilterChildOf => f.type === 'child-of'); // has-parent and (negated) annotation predicates are local checks, planned as post-filters. const localFilters = flatFilters.filter((f) => f.type === 'has-parent' || _isAnnotationPredicate(f)); const otherFilters = flatFilters.filter( (f) => f.type !== 'timestamp' && f.type !== 'child-of' && !localFilters.includes(f), ); if (timestampFilters.length > 0 && context.selectionInverted) { throw new QueryError({ message: 'Negated timestamp filters are not supported. Use Filter.updated/Filter.created with the inverted range instead.', context: { query: context.originalQuery }, }); } if ( timestampFilters.length > 0 && otherFilters.length <= 1 && childOfFilters.length === 0 && localFilters.length === 0 ) { const innerFilter = otherFilters[0]; const innerPlan = innerFilter ? this._generateSelectionFromFilter(innerFilter, context) : QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector' }, }, ...this._generateDeletedHandlingSteps(context), ]); const selectIdx = innerPlan.steps.findIndex((s) => s._tag === 'SelectStep'); if (selectIdx !== -1) { const newSteps = [...innerPlan.steps]; newSteps.splice(selectIdx + 1, 0, { _tag: 'FilterStep', filter: { type: 'and', filters: timestampFilters }, }); return QueryPlan.Plan.make(newSteps); } const selector = _mergeTimestampSelectors(timestampFilters.map(_timestampFilterToSelector)); return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector, }, ...this._generateDeletedHandlingSteps(context), ]); } if (timestampFilters.length > 0 && childOfFilters.length === 0 && localFilters.length === 0) { throw new QueryError({ message: 'Timestamp filters can only be combined with a single type or property filter via AND. Split complex filters into a subquery.', context: { query: context.originalQuery }, }); } // child-of and the local filters plan as post-filters appended to the remaining filters' // plan, so `and(type(X), hasParent(false))` keeps its type-indexed select. if (childOfFilters.length > 0 || localFilters.length > 0) { // A negated conjunction cannot distribute over its conjuncts (`not(and(a, b))` is not // `not(a) && b`), so under inversion the WHOLE negated AND becomes one post-filter — // possible only when every conjunct is root-executable (child-of is not). if (context.selectionInverted) { if (childOfFilters.length > 0 || !flatFilters.every(isRootExecutable)) { throw queryTooComplexError(context.originalQuery); } return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector' }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: { type: 'not', filter: { type: 'and', filters: flatFilters } }, }, ]); } const remainingFilters: QueryAST.Filter[] = [...otherFilters, ...timestampFilters]; const innerPlan = remainingFilters.length === 1 ? this._generateSelectionFromFilter(remainingFilters[0], context) : remainingFilters.length > 1 ? this._generateSelectionFromFilter({ type: 'and', filters: remainingFilters }, context) : QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector' }, }, ...this._generateDeletedHandlingSteps(context), ]); const postFilterSteps: QueryPlan.Step[] = [...childOfFilters, ...localFilters].map((f) => ({ _tag: 'FilterStep' as const, filter: f, })); return QueryPlan.Plan.make([...innerPlan.steps, ...postFilterSteps]); } // Simple AND: all filters are root-executable against in-memory objects after a wildcard select. // The text search must drive the selection — the in-memory matcher cannot evaluate one — // and inverting it would need objects outside the FTS hits, which the index cannot produce. const textFilters = flatFilters.filter((f): f is QueryAST.FilterTextSearch => f.type === 'text-search'); if (textFilters.length === 1 && !context.selectionInverted) { const [textFilter] = textFilters; const rest = flatFilters.filter((f) => f.type !== 'text-search'); if (rest.length === 0) { return this._generateSelectionFromFilter(textFilter, context); } if (rest.every(isRootExecutable)) { const typename = rest.map(_extractFilterTypenames).find((list) => list !== null) ?? null; return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'TextSelector', text: textFilter.text, searchKind: textFilter.searchKind ?? this._options.defaultTextSearchKind, typename, }, }, ...this._generateDeletedHandlingSteps(context), // The selector's typename narrowing is an over-approximation (it cannot distinguish // schema versions), so the residual filters are always re-checked here. { _tag: 'FilterStep', filter: rest.length === 1 ? { ...rest[0] } : { type: 'and', filters: rest }, }, ]); } } if (textFilters.length > 0) { throw queryTooComplexError(context.originalQuery); } if (flatFilters.every(isRootExecutable)) { const innerFilter: QueryAST.Filter = { type: 'and', filters: flatFilters }; const plannedFilter: QueryAST.Filter = context.selectionInverted ? { type: 'not', filter: innerFilter } : innerFilter; return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: { _tag: 'WildcardSelector' }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: plannedFilter, }, ]); } throw queryTooComplexError(context.originalQuery); } case 'or': // Optimized case if (filter.filters.every(isTrivialTypenameFilter)) { const typenames = filter.filters.map((filter) => { invariant(filter.type === 'object' && filter.typename !== null); return filter.typename; }); // When noIndexes is set, use WildcardSelector so all loaded cores are scanned; a WildcardSelector // carries no inversion, so the FilterStep below must apply the negation instead of the selector. const orSelector: QueryPlan.Selector = this._options.noIndexes ? { _tag: 'WildcardSelector' } : { _tag: 'TypeSelector', typename: typenames, inverted: context.selectionInverted }; // The FilterStep re-checks the selector's predicate (it also disambiguates same-named schema // versions the index doesn't distinguish), so it must encode the same inversion as the selector. const orFilter: QueryAST.Filter = context.selectionInverted ? { type: 'not', filter: { ...filter } } : { ...filter }; return QueryPlan.Plan.make([ { _tag: 'SelectStep', scope: context.scope, selector: orSelector, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: orFilter, }, ]); } else { throw queryTooComplexError(context.originalQuery); } default: throw new QueryError({ message: `Unsupported filter type: ${(filter as any).type}`, context: { query: context.originalQuery }, }); } } private _generateDeletedHandlingSteps(context: GenerationContext): QueryPlan.Step[] { switch (context.deletedHandling) { case 'include': return []; case 'exclude': return [ { _tag: 'FilterDeletedStep', mode: 'only-non-deleted', }, ]; case 'only': return [ { _tag: 'FilterDeletedStep', mode: 'only-deleted', }, ]; } } private _generateUnionClause(query: QueryAST.QueryUnionClause, context: GenerationContext): QueryPlan.Plan { return QueryPlan.Plan.make([ { _tag: 'UnionStep', plans: query.queries.map((query) => this._generate(query, context)), }, ]); } private _generateSetDifferenceClause( query: QueryAST.QuerySetDifferenceClause, context: GenerationContext, ): QueryPlan.Plan { return QueryPlan.Plan.make([ { _tag: 'SetDifferenceStep', source: this._generate(query.source, context), exclude: this._generate(query.exclude, context), }, ]); } private _generateReferenceTraversalClause( query: QueryAST.QueryReferenceTraversalClause, context: GenerationContext, ): QueryPlan.Plan { return QueryPlan.Plan.make([ ...this._generate(query.anchor, context).steps, { _tag: 'TraverseStep', traversal: { _tag: 'ReferenceTraversal', direction: 'outgoing', property: query.property, }, }, ...this._generateDeletedHandlingSteps(context), ]); } private _generateIncomingReferencesClause( query: QueryAST.QueryIncomingReferencesClause, context: GenerationContext, ): QueryPlan.Plan { // `Query.select(Filter.key(dxn)).referencedBy()` collapses to a single index lookup. Evaluating // the anchor would be both a scan (a meta-key filter is matched in memory, not indexed) and // empty for the case this exists to serve: a named entity, which is never in the graph. const namedAnchor = namedEntityAnchor(query.anchor); if (namedAnchor !== undefined) { return QueryPlan.Plan.make([ { _tag: 'SelectStep', selector: { _tag: 'IncomingReferenceSelector', targetDXN: namedAnchor, property: query.property ?? null, }, scope: context.scope, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: { type: 'object', typename: query.typename, props: {}, }, }, ]); } return QueryPlan.Plan.make([ ...this._generate(query.anchor, context).steps, { _tag: 'TraverseStep', traversal: { _tag: 'ReferenceTraversal', direction: 'incoming', property: query.property ?? null, }, }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: { type: 'object', typename: query.typename, props: {}, }, }, ]); } private _generateRelationTraversalClause( query: QueryAST.QueryRelationTraversalClause, context: GenerationContext, ): QueryPlan.Plan { switch (query.direction) { case 'source': { return QueryPlan.Plan.make([ ...this._generate(query.anchor, context).steps, createRelationTraversalStep('relation-to-source'), ...this._generateDeletedHandlingSteps(context), ]); } case 'target': { return QueryPlan.Plan.make([ ...this._generate(query.anchor, context).steps, createRelationTraversalStep('relation-to-target'), ...this._generateDeletedHandlingSteps(context), ]); } case 'both': { const anchorPlan = this._generate(query.anchor, context); return QueryPlan.Plan.make([ ...anchorPlan.steps, { _tag: 'UnionStep', plans: [ QueryPlan.Plan.make([createRelationTraversalStep('relation-to-source')]), QueryPlan.Plan.make([createRelationTraversalStep('relation-to-target')]), ], }, ...this._generateDeletedHandlingSteps(context), ]); } } } private _generateRelationClause(query: QueryAST.QueryRelationClause, context: GenerationContext): QueryPlan.Plan { switch (query.direction) { case 'outgoing': { return QueryPlan.Plan.make([ ...this._generate(query.anchor, context).steps, createRelationTraversalStep('source-to-relation'), ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: query.filter ?? NOOP_FILTER, }, ]); } case 'incoming': { return QueryPlan.Plan.make([ ...this._generate(query.anchor, context).steps, createRelationTraversalStep('target-to-relation'), ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: query.filter ?? NOOP_FILTER, }, ]); } case 'both': { const anchorPlan = this._generate(query.anchor, context); return QueryPlan.Plan.make([ ...anchorPlan.steps, { _tag: 'UnionStep', plans: [ QueryPlan.Plan.make([createRelationTraversalStep('source-to-relation')]), QueryPlan.Plan.make([createRelationTraversalStep('target-to-relation')]), ], }, ...this._generateDeletedHandlingSteps(context), { _tag: 'FilterStep', filter: query.filter ?? NOOP_FILTER, }, ]); } } } private _generateFilterClause(query: QueryAST.QueryFilterClause, context: GenerationContext): QueryPlan.Plan { return QueryPlan.Plan.make([ ...this._generate(query.selection, context).steps, { _tag: 'FilterStep', filter: query.filter, }, ]); } private _generateHierarchyTraversalClause( query: QueryAST.QueryHierarchyTraversalClause, context: GenerationContext, ): QueryPlan.Plan { return QueryPlan.Plan.make([ ...this._generate(query.anchor, context).steps, { _tag: 'TraverseStep', traversal: { _tag: 'HierarchyTraversal', direction: query.direction, }, }, ...this._generateDeletedHandlingSteps(context), ]); } private _validateQueryScoped(query: QueryAST.Query): void { let hasScope = false; QueryAST.visit(query, (node) => { if (node.type === 'from') { hasScope = true; } }); if (!hasScope) { throw new QueryError({ message: 'Query must be scoped with a from() clause', context: { query }, }); } } /** * `aggregate` must be the outermost data clause: only `from()`/`options()` and the group-level * pagination clauses `limit()`/`skip()` may wrap it. At most one `aggregate` may appear anywhere * in the tree — including inside a `.from(subquery)` source, which the planner flattens (so an * aggregated subquery would otherwise produce an unsupported double-`aggregate`). The DSL's types * can't enforce this (`Query` still exposes `orderBy`/`select`/etc.), so * it's validated here at plan time. * * `limit`/`skip` above an `aggregate` page over whole groups (see the group-aware `LimitStep`/ * `SkipStep` execution); a `limit`/`skip` below it windows the flat object stream before aggregating. */ private _validateAggregatePlacement(query: QueryAST.Query): void { // Count every aggregate anywhere in the tree. `QueryAST.visit` recurses through `from` sources, // so this also sees aggregated subqueries that flattening would merge in. let aggregateCount = 0; QueryAST.visit(query, (node) => { if (node.type === 'aggregate') { aggregateCount += 1; } }); if (aggregateCount === 0) { return; } if (aggregateCount > 1) { throw new QueryError({ message: 'Only one aggregate clause is supported per query', context: { query }, }); } // Exactly one aggregate: it must sit at the outermost data position (only from/options/order/ // limit/skip may wrap it). A wrapping `order` reorders whole groups; an `order` inside the // aggregate's own query orders members within each group. Unwrap the permitted wrappers and // require the aggregate to be what remains. let root = query; while ( root.type === 'options' || root.type === 'from' || root.type === 'order' || root.type === 'limit' || root.type === 'skip' ) { root = root.query; } if (root.type !== 'aggregate') { throw new QueryError({ message: 'aggregate must be the outermost query clause — only from(), options(), orderBy(), limit() and skip() may follow it', context: { query }, }); } } /** * Removes filter steps that have no predicates. */ private _optimizeEmptyFilters(plan: QueryPlan.Plan): QueryPlan.Plan { return QueryPlan.Plan.make( plan.steps .filter((step) => { if (step._tag === 'FilterStep') { return !QueryPlan.FilterStep.isNoop(step); } else { return true; } }) .map((step) => { if (step._tag === 'UnionStep') { return { _tag: 'UnionStep', plans: step.plans.map((plan) => this._optimizeEmptyFilters(plan)), }; } else { return step; } }), ); } /** * Removes union steps that have only one child. */ private _optimizeSoloUnions(plan: QueryPlan.Plan): QueryPlan.Plan { // TODO(dmaretskyi): Implement this. return plan; } private _generateOrderClause(query: QueryAST.QueryOrderClause, context: GenerationContext): QueryPlan.Plan { return QueryPlan.Plan.make([ ...this._generate(query.query, context).steps, { _tag: 'OrderStep', order: query.order, }, ]); } private _generateLimitClause(query: QueryAST.QueryLimitClause, context: GenerationContext): QueryPlan.Plan { return QueryPlan.Plan.make([ ...this._generate(query.query, context).steps, { _tag: 'LimitStep', limit: query.limit, }, ]); } private _generateSkipClause(query: QueryAST.QuerySkipClause, context: GenerationContext): QueryPlan.Plan { return QueryPlan.Plan.make([ ...this._generate(query.query, context).steps, { _tag: 'SkipStep', skip: query.skip, }, ]); } private _generateAggregateClause(query: QueryAST.QueryAggregateClause, context: GenerationContext): QueryPlan.Plan { return QueryPlan.Plan.make([ ...this._generate(query.query, context).steps, { _tag: 'AggregateStep', aggregates: query.aggregates, }, ]); } // After complete plan is built, inspect it from the end: // - Walk backwards until hitting an object set changer. // - If an order step is found, skip. // - Otherwise insert natural order before any limit steps (since limit should be applied after ordering). // This method is recursive and also processes sub-plans in unions and set differences. private _ensureOrderStep(plan: QueryPlan.Plan): QueryPlan.Plan { // First, recursively process any sub-plans. const processedSteps = plan.steps.map((step): QueryPlan.Step => { if (step._tag === 'UnionStep') { return { _tag: 'UnionStep', plans: step.plans.map((subPlan) => this._ensureOrderStep(subPlan)), }; } else if (step._tag === 'SetDifferenceStep') { return { _tag: 'SetDifferenceStep', source: this._ensureOrderStep(step.source), exclude: this._ensureOrderStep(step.exclude), }; } return step; }); const processedPlan = QueryPlan.Plan.make(processedSteps); const OBJECT_SET_CHANGERS = new Set(['SelectStep', 'TraverseStep', 'UnionStep', 'SetDifferenceStep']); for (let i = processedPlan.steps.length - 1; i >= 0; i--) { const step = processedPlan.steps[i]; if (step._tag === 'OrderStep') { return processedPlan; } if (OBJECT_SET_CHANGERS.has(step._tag)) { // An outgoing reference traversal emits each anchor's refs in array order, which is the only // order a ref array has. Order the anchors instead, so the result stays deterministic. if (isOutgoingReferenceTraversal(step)) { const anchor = this._ensureOrderStep(QueryPlan.Plan.make(processedPlan.steps.slice(0, i))); return QueryPlan.Plan.make([...anchor.steps, ...processedPlan.steps.slice(i)]); } break; } } // Find the position to insert the order step (before any trailing limit/skip/aggregate steps — // aggregation must see the intended order already applied, both within and between groups). let insertIndex = processedPlan.steps.length; for (let i = processedPlan.steps.length - 1; i >= 0; i--) { const tag = processedPlan.steps[i]._tag; if (tag === 'LimitStep' || tag === 'SkipStep' || tag === 'AggregateStep') { insertIndex = i; } else { break; } } const newSteps = [...processedPlan.steps]; newSteps.splice(insertIndex, 0, { _tag: 'OrderStep', order: [Order.natural().ast], }); return QueryPlan.Plan.make(newSteps); } /** * Propagates limits from LimitStep to SelectStep and OrderStep when possible. * Limits can only be propagated if there are no unions or traversals between the LimitStep and SelectStep/OrderStep. */ private _optimizeLimits(plan: QueryPlan.Plan): QueryPlan.Plan { // First, recursively process any sub-plans. const processedSteps = plan.steps.map((step): QueryPlan.Step => { if (step._tag === 'UnionStep') { return { _tag: 'UnionStep', plans: step.plans.map((subPlan) => this._optimizeLimits(subPlan)), }; } else if (step._tag === 'SetDifferenceStep') { return { _tag: 'SetDifferenceStep', source: this._optimizeLimits(step.source), exclude: this._optimizeLimits(step.exclude), }; } return step; }); // Find if there's a LimitStep at the end (possibly after OrderStep). let limitStepIndex = -1; let limitValue: number | undefined; for (let i = processedSteps.length - 1; i >= 0; i--) { const step = processedSteps[i]; if (step._tag === 'LimitStep') { limitStepIndex = i; limitValue = step.limit; break; } // Only allow OrderStep after LimitStep when looking backwards. if (step._tag !== 'OrderStep') { break; } } if (limitStepIndex === -1 || limitValue === undefined) { return QueryPlan.Plan.make(processedSteps); } // Check if we can propagate the limit to a SelectStep and/or OrderStep. // We can only do this if there are no unions, traversals, or set differences between them. // AggregateStep is also a blocker: a limit above it counts whole groups, so it must not be // pushed down into the flat SelectStep/OrderStep scan (that would slice objects, not groups). const BLOCKERS = new Set(['UnionStep', 'TraverseStep', 'SetDifferenceStep', 'AggregateStep']); let selectStepIndex = -1; let orderStepIndex = -1; for (let i = 0; i < limitStepIndex; i++) { const step = processedSteps[i]; if (step._tag === 'SelectStep') { selectStepIndex = i; } if (step._tag === 'OrderStep') { orderStepIndex = i; } if (BLOCKERS.has(step._tag)) { // Found a blocker after the select/order step - can't propagate. selectStepIndex = -1; orderStepIndex = -1; } // A child-of/has-parent FilterStep prunes results in-memory after the SelectStep, so pushing // the limit into the SelectStep would slice candidates before the filter runs and starve // the result set (e.g. wildcard select of 10 random objects, then child-of leaves 0). if (step._tag === 'FilterStep' && _filterContainsPostSelectPrune(step.filter)) { selectStepIndex = -1; orderStepIndex = -1; } // Same reasoning for a nested subquery-membership predicate (`Filter.in(query.project(...))`): // it prunes results in-memory after the SelectStep based on a set resolved at execution time, // so pushing the limit earlier would slice candidates before the semi-join runs and starve // the result set. if (step._tag === 'FilterStep' && filterContainsInQuery(step.filter)) { selectStepIndex = -1; orderStepIndex = -1; } } if (selectStepIndex === -1 && orderStepIndex === -1) { return QueryPlan.Plan.make(processedSteps); } // A feed scan can be ordered and capped by the storage layer itself, so it takes the limit in // either natural direction — which is the point: a bounded feed query must read bounded work. const feedScan = selectStepIndex !== -1 ? feedScanForLimit(processedSteps, selectStepIndex, orderStepIndex, limitStepIndex) : undefined; // Pushing the limit into the SelectStep is only sound when the scan enumerates candidates in the // requested order, so that the first N of the scan are the first N of the result. Absent a feed // scan the select runs in ascending natural order (by id / queue position). A content-based // reorder (property, annotation or system timestamp) or a descending natural order does not match that scan // order, so slicing at select time would keep the wrong N; those need the FULL candidate set and // only the OrderStep may apply the limit. Ascending natural and rank (the FTS scan already // returns by rank) stay consistent with the scan, so keep optimizing those. if (orderStepIndex !== -1 && feedScan === undefined) { const orderStep = processedSteps[orderStepIndex]; const scanOrderMismatch = orderStep._tag === 'OrderStep' && orderStep.order.some( (order) => order.kind === 'property' || order.kind === 'annotation' || order.kind === 'timestamp' || (order.kind === 'natural' && order.direction === 'desc'), ); if (scanOrderMismatch) { selectStepIndex = -1; } } // A SkipStep between a propagation target and the LimitStep drops items after the limit // would be applied. Since the LimitStep is removed, the limit pushed into the earlier step // must also cover the skipped prefix — otherwise `skip(k).limit(n)` yields only `n - k` items. // A feed scan drops the prefix itself, before any document loads, so it takes the SkipSteps instead. const skipBetween = (fromIndex: number): number => { if (feedScan !== undefined) { return 0; } let total = 0; for (let i = fromIndex + 1; i < limitStepIndex; i++) { const step = processedSteps[i]; if (step._tag === 'SkipStep') { total += step.skip; } } return total; }; // Create a mutable copy of steps to modify. const newSteps = [...processedSteps]; // Propagate the limit to the SelectStep if found. if (selectStepIndex !== -1) { const selectStep = newSteps[selectStepIndex] as QueryPlan.SelectStep; newSteps[selectStepIndex] = { ...selectStep, limit: limitValue + skipBetween(selectStepIndex), ...(feedScan ? { feedScan } : {}), }; } // Propagate the limit to the OrderStep if found. if (orderStepIndex !== -1) { const orderStep = newSteps[orderStepIndex] as QueryPlan.OrderStep; newSteps[orderStepIndex] = { ...orderStep, limit: limitValue + skipBetween(orderStepIndex), }; } // Remove the LimitStep since limit is now propagated, and the SkipSteps a feed scan applies. return QueryPlan.Plan.make( newSteps.filter( (step, index) => index !== limitStepIndex && !(feedScan !== undefined && step._tag === 'SkipStep' && index > selectStepIndex && index < limitStepIndex), ), ); } } /** * Context for query planning. */ /** * The DXN named by a `Query.select(Filter.key(dxn))` anchor, or undefined when the anchor is any * other shape. A version-constrained key is excluded: the reverse-reference index keys a named * entity without its version, so the range could not be honoured. */ const namedEntityAnchor = (anchor: QueryAST.Query): URI.URI | undefined => { if (anchor.type !== 'select' || anchor.filter.type !== 'object') { return undefined; } const filter = anchor.filter; if ( filter.metaKey === undefined || filter.metaVersion !== undefined || filter.typename !== null || (filter.id !== undefined && filter.id.length > 0) || Object.keys(filter.props).length > 0 || (filter.foreignKeys !== undefined && filter.foreignKeys.length > 0) ) { return undefined; } // `Filter.key` takes a bare NSID, but a caller holding a DXN passes it through unchanged. return DXN.isDXN(filter.metaKey) ? DXN.tryMake(filter.metaKey) : DXN.tryMake(`dxn:${filter.metaKey}`); }; type GenerationContext = { /** * The original query. */ originalQuery: QueryAST.Query | null; /** * The scope to select from (space IDs, queues, etc.). */ scope: readonly QueryAST.Scope[]; /** * How to handle deleted objects. */ deletedHandling: 'include' | 'exclude' | 'only'; /** * When generating a selection clause, whether to invert the filter. */ selectionInverted: boolean; }; const DEFAULT_CONTEXT: GenerationContext = { originalQuery: null, scope: [], deletedHandling: 'exclude', selectionInverted: false, }; const NOOP_FILTER: QueryAST.Filter = { type: 'object', typename: null, id: [], props: {}, }; const isOutgoingReferenceTraversal = (step: QueryPlan.Step): boolean => step._tag === 'TraverseStep' && step.traversal._tag === 'ReferenceTraversal' && step.traversal.direction === 'outgoing'; const createRelationTraversalStep = (direction: QueryPlan.RelationTraversal['direction']): QueryPlan.Step => ({ _tag: 'TraverseStep', traversal: { _tag: 'RelationTraversal', direction, }, }); /** * The scan shape that lets a feed-only SelectStep apply the query's `limit` itself, or `undefined` * when it may not: a bounded feed query is the whole point of pushing the limit into storage, but * a page capped before a step that prunes it would come back short of what the caller asked for. * * Sound only when every step between the select and the limit is one the scan reproduces: * the deleted filter and any skip (both folded into the returned scan), a residual filter the * selector already enforces, and the order step the scan matches. */ const feedScanForLimit = ( steps: readonly QueryPlan.Step[], selectStepIndex: number, orderStepIndex: number, limitStepIndex: number, ): QueryPlan.FeedScan | undefined => { const selectStep = steps[selectStepIndex]; if (selectStep._tag !== 'SelectStep') { return undefined; } // Only a feed scan orders and caps its own rows; a space scan has no ordering to cap against, // and a mixed scope has no single ordering at all. if (selectStep.scope.length === 0 || !selectStep.scope.every((scope) => scope._tag === 'feed')) { return undefined; } // A cursor read is already windowed by position, and a walk by its path: both are different orderings. if ( selectStep.feedCursorRange !== undefined || selectStep.scope.some((scope) => scope._tag === 'feed' && scope.walk) ) { return undefined; } // The index seeks by id or type; every other selector reaches rows the window cannot order. if (selectStep.selector._tag !== 'WildcardSelector' && selectStep.selector._tag !== 'TypeSelector') { return undefined; } const direction = feedScanDirection(steps, orderStepIndex); if (direction === undefined) { return undefined; } let deleted: boolean | undefined; let skip = 0; for (let index = selectStepIndex + 1; index < limitStepIndex; index++) { const step = steps[index]; switch (step._tag) { case 'FilterDeletedStep': deleted = step.mode === 'only-deleted'; break; case 'FilterStep': if (!isSelectorResidualFilter(step.filter, selectStep.selector)) { return undefined; } break; case 'OrderStep': // Only the step `direction` was derived from; a second one would reorder the capped page. if (index !== orderStepIndex) { return undefined; } break; case 'SkipStep': // A skip below the order composes the other way round: the plan drops rows in scan order // and orders what is left, where the scan orders first and drops from that. if (orderStepIndex !== -1 && index < orderStepIndex) { return undefined; } skip += step.skip; break; default: return undefined; } } return { direction, ...(deleted !== undefined ? { deleted } : {}), ...(skip > 0 ? { skip } : {}), }; }; /** * The natural direction a feed scan must run to satisfy the plan's ordering, or `undefined` when * the ordering is not one the scan can produce (a content-based reorder needs the full candidate * set). An absent order step means natural ascending, which is what the planner inserts. */ const feedScanDirection = ( steps: readonly QueryPlan.Step[], orderStepIndex: number, ): QueryPlan.FeedScan['direction'] | undefined => { if (orderStepIndex === -1) { return 'asc'; } const orderStep = steps[orderStepIndex]; if (orderStep._tag !== 'OrderStep') { return undefined; } if (orderStep.order.length === 0) { return 'asc'; } // Entity ids are unique, so a secondary order could only break ties the scan never produces. if (orderStep.order.length !== 1 || orderStep.order[0].kind !== 'natural') { return undefined; } return orderStep.order[0].direction === 'desc' ? 'desc' : 'asc'; }; /** * Whether a residual FilterStep can only re-check what the selector already enforced, so capping * the scan before it cannot drop a row it would have kept. True for the empty filter, and for the * typename re-check `_generateSelectionFromFilter` emits alongside a TypeSelector — the index * matches the same typenames, versioned or not, that `compareTypenameStrings` accepts. */ const isSelectorResidualFilter = (filter: QueryAST.Filter, selector: QueryPlan.Selector): boolean => { if (filter.type !== 'object') { return false; } const hasOnlyTypename = (filter.id === undefined || filter.id.length === 0) && (filter.props === undefined || Object.keys(filter.props).length === 0) && (filter.foreignKeys === undefined || filter.foreignKeys.length === 0) && filter.metaKey === undefined; if (!hasOnlyTypename) { return false; } if (filter.typename === null) { return true; } return ( selector._tag === 'TypeSelector' && !selector.inverted && selector.typename.length === 1 && selector.typename[0] === filter.typename ); }; const _isAnnotationPredicate = (filter: QueryAST.Filter): boolean => filter.type === 'annotation' || (filter.type === 'not' && filter.filter.type === 'annotation'); /** * Returns true if the filter is `annotation`, `child-of`, `has-parent` or `mnemonic` — the post-select pruning filters — * or composes one via `and` / `or` / `not`. Their FilterSteps genuinely subtract from the * SelectStep's candidates (the step is not a re-check of the selector's own predicate), so a * limit must never be pushed past them. */ const _filterContainsPostSelectPrune = (filter: QueryAST.Filter): boolean => { switch (filter.type) { case 'annotation': case 'child-of': case 'has-parent': case 'mnemonic': return true; case 'not': return _filterContainsPostSelectPrune(filter.filter); case 'and': case 'or': return filter.filters.some(_filterContainsPostSelectPrune); default: return false; } }; /** Whether hourly activity buckets answer the steps after a changes select as individual changes would. */ const activityIndexAnswers = (steps: readonly QueryPlan.Step[]): boolean => { const aggregateIndex = steps.findIndex((step) => step._tag === 'AggregateStep'); const aggregate = steps[aggregateIndex]; return ( aggregate?._tag === 'AggregateStep' && steps.slice(0, aggregateIndex).every(isNaturalOrderStep) && aggregate.aggregates.every(readsOnlyBucketFields) ); }; const isNaturalOrderStep = (step: QueryPlan.Step): boolean => step._tag === 'OrderStep' && step.order.every((order) => order.kind === 'natural'); const readsOnlyBucketFields = (aggregate: QueryAST.GroupAggregate): boolean => aggregate.kind === 'count' || (aggregate.kind === 'sum' && aggregate.property === 'ops') || (aggregate.kind === 'time' && aggregate.property === 'time') || (aggregate.kind === 'group' && aggregate.properties.length === 1 && aggregate.properties[0] === 'source'); const filterContainsChanges = (filter: QueryAST.Filter): boolean => { switch (filter.type) { case 'changes': return true; case 'not': return filterContainsChanges(filter.filter); case 'and': case 'or': return filter.filters.some(filterContainsChanges); default: return false; } }; export const queryContainsChanges = (query: QueryAST.Query): boolean => { let found = false; QueryAST.visit(query, (node) => { if ((node.type === 'select' || node.type === 'filter') && filterContainsChanges(node.filter)) { found = true; } }); return found; }; /** * Returns true if the filter is a subquery-membership predicate (`Filter.in(query.project(...))`, * AST type `in-query`) or composes one via `and` / `or` / `not` / a nested `object` prop. Unlike * `child-of`, which is only ever a root filter, `in-query` is always nested inside an `object` * filter's `props` — the residual FilterStep produced by `_generateSelectionFromFilter`'s `object` * case (above) is always `type: 'object'`, so this must recurse into `props` to find it. * * Exported (unlike the sibling `_filterContains*` helpers) so `query-executor.ts`'s `extractScopes` * can reuse it — a bare `filter.type === 'in-query'` check there would miss the common case. */ export const filterContainsInQuery = (filter: QueryAST.Filter): boolean => { switch (filter.type) { case 'in-query': return true; case 'object': return Object.values(filter.props).some(filterContainsInQuery); case 'not': return filterContainsInQuery(filter.filter); case 'and': case 'or': return filter.filters.some(filterContainsInQuery); default: return false; } }; /** * Recursively flattens nested `and` filters into a single list. */ /** * Lift a `feed-cursor` filter out of the top level of a filter tree, returning the bound and * whatever else the tree selects. * * A cursor is a scan bound, not a predicate over an object, so it composes with AND and with * nothing else: negating or OR-ing one has no scan to bound, and two of them have no single bound. * Those are rejected rather than silently dropped, which would return the whole feed. */ const _splitFeedCursor = ( filter: QueryAST.Filter, context: GenerationContext, ): { range?: { begin?: string; end?: string }; rest?: QueryAST.Filter } => { const reject = () => { throw new QueryError({ message: 'A feed cursor filter can only be combined with other filters via AND.', context: { query: context.originalQuery }, }); }; if (filter.type === 'feed-cursor') { if (context.selectionInverted) { reject(); } return { range: _feedCursorRange(filter) }; } if (filter.type !== 'and') { if (_containsFeedCursor(filter)) { reject(); } return {}; } const flat = _flattenAnd(filter.filters); const cursors = flat.filter((f): f is QueryAST.FilterFeedCursor => f.type === 'feed-cursor'); const rest = flat.filter((f) => f.type !== 'feed-cursor'); if (cursors.length === 0) { if (rest.some(_containsFeedCursor)) { reject(); } return {}; } if (cursors.length > 1 || context.selectionInverted || rest.some(_containsFeedCursor)) { reject(); } return { range: _feedCursorRange(cursors[0]), rest: rest.length === 0 ? undefined : rest.length === 1 ? rest[0] : { type: 'and', filters: rest }, }; }; const _feedCursorRange = ( filter: QueryAST.FilterFeedCursor, ): { begin?: string; end?: string; positions?: 'local' | 'edge' } => ({ ...(filter.begin !== undefined ? { begin: filter.begin } : {}), ...(filter.end !== undefined ? { end: filter.end } : {}), ...(filter.positions !== undefined ? { positions: filter.positions } : {}), }); const _containsFeedCursor = (filter: QueryAST.Filter): boolean => { switch (filter.type) { case 'feed-cursor': return true; case 'not': return _containsFeedCursor(filter.filter); case 'and': case 'or': return filter.filters.some(_containsFeedCursor); default: return false; } }; const _flattenAnd = (filters: readonly QueryAST.Filter[]): QueryAST.Filter[] => { const result: QueryAST.Filter[] = []; for (const f of filters) { if (f.type === 'and') { result.push(..._flattenAnd(f.filters)); } else { result.push(f); } } return result; }; const _timestampFilterToSelector = (filter: QueryAST.FilterTimestamp): QueryPlan.TimestampSelector => { const selector: QueryPlan.TimestampSelector = { _tag: 'TimestampSelector' }; const key = filter.field === 'updatedAt' ? filter.operator === 'gte' || filter.operator === 'gt' ? 'updatedAfter' : 'updatedBefore' : filter.operator === 'gte' || filter.operator === 'gt' ? 'createdAfter' : 'createdBefore'; selector[key] = filter.value; return selector; }; const _mergeTimestampSelectors = (selectors: QueryPlan.TimestampSelector[]): QueryPlan.TimestampSelector => { const merged: QueryPlan.TimestampSelector = { _tag: 'TimestampSelector' }; for (const selector of selectors) { if (selector.updatedAfter != null) { merged.updatedAfter = Math.max(merged.updatedAfter ?? 0, selector.updatedAfter); } if (selector.updatedBefore != null) { merged.updatedBefore = Math.min(merged.updatedBefore ?? Infinity, selector.updatedBefore); } if (selector.createdAfter != null) { merged.createdAfter = Math.max(merged.createdAfter ?? 0, selector.createdAfter); } if (selector.createdBefore != null) { merged.createdBefore = Math.min(merged.createdBefore ?? Infinity, selector.createdBefore); } } return merged; }; /** * Root-executable: the filter can run against in-memory objects after a wildcard select. * Covers true root selectors (`object`, `tag`) plus negations / unions of those. * Property-level filters (`compare`, `in`, `range`, `contains`) are intentionally excluded because * `filterMatchDoc` only handles them as nested predicates inside an `object` filter, not at the root. */ const isRootExecutable = (filter: QueryAST.Filter): boolean => { switch (filter.type) { case 'object': case 'tag': case 'annotation': case 'has-parent': case 'mnemonic': return true; case 'not': return isRootExecutable(filter.filter); case 'or': return filter.filters.every(isRootExecutable); default: return false; } }; /** * Typenames a filter constrains its matches to, or null when it admits objects of any type * (so no narrowing is possible). Used to narrow an index selector; the full filter is still * re-checked in memory, so returning null is always sound. */ const _extractFilterTypenames = (filter: QueryAST.Filter): NonNullable[] | null => { switch (filter.type) { case 'object': return filter.typename !== null ? [filter.typename] : null; case 'or': { const combined: NonNullable[] = []; for (const inner of filter.filters) { const list = _extractFilterTypenames(inner); if (list === null) { return null; } combined.push(...list); } return combined; } default: return null; } }; const isTrivialTypenameFilter = (filter: QueryAST.Filter): boolean => { return ( filter.type === 'object' && filter.typename !== null && Object.keys(filter.props).length === 0 && (filter.id === undefined || filter.id.length === 0) && (filter.foreignKeys === undefined || filter.foreignKeys.length === 0) ); };