// // Copyright 2025 DXOS.org // import * as A from '@automerge/automerge'; import { type DocumentId, interpretAsDocumentId, isValidAutomergeUrl, isValidDocumentId, } from '@automerge/automerge-repo'; import * as Effect from 'effect/Effect'; import * as SqlClient from 'effect/sql/SqlClient'; import { ContextDisposedError, LifecycleState, Resource } from '@dxos/context'; import { type Obj, Query } from '@dxos/echo'; import { BACKED_OBJECT_LIMIT, DatabaseDirectory, EchoFeedCodec, EncodedReference, type EntityPropPath, EntityStructure, EscapedPropPath, PROPERTY_ID, QueryAST, backingJson, isEncodedReference, } from '@dxos/echo-protocol'; import { ATTR_DELETED, ATTR_META, ATTR_PARENT, ATTR_RELATION_SOURCE, ATTR_RELATION_TARGET, ATTR_TYPE, objectStructureFromJson, objectStructureToJson, } from '@dxos/echo/internal'; import * as RuntimeProvider from '@dxos/effect/RuntimeProvider'; import { type FeedOptions, type FeedStore } from '@dxos/feed'; import { type EntityMeta, type IndexEngine, type ObjectSnapshot, type QueueRef, type QueueWindow, type ReverseRef, queueBranchesOf, } from '@dxos/index-core'; import { invariant } from '@dxos/invariant'; import { EID, EntityId, SpaceId, URI } from '@dxos/keys'; import { log } from '@dxos/log'; import { type FeedProtocol } from '@dxos/protocols'; import { type QueryReactivity } from '@dxos/protocols/buf/dxos/echo/query_pb'; import { type QueryService } from '@dxos/protocols/rpc'; import { chunkArray, compositeKey, countWork, getDeep, isNonNullable } from '@dxos/util'; import type { AutomergeHost } from '../automerge/index.ts'; import type { SpaceStateManager } from '../db-host/index.ts'; import { type InvalidationHint, canonicalTypename } from '../db-host/invalidation-hint.ts'; import { filterMatchDoc, filterMatchEntityMeta, filterMatchObjectJSON, getEntityMetaTypeURI } from '../filter/index.ts'; import { type ChangeItem, changeResults, executeChangesPlan, serializeChangeResults } from './changes-executor.ts'; import { QueryError } from './errors.ts'; import { type GroupAggregates, GroupBy, type GroupKeyValue, compareCodeUnits } from './group-by.ts'; import { isSaved } from './object-state.ts'; import { QueryPlan } from './plan.ts'; import { QueryPlanner, filterContainsInQuery } from './query-planner.ts'; import { type CompiledRow, MAX_EDGES_PER_ROW, compilePlan, planDeclinedByCompiler, withFeedCutoffs, } from './sql/index.ts'; /** * Which evaluation path a plan targets: `memory` leaves every step for the executor to evaluate in * JS over loaded objects; `sql` compiles the steps into a single {@link QueryPlan.SqlStep} over the * index tables. `memory` is the default; the host resolves where the choice comes from. */ export type QueryExecutorMode = 'sql' | 'memory'; type QueryExecutorOptions = { indexEngine: IndexEngine; runtime: RuntimeProvider.RuntimeProvider; automergeHost: AutomergeHost; spaceStateManager: SpaceStateManager; queryId: string; query: QueryAST.Query; reactivity: QueryReactivity; executor?: QueryExecutorMode; /** Builds compiled statements; needed only under the `sql` executor. */ sql?: SqlClient.SqlClient; /** Whether the client already holds a document; its rows ship without JSON and stored changes. */ holds?: (documentId: DocumentId) => boolean; /** * The feed store, read for the feeds whose indexing is disabled (they have no index rows) and for * the `maxAge` an index row of a feed item is checked against. Absent, every feed is read from the index. */ feedStore?: FeedStore; }; /** A feed whose indexing is disabled, which a run reads from the feed store instead of the index. */ type StoreFeed = { spaceId: SpaceId; feedNamespace: string }; type QueryExecutionResult = { /** * Whether the query results have changed since the last execution. */ changed: boolean; }; /** * Represents an item in the query working set during execution. */ type QueryItem = { objectId: EntityId; spaceId: SpaceId; queueId: EntityId | null; queueNamespace: string | null; // For objects from automerge documents. documentId: DocumentId | null; // For objects from automerge documents. doc: EntityStructure | null; // For objects from queues. data: Obj.JSON | null; /** For objects selected from the index without loading, when both `doc` and `data` are null. */ meta?: EntityMeta; /** * Relevance rank for this item. * Higher values indicate better matches for FTS/vector searches. * Defaults to 1 for non-ranked queries (predicate matches). */ rank: number; /** * System timestamps from the object meta index (unix ms), used for `timestamp` ordering. * Null when the index has not recorded a timestamp for the item. */ createdAt: number | null; updatedAt: number | null; /** * Group key, set by `AggregateStep`. Undefined for queries without an `aggregate` clause; `{}` for * an aggregate clause with no `group` entries (a single group over the whole input). */ groupKey?: GroupKeyValue; /** * Named group aggregates, stamped by `AggregateStep` when the query declares non-`items` aggregates; * shared by every member of a group and read by a following group-level `OrderStep`. */ aggregates?: GroupAggregates; /** * Set when this item stands for its whole group: the query declared no `items` aggregate, so * `AggregateStep` kept one member per group and the result ships only `groupKey`/`aggregates`. */ collapsed?: { size: number }; /** * The shipped form, already built by a `SqlStep` from the row SQLite returned. Such an item * carries no document, data or meta, so it is only ever produced by the plan's last step. */ result?: QueryService.QueryResult; recordId?: number; /** * The place of the item on a walk, which the natural order of a walk scope sorts by: the index of its * first block on the path read forward, so a descending order gives the backward walk. */ walkIndex?: number; backing?: { heads: readonly string[]; json: string }; /** Heads of the document the item was read at, which the row ships as its version. */ heads?: readonly string[]; /** A feed item's global block position, which the row ships as its version. */ position?: number | null; /** How a traversal reached the item, one path per derivation; absent outside traversals. */ paths?: readonly (readonly QueryService.PathEdge[])[]; /** Set when some derivation of the item could not be stated, so its paths are not shipped. */ derivationUnknown?: boolean; /** Each member of a collapsed group with its share of the scalar aggregates; set by `AggregateStep`. */ manifest?: readonly QueryService.ManifestEntry[]; }; /** Parsed once per index row: an order step reads it on every comparison. */ const indexedAnnotations = new WeakMap> | undefined>(); const parseIndexedAnnotations = (meta: EntityMeta): Readonly> | undefined => { if (!indexedAnnotations.has(meta)) { indexedAnnotations.set(meta, meta.annotations === null ? undefined : JSON.parse(meta.annotations)); } return indexedAnnotations.get(meta); }; const QueryItem = Object.freeze({ /** An item for an index row, carrying no document; `null` for a row that is not document-backed. */ fromIndexRow: (meta: EntityMeta): QueryItem | null => meta.documentId ? { objectId: meta.objectId, documentId: meta.documentId as DocumentId, spaceId: meta.spaceId, queueId: null, queueNamespace: null, doc: null, data: null, meta, rank: 1, createdAt: meta.createdAt, updatedAt: meta.updatedAt, } : null, /** The state the item was read at, as a row ships it; undefined when the item does not know it. */ getVersion: (item: QueryItem): QueryService.RowVersion | undefined => { if (item.documentId && item.heads) { return { kind: 'automerge', documentId: item.documentId, heads: [...item.heads] }; } if (item.queueId && typeof item.position === 'number') { return { kind: 'feed', insertionId: item.position }; } return undefined; }, /** An item for a document object read from the index's copy, which carries its version and backing. */ fromSnapshot: (meta: EntityMeta, documentId: DocumentId, snapshot: ObjectSnapshot): QueryItem => ({ objectId: meta.objectId, documentId, spaceId: meta.spaceId, queueId: null, queueNamespace: null, doc: objectStructureFromJson(JSON.parse(snapshot.json), { createdAt: meta.createdAt ?? undefined }), data: null, rank: 1, createdAt: meta.createdAt, updatedAt: meta.updatedAt, recordId: meta.recordId, backing: snapshot.heads ? { heads: snapshot.heads, json: snapshot.json } : undefined, heads: snapshot.version, }), /** * Checks if the item is deleted. * Only applies to this item, not its parents. */ isDeleted: (item: QueryItem) => { if (item.doc) { return EntityStructure.isDeleted(item.doc); } else if (item.data) { return item.data['@deleted'] === true; } else if (item.meta) { return item.meta.deleted; } else { throw new Error('Invalid query item'); } }, /** The entity's `meta.annotations`, from whichever representation the item carries. */ getAnnotations: (item: QueryItem): Readonly> | undefined => { if (item.doc) { return item.doc.meta?.annotations; } else if (item.data) { return item.data[ATTR_META]?.annotations; } else if (item.meta) { return parseIndexedAnnotations(item.meta); } else { return undefined; } }, getProperty: (item: QueryItem, property: EntityPropPath) => { if (item.doc) { return getDeep(item.doc.data, property); } else if (item.data) { return getDeep(item.data, property); } else { throw new Error('Invalid query item'); } }, /** * Reads a top-level property for the `aggregate` clause, resolving `id` to the entity id — every * object exposes `id` through the API, but documents don't store it in their data (see * `PROPERTY_ID` handling in the echo handler), so a group key falling back to `id` would otherwise * collapse every keyless member into the shared `null` group. */ getAggregateProperty: (item: QueryItem, property: string): unknown => property === PROPERTY_ID ? item.objectId : QueryItem.getProperty(item, [property]), /** * Computes the composite group key for this item from the aggregate's `group`-kind entries, keyed * by result field name. No `group` entries yields `{}` — a single group over the whole input. */ getGroupKey: (item: QueryItem, aggregates: readonly QueryAST.GroupAggregate[]): GroupKeyValue => { const key: GroupKeyValue = {}; for (const aggregate of aggregates) { switch (aggregate.kind) { case 'group': key[aggregate.name] = GroupBy.resolveKeyComponent(aggregate.properties, (property) => QueryItem.getAggregateProperty(item, property), ); break; case 'type': key[aggregate.name] = QueryItem.getTypeUri(item); break; case 'timestamp': key[aggregate.name] = GroupBy.truncateTime(item[aggregate.field], aggregate.unit); break; case 'time': key[aggregate.name] = GroupBy.truncateTime( QueryItem.getAggregateProperty(item, aggregate.property), aggregate.unit, ); break; } } return key; }, /** The stored type reference as a URI string, or `null` for an untyped object. */ getTypeUri: (item: QueryItem): string | null => { if (item.doc) { return EntityStructure.getTypeReference(item.doc)?.['/'] ?? null; } else if (item.data) { const type = item.data[ATTR_TYPE]; return typeof type === 'string' ? type : null; } else if (item.meta) { return getEntityMetaTypeURI(item.meta) ?? null; } else { throw new Error('Invalid query item'); } }, getParent: (item: QueryItem): EID.EID | undefined => { let raw: string | undefined; if (item.doc) { raw = EntityStructure.getParent(item.doc)?.['/']; } else if (item.data) { raw = item.data[ATTR_PARENT]; } else if (item.meta) { raw = item.meta.parent ?? undefined; } else { throw new Error('Invalid query item'); } return raw !== undefined ? EID.tryParse(raw) : undefined; }, getRelationSource: (item: QueryItem): EID.EID | undefined => { let raw: string | undefined; if (item.doc) { raw = EntityStructure.getRelationSource(item.doc)?.['/']; } else if (item.data) { raw = item.data[ATTR_RELATION_SOURCE]; } else if (item.meta) { raw = item.meta.source ?? undefined; } else { throw new Error('Invalid query item'); } return raw !== undefined ? EID.tryParse(raw) : undefined; }, getRelationTarget: (item: QueryItem): EID.EID | undefined => { let raw: string | undefined; if (item.doc) { raw = EntityStructure.getRelationTarget(item.doc)?.['/']; } else if (item.data) { raw = item.data[ATTR_RELATION_TARGET]; } else if (item.meta) { raw = item.meta.target ?? undefined; } else { throw new Error('Invalid query item'); } return raw !== undefined ? EID.tryParse(raw) : undefined; }, /** * EIDs of objects this item strongly depends on: the schema object (when the type is an * ECHO object reference), relation source/target, the parent, and the tags (read from the * document only: an index row carries no meta). Mirrors * `ObjectCore.getStrongDependencies` on the client. Queue items hydrate from indexed * snapshots and don't gate on dependency loads, so they report no strong deps. */ getStrongDependencies: (item: QueryItem): EID.EID[] => { if (!item.doc && item.meta) { const { typeDXN, entityKind, source, target, parent } = item.meta; const endpoints = entityKind === 'relation' ? [source, target] : []; return [typeDXN, ...endpoints, parent].flatMap((raw) => { const uri = raw ? EID.tryParse(raw) : undefined; return uri ? [uri] : []; }); } if (!item.doc) { return []; } const res: EID.EID[] = []; const push = (ref: EncodedReference | undefined) => { if (!ref) { return; } try { const uri = EID.tryParse(EncodedReference.toURI(ref)); if (uri) { res.push(uri); } } catch { log.warn('invalid reference', { ref: ref['/'] }); } }; push(EntityStructure.getTypeReference(item.doc)); if (EntityStructure.getEntityKind(item.doc) === 'relation') { push(EntityStructure.getRelationSource(item.doc)); push(EntityStructure.getRelationTarget(item.doc)); } push(EntityStructure.getParent(item.doc)); for (const tag of EntityStructure.getTags(item.doc)) { // A legacy tag is a bare URI rather than an encoded reference. push(typeof tag === 'string' ? EncodedReference.fromURI(URI.make(tag)) : tag); } return res; }, }); /** * Recursive data structure that represents the execution trace of a query. */ export type ExecutionTrace = { name: string; details: string; objectCount: number; documentsLoaded: number; indexHits: number; beginTs: number; endTs: number; executionTime: number; indexQueryTime: number; documentLoadTime: number; children: ExecutionTrace[]; /** The compiled statement, on the `sql` path. */ sql?: string; /** `EXPLAIN QUERY PLAN` of that statement, when execution tracing is on. */ explain?: string[]; }; export const ExecutionTrace = Object.freeze({ makeEmpty: (): ExecutionTrace => ({ name: 'Empty', details: '', objectCount: 0, documentsLoaded: 0, indexHits: 0, beginTs: 0, endTs: 0, indexQueryTime: 0, documentLoadTime: 0, executionTime: 0, children: [], }), markEnd: (trace: ExecutionTrace) => { trace.endTs = performance.now(); trace.executionTime = trace.endTs - trace.beginTs; }, putOnPerformanceTimeline: (trace: ExecutionTrace) => { performance.measure(trace.name, { start: trace.beginTs, end: trace.endTs, detail: { devtools: { dataType: 'track-entry', track: 'Query Execution', trackGroup: 'ECHO', // Group related tracks together color: 'tertiary-dark', properties: [ ['objectCount', trace.objectCount], ['documentsLoaded', trace.documentsLoaded], ['index hits', trace.indexHits], ['indexQueryTime', trace.indexQueryTime], ['documentLoadTime', trace.documentLoadTime], ], tooltipText: trace.details, }, }, }); for (const child of trace.children) { ExecutionTrace.putOnPerformanceTimeline(child); } }, format: (trace: ExecutionTrace): string => { const go = (trace: ExecutionTrace, indent: number): string => { return [ `${' '.repeat(indent)} - ${trace.name}(${trace.details})`, `${' '.repeat(indent)} objects: ${trace.objectCount} docs: ${trace.documentsLoaded} index hits: ${trace.indexHits} | total: ${trace.executionTime.toFixed(0)}ms index: ${trace.indexQueryTime.toFixed(0)}ms load: ${trace.documentLoadTime.toFixed(0)}ms`, '', ...trace.children.map((child) => go(child, indent + 2)), ].join('\n'); }; return go(trace, 0); }, }); type StepExecutionResult = { workingSet: QueryItem[]; trace: ExecutionTrace; }; declare global { interface ImportMeta { env: ImportMetaEnv; } interface ImportMetaEnv { DX_TRACE_QUERY_EXECUTION: string; DX_ECHO_QUERY_EXECUTOR: string; } } const TRACE_QUERY_EXECUTION = !!import.meta.env?.DX_TRACE_QUERY_EXECUTION; const MAX_DEPTH_FOR_DELETION_TRACING = 10; const MAX_DEPTH_FOR_CHILD_OF_TRACING = 10; const MAX_DEPTH_FOR_STRONG_DEP_TRACING = 10; /** * Cached scope constraints extracted from a query plan. * Used to quickly determine whether an invalidation hint can affect this query. * * A null dimension means the query is unconstrained on that dimension (matches any value). */ type QueryScopes = { /** * False for text-search, traversal, union, set-difference, or child-of queries. * When false, matchesHint always returns true (conservative: always re-execute). */ isSimple: boolean; spaceIds: Set | null; queueIds: Set | null; typenames: Set | null; objectIds: Set | null; readsFeeds: boolean; /** * Typenames of the relations a plan ending in a typed relation traversal (`targetOf` / `sourceOf`) selects. * Such a plan also re-runs when a relation of one of these types changes, since that never touches its * anchors, or when an endpoint of a relation it returned changes. Null for every other plan. */ relationTypenames: Set | null; }; /** * Replaces each compiled {@link QueryPlan.SqlStep} with the steps it stands for: scope analysis must * see the original selects and filters, or every compiled query reads as unconstrained and re-runs on * every write. */ const flattenSqlSteps = (steps: readonly QueryPlan.Step[]): QueryPlan.Step[] => steps.flatMap((step) => (step._tag === 'SqlStep' ? flattenSqlSteps(step.steps) : [step])); const extractScopes = (plan: QueryPlan.Plan): QueryScopes => { const scopes: QueryScopes = { isSimple: true, spaceIds: null, queueIds: null, typenames: null, objectIds: null, readsFeeds: false, relationTypenames: null, }; // Set by a relation traversal until the typed filter after it names the relations it selects. let untypedRelationTraversal = false; for (const step of flattenSqlSteps(plan.steps)) { switch (step._tag) { case 'SelectStep': { // Extract spaceIds from space-scoped entries. const spaceScopes = step.scope.filter((scope): scope is QueryAST.SpaceScope => scope._tag === 'space'); if (spaceScopes.length > 0) { if (!scopes.spaceIds) { scopes.spaceIds = new Set(); } for (const spaceScope of spaceScopes) { scopes.spaceIds.add(spaceScope.spaceId as SpaceId); } } // Extract queueIds from feed-scoped entries and derive spaceIds from them. const feedScopesForExtract = step.scope.filter((scope): scope is QueryAST.FeedScope => scope._tag === 'feed'); const hasIncludeAllFeeds = spaceScopes.some((s) => s.includeAllFeeds === true); if (feedScopesForExtract.length > 0 || hasIncludeAllFeeds) { scopes.readsFeeds = true; } if (feedScopesForExtract.length > 0 && !hasIncludeAllFeeds) { let parseFailed = false; const derivedQueueIds = new Set(); const derivedSpaceIds = new Set(); for (const feedEntry of feedScopesForExtract) { const echoUri = EID.tryParse(String(feedEntry.feedUri)); if (echoUri) { const queueId = EID.getEntityId(echoUri); const spaceId = EID.getSpaceId(echoUri); if (queueId) { derivedQueueIds.add(queueId); } if (spaceId) { derivedSpaceIds.add(spaceId); } } else { parseFailed = true; } } if (!parseFailed) { if (derivedQueueIds.size > 0) { scopes.queueIds ??= new Set(); for (const id of derivedQueueIds) { scopes.queueIds.add(id); } } if (derivedSpaceIds.size > 0) { scopes.spaceIds ??= new Set(); for (const id of derivedSpaceIds) { // Derive spaceId from the queue DXN so space-scoped hints can skip this query. scopes.spaceIds.add(id); } } } // On any parse error, leave queue-derived dimensions unconstrained. } // Extract typename / objectId constraints from selector. switch (step.selector._tag) { case 'TypeSelector': { if (step.selector.inverted) { // Inverted type selectors come from Filter.not — mark as non-simple. scopes.isSimple = false; } else { if (!scopes.typenames) { scopes.typenames = new Set(); } for (const typename of step.selector.typename) { scopes.typenames.add(canonicalTypename(typename as string)); } } break; } case 'IdSelector': { if (!scopes.objectIds) { scopes.objectIds = new Set(); } for (const id of step.selector.objectIds) { scopes.objectIds.add(id); } break; } case 'TextSelector': { scopes.isSimple = false; break; } default: // WildcardSelector, TimestampSelector — no type/id constraint. break; } break; } case 'FilterStep': { if (untypedRelationTraversal) { if (step.filter.type === 'object' && typeof step.filter.typename === 'string') { scopes.relationTypenames ??= new Set(); scopes.relationTypenames.add(canonicalTypename(step.filter.typename)); untypedRelationTraversal = false; } else { scopes.isSimple = false; } } // child-of filters require transitive parent traversal which can't be hinted. if (step.filter.type === 'child-of') { scopes.isSimple = false; } // A nested in-query (subquery-membership) predicate's result depends on the subquery's // own scope/typenames — which may differ entirely from this query's — so a hint scoped // to this query's dimensions could miss a change that alters the subquery's result set. // `filterContainsInQuery` (not a bare `step.filter.type` check) is required: the residual // filter here is always `type: 'object'` with the in-query nested in `props`. if (filterContainsInQuery(step.filter)) { scopes.isSimple = false; } break; } case 'TraverseStep': { // One step from the anchors to the relations on them can be bounded by the relations' type; any other // traversal reaches objects the hint cannot name. const { traversal } = step; const toRelations = traversal._tag === 'RelationTraversal' && (traversal.direction === 'source-to-relation' || traversal.direction === 'target-to-relation'); if (toRelations && scopes.relationTypenames === null && !untypedRelationTraversal) { untypedRelationTraversal = true; } else { scopes.isSimple = false; } break; } case 'UnionStep': case 'SetDifferenceStep': scopes.isSimple = false; break; default: // ClearWorkingSetStep, FilterDeletedStep, OrderStep, LimitStep are fine. break; } } if (untypedRelationTraversal) { scopes.isSimple = false; } return scopes; }; /** The spaces any select step (including those nested in UnionStep/SetDifferenceStep subplans) scopes with {@link QueryAST.SpaceScope.includeAllFeeds}. */ const extractAllFeedsSpaces = (plan: QueryPlan.Plan): Set => new Set( plan.steps.flatMap((step): SpaceId[] => { switch (step._tag) { case 'SelectStep': return step.scope.flatMap((scope) => scope._tag === 'space' && scope.includeAllFeeds === true ? [scope.spaceId as SpaceId] : [], ); case 'UnionStep': return step.plans.flatMap((subplan) => [...extractAllFeedsSpaces(subplan)]); case 'SetDifferenceStep': return [...extractAllFeedsSpaces(step.source), ...extractAllFeedsSpaces(step.exclude)]; default: return []; } }), ); const setsOverlap = (a: ReadonlySet, b: ReadonlySet): boolean => { const [smaller, larger]: [ReadonlySet, ReadonlySet] = a.size <= b.size ? [a, b] : [b, a]; for (const item of smaller) { if (larger.has(item)) { return true; } } return false; }; /** The id of the object that directly owns `item`: its parent, else the feed it was appended to. */ const childOfOwnerId = (item: QueryItem): EntityId | undefined => { const parent = QueryItem.getParent(item); if (parent) { return EID.getEntityId(parent); } return item.queueId ?? undefined; }; /** The ids of the objects the relations in `items` connect, read from whichever form each item carries. */ const relationEndpoints = (items: readonly QueryItem[]): Set => { const endpoints = new Set(); const add = (uri: string | null | undefined) => { const eid = uri ? EID.tryParse(uri) : undefined; const entityId = eid && EID.getEntityId(eid); if (entityId) { endpoints.add(entityId); } }; for (const item of items) { if (item.meta) { add(item.meta.source); add(item.meta.target); } const source = item.doc && EntityStructure.getRelationSource(item.doc); const target = item.doc && EntityStructure.getRelationTarget(item.doc); add(source && EncodedReference.toURI(source)); add(target && EncodedReference.toURI(target)); } return endpoints; }; const overlapsOrUnconstrained = (hintSet: ReadonlySet | undefined, scopeSet: Set | null): boolean => hintSet === undefined || scopeSet === null || setsOverlap(hintSet, scopeSet); /** * Serializes a possibly-absent group key for `changed` diffing. `undefined` (non-grouped * queries) serializes to a distinct sentinel so it never collides with a real (empty) group key. */ const _serializeOptionalGroupKey = (key: GroupKeyValue | undefined): string => key === undefined ? '\0' : GroupBy.serializeGroupKey(key); const _serializeCollapsed = (item: QueryItem): string => item.collapsed === undefined ? '' : JSON.stringify([item.collapsed.size, item.aggregates ?? null]); /** True once the working set has been partitioned by an AggregateStep (every item carries a group key). */ const isGrouped = (workingSet: QueryItem[]): boolean => workingSet.length > 0 && workingSet[0].groupKey !== undefined; // Non-null assertion is sound: only called from group-aware limit/skip, which run exclusively on a // working set already partitioned by AggregateStep (guarded by `isGrouped`), where every item has a key. const serializeItemGroupKey = (item: QueryItem): string => GroupBy.serializeGroupKey(item.groupKey!); /** * Executes query plans against the IndexEngine and AutomergeHost. * * The QueryExecutor is responsible for: * - Executing query plans step by step * - Managing the working set of query results * - Loading documents from the database * - Tracking execution performance metrics * - Handling different types of query operations (select, filter, traverse, etc.) */ export class QueryExecutor extends Resource { private readonly _indexEngine: IndexEngine; private readonly _runtime: RuntimeProvider.RuntimeProvider; private readonly _automergeHost: AutomergeHost; private readonly _spaceStateManager: SpaceStateManager; /** * Id of this query. */ private readonly _id: string; private readonly _query: QueryAST.Query; // TODO(dmaretskyi): Might be used in the future. private readonly _reactivity: QueryReactivity; /** The uncompiled steps until the first execution, which swaps in the compiled plan. */ private _plan: QueryPlan.Plan; /** The steps before compilation, run instead of a compiled plan when a feed in scope has no index rows. */ readonly #uncompiledPlan: QueryPlan.Plan; readonly #feedStore: FeedStore | undefined; /** Feeds the current run reads from the feed store, keyed by feed id; set at the top of every run. */ #storeFeeds = new Map(); /** Per feed in scope with a `maxAge` (keyed `/`), the time its rows expire before; set every run. */ #feedCutoffs = new Map(); /** Recompiles the plan with this run's feed cutoffs; absent when the plan was not compiled. */ readonly #compile: ((feedCutoffs: ReadonlyMap) => QueryPlan.Plan) | undefined; #scopes: QueryScopes; /** Endpoints of the relations in the last result, for a plan bounded by {@link QueryScopes.relationTypenames}. */ #relationEndpoints = new Set(); readonly #allFeedsSpaces: ReadonlySet; private _trace: ExecutionTrace = ExecutionTrace.makeEmpty(); private _lastResultSet: QueryItem[] = []; #truncated: 'paths' | 'manifest' | undefined = undefined; #changeResultSet: ChangeItem[] | undefined; readonly #planner: QueryPlanner; readonly #mode: QueryExecutorMode; readonly #holds: (documentId: DocumentId) => boolean; /** * Resolved `in-query` (subquery-membership) sets for the current `execQuery` run, keyed by * `JSON.stringify(subquery) + '\0' + property`. Two FilterSteps embedding the same subquery * (e.g. both branches of a `Query.all` union) share one resolution instead of re-running it; * the `Promise` (rather than the resolved value) is cached so concurrent lookups — `UnionStep` * branches execute via `Promise.all` — await the same in-flight resolution instead of racing. * Cleared at the top of every `execQuery()` since subquery results can change between runs. */ #inQuerySetCache = new Map; trace: ExecutionTrace }>>(); /** Subquery-resolution traces already attached to a FilterStep's trace this `execQuery` run. */ #inQueryTracesAttached = new Set(); /** * Strong dependencies loaded during the current `execQuery` run, keyed by how they resolve (see * {@link QueryExecutor._loadDependency}). Siblings share their parents, and each load is a lookup. */ #dependencyCache = new Map>(); constructor(options: QueryExecutorOptions) { super(); this._indexEngine = options.indexEngine; this._runtime = options.runtime; this._automergeHost = options.automergeHost; this._spaceStateManager = options.spaceStateManager; this._id = options.queryId; this._query = options.query; this._reactivity = options.reactivity; this.#holds = options.holds ?? (() => false); this.#mode = options.executor ?? 'memory'; this.#feedStore = options.feedStore; this.#planner = new QueryPlanner(); const plan = this.#planner.createPlan(this._query); this.#uncompiledPlan = plan; const planSubquery = (query: QueryAST.Query) => this.#planner.createPlan(query); const sql = options.sql; this.#compile = this.#mode === 'sql' && sql !== undefined && !planDeclinedByCompiler(plan, planSubquery) ? (feedCutoffs) => compilePlan(sql, plan, planSubquery, { feedCutoffs }).plan : undefined; this._plan = this.#compile?.(new Map()) ?? plan; this.#scopes = extractScopes(this._plan); this.#allFeedsSpaces = extractAllFeedsSpaces(plan); } get queryId(): string { return this._id; } get query(): QueryAST.Query { return this._query; } get plan(): QueryPlan.Plan { return this._plan; } get trace(): ExecutionTrace { return this._trace; } get compiled(): boolean { return this._plan.steps.some((step) => step._tag === 'SqlStep'); } get selectsById(): boolean { return this.#scopes.isSimple && this.#scopes.objectIds !== null && this.#scopes.relationTypenames === null; } /** Spaces the query reads; null when unconstrained or when the plan is too complex to bound. */ get spaceIds(): ReadonlySet | null { return this.#scopes.isSimple ? this.#scopes.spaceIds : null; } /** Whether the query can read feed rows; assumed for a plan too complex to bound. */ get readsFeeds(): boolean { return !this.#scopes.isSimple || this.#scopes.readsFeeds; } /** What the last {@link getResults} left out to stay within its byte budget. */ get truncated(): 'paths' | 'manifest' | undefined { return this.#truncated; } async getResults(): Promise { this.#truncated = undefined; if (this.#changeResultSet) { return changeResults(this.#changeResultSet); } const shipPaths = withinBudget(this._lastResultSet.map((item) => item.paths)); const shipManifests = withinBudget(this._lastResultSet.map((item) => item.manifest)); if (!shipPaths) { this.#truncated = 'paths'; } else if (!shipManifests) { this.#truncated = 'manifest'; } // Computed over the final (post-filter) result set so counts always match shipped records. const groupCounts = new Map(); for (const item of this._lastResultSet) { if (item.groupKey === undefined) { continue; } const serialized = GroupBy.serializeGroupKey(item.groupKey); groupCounts.set(serialized, (groupCounts.get(serialized) ?? 0) + 1); } const results = this._lastResultSet.map((item): QueryService.QueryResult => { if (item.result !== undefined) { return { ...item.result, ...(shipPaths && item.paths && !item.derivationUnknown && { paths: item.paths.map((path) => [...path]) }), ...(shipManifests && item.manifest && { manifest: [...item.manifest] }), }; } const serializedGroupKey = item.groupKey !== undefined ? GroupBy.serializeGroupKey(item.groupKey) : undefined; if (item.collapsed !== undefined && serializedGroupKey !== undefined) { return { id: serializedGroupKey, spaceId: item.spaceId, rank: item.rank, groupKey: serializedGroupKey, groupCount: item.collapsed.size, aggregates: JSON.stringify(item.aggregates ?? {}), manifest: shipManifests && item.manifest ? [...item.manifest] : undefined, }; } return { id: item.objectId, documentId: item.documentId ?? undefined, queueId: item.queueId ?? undefined, queueNamespace: item.queueNamespace ?? undefined, spaceId: item.spaceId, rank: item.rank, documentJson: item.backing?.json ?? (item.data ? JSON.stringify(item.data) : undefined), groupKey: serializedGroupKey, groupCount: serializedGroupKey !== undefined ? groupCounts.get(serializedGroupKey) : undefined, heads: item.backing ? [...item.backing.heads] : undefined, createdAt: item.backing ? (item.createdAt ?? undefined) : undefined, updatedAt: item.backing ? (item.updatedAt ?? undefined) : undefined, version: QueryItem.getVersion(item), paths: shipPaths && item.paths && !item.derivationUnknown ? item.paths.map((path) => [...path]) : undefined, }; }); return this.#withBacking(results, this._lastResultSet); } /** * Backs each document row the client does not hold with its JSON, heads and stored changes. A row * that cannot be backed ships bare, and is tried again on the next emission while the client lacks it. */ async #withBacking( results: QueryService.QueryResult[], items: readonly QueryItem[], ): Promise { const unheld = results.flatMap((result, index) => result.heads !== undefined && result.documentId !== undefined && !this.#holds(result.documentId as DocumentId) ? [index] : [], ); const sources = await this.#readBackingSources(results, items, unheld); const backings = await this.#readStoredChanges(results, sources); return results.map((result, index) => { if (result.heads === undefined) { return result; } const backing = backings.get(index); return backing ? { ...result, documentJson: backing.json, heads: backing.heads, bytes: backing.bytes } : withoutBacking(result); }); } /** * The JSON each row is backed with and the heads it was read at: the row's own, or for a compiled row * the index's, both from one read so a pass between the plan and this read cannot pair them wrongly. */ async #readBackingSources( results: readonly QueryService.QueryResult[], items: readonly QueryItem[], indices: readonly number[], ): Promise> { const fromIndex = indices.filter( (index) => results[index].documentJson === undefined && items[index]?.recordId !== undefined, ); const indexed = fromIndex.length > 0 ? await this._runInRuntime( this._indexEngine.queryBackings(fromIndex.map((index) => items[index].recordId!)), ).catch((err) => { log.warn('index JSON could not be read for rows', { err }); return []; }) : []; const byRecord = new Map(indexed.map((row) => [row.recordId, row])); const sources = new Map(); for (const index of indices) { const row = byRecord.get(items[index]?.recordId ?? -1); const json = results[index].documentJson ?? row?.json; if (json !== undefined) { sources.set(index, { json, heads: row?.heads ?? results[index].heads! }); } } return sources; } /** Stored changes for each row with a source, {@link STORED_CHANGES_CONCURRENCY} reads at a time. */ async #readStoredChanges( results: readonly QueryService.QueryResult[], sources: ReadonlyMap, ): Promise> { const backings = new Map(); for (const chunk of chunkArray([...sources], STORED_CHANGES_CONCURRENCY)) { await Promise.all( chunk.map(async ([index, source]) => { const documentId = results[index].documentId as DocumentId; const bytes = await this._automergeHost .readStoredChanges(documentId, { limit: BACKED_OBJECT_LIMIT }) .catch((err) => { log.warn('stored changes could not be read for a row', { documentId, err }); return undefined; }); if (bytes !== undefined) { backings.set(index, { ...source, bytes }); } }), ); } return backings; } /** * Returns true if the given invalidation hint could affect this query's result set. * When false, the query can safely be skipped for this invalidation cycle. * * Conservative: returns true for complex queries (traversals, text-search, unions) and * for any dimension where either the hint or the query is unconstrained. */ matchesHint(hint: InvalidationHint): boolean { if (!this.#scopes.isSimple) { return true; } if ( !overlapsOrUnconstrained(hint.spaceIds, this.#scopes.spaceIds) || !overlapsOrUnconstrained(hint.queueIds, this.#scopes.queueIds) ) { return false; } if ( overlapsOrUnconstrained(hint.typenames, this.#scopes.typenames) && overlapsOrUnconstrained(hint.objectIds, this.#scopes.objectIds) ) { return true; } const { relationTypenames } = this.#scopes; return ( relationTypenames !== null && (overlapsOrUnconstrained(hint.typenames, relationTypenames) || (hint.objectIds !== undefined && setsOverlap(hint.objectIds, this.#relationEndpoints))) ); } async execQuery(): Promise { invariant(this._lifecycleState === LifecycleState.OPEN); log('exec query', { queryId: this._id, query: Query.pretty(Query.fromAst(this._query)), mode: this.#mode, }); // Subquery results can change between reactive runs, so resolved `in-query` sets must not // survive across `execQuery` calls. this.#inQuerySetCache = new Map(); this.#inQueryTracesAttached = new Set(); const [select] = this._plan.steps; if (select?._tag === 'SelectStep' && select.selector._tag === 'ChangesSelector') { const previous = this.#changeResultSet; const next = await executeChangesPlan(this._ctx, this._plan, { indexEngine: this._indexEngine, automergeHost: this._automergeHost, spaceStateManager: this._spaceStateManager, runInRuntime: (effect) => this._runInRuntime(effect), }); this.#changeResultSet = next; return { changed: serializeChangeResults(previous ?? []) !== serializeChangeResults(next) }; } const previous = this._lastResultSet; const { workingSet, trace } = await this._resolveWorkingSet(); this._lastResultSet = workingSet; if (this.#scopes.relationTypenames !== null) { this.#relationEndpoints = relationEndpoints(workingSet); } trace.name = 'Root'; trace.details = JSON.stringify({ id: this._id, query: Query.pretty(Query.fromAst(this._query)) }); // A `SqlStep` ran the statement one level down; surface it on the root the trace prints. trace.sql = trace.children.find((child) => child.sql !== undefined)?.sql; trace.explain = trace.children.find((child) => child.explain !== undefined)?.explain; this._trace = trace; const changed = previous.length !== workingSet.length || previous.some((item, index) => !_sameResult(workingSet[index], item)); // Disabled because concurrent queries don't print hierarchies correctly. // ExecutionTrace.putOnPerformanceTimeline(trace); if (TRACE_QUERY_EXECUTION) { // eslint-disable-next-line no-console console.log(ExecutionTrace.format(trace), trace.sql, trace.explain); } return { changed }; } /** Runs the plan, then drops items whose strong dependencies cannot be resolved from local state. */ private async _resolveWorkingSet(): Promise<{ workingSet: QueryItem[]; trace: ExecutionTrace }> { try { const now = Date.now(); ({ storeFeeds: this.#storeFeeds, feedCutoffs: this.#feedCutoffs } = await this.#readScopedFeeds(now)); // A compiled statement reads only the index, which holds nothing of a disabled feed; the cutoffs are // bound into the statement, so a run with any recompiles it. const plan = this.#storeFeeds.size > 0 ? this.#uncompiledPlan : this.#feedCutoffs.size > 0 ? (this.#compile?.(this.#feedCutoffs) ?? this._plan) : this._plan; const { workingSet: planned, trace } = await this._execPlan(plan, []); const workingSet = await this.#withoutExpired(planned, now); // A compiled plan resolved these in SQL. Keyed on the plan rather than the mode, because a plan // the compiler declined runs step by step even under `sql` and needs the filter. if (plan.steps.some((step) => step._tag === 'SqlStep')) { return { workingSet, trace }; } // Unresolvable items never reach the client, where hydration would fail or stall on them. return { workingSet: await this._filterUnresolvableStrongDeps(workingSet), trace }; } finally { // An idle reactive query keeps its executor, which would otherwise hold these items until its next run. this.#dependencyCache.clear(); } } /** Each space's stored feed options, or none when the store cannot say; a read failure answers from the index. */ async #listFeedOptions(spaceId: SpaceId): Promise> { const feedStore = this.#feedStore; if (!feedStore) { return new Map(); } return this._runInRuntime(feedStore.listFeedOptions(spaceId)).catch((err) => { log.warn('feed options could not be read; answering feeds from the index', { spaceId, err }); return new Map(); }); } /** * Of the feeds the plan scopes to — by name, or as every feed of a space — those read from the store, * keyed by feed id: indexing disabled, or named with a branch other than main while the index holds * only the main branch. Also the retention cutoff of the named ones with a `maxAge`, keyed * `/`. */ async #readScopedFeeds( now: number, ): Promise<{ storeFeeds: Map; feedCutoffs: Map }> { const storeFeeds = new Map(); const feedCutoffs = new Map(); const feedStore = this.#feedStore; const feedRefs = extractQueueRefs(extractFeedScopes(this.#uncompiledPlan)) ?? []; if (!feedStore || (feedRefs.length === 0 && this.#allFeedsSpaces.size === 0)) { return { storeFeeds, feedCutoffs }; } const spaceIds = new Set([ ...this.#allFeedsSpaces, ...feedRefs.flatMap((ref) => (ref.spaceId !== undefined && SpaceId.isValid(ref.spaceId) ? [ref.spaceId] : [])), ]); const addStoreFeed = async (spaceId: SpaceId, feedId: string) => { const feedNamespace = await this._runInRuntime(feedStore.getFeedNamespace({ spaceId, feedId })); if (feedNamespace !== undefined) { storeFeeds.set(feedId, { spaceId, feedNamespace }); } }; // A walk reads the branch tree of the store, which the index does not hold. const walkRefs = extractQueueRefs(extractFeedScopes(this.#uncompiledPlan).filter((scope) => scope.walk)) ?? []; for (const spaceId of spaceIds) { for (const ref of walkRefs) { if (ref.spaceId === spaceId && !storeFeeds.has(ref.queueId)) { await addStoreFeed(spaceId, ref.queueId); } } const options = await this.#listFeedOptions(spaceId); if (this.#allFeedsSpaces.has(spaceId)) { for (const [feedId, feedOptions] of options) { if (feedOptions.indexing?.enabled === false) { await addStoreFeed(spaceId, feedId); } } } for (const ref of feedRefs) { const maxAge = ref.spaceId === spaceId ? options.get(ref.queueId)?.retention?.maxAge : undefined; if (maxAge !== undefined) { feedCutoffs.set(`${spaceId}/${ref.queueId}`, now - maxAge); } // A feed indexing only its main branch has no rows for any other, so reading one is a store read. const feedOptions = options.get(ref.queueId); if ( ref.spaceId === spaceId && !storeFeeds.has(ref.queueId) && (feedOptions?.indexing?.enabled === false || (feedOptions?.indexing?.mode !== 'all' && (ref.branches === undefined || ref.branches.some((branch) => branch !== null)))) ) { await addStoreFeed(spaceId, ref.queueId); } } } return { storeFeeds, feedCutoffs }; } /** * Drops feed items whose block is past its feed's `maxAge`: the store hides them at once but deletes * them, and so their index rows, only at its next trim. A feed scope's read already excludes them; * this catches the rows no read could bound — reached by a traversal, a space's all-feeds scope, or * an unqualified feed URI. */ async #withoutExpired(workingSet: QueryItem[], now: number): Promise { const spaceIds = new Set(workingSet.flatMap((item) => (item.queueId !== null ? [item.spaceId] : []))); if (!this.#feedStore || spaceIds.size === 0) { return workingSet; } const maxAges = new Map(); for (const spaceId of spaceIds) { for (const [feedId, options] of await this.#listFeedOptions(spaceId)) { if (options.retention?.maxAge !== undefined) { maxAges.set(`${spaceId}/${feedId}`, options.retention.maxAge); } } } if (maxAges.size === 0) { return workingSet; } return workingSet.filter((item) => { // A collapsed group stands for members the row does not list, so it cannot drop one of them. const maxAge = item.queueId !== null && item.groupKey === undefined ? maxAges.get(`${item.spaceId}/${item.queueId}`) : undefined; return maxAge === undefined || item.updatedAt === null || item.updatedAt >= now - maxAge; }); } /** * The current items of the store-read feeds `refs` names, one per object id at its latest block. * A partial block (a removal tombstone) keeps the body of the block before it, as the index does. */ async #readStoreFeedItems(refs: readonly QueueRef[]): Promise { const feedStore = this.#feedStore; if (!feedStore) { return []; } const items: QueryItem[] = []; for (const ref of refs) { const feed = this.#storeFeeds.get(ref.queueId); if (!feed || (ref.spaceId !== undefined && ref.spaceId !== feed.spaceId) || !EntityId.isValid(ref.queueId)) { continue; } const { blocks } = await this._runInRuntime( feedStore.query({ spaceId: feed.spaceId, feedNamespace: feed.feedNamespace, query: { feedIds: [ref.queueId] }, }), ); const byId = new Map(); for (const block of [...blocks].sort((left, right) => (left.insertionId ?? 0) - (right.insertionId ?? 0))) { const data = EchoFeedCodec.decodeBlock(block); const previous = typeof data.id === 'string' ? byId.get(data.id)?.data : undefined; const merged = data[ATTR_TYPE] === undefined && previous ? { ...previous, ...data } : data; if (!isObjectJSON(merged)) { continue; } const objectId = merged.id; byId.set(objectId, { objectId, spaceId: feed.spaceId, queueId: ref.queueId, queueNamespace: feed.feedNamespace, documentId: null, doc: null, data: merged, rank: 1, createdAt: block.timestamp, updatedAt: block.timestamp, position: block.position, }); } items.push(...[...byId.values()].filter((item) => item.data !== null && isOnBranches(item.data, ref.branches))); } return items; } /** * The items of a walk of one feed after the cursor of `range`, in walk order, each once at the place of its * first block on the walk and with the content of its latest one [D-69]. The direction is the natural order * the query asks for. */ /** * A walk of every branch: the store's blocks after the cursor (before it, walking backward), in local order, so a * page costs the blocks it reads rather than the feed. Each item comes once, at the first of its blocks the page * holds, with the content of its latest; an item changed after the cursor comes again, since whether it started * before the cursor is only known by reading the blocks there [D-75]. A backward walk with a limit reads pages from * the end until the selector keeps enough. */ async #walkAll( scope: QueryAST.FeedScope, range: QueryPlan.SelectStep['feedCursorRange'], select: (items: QueryItem[]) => Promise, limit: number | undefined, ): Promise<{ selected: QueryItem[]; read: number }> { const feedStore = this.#feedStore; const ref = extractQueueRefs([scope])?.[0]; const feed = ref === undefined ? undefined : this.#storeFeeds.get(ref.queueId); if (!feedStore || ref === undefined || feed === undefined) { return { selected: [], read: 0 }; } if (range?.end !== undefined || range?.positions === 'edge') { throw new QueryError({ message: 'A walk starts after a local cursor and has no end cursor.', context: { query: null }, }); } const direction = walkDirection(this.#uncompiledPlan); const after = range?.begin ? parseLocalCursor(range.begin)?.block : undefined; const read = (pageLimit: number | undefined) => this._runInRuntime( feedStore.walk({ spaceId: feed.spaceId, feedNamespace: feed.feedNamespace, feedId: ref.queueId, branch: 'all', direction, ...(after !== undefined ? { after } : {}), ...(pageLimit !== undefined ? { limit: pageLimit } : {}), }), ); const toItems = (blocks: readonly FeedProtocol.Block[]): QueryItem[] => { const items = new Map(); for (const block of direction === 'desc' ? [...blocks].reverse() : blocks) { const data = EchoFeedCodec.decodeBlock(block); const id = typeof data.id === 'string' ? data.id : undefined; if (id === undefined) { continue; } const previous = items.get(id); // A partial block (a removal tombstone) keeps the body of the block before it, as the index does. const merged = data[ATTR_TYPE] === undefined && previous?.data ? { ...previous.data, ...data } : data; items.set(id, { first: previous?.first ?? block, last: block, data: isObjectJSON(merged) ? merged : null }); } // In the walk's direction: the step cuts its limit before any ordering, so the first items must be the ones // the walk reaches first. const ordered = [...items.entries()].sort( ([, left], [, right]) => (direction === 'desc' ? -1 : 1) * ((left.first.insertionId ?? 0) - (right.first.insertionId ?? 0)), ); return ordered.flatMap(([objectId, { first, last, data }]): QueryItem[] => data === null || !EntityId.isValid(objectId) ? [] : [ { objectId: EntityId.make(objectId), spaceId: feed.spaceId, queueId: ref.queueId, queueNamespace: feed.feedNamespace, documentId: null, doc: null, data, rank: 1, createdAt: first.timestamp, updatedAt: last.timestamp, position: last.position, walkIndex: first.insertionId ?? 0, }, ], ); }; if (direction === 'asc' || limit === undefined) { const blocks = await read(undefined); return { selected: await select(toItems(blocks)), read: blocks.length }; } // Pages grow fourfold, so a selector that keeps few of the blocks still ends in a handful of reads. for (let pageLimit = Math.max(limit * 4, 8); ; pageLimit *= 4) { const blocks = await read(pageLimit); const selected = await select(toItems(blocks)); if (selected.length >= limit || blocks.length < pageLimit) { return { selected, read: blocks.length }; } } } async #walkFeed(scope: QueryAST.FeedScope, range: QueryPlan.SelectStep['feedCursorRange']): Promise { const feedStore = this.#feedStore; const ref = extractQueueRefs([scope])?.[0]; const feed = ref === undefined ? undefined : this.#storeFeeds.get(ref.queueId); if (!feedStore || ref === undefined || feed === undefined) { return []; } if (range?.end !== undefined || range?.positions === 'edge') { throw new QueryError({ message: 'A walk starts after a local cursor and has no end cursor.', context: { query: null }, }); } const direction = walkDirection(this.#uncompiledPlan); const cursor = range?.begin ? parseLocalCursor(range.begin) : undefined; // The whole path, read forward: an item's place is its first block, which may lie before the cursor. const branch = scope.walk?.branch !== undefined ? scope.walk.branch : direction === 'desc' ? cursor?.branch : null; const blocks = await this._runInRuntime( feedStore.walk({ spaceId: feed.spaceId, feedNamespace: feed.feedNamespace, feedId: ref.queueId, ...(branch !== undefined ? { branch } : {}), direction: 'asc', forks: scope.walk?.forks === true, }), ); // Each item once: placed at its first block, with the content of its latest one. const items = new Map(); const blockItems: (string | undefined)[] = []; blocks.forEach((block, index) => { const data = EchoFeedCodec.decodeBlock(block); const id = typeof data.id === 'string' ? data.id : undefined; blockItems.push(id); if (id === undefined) { return; } const previous = items.get(id); // A partial block (a removal tombstone) keeps the body of the block before it, as the index does. const merged = data[ATTR_TYPE] === undefined && previous?.data ? { ...previous.data, ...data } : data; items.set(id, { first: previous?.first ?? index, last: index, data: isObjectJSON(merged) ? merged : null }); }); // A cursor names the latest block of an item, so the walk resumes after the place of that item. let after: number | undefined; if (cursor !== undefined) { const cursorIndex = blocks.findIndex( (block) => EchoFeedCodec.blockId(block.actorId, block.sequence) === cursor.block, ); const cursorItem = cursorIndex === -1 ? undefined : blockItems[cursorIndex]; after = cursorItem === undefined ? undefined : items.get(cursorItem)?.first; if (after === undefined) { return []; } } const sign = direction === 'desc' ? -1 : 1; return [...items.entries()] .filter(([, { first }]) => after === undefined || sign * (first - after) > 0) .sort(([, left], [, right]) => sign * (left.first - right.first)) .flatMap(([objectId, { first, last, data }]): QueryItem[] => { if (data === null || !EntityId.isValid(objectId)) { return []; } const block = blocks[last]; return [ { objectId: EntityId.make(objectId), spaceId: feed.spaceId, queueId: ref.queueId, queueNamespace: feed.feedNamespace, documentId: null, doc: null, data, rank: 1, createdAt: blocks[first].timestamp, updatedAt: block.timestamp, position: block.position, walkIndex: first, }, ]; }); } private async _execPlan(plan: QueryPlan.Plan, workingSet: QueryItem[]): Promise { const trace = ExecutionTrace.makeEmpty(); for (const step of plan.steps) { if (this._ctx.disposed) { throw new ContextDisposedError(); } const result = await this._execStep(step, workingSet); workingSet = result.workingSet; trace.children.push(result.trace); } trace.objectCount = workingSet.length; ExecutionTrace.markEnd(trace); return { workingSet, trace }; } private async _execStep(step: QueryPlan.Step, workingSet: QueryItem[]): Promise { if (this._ctx.disposed) { return { workingSet, trace: ExecutionTrace.makeEmpty() }; } let newWorkingSet: QueryItem[], trace: ExecutionTrace; const begin = performance.now(); switch (step._tag) { case 'ClearWorkingSetStep': newWorkingSet = []; trace = ExecutionTrace.makeEmpty(); break; case 'SelectStep': ({ workingSet: newWorkingSet, trace } = await this._execSelectStep(step, workingSet)); break; case 'FilterStep': ({ workingSet: newWorkingSet, trace } = await this._execFilterStep(step, workingSet)); break; case 'FilterDeletedStep': ({ workingSet: newWorkingSet, trace } = await this._execFilterDeletedStep(step, workingSet)); break; case 'UnionStep': ({ workingSet: newWorkingSet, trace } = await this._execUnionStep(step, workingSet)); break; case 'SetDifferenceStep': ({ workingSet: newWorkingSet, trace } = await this._execSetDifferenceStep(step, workingSet)); break; case 'TraverseStep': ({ workingSet: newWorkingSet, trace } = await this._execTraverseStep(step, workingSet)); break; case 'OrderStep': ({ workingSet: newWorkingSet, trace } = await this._execOrderStep(step, workingSet)); break; case 'LimitStep': ({ workingSet: newWorkingSet, trace } = await this._execLimitStep(step, workingSet)); break; case 'SkipStep': ({ workingSet: newWorkingSet, trace } = await this._execSkipStep(step, workingSet)); break; case 'AggregateStep': ({ workingSet: newWorkingSet, trace } = await this._execAggregateStep(step, workingSet)); break; case 'SqlStep': ({ workingSet: newWorkingSet, trace } = await this._execSqlStep(step)); break; default: throw new Error(`Unknown step type: ${(step as any)._tag}`); } trace.beginTs = begin; ExecutionTrace.markEnd(trace); return { workingSet: newWorkingSet, trace }; } private async _execSelectStep(step: QueryPlan.SelectStep, workingSet: QueryItem[]): Promise { workingSet = [...workingSet]; const execSpaceScopes = step.scope.filter((s): s is QueryAST.SpaceScope => s._tag === 'space'); const spaces = execSpaceScopes.map((s) => s.spaceId as SpaceId); const scopedQueues = step.scope.filter((s): s is QueryAST.FeedScope => s._tag === 'feed'); const allQueuesFromSpaces = execSpaceScopes.some((s) => s.includeAllFeeds === true); const trace: ExecutionTrace = { ...ExecutionTrace.makeEmpty(), name: 'Select', details: JSON.stringify(step.selector), beginTs: performance.now(), }; const walkScopes = scopedQueues.filter((scope) => scope.walk !== undefined); if (walkScopes.length > 0) { if (scopedQueues.length > 1 || execSpaceScopes.length > 0) { throw new QueryError({ message: 'A walk reads one feed scope alone.', context: { query: null } }); } // The walk itself is the window, so the selector applies without the cursor range the walk consumed. const select = (items: QueryItem[]) => selectStoreItems({ ...step, feedCursorRange: undefined, feedScan: undefined }, items); // A page of a walk counts what the plan keeps of it; the filter steps run again on the result, unchanged. const narrowing = this.#uncompiledPlan.steps.filter( (planStep): planStep is QueryPlan.FilterStep | QueryPlan.FilterDeletedStep => planStep._tag === 'FilterStep' || planStep._tag === 'FilterDeletedStep', ); const keep = async (items: QueryItem[]) => { let kept = select(items); for (const planStep of narrowing) { kept = ( planStep._tag === 'FilterStep' ? await this._execFilterStep(planStep, kept) : await this._execFilterDeletedStep(planStep, kept) ).workingSet; } return kept; }; const { selected, read } = walkScopes[0].walk?.branch === 'all' ? await this.#walkAll( walkScopes[0], step.feedCursorRange, keep, step.limit ?? walkLimit(this.#uncompiledPlan), ) : await this.#walkFeed(walkScopes[0], step.feedCursorRange).then((walked) => ({ selected: select(walked), read: walked.length, })); workingSet.push(...(step.limit === undefined ? selected : selected.slice(0, step.limit))); trace.documentsLoaded += read; trace.objectCount = workingSet.length; return { workingSet, trace }; } // A feed with indexing disabled has no index rows, so its items come from the store, selected here. const isStoreFeed = (scope: QueryAST.FeedScope) => { const ref = extractQueueRefs([scope])?.[0]; return ref !== undefined && this.#storeFeeds.has(ref.queueId); }; const allFeedsSpaces = new Set(execSpaceScopes.flatMap((s) => (s.includeAllFeeds === true ? [s.spaceId] : []))); const storeRefs = new Map([ ...[...this.#storeFeeds] .filter(([, feed]) => allFeedsSpaces.has(feed.spaceId)) // A read of every feed is a default read, so it covers only the main branch. .map(([queueId, feed]): [string, QueueRef] => [queueId, { queueId, spaceId: feed.spaceId, branches: [null] }]), ]); // Several scopes of one feed read it once, over the union of their branches. for (const ref of extractQueueRefs(scopedQueues.filter(isStoreFeed)) ?? []) { const previous = storeRefs.get(ref.queueId); storeRefs.set(ref.queueId, previous === undefined ? ref : { ...ref, branches: unionBranches(previous, ref) }); } const queues = scopedQueues.filter((scope) => !isStoreFeed(scope)); if (storeRefs.size > 0) { const storeItems = selectStoreItems(step, await this.#readStoreFeedItems([...storeRefs.values()])); workingSet.push(...storeItems); trace.documentsLoaded += storeItems.length; if (queues.length === 0 && spaces.length === 0) { if (step.limit !== undefined && workingSet.length > step.limit) { workingSet = workingSet.slice(0, step.limit); } trace.objectCount = workingSet.length; return { workingSet, trace }; } } switch (step.selector._tag) { case 'WildcardSelector': { const beginIndexQuery = performance.now(); const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs); const metas = await this._queryAllFromSqlIndex( spaces, allQueuesFromSpaces, queueRefs, extractQueueWindow(step), ); trace.indexHits = metas.length; trace.indexQueryTime += performance.now() - beginIndexQuery; if (this._ctx.disposed) { return { workingSet, trace }; } const documentLoadStart = performance.now(); const results = step.bare ? metas.map(QueryItem.fromIndexRow) : await this._loadDocumentsAfterSqlQuery(metas); trace.documentsLoaded += step.bare ? 0 : results.length; trace.documentLoadTime += performance.now() - documentLoadStart; workingSet.push(...results.filter(isNonNullable)); trace.objectCount = workingSet.length; break; } case 'IdSelector': { const beginLoad = performance.now(); if (allQueuesFromSpaces && spaces.length > 0) { const objectIds = step.selector.objectIds.filter((id) => EntityId.isValid(id)); if (objectIds.length > 0) { const metas = await this._runInRuntime(this._indexEngine.queryObjectIds({ spaceIds: spaces, objectIds })); const results = await this._loadDocumentsAfterSqlQuery(metas); trace.documentLoadTime += performance.now() - beginLoad; workingSet.push(...results.filter(isNonNullable)); trace.objectCount = workingSet.length; break; } } const items = await Promise.all( step.selector.objectIds.map(async (id) => { if (!EntityId.isValid(id)) { return null; } if (queues.length > 0) { const ref = extractQueueRefs([queues[0]])?.[0]; if (ref?.spaceId !== undefined && SpaceId.isValid(ref.spaceId) && EntityId.isValid(ref.queueId)) { const item = await this._loadQueueItemById(ref.spaceId, ref.queueId, id); return item?.data && isOnBranches(item.data, ref.branches) ? item : null; } return null; } else if (spaces.length > 0) { return this._loadFromDXN(EID.make({ entityId: id }), { sourceSpaceId: spaces[0] }); } else { return null; // Unknown scope. } }), ); trace.documentLoadTime += performance.now() - beginLoad; workingSet.push(...items.filter(isNonNullable)); trace.objectCount = workingSet.length; break; } case 'TypeSelector': { const beginIndexQuery = performance.now(); const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs); const metas = await this._queryTypesFromSqlIndex( spaces, step.selector.typename, step.selector.inverted, allQueuesFromSpaces, queueRefs, extractQueueWindow(step), ); trace.indexHits = metas.length; trace.indexQueryTime += performance.now() - beginIndexQuery; if (this._ctx.disposed) { return { workingSet, trace }; } const documentLoadStart = performance.now(); const results = step.bare ? metas.map(QueryItem.fromIndexRow) : await this._loadDocumentsAfterSqlQuery(metas); trace.documentsLoaded += step.bare ? 0 : results.length; trace.documentLoadTime += performance.now() - documentLoadStart; workingSet.push(...results.filter(isNonNullable)); trace.objectCount = workingSet.length; break; } case 'TimestampSelector': { const beginIndexQuery = performance.now(); const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs); const metas = await this._runInRuntime( this._indexEngine.queryByTimeRange({ spaceIds: spaces, updatedAfter: step.selector.updatedAfter, updatedBefore: step.selector.updatedBefore, createdAfter: step.selector.createdAfter, createdBefore: step.selector.createdBefore, includeAllQueues: allQueuesFromSpaces, queues: queueRefs, }), ); trace.indexHits = metas.length; trace.indexQueryTime += performance.now() - beginIndexQuery; if (this._ctx.disposed) { return { workingSet, trace }; } const documentLoadStart = performance.now(); const results = step.bare ? metas.map(QueryItem.fromIndexRow) : await this._loadDocumentsAfterSqlQuery(metas); trace.documentsLoaded += step.bare ? 0 : results.length; trace.documentLoadTime += performance.now() - documentLoadStart; workingSet.push(...results.filter(isNonNullable)); trace.objectCount = workingSet.length; break; } case 'ChangesSelector': throw new Error('A changes plan runs through executeChangesPlan.'); case 'IncomingReferenceSelector': { const beginIndexQuery = performance.now(); const metas = await this._queryIncomingReferencesByTarget([step.selector.targetDXN], step.selector.property); trace.indexHits = metas.length; trace.indexQueryTime += performance.now() - beginIndexQuery; if (this._ctx.disposed) { return { workingSet, trace }; } const documentLoadStart = performance.now(); // The index is per-space, but the scope may name a subset of the queried spaces. const scoped = spaces.length > 0 ? metas.filter((meta) => spaces.includes(meta.spaceId)) : metas; const results = await this._loadDocumentsAfterSqlQuery(scoped); trace.documentsLoaded += results.length; trace.documentLoadTime += performance.now() - documentLoadStart; workingSet.push(...results.filter(isNonNullable)); trace.objectCount = workingSet.length; break; } case 'TextSelector': { // TODO(dmaretskyi): nice to have matched text snippets/highlighting. if (step.selector.searchKind === 'vector') { // Vector search is not currently supported. log.warn('Vector search is not supported'); break; } // Full-text search using SQLite FTS5, optionally scoped by type. const beginIndexQuery = performance.now(); invariant(spaces.length <= 1, 'Multiple spaces are not supported for full-text search'); const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs); const textResults = await this._runInRuntime( this._indexEngine.queryText({ query: step.selector.text, spaceId: spaces, includeAllQueues: allQueuesFromSpaces, queues: queueRefs, typeDxns: step.selector.typename, }), ); trace.indexHits = textResults.length; trace.indexQueryTime += performance.now() - beginIndexQuery; if (this._ctx.disposed) { return { workingSet, trace }; } // Load documents from the results. const documentLoadStart = performance.now(); // Separate queue items from space items. const queueResults = textResults.filter((r) => r.queueId); const spaceResults = textResults.filter((r) => !r.queueId); // Build a map from recordId to rank for all FTS results. const rankMap = new Map(textResults.map((r) => [r.recordId, r.rank])); // Load queue items from indexed snapshots. let queueItems: QueryItem[] = []; if (queueResults.length > 0) { const snapshots = await this._runInRuntime( this._indexEngine.querySnapshotsJSON(queueResults.map((r) => r.recordId)), ); const snapshotMap = new Map(snapshots.map((s) => [s.recordId, s.snapshot])); queueItems = queueResults .map((result): QueryItem | null => { const snapshot = snapshotMap.get(result.recordId); if (!snapshot || typeof snapshot !== 'object') { return null; } if (!EntityId.isValid(result.queueId)) { return null; } return { objectId: result.objectId, spaceId: result.spaceId, queueId: result.queueId, queueNamespace: result.queueNamespace || null, documentId: null, doc: null, data: snapshot as Obj.JSON, rank: rankMap.get(result.recordId) ?? 1, createdAt: result.createdAt, updatedAt: result.updatedAt, }; }) .filter(isNonNullable); } // Load space items from documents. const spaceItems = await Promise.all( spaceResults.map(async (result): Promise => { const dxn = EID.make({ entityId: result.objectId }); const item = await this._loadFromDXN(dxn, { sourceSpaceId: result.spaceId }); if (item) { // Override the default rank with the FTS rank. item.rank = rankMap.get(result.recordId) ?? 1; } return item; }), ); const items = [...queueItems, ...spaceItems.filter(isNonNullable)]; trace.documentsLoaded += items.length; trace.documentLoadTime += performance.now() - documentLoadStart; workingSet.push( ...items.filter((item) => { if (spaces.includes(item.spaceId)) { return true; } if (item.queueId) { return queues.some((scope) => { const queueId = extractQueueRefs([scope])?.[0]?.queueId; const spaceId = extractSpaceIdFromQueue(String(scope.feedUri)); return queueId === item.queueId && spaceId === item.spaceId; }); } return false; }), ); trace.objectCount = workingSet.length; break; } default: throw new Error(`Unknown selector type: ${(step.selector as any)._tag}`); } // Apply limit if specified on the select step. if (step.limit !== undefined && workingSet.length > step.limit) { workingSet = workingSet.slice(0, step.limit); trace.objectCount = workingSet.length; } return { workingSet, trace }; } private async _execFilterStep(step: QueryPlan.FilterStep, workingSet: QueryItem[]): Promise { if (step.filter.type === 'child-of') { return this._execChildOfFilterStep(step.filter, workingSet); } const timestampParams = extractTimestampParams(step.filter); if (timestampParams !== null) { return this._execTimestampFilterStep(step, workingSet, timestampParams); } if (filterContainsTimestamp(step.filter)) { throw new QueryError({ message: 'Timestamp filter in unsupported composition (not, or). Use Filter.updated/Filter.created with explicit range instead.', context: {}, }); } // A nested `in-query` (subquery-membership) predicate is not a matcher-level concept — resolve // each one to a concrete literal `in` before falling through to the normal in-memory matchers, // which only know how to test a value against a static set. const subqueryTraces: ExecutionTrace[] = []; const filter = filterContainsInQuery(step.filter) ? await this._resolveInQueryFilter(step.filter, subqueryTraces) : step.filter; const result = workingSet.filter((item) => { if (item.doc) { return filterMatchDoc(filter, { id: item.objectId, spaceId: item.spaceId, doc: item.doc, }); } else if (item.data) { return filterMatchObjectJSON(filter, item.data); } else if (item.meta) { return filterMatchEntityMeta(filter, item.meta); } else { return false; } }); return { workingSet: result, trace: { ...ExecutionTrace.makeEmpty(), name: 'Filter', details: JSON.stringify(step.filter), objectCount: result.length, children: subqueryTraces, }, }; } /** * Recursively rewrites every `in-query` node in `filter` to a literal `in` node, resolving each * subquery's projected value set at most once per `execQuery` run (see `#inQuerySetCache`). * `subqueryTraces` collects the resolution's `ExecutionTrace` the first time each subquery is * resolved this run, so its cost is visible under the FilterStep that triggered it. */ private async _resolveInQueryFilter( filter: QueryAST.Filter, subqueryTraces: ExecutionTrace[], ): Promise { switch (filter.type) { case 'in-query': { const { values, trace } = await this._resolveInQuerySet(filter); const cacheKey = _inQueryCacheKey(filter); if (!this.#inQueryTracesAttached.has(cacheKey)) { this.#inQueryTracesAttached.add(cacheKey); subqueryTraces.push(trace); } return { type: 'in', values: [...values] }; } case 'object': { if (Object.keys(filter.props).length === 0) { return filter; } const props: Record = {}; for (const [key, propFilter] of Object.entries(filter.props)) { props[key] = await this._resolveInQueryFilter(propFilter, subqueryTraces); } return { ...filter, props }; } case 'not': return { ...filter, filter: await this._resolveInQueryFilter(filter.filter, subqueryTraces) }; case 'and': return { ...filter, filters: await Promise.all(filter.filters.map((f) => this._resolveInQueryFilter(f, subqueryTraces))), }; case 'or': return { ...filter, filters: await Promise.all(filter.filters.map((f) => this._resolveInQueryFilter(f, subqueryTraces))), }; default: return filter; } } /** * Resolves a single `in-query` node's projected value set, sharing one resolution across every * occurrence of the same subquery+property within this `execQuery` run (e.g. both branches of a * `Query.all` union embedding the same subquery). The `Promise` is cached (not just the value) so * concurrent callers — `UnionStep` branches run under `Promise.all` — await the same in-flight * resolution instead of each starting their own. */ private _resolveInQuerySet( node: QueryAST.FilterInQuery, ): Promise<{ values: ReadonlySet; trace: ExecutionTrace }> { const cacheKey = _inQueryCacheKey(node); let cached = this.#inQuerySetCache.get(cacheKey); if (!cached) { cached = this._computeInQuerySet(node); this.#inQuerySetCache.set(cacheKey, cached); } return cached; } private async _computeInQuerySet( node: QueryAST.FilterInQuery, ): Promise<{ values: ReadonlySet; trace: ExecutionTrace }> { // TODO(dmaretskyi): Push membership into the SQL index once custom property indexes are // supported, instead of a full in-memory scan of the subquery's candidates. const subPlan = new QueryPlanner().createPlan(node.subquery); const { workingSet: subResults, trace } = await this._execPlan(subPlan, []); trace.name = 'Subquery'; trace.details = Query.pretty(Query.fromAst(node.subquery)); const values = new Set(); for (const item of subResults) { const rawValue = QueryItem.getProperty(item, [node.property]); // Omit missing/null projected values so a subquery object lacking the property never // broadens the membership set (it must not make parents that also lack the property match). if (rawValue === undefined || rawValue === null) { continue; } values.add(isEncodedReference(rawValue) ? EncodedReference.toURI(rawValue) : rawValue); } return { values, trace }; } private async _execTimestampFilterStep( step: QueryPlan.FilterStep, workingSet: QueryItem[], params: { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number }, ): Promise { const spaces = [...new Set(workingSet.map((item) => item.spaceId).filter(isNonNullable))]; const metas = await this._runInRuntime( this._indexEngine.queryByTimeRange({ spaceIds: spaces, ...params, includeAllQueues: false, queues: [], }), ); const matchingIds = new Set(metas.map((m) => m.objectId)); const result = workingSet.filter((item) => matchingIds.has(item.objectId)); return { workingSet: result, trace: { ...ExecutionTrace.makeEmpty(), name: 'Filter(timestamp)', details: JSON.stringify(params), objectCount: result.length, }, }; } private async _execFilterDeletedStep( step: QueryPlan.FilterDeletedStep, workingSet: QueryItem[], ): Promise { const expected = step.mode === 'only-deleted'; const deletedState = workingSet.map((item) => QueryItem.isDeleted(item)); await Promise.all( workingSet.map(async (item, index) => { if (deletedState[index]) { return; } deletedState[index] ||= await this._getTransitiveDeletionState(item, MAX_DEPTH_FOR_DELETION_TRACING); }), ); const result = workingSet.filter((item, index) => deletedState[index] === expected); // TODO(dmaretskyi): How do we handle items with parents and cascade deletions? -- perhaps we forbid queue items from having parents -- i.e. queue is their parent. return { workingSet: result, trace: { ...ExecutionTrace.makeEmpty(), name: 'FilterDeleted', details: step.mode, objectCount: result.length, }, }; } private async _execChildOfFilterStep( filter: QueryAST.FilterChildOf, workingSet: QueryItem[], ): Promise { const parentObjectIds = new Set(); for (const parentDxnStr of filter.parents) { const echoUri = EID.tryParse(parentDxnStr); if (echoUri) { const objectId = EID.getEntityId(echoUri); if (objectId) { parentObjectIds.add(objectId); } } } const maxDepth = filter.transitive ? MAX_DEPTH_FOR_CHILD_OF_TRACING : 1; const trace = ExecutionTrace.makeEmpty(); const beginIndexQuery = performance.now(); const ownerIds = await this._collectChildOfOwners(parentObjectIds, maxDepth, workingSet, trace); trace.indexQueryTime += performance.now() - beginIndexQuery; const result = workingSet.filter((item) => { const ownerId = childOfOwnerId(item); return ownerId !== undefined && ownerIds.has(ownerId); }); return { workingSet: result, trace: { ...trace, name: 'Filter(child-of)', details: JSON.stringify({ parents: filter.parents, transitive: filter.transitive }), objectCount: result.length, }, }; } /** * The ids an item's direct owner must be among to sit within `maxDepth` levels of a parent: the parents * and their descendants down to `maxDepth - 1` levels, walked down the children index so that no * ancestor document of any working-set item is loaded. */ private async _collectChildOfOwners( parentObjectIds: ReadonlySet, maxDepth: number, workingSet: readonly QueryItem[], trace: ExecutionTrace, ): Promise> { const ownerIds = new Set(parentObjectIds); if (maxDepth <= 1 || ownerIds.size === 0 || workingSet.length === 0) { return ownerIds; } const spaceIds = [...new Set(workingSet.map((item) => item.spaceId))]; let frontier = [...ownerIds]; for (let depth = 1; depth < maxDepth && frontier.length > 0; depth++) { const children = await this._runInRuntime( this._indexEngine.queryChildren({ spaceId: spaceIds, parentIds: frontier }), ); trace.indexHits += children.length; frontier = []; for (const child of children) { // Only a document owns further objects; a feed item is a leaf. if (child.queueId === '' && !ownerIds.has(child.objectId)) { ownerIds.add(child.objectId); frontier.push(child.objectId); } } } return ownerIds; } // TODO(dmaretskyi): This needs to be completed. private async _execTraverseStep(step: QueryPlan.TraverseStep, workingSet: QueryItem[]): Promise { const trace: ExecutionTrace = { ...ExecutionTrace.makeEmpty(), name: 'Traverse', details: JSON.stringify(step.traversal), }; // Every item reached, with the edge that reached it; items reached more than once are merged below. const reached: { item: QueryItem; from: QueryItem; edge: TraversalEdge | undefined }[] = []; switch (step.traversal._tag) { case 'ReferenceTraversal': { switch (step.traversal.direction) { case 'outgoing': { invariant(step.traversal.property !== null, 'Outgoing reference traversal requires a property'); const escapedProperty = step.traversal.property; const property = EscapedPropPath.unescape(escapedProperty); const refs = workingSet.flatMap((item) => { const ref = QueryItem.getProperty(item, property); const refs = Array.isArray(ref) ? ref : [ref]; return refs.flatMap((ref) => { try { return isEncodedReference(ref) ? [{ ref: EncodedReference.toURI(ref), from: item }] : []; } catch { log.warn('invalid reference', { ref: ref['/'] }); return []; } }); }); const beginLoad = performance.now(); const items = await Promise.all( refs.map(({ ref, from }) => this._loadReferencedTarget(ref, { sourceSpaceId: from.spaceId })), ); trace.documentLoadTime += performance.now() - beginLoad; items.forEach((item, index) => { const { from } = refs[index]; if (item) { reached.push({ item, from, edge: { kind: 'ref', property: escapedProperty, holder: from } }); } }); break; } case 'incoming': { const beginIndexQuery = performance.now(); const { metas, referrers } = await this.#queryIncomingReferences(workingSet, step.traversal.property); trace.indexHits += metas.length; trace.indexQueryTime += performance.now() - beginIndexQuery; const documentLoadStart = performance.now(); const results = await this._loadDocumentsAfterSqlQuery(metas); trace.documentsLoaded += results.length; trace.documentLoadTime += performance.now() - documentLoadStart; results.forEach((item, index) => { if (!item) { return; } for (const { anchor, propPath } of referrers.get(metas[index].recordId) ?? []) { reached.push({ item, from: anchor, edge: { kind: 'incoming-ref', property: propPath, holder: item } }); } }); break; } } break; } case 'RelationTraversal': { switch (step.traversal.direction) { case 'relation-to-source': case 'relation-to-target': { const toSource = step.traversal.direction === 'relation-to-source'; const refs = workingSet.flatMap((item) => { const dxn = toSource ? QueryItem.getRelationSource(item) : QueryItem.getRelationTarget(item); return dxn ? [{ ref: dxn, from: item }] : []; }); const beginLoad = performance.now(); const items = await Promise.all( refs.map(({ ref, from }) => this._loadFromDXN(ref, { sourceSpaceId: from.spaceId })), ); trace.documentLoadTime += performance.now() - beginLoad; items.forEach((item, index) => { const { from } = refs[index]; if (item) { reached.push({ item, from, edge: { kind: toSource ? 'relation-source' : 'relation-target', holder: from }, }); } }); break; } case 'source-to-relation': case 'target-to-relation': { const endpoint = step.traversal.direction === 'source-to-relation' ? 'source' : 'target'; const beginIndexQuery = performance.now(); const metas = await this._queryRelationsFromSqlIndex(workingSet, endpoint); trace.indexHits += metas.length; trace.indexQueryTime += performance.now() - beginIndexQuery; const documentLoadStart = performance.now(); const results = await this._loadDocumentsAfterSqlQuery(metas); trace.documentsLoaded += results.length; trace.documentLoadTime += performance.now() - documentLoadStart; const anchors = itemsById(workingSet); results.forEach((item, index) => { const anchorId = entityIdOf(endpoint === 'source' ? metas[index].source : metas[index].target); const from = anchorId !== undefined ? anchors.get(anchorId) : undefined; if (item && from) { reached.push({ item, from, edge: { kind: endpoint === 'source' ? 'relation-source' : 'relation-target', holder: item }, }); } }); break; } } break; } case 'HierarchyTraversal': { switch (step.traversal.direction) { case 'to-parent': { // Traverse from child to parent using the parent reference in the document. const refs = workingSet.flatMap((item) => { if (!item.doc) { return []; // TODO(dmaretskyi): Queue items not supported here. } const ref = EntityStructure.getParent(item.doc); return EncodedReference.isEncodedReference(ref) ? [{ ref: EncodedReference.toURI(ref), from: item }] : []; }); const beginLoad = performance.now(); const items = await Promise.all( refs.map(({ ref, from }) => this._loadFromDXN(ref, { sourceSpaceId: from.spaceId })), ); trace.documentLoadTime += performance.now() - beginLoad; items.forEach((item, index) => { const { from } = refs[index]; if (item) { reached.push({ item, from, edge: { kind: 'parent', holder: from } }); } }); break; } case 'to-children': { // Traverse from parent to children using the SQL index. // Covers both standard parent/child hierarchy (via the `parent` field) and // feed -> queue items (via the `queueId` field — a feed's queue id matches the feed's object id). // Group working set by spaceId. const bySpace = new Map(); for (const item of workingSet) { const existing = bySpace.get(item.spaceId); if (existing) { existing.push(item.objectId); } else { bySpace.set(item.spaceId, [item.objectId]); } } const beginIndexQuery = performance.now(); const allMetas: EntityMeta[] = []; for (const [spaceId, parentIds] of bySpace) { const children = await this._runInRuntime( this._indexEngine.queryChildren({ spaceId: [spaceId], parentIds }), ); allMetas.push(...children); } trace.indexHits += allMetas.length; trace.indexQueryTime += performance.now() - beginIndexQuery; const documentLoadStart = performance.now(); const results = await this._loadDocumentsAfterSqlQuery(allMetas); trace.documentsLoaded += results.filter(isNonNullable).length; trace.documentLoadTime += performance.now() - documentLoadStart; const anchors = itemsById(workingSet); results.forEach((item, index) => { const meta = allMetas[index]; // A feed's items name it by queue id; a document child names its parent. const parentId = entityIdOf(meta.parent) ?? (meta.queueId ? meta.queueId : undefined); const from = parentId !== undefined ? anchors.get(parentId) : undefined; if (item && from) { reached.push({ item, from, edge: { kind: 'child', holder: item } }); } else if (item) { reached.push({ item, from: item, edge: undefined }); } }); break; } } break; } default: throw new Error(`Unknown traversal type: ${(step.traversal as any)._tag}`); } const newWorkingSet = mergeReached(reached); trace.objectCount = newWorkingSet.length; return { workingSet: newWorkingSet, trace }; } private async _execUnionStep(step: QueryPlan.UnionStep, workingSet: QueryItem[]): Promise { const results = new Map(); const resultSets = await Promise.all(step.plans.map((plan) => this._execPlan(plan, [...workingSet]))); const trace: ExecutionTrace = { ...ExecutionTrace.makeEmpty(), name: 'Union', }; // NOTE: Doing insertion after execution to ensure deterministic results. Probably not needed. for (const resultSet of resultSets) { for (const item of resultSet.workingSet) { // Could be duplicate object ids in different spaces or in different epochs of the same space. results.set(compositeKey(item.spaceId, String(item.documentId), item.objectId), item); } trace.children.push(resultSet.trace); } return { workingSet: [...results.values()], trace, }; } private async _execSetDifferenceStep( step: QueryPlan.SetDifferenceStep, workingSet: QueryItem[], ): Promise { const trace: ExecutionTrace = { ...ExecutionTrace.makeEmpty(), name: 'SetDifference', }; const sourceResult = await this._execPlan(step.source, [...workingSet]); const excludeResult = await this._execPlan(step.exclude, [...workingSet]); trace.children.push(sourceResult.trace, excludeResult.trace); return { workingSet: sourceResult.workingSet.filter((item) => { const index = excludeResult.workingSet.findIndex((i) => i.objectId === item.objectId); return index === -1; }), trace, }; } private async _execOrderStep(step: QueryPlan.OrderStep, workingSet: QueryItem[]): Promise { // After an AggregateStep the working set is partitioned into contiguous groups; a post-group order // reorders whole groups (by their aggregates), and a pushed-down limit pages over whole groups. // Otherwise it sorts and slices the flat object stream. let sortedWorkingSet = isGrouped(workingSet) ? GroupBy.orderGroups(workingSet, serializeItemGroupKey, (a, b) => this._compareMultiOrder(a, b, step.order)) : [...workingSet].sort((a, b) => this._compareMultiOrder(a, b, step.order)); // Apply limit if specified on the order step. if (step.limit !== undefined && sortedWorkingSet.length > step.limit) { sortedWorkingSet = isGrouped(sortedWorkingSet) ? GroupBy.takeGroups(sortedWorkingSet, step.limit, serializeItemGroupKey) : sortedWorkingSet.slice(0, step.limit); } return { workingSet: sortedWorkingSet, trace: { ...ExecutionTrace.makeEmpty(), name: 'Order', details: JSON.stringify({ order: step.order, limit: step.limit }), objectCount: sortedWorkingSet.length, }, }; } private async _execLimitStep(step: QueryPlan.LimitStep, workingSet: QueryItem[]): Promise { // After an AggregateStep the working set is partitioned into contiguous groups; limit then pages // over whole groups. Otherwise it slices the flat object stream. const limitedWorkingSet = isGrouped(workingSet) ? GroupBy.takeGroups(workingSet, step.limit, serializeItemGroupKey) : workingSet.slice(0, step.limit); return { workingSet: limitedWorkingSet, trace: { ...ExecutionTrace.makeEmpty(), name: 'Limit', details: JSON.stringify({ limit: step.limit }), objectCount: limitedWorkingSet.length, }, }; } private async _execSkipStep(step: QueryPlan.SkipStep, workingSet: QueryItem[]): Promise { const skippedWorkingSet = isGrouped(workingSet) ? GroupBy.dropGroups(workingSet, step.skip, serializeItemGroupKey) : workingSet.slice(step.skip); return { workingSet: skippedWorkingSet, trace: { ...ExecutionTrace.makeEmpty(), name: 'Skip', details: JSON.stringify({ skip: step.skip }), objectCount: skippedWorkingSet.length, }, }; } /** * Runs a compiled statement. A source step: it ignores the incoming working set, because the * statement already stands for every step that produced one. */ private async _execSqlStep(step: QueryPlan.SqlStep): Promise { const trace = ExecutionTrace.makeEmpty(); const begin = performance.now(); const { rows, explain } = await this._runInRuntime( Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const rows = yield* sql.unsafe(step.sql, step.params); const explain = TRACE_QUERY_EXECUTION ? (yield* sql.unsafe<{ detail: string }>(`EXPLAIN QUERY PLAN ${step.sql}`, step.params)).map( (row) => row.detail, ) : undefined; return { rows, explain }; }), ); trace.indexQueryTime = performance.now() - begin; trace.indexHits = rows.length; trace.objectCount = rows.length; trace.sql = step.sql; trace.explain = explain; return { workingSet: rows.map(compiledRowToItem), trace }; } private async _execAggregateStep( step: QueryPlan.AggregateStep, workingSet: QueryItem[], ): Promise { const withKeys = workingSet.map((item) => ({ ...item, groupKey: QueryItem.getGroupKey(item, step.aggregates) })); const partitioned = GroupBy.partitionByGroupKey(withKeys, (item) => GroupBy.serializeGroupKey(item.groupKey!)); const stamped = GroupBy.withGroupAggregates( partitioned, (item) => GroupBy.serializeGroupKey(item.groupKey!), step.aggregates, (item, property) => QueryItem.getAggregateProperty(item, property), (a, b, order) => this._compareByOrder(a, b, order), ); const groupedWorkingSet = step.aggregates.some((aggregate) => aggregate.kind === 'items') ? stamped : withManifests(GroupBy.collapseGroups(stamped, serializeItemGroupKey), stamped, step.aggregates); return { workingSet: groupedWorkingSet, trace: { ...ExecutionTrace.makeEmpty(), name: 'Aggregate', details: JSON.stringify({ aggregates: step.aggregates }), objectCount: groupedWorkingSet.length, }, }; } private _compareMultiOrder(a: QueryItem, b: QueryItem, orders: readonly QueryAST.Order[]): number { // Short circuit for common cases. if (orders.length === 0) { return 0; } else if (orders.length === 1) { return this._compareByOrder(a, b, orders[0]); } for (const order of orders) { const comparison = this._compareByOrder(a, b, order); if (comparison !== 0) { return comparison; } } return 0; } private _compareByOrder(a: QueryItem, b: QueryItem, order: QueryAST.Order): number { switch (order.kind) { case 'natural': { if (a.walkIndex !== undefined && b.walkIndex !== undefined) { const comparison = a.walkIndex - b.walkIndex; return order.direction === 'desc' ? -comparison : comparison; } // Code-unit order, not `localeCompare`: the feed scan pushes this ordering into SQLite's // `ORDER BY objectId`, which collates BINARY, and an entity id may be lower-case (the // format check is case-insensitive). Under a locale collation the two would disagree on a // mixed-case pair, and the scan's capped page would not be the page this sort produces. const comparison = a.objectId < b.objectId ? -1 : a.objectId > b.objectId ? 1 : 0; return order.direction === 'desc' ? -comparison : comparison; } case 'property': { const comparison = this._compareByProperty(a, b, order.property); return order.direction === 'desc' ? -comparison : comparison; } case 'rank': { // Higher rank = better match. By default, descending order (best first). const comparison = a.rank - b.rank; return order.direction === 'desc' ? -comparison : comparison; } case 'annotation': return QueryAST.compareAnnotationOrderValues( QueryAST.getAnnotationOrderValue(QueryItem.getAnnotations(a), order), QueryAST.getAnnotationOrderValue(QueryItem.getAnnotations(b), order), order.direction, ); case 'timestamp': { // Order by the system createdAt/updatedAt timestamp from the meta index. // Missing timestamps sort as oldest (0). const aValue = (order.field === 'updatedAt' ? a.updatedAt : a.createdAt) ?? 0; const bValue = (order.field === 'updatedAt' ? b.updatedAt : b.createdAt) ?? 0; const comparison = aValue - bValue; return order.direction === 'desc' ? -comparison : comparison; } default: // Should never reach here with proper TypeScript types. return 0; } } private _compareByProperty(a: QueryItem, b: QueryItem, property: string): number { // On a grouped working set, a property order names a group field: prefer a stamped scalar // aggregate (max/min/count) when present, else fall through to the member/row property (which // also covers ordering by a group-key component, shared by every member). const aValue = a.aggregates && property in a.aggregates ? a.aggregates[property] : QueryItem.getProperty(a, [property]); const bValue = b.aggregates && property in b.aggregates ? b.aggregates[property] : QueryItem.getProperty(b, [property]); // Both null or undefined if (aValue == null && bValue == null) { return 0; } // Only a is null/undefined if (aValue == null) { return 1; } // Only b is null/undefined if (bValue == null) { return -1; } // Both strings, in the collation SQLite sorts by. if (typeof aValue === 'string' && typeof bValue === 'string') { return compareCodeUnits(aValue, bValue); } // Both numbers if (typeof aValue === 'number' && typeof bValue === 'number') { return aValue - bValue; } // Both booleans if (typeof aValue === 'boolean' && typeof bValue === 'boolean') { return aValue === bValue ? 0 : aValue ? 1 : -1; } // Fallback: convert to strings and compare return compareCodeUnits(String(aValue), String(bValue)); } private async _runInRuntime(effect: Effect.Effect): Promise { const runtimeProvider = this._runtime; invariant(runtimeProvider, 'SQL runtime is required.'); return await RuntimeProvider.runPromise(runtimeProvider)(effect); } private async _queryAllFromSqlIndex( spaceIds: readonly SpaceId[], includeAllQueues: boolean, queues: readonly QueueRef[] | null, window?: QueueWindow, ): Promise { return await this._runInRuntime(this._indexEngine.queryAll({ spaceIds, includeAllQueues, queues, window })); } private async _queryTypesFromSqlIndex( spaceIds: readonly SpaceId[], typeDxns: readonly URI.URI[], inverted: boolean, includeAllQueues: boolean, queues: readonly QueueRef[] | null, window?: QueueWindow, ): Promise { return await this._runInRuntime( this._indexEngine.queryTypes({ spaceIds, typeDxns, inverted, includeAllQueues, queues, window }), ); } /** The objects referencing each anchor through `property`, with the anchors and property paths each references them by. */ async #queryIncomingReferences( workingSet: readonly QueryItem[], property: EscapedPropPath | null, ): Promise<{ metas: readonly EntityMeta[]; referrers: Map }> { const queryPath = property === null ? null : EscapedPropPath.unescape(property); const rowsByAnchor = await Promise.all( workingSet.map(async (anchor) => ({ anchor, rows: await this._runInRuntime( this._indexEngine.queryReverseRef({ targetDXN: QueryExecutor._anchorTargetDxn(anchor) }), ), })), ); const referrers = new Map(); for (const { anchor, rows } of rowsByAnchor) { for (const row of rows) { if ( queryPath !== null && !QueryExecutor._matchesReferencePropertyPath(EscapedPropPath.unescape(row.propPath), queryPath) ) { continue; } const list = referrers.get(row.recordId) ?? []; list.push({ anchor, propPath: row.propPath }); referrers.set(row.recordId, list); } } const metas = await this._runInRuntime(this._indexEngine.lookupByRecordIds([...referrers.keys()])); return { metas, referrers }; } private static _anchorTargetDxn(item: QueryItem): EID.EID { // Queue items are indexed with fully-qualified DXNs; local `echo:/` anchors miss them. if (item.queueId != null) { return EID.make({ spaceId: item.spaceId, entityId: item.objectId }); } return EID.make({ entityId: item.objectId }); } /** * Reverse-reference lookup by target URI. Anchors that are not entities (a named entity's `dxn:`) * reach this directly, without a working set. */ private async _queryIncomingReferencesByTarget( anchorDxns: readonly URI.URI[], property: EscapedPropPath | null, ): Promise { const rows: readonly ReverseRef[] = ( await Promise.all( anchorDxns.map((targetDXN) => this._runInRuntime(this._indexEngine.queryReverseRef({ targetDXN }))), ) ).flat(); const recordIds = rows .filter((row) => { if (property === null) { return true; } const queryPath = EscapedPropPath.unescape(property); const rowPath = EscapedPropPath.unescape(row.propPath); return QueryExecutor._matchesReferencePropertyPath(rowPath, queryPath); }) .map((row) => row.recordId); const uniqueRecordIds = Array.from(new Set(recordIds)); return await this._runInRuntime(this._indexEngine.lookupByRecordIds(uniqueRecordIds)); } /** * Matches a reverse-reference row path against a query property path. * Allows numeric segments in the row path (array indices) that are not present in the query. * * Examples: * - query: ['assignee'] matches row: ['assignee'] and ['assignee', '0']. * - query: ['items', 'assignee'] matches row: ['items', '0', 'assignee']. * - query: ['a', 'b'] does NOT match row: ['a']. * - query: ['a'] does NOT match row: ['a', 'b']. */ private static _matchesReferencePropertyPath(rowPath: readonly string[], queryPath: readonly string[]): boolean { const isNumericSegment = (segment: string) => /^[0-9]+$/.test(segment); let i = 0; // queryPath index. let j = 0; // rowPath index. while (i < queryPath.length && j < rowPath.length) { if (rowPath[j] === queryPath[i]) { i++; j++; continue; } // Row may contain array indices that aren't present in the query path. if (isNumericSegment(rowPath[j])) { j++; continue; } return false; } // Must consume full query path. if (i !== queryPath.length) { return false; } // Any remaining row segments must be numeric (array indices). for (; j < rowPath.length; j++) { if (!isNumericSegment(rowPath[j])) { return false; } } return true; } private async _queryRelationsFromSqlIndex( workingSet: QueryItem[], endpoint: 'source' | 'target', ): Promise { const anchorDxns = workingSet.map((item) => EID.make({ entityId: item.objectId })); return await this._runInRuntime(this._indexEngine.queryRelations({ endpoint, anchorDxns })); } private async _loadDocumentsAfterSqlQuery(metas: readonly EntityMeta[]): Promise<(QueryItem | null)[]> { const snapshotMap = await this._loadQueueSnapshotMap(metas); const documentIds = [...new Set(metas.flatMap((meta) => (meta.documentId ? [meta.documentId as DocumentId] : [])))]; const storedHeads = documentIds.length > 0 ? new Map( (await this._automergeHost.getStoredHeads(documentIds)).map((heads, index) => [documentIds[index], heads]), ) : new Map(); const snapshots = await this.#readCurrentSnapshots(metas, documentIds); return await Promise.all( metas.map(async (meta) => { // Branch 1: Document-backed object, from the index's copy when it was read at the stored heads. if (meta.documentId) { const snapshot = snapshots.get(meta.recordId); return snapshot && isValidDocumentId(meta.documentId) ? QueryItem.fromSnapshot(meta, meta.documentId, snapshot) : this._loadFromAutomerge(meta, storedHeads.get(meta.documentId as DocumentId)); } // Branch 2: Queue-backed object. if (meta.queueId) { return this._loadFromQueue(meta, snapshotMap); } return null; }), ); } /** * The index's copies of the document objects among `metas` that were read at their document's current heads, * keyed by record id: the heads in memory when the document is loaded, its stored heads otherwise. Such a copy * is the document's own state, so it stands in for loading the document. */ async #readCurrentSnapshots( metas: readonly EntityMeta[], documentIds: readonly DocumentId[], ): Promise> { const documentMetas = new Map(metas.filter((meta) => meta.documentId).map((meta) => [meta.recordId, meta])); if (documentMetas.size === 0) { return new Map(); } const [snapshots, heads] = await Promise.all([ this._runInRuntime(this._indexEngine.querySnapshots([...documentMetas.keys()])).catch((err) => { log.warn('index snapshots could not be read; loading the documents', { err }); return []; }), this._automergeHost.getHeads([...documentIds]), ]); const currentHeads = new Map( documentIds.map((documentId, index) => [documentId, heads[index]]), ); const current = new Map(); for (const snapshot of snapshots) { const meta = documentMetas.get(snapshot.recordId); if (meta?.documentId && isSaved(currentHeads.get(meta.documentId), snapshot.version)) { current.set(snapshot.recordId, snapshot); } } countWork('echo.querySnapshotHits', current.size); return current; } private async _loadQueueSnapshotMap(metas: readonly EntityMeta[]): Promise> { const queueMetas = metas.filter((meta) => !meta.documentId && !!meta.queueId); if (queueMetas.length === 0) { return new Map(); } const snapshots = await this._runInRuntime( this._indexEngine.querySnapshotsJSON(queueMetas.map((meta) => meta.recordId)), ); return new Map(snapshots.map((s) => [s.recordId, s.snapshot])); } /** * Loads a queue-backed object from an indexed snapshot (by `recordId`). * Returns `null` when the snapshot is missing or is not a JSON object. */ private _loadFromQueue(meta: EntityMeta, snapshotMap: Map): QueryItem | null { const snapshot = snapshotMap.get(meta.recordId); if (!snapshot || typeof snapshot !== 'object') { return null; } if (!EntityId.isValid(meta.queueId)) { return null; } return { objectId: meta.objectId, spaceId: meta.spaceId, queueId: meta.queueId, queueNamespace: meta.queueNamespace || null, documentId: null, doc: null, data: snapshot as Obj.JSON, rank: 1, createdAt: meta.createdAt, updatedAt: meta.updatedAt, position: meta.queuePosition, }; } /** * Loads a document-backed object from an Automerge `DatabaseDirectory`. * Returns `null` if the document can't be loaded, the inline object isn't present, or if the meta does not have a * document id (e.g. queue-backed objects). */ private async _loadFromAutomerge(meta: EntityMeta, storedHeads: A.Heads | undefined): Promise { if (!meta.documentId) { return null; } using lease = await this._automergeHost.loadDoc(this._ctx, meta.documentId as DocumentId, { fetchFromNetwork: false, }); if (!lease) { return null; } const doc = lease.doc(); const object = DatabaseDirectory.getInlineObject(doc, meta.objectId); if (!object) { return null; } countWork('echo.queryDocumentLoads'); const json = objectStructureToJson(meta.objectId, object); const heads = A.getHeads(doc); const text = isSaved(storedHeads, heads) ? backingJson(doc, object, json) : undefined; return { objectId: meta.objectId, documentId: meta.documentId as DocumentId, spaceId: meta.spaceId, queueId: null, queueNamespace: null, doc: object, data: null, rank: 1, createdAt: meta.createdAt, updatedAt: meta.updatedAt, backing: text !== undefined ? { heads, json: text } : undefined, heads, recordId: meta.recordId, }; } /** * Loads the target of an outgoing reference traversal. * Space-db objects load from Automerge; with `includeAllFeeds` scope, queue items resolve via the SQL index. */ private async _loadReferencedTarget( dxn: URI.URI, { sourceSpaceId }: { sourceSpaceId: SpaceId }, ): Promise { const fromSpace = await this._loadFromDXN(dxn, { sourceSpaceId }); if (fromSpace) { return fromSpace; } if (this.#allFeedsSpaces.size === 0) { return null; } const parsedEchoUri = EID.tryParse(dxn); const objectId = parsedEchoUri ? EID.getEntityId(parsedEchoUri) : undefined; const spaceId = (parsedEchoUri ? EID.getSpaceId(parsedEchoUri) : undefined) ?? sourceSpaceId; if (!objectId || !spaceId) { return null; } const metas = await this._runInRuntime( this._indexEngine.queryObjectIds({ spaceIds: [spaceId], objectIds: [objectId] }), ); if (metas.length === 0) { return null; } const [item] = await this._loadDocumentsAfterSqlQuery(metas); return item ?? null; } private async _loadFromDXN(dxn: URI.URI, { sourceSpaceId }: { sourceSpaceId: SpaceId }): Promise { const echoUri = EID.tryParse(dxn); if (!echoUri) { log.warn('unable to resolve DXN', { dxn }); return null; } const objectId = EID.getEntityId(echoUri); if (!objectId) { log.warn('unable to resolve DXN', { dxn }); return null; } const spaceId = EID.getSpaceId(echoUri) ?? sourceSpaceId; const spaceRoot = this._spaceStateManager.getRootBySpaceId(spaceId); if (!spaceRoot) { log.warn('no space state found for', { spaceId }); return null; } const dbDirectory = spaceRoot.directory(); const directoryHeads = spaceRoot.heads(); if (!dbDirectory || !directoryHeads) { log.warn('no space state found for', { spaceId }); return null; } // Deprecated inline directory object, read until the inline object migration moves it. // TODO(dmaretskyi): Drop once every space has run the inline object migration. const inlineObject = DatabaseDirectory.getInlineObject(dbDirectory, objectId); if (inlineObject) { return { objectId, documentId: spaceRoot.documentId, spaceId, queueId: null, queueNamespace: null, data: null, doc: inlineObject, rank: 1, // DXN traversal results are not sourced from the meta index; timestamps are unavailable. createdAt: null, updatedAt: null, heads: directoryHeads, }; } const link = DatabaseDirectory.getLink(dbDirectory, objectId); if (!link || !isValidAutomergeUrl(link)) { return null; } const fromIndex = await this.#loadFromIndexCopy(spaceId, objectId, interpretAsDocumentId(link)); if (fromIndex) { return fromIndex; } using lease = await this._automergeHost.loadDoc(this._ctx, link, { fetchFromNetwork: false, }); if (!lease) { return null; } const object = DatabaseDirectory.getInlineObject(lease.doc(), objectId); if (!object) { return null; } countWork('echo.queryDocumentLoads'); return { objectId, documentId: lease.documentId, spaceId, queueId: null, queueNamespace: null, data: null, doc: object, rank: 1, // DXN traversal results are not sourced from the meta index; timestamps are unavailable. createdAt: null, updatedAt: null, heads: A.getHeads(lease.doc()), }; } /** * The index's copy of an object in the document the space directory places it in, when the index read it * at that document's stored heads; null when the document has to be loaded. */ async #loadFromIndexCopy(spaceId: SpaceId, objectId: EntityId, documentId: DocumentId): Promise { const meta = await this._runInRuntime(this._indexEngine.lookupByObjectId({ objectId, spaceId, queueId: '' })).catch( (err) => { log.warn('index row could not be read; loading the document', { objectId, err }); return null; }, ); if (!meta || meta.documentId !== documentId) { return null; } const snapshot = (await this.#readCurrentSnapshots([meta], [documentId])).get(meta.recordId); return snapshot ? QueryItem.fromSnapshot(meta, documentId, snapshot) : null; } /** * Loads a queue item by its object ID from the SQL index. * Used by the IdSelector path when querying within a queue scope. */ private async _loadQueueItemById(spaceId: SpaceId, queueId: EntityId, objectId: EntityId): Promise { const meta = await this._runInRuntime(this._indexEngine.lookupByObjectId({ objectId, spaceId, queueId })); if (!meta) { return null; } const snapshotMap = await this._loadQueueSnapshotMap([meta]); return this._loadFromQueue(meta, snapshotMap); } /** * Filters out items whose strong dependencies (schema object, relation endpoints, * parent) are not resolvable from local state — dangling references or docs that are * not on disk. Mirrors the client-side working-set filter so dep-broken objects are * excluded consistently on both sides of the query pipeline. */ private async _filterUnresolvableStrongDeps(workingSet: QueryItem[]): Promise { // Resolved dep verdicts shared across items (e.g. a common schema object). const verdicts = new Map(); const resolvable = await Promise.all( workingSet.map((item) => this._areStrongDepsResolvable(item, MAX_DEPTH_FOR_STRONG_DEP_TRACING, verdicts, new Set()), ), ); const result = workingSet.filter((_item, index) => resolvable[index]); if (result.length !== workingSet.length) { log('omitted items with unresolvable strong deps', { queryId: this._id, omitted: workingSet.filter((_item, index) => !resolvable[index]).map((item) => item.objectId), }); } return result; } private async _areStrongDepsResolvable( item: QueryItem, remainingDepth: number, verdicts: Map, seen: Set, ): Promise { if (remainingDepth <= 0) { // Depth cap reached — give the item the benefit of the doubt rather than excluding it. return true; } const results = await Promise.all( QueryItem.getStrongDependencies(item).map(async (dep) => { if (!EID.isLocal(dep)) { // Cross-space references are not gated (mirrors `ObjectCore.getStrongDependencies` usage). return true; } const key = compositeKey(item.spaceId, dep); const cached = verdicts.get(key); if (cached !== undefined) { return cached; } if (seen.has(key)) { // Reference cycle — treat as resolvable (mirrors the client's seen-set behavior). return true; } seen.add(key); const depItem = await this._loadDependency(item, dep); const verdict = depItem != null && (await this._areStrongDepsResolvable(depItem, remainingDepth - 1, verdicts, seen)); verdicts.set(key, verdict); return verdict; }), ); return results.every(Boolean); } /** * Resolves an object `item` depends on, in the same form as `item`: an item selected from the index * resolves its dependencies from the index too, so checking them loads no documents either. Each * dependency loads once per `execQuery` run. */ private _loadDependency(item: QueryItem, dxn: URI.URI): Promise { const fromDocument = Boolean(item.doc || item.data || !item.meta); const key = compositeKey(item.spaceId, dxn, fromDocument ? 'document' : 'index'); let loaded = this.#dependencyCache.get(key); if (!loaded) { loaded = fromDocument ? this._loadFromDXN(dxn, { sourceSpaceId: item.spaceId }) : this._loadDependencyFromIndex(item.spaceId, dxn); this.#dependencyCache.set(key, loaded); } return loaded; } private async _loadDependencyFromIndex(sourceSpaceId: SpaceId, dxn: URI.URI): Promise { const echoUri = EID.tryParse(dxn); const objectId = echoUri ? EID.getEntityId(echoUri) : undefined; if (!echoUri || !objectId) { return null; } const spaceId = EID.getSpaceId(echoUri) ?? sourceSpaceId; const metas = await this._runInRuntime( this._indexEngine.queryObjectIds({ spaceIds: [spaceId], objectIds: [objectId] }), ); const meta = metas.find((candidate) => candidate.documentId); return meta ? QueryItem.fromIndexRow(meta) : null; } private async _getTransitiveDeletionState(item: QueryItem, remainingDepth: number): Promise { const strongDeps = [ QueryItem.getParent(item), QueryItem.getRelationSource(item), QueryItem.getRelationTarget(item), ].filter((x) => x !== undefined); if (strongDeps.length === 0) { return false; } // TODO(dmaretskyi): This could be optimized to bail early if any of the dependencies are deleted. const strongDepStates = await Promise.all( strongDeps.map(async (dxn) => { const dep = await this._loadDependency(item, dxn); if (!dep) { return false; } if (QueryItem.isDeleted(dep)) { return true; } if (remainingDepth > 0) { return this._getTransitiveDeletionState(dep, remainingDepth - 1); } return false; }), ); return strongDepStates.some((x) => x); } } const extractSpaceIdFromQueue = (feedUri: string): SpaceId | undefined => { const echoUri = EID.tryParse(feedUri); return echoUri ? EID.getSpaceId(echoUri) : undefined; }; /** A decoded feed block carrying a valid object id, which is all a feed item's JSON is checked for. */ const isObjectJSON = (value: Record): value is Obj.JSON => typeof value.id === 'string' && EntityId.isValid(value.id); /** Every feed scope any select step of the plan (subplans included) names. */ const extractFeedScopes = (plan: QueryPlan.Plan): QueryAST.FeedScope[] => plan.steps.flatMap((step) => { switch (step._tag) { case 'SelectStep': return step.scope.filter((scope): scope is QueryAST.FeedScope => scope._tag === 'feed'); case 'UnionStep': return step.plans.flatMap(extractFeedScopes); case 'SetDifferenceStep': return [...extractFeedScopes(step.source), ...extractFeedScopes(step.exclude)]; default: return []; } }); /** Whether a feed item is a member of one of `branches` (`null` is main); absent admits every branch. */ const isOnBranches = (data: Record, branches: QueueRef['branches']): boolean => branches === undefined || branches.includes(EchoFeedCodec.branchOf(data) ?? null); /** The branches two scopes of one feed read together; either reading every branch reads them all. */ const unionBranches = (left: QueueRef, right: QueueRef): QueueRef['branches'] => left.branches === undefined || right.branches === undefined ? undefined : [...new Set([...left.branches, ...right.branches])]; /** * The store-read feed items a select step picks, as the index would have answered it: by selector, * then the step's feed window. Text and reference selectors match nothing, since they are answered * from indexes a disabled feed is not in. */ const selectStoreItems = (step: QueryPlan.SelectStep, items: readonly QueryItem[]): QueryItem[] => { const { selector } = step; const selected = items.filter((item) => { const data = item.data; if (!data) { return false; } switch (selector._tag) { case 'WildcardSelector': return true; case 'IdSelector': return selector.objectIds.includes(item.objectId); case 'TypeSelector': { const matches = selector.typename.some((typename) => filterMatchObjectJSON({ type: 'object', typename, props: {} }, data), ); return matches !== selector.inverted; } case 'TimestampSelector': { const updatedAt = item.updatedAt ?? 0; const createdAt = item.createdAt ?? 0; return ( (selector.updatedAfter === undefined || updatedAt > selector.updatedAfter) && (selector.updatedBefore === undefined || updatedAt < selector.updatedBefore) && (selector.createdAfter === undefined || createdAt > selector.createdAfter) && (selector.createdBefore === undefined || createdAt < selector.createdBefore) ); } default: return false; } }); const window = extractQueueWindow(step); if (window === undefined) { return selected; } if (window.kind === 'cursor') { return selected .filter( (item) => typeof item.position === 'number' && item.position > window.after && (window.before === undefined || item.position < window.before), ) .sort((left, right) => (left.position ?? 0) - (right.position ?? 0)) .slice(0, window.limit); } const sorted = selected .filter((item) => window.deleted === undefined || (item.data?.[ATTR_DELETED] === true) === window.deleted) .sort((left, right) => compareCodeUnits(left.objectId, right.objectId)); const ordered = window.direction === 'desc' ? sorted.reverse() : sorted; const skip = window.skip ?? 0; return ordered.slice(skip, skip + window.limit); }; /** Bound below every assigned position, which start at 0. */ const BEFORE_FIRST_POSITION = -1; /** * The index-level window for a select the storage layer can bound itself, so a bounded query costs * what it asks for rather than the whole feed: a cursor range resumes by position, and a * `feedScan` (set by the planner only where it proved the cap sound) reads in natural order. * * Every cursor range windows the scan, an empty one included — it bounds nothing but still asks for * a cursor read, which is over positioned blocks in position order. A reader that paged the * unpositioned blocks in first would stop at a page of items it cannot act on while positioned ones * waited behind them. * * A bound that is not a decimal position is treated as unsatisfiable rather than as absent: * resuming a corrupted checkpoint from the beginning would re-dispatch the whole feed. */ const extractQueueWindow = (step: QueryPlan.SelectStep): QueueWindow | undefined => { const range = step.feedCursorRange; if (range === undefined) { if (step.feedScan === undefined || step.limit === undefined) { return undefined; } return { kind: 'natural', direction: step.feedScan.direction, limit: step.limit, ...(step.feedScan.skip !== undefined ? { skip: step.feedScan.skip } : {}), ...(step.feedScan.deleted !== undefined ? { deleted: step.feedScan.deleted } : {}), }; } // Backstop for the planner's check, which is where a cursor over a space's documents is refused. if (!step.scope.every((scope) => scope._tag === 'feed')) { throw new QueryError({ message: 'A feed cursor filter can only be used with a feed scope.', context: { query: null }, }); } return { kind: 'cursor', // The empty string is the start sentinel (`Feed.START`), which bounds nothing. after: range.begin ? parseCursor(range.begin, Number.MAX_SAFE_INTEGER) : BEFORE_FIRST_POSITION, ...(range.end ? { before: parseCursor(range.end, BEFORE_FIRST_POSITION) } : {}), ...(step.limit !== undefined ? { limit: step.limit } : {}), }; }; /** The block id a local cursor (`|`) resumes after; the start sentinel `''` names none. */ /** A local cursor is `|`, with an empty branch for the root. */ const parseLocalCursor = (cursor: string): { branch: string | null; block: string } => { const separator = cursor.indexOf('|'); const branch = cursor.slice(0, separator); return { branch: branch === '' ? null : branch, block: cursor.slice(separator + 1) }; }; /** * The direction of a walk: the natural order the plan asks for, ascending when it asks for none. A * walk has no other order, since its natural order is the walk itself. */ const walkDirection = (plan: QueryPlan.Plan): 'asc' | 'desc' => { const orders = plan.steps.flatMap((step) => (step._tag === 'OrderStep' ? step.order : [])); const unsupported = orders.find((order) => order.kind !== 'natural'); if (unsupported !== undefined) { throw new QueryError({ message: `A walk accepts only the natural order, not the ${unsupported.kind} order.`, context: { query: null, order: unsupported.kind }, }); } return orders[0]?.kind === 'natural' ? orders[0].direction : 'asc'; }; /** * The page a walk is cut to: the plan's limit, when it only selects, filters and orders before it. A walk counts what * the filters keep of each page, so reading pages until that many remain is enough. */ const walkLimit = (plan: QueryPlan.Plan): number | undefined => { // The planner moves a trailing limit onto the order step, removing the limit step. const ordered = plan.steps.find((step) => step._tag === 'OrderStep'); const limit = plan.steps.find((step) => step._tag === 'LimitStep'); const passing = new Set([ 'SelectStep', 'OrderStep', 'ClearWorkingSetStep', 'FilterDeletedStep', 'FilterStep', 'LimitStep', ]); const narrowing = plan.steps.some((step) => !passing.has(step._tag)); return narrowing ? undefined : limit?._tag === 'LimitStep' ? limit.limit : ordered?._tag === 'OrderStep' ? ordered.limit : undefined; }; /** A cursor's position, or `unsatisfiable` when it does not name one. */ const parseCursor = (cursor: string, unsatisfiable: number): number => { const position = /^\d+$/.test(cursor) ? Number(cursor) : Number.NaN; return Number.isSafeInteger(position) ? position : unsatisfiable; }; /** * The queues a feed scope names, each carrying the space its URI qualifies it with so the index * seek cannot cross spaces — a queue id is unique only within its own. An unqualified URI * (`echo:///`) names no space, and matches on its id alone. */ const extractQueueRefs = (queues: readonly QueryAST.FeedScope[]): QueueRef[] | null => { if (queues.length === 0) { return null; } return queues .map((scope): QueueRef | undefined => { const echoUri = EID.tryParse(String(scope.feedUri)); if (!echoUri) { return undefined; } const queueId = EID.getEntityId(echoUri); if (!queueId) { return undefined; } const spaceId = EID.getSpaceId(echoUri); return { queueId, ...(spaceId !== undefined ? { spaceId } : {}), ...queueBranchesOf(scope.branches), }; }) .filter(isNonNullable); }; /** * Extract timestamp parameters from a filter AST node. * Returns null if the filter doesn't contain timestamp nodes. */ const extractTimestampParams = ( filter: QueryAST.Filter, ): { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number } | null => { const collect = (f: QueryAST.Filter): QueryAST.FilterTimestamp[] => { if (f.type === 'timestamp') { return [f]; } if (f.type === 'and') { return f.filters.flatMap(collect); } return []; }; const timestamps = collect(filter); if (timestamps.length === 0) { return null; } const params: { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number } = {}; for (const ts of timestamps) { if (ts.field === 'updatedAt' && (ts.operator === 'gt' || ts.operator === 'gte')) { params.updatedAfter = ts.value; } else if (ts.field === 'updatedAt' && (ts.operator === 'lt' || ts.operator === 'lte')) { params.updatedBefore = ts.value; } else if (ts.field === 'createdAt' && (ts.operator === 'gt' || ts.operator === 'gte')) { params.createdAfter = ts.value; } else if (ts.field === 'createdAt' && (ts.operator === 'lt' || ts.operator === 'lte')) { params.createdBefore = ts.value; } } return params; }; function filterContainsTimestamp(filter: QueryAST.Filter): boolean { if (filter.type === 'timestamp') { return true; } if (filter.type === 'and' || filter.type === 'or') { return filter.filters.some(filterContainsTimestamp); } if (filter.type === 'not') { return filterContainsTimestamp(filter.filter); } return false; } /** * Cache key identifying an `in-query` node's subquery + projected property, used to share one * resolution across every occurrence of the same subquery within an `execQuery` run. */ const _inQueryCacheKey = (node: QueryAST.FilterInQuery): string => `${JSON.stringify(node.subquery)}\0${node.property}`; /** * A compiled row as a working-set item. The shipped form is built here rather than in * `getResults`, since the row already carries everything the client needs and the item carries no * document to derive it from. A collapsed group stands for its members, so it ships no object * fields and its id is the serialized group key. */ const compiledRowToItem = (row: CompiledRow): QueryItem => { const result: QueryService.QueryResult = row.aggregates !== null && row.groupKey !== null ? { id: row.groupKey, spaceId: row.spaceId, rank: row.rank, groupKey: row.groupKey, groupCount: row.groupCount ?? undefined, aggregates: row.aggregates, } : { id: row.objectId, spaceId: row.spaceId, documentId: row.documentId !== '' ? row.documentId : undefined, queueId: row.queueId !== '' ? row.queueId : undefined, queueNamespace: row.queueNamespace !== '' ? row.queueNamespace : undefined, rank: row.rank, documentJson: row.documentJson ?? undefined, groupKey: row.groupKey ?? undefined, groupCount: row.groupCount ?? undefined, heads: row.heads !== null ? JSON.parse(row.heads) : undefined, createdAt: row.heads !== null ? (row.createdAt ?? undefined) : undefined, updatedAt: row.heads !== null ? (row.updatedAt ?? undefined) : undefined, version: compiledRowVersion(row), }; const paths = row.edges !== null ? pathsFromEdges(row.objectId, parseEdges(row.edges)) : undefined; return { objectId: row.objectId, spaceId: row.spaceId, documentId: row.documentId !== '' ? (row.documentId as DocumentId) : null, queueId: row.queueId !== '' ? (row.queueId as EntityId) : null, queueNamespace: row.queueNamespace !== '' ? row.queueNamespace : null, doc: null, data: null, rank: row.rank, createdAt: row.createdAt, updatedAt: row.updatedAt, recordId: row.recordId, result, ...(paths === null ? { derivationUnknown: true } : paths && { paths }), ...(row.manifest !== null && { manifest: parseCompiledManifest(row.manifest) }), }; }; /** The state a compiled row was read at: its document's index heads, or its feed block's position. */ const compiledRowVersion = (row: { documentId: string; queueId: string; versionHeads: string | null; queuePosition: number | null; }): QueryService.RowVersion | undefined => { if (row.queueId !== '') { return row.queuePosition !== null ? { kind: 'feed', insertionId: row.queuePosition } : undefined; } if (row.documentId !== '' && row.versionHeads !== null) { return { kind: 'automerge', documentId: row.documentId, heads: parseStringArray(JSON.parse(row.versionHeads)) }; } return undefined; }; const parseStringArray = (value: unknown): string[] => Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []; const PATH_EDGE_KINDS: readonly QueryService.PathEdge['kind'][] = [ 'ref', 'incoming-ref', 'relation-source', 'relation-target', 'parent', 'child', ]; const isPathEdgeKind = (value: unknown): value is QueryService.PathEdge['kind'] => PATH_EDGE_KINDS.some((kind) => kind === value); type HopEdge = QueryService.PathEdge & { hop: number }; /** A compiled row's edges, or undefined past {@link MAX_EDGES_PER_ROW}, where the row's derivation is unknown. */ const parseEdges = (text: string): HopEdge[] | undefined => { const parsed: unknown = JSON.parse(text); if (!Array.isArray(parsed) || parsed.length > MAX_EDGES_PER_ROW) { return undefined; } return parsed.flatMap((raw: unknown): HopEdge[] => { if (typeof raw !== 'object' || raw === null) { return []; } const { hop, from, to, kind, property, holder, holderHeads } = Object.fromEntries(Object.entries(raw)); if ( typeof hop !== 'number' || typeof from !== 'string' || typeof to !== 'string' || typeof holder !== 'string' || !isPathEdgeKind(kind) ) { return []; } return [ { hop, from, to, kind, ...(typeof property === 'string' && { property }), holder, ...(Array.isArray(holderHeads) && { holderHeads: parseStringArray(holderHeads) }), }, ]; }); }; /** * The derivations of a row reached by a traversal chain, rebuilt from its edges by walking back from the * last hop to the first. Null when the edges were cut off or the derivations exceed * {@link MAX_PATHS_PER_ITEM}, as the in-memory traversal leaves such a derivation unknown. */ const pathsFromEdges = ( objectId: string, edges: readonly HopEdge[] | undefined, ): QueryService.PathEdge[][] | null | undefined => { if (edges === undefined) { return null; } const last = edges.reduce((max, edge) => Math.max(max, edge.hop), 0); if (last === 0) { return undefined; } const into = new Map(); for (const edge of edges) { const key = `${edge.hop}:${edge.to}`; into.set(key, [...(into.get(key) ?? []), edge]); } const paths = new Map(); let overflow = false; const walk = (hop: number, to: string, suffix: readonly QueryService.PathEdge[]): void => { for (const { hop: _hop, ...edge } of into.get(`${hop}:${to}`) ?? []) { if (overflow) { return; } const path = [edge, ...suffix]; if (hop > 1) { walk(hop - 1, edge.from, path); continue; } const key = path.map(({ from, to, kind, property }) => `${from}>${to}:${kind}:${property ?? ''}`).join('|'); if (!paths.has(key) && paths.size >= MAX_PATHS_PER_ITEM) { overflow = true; return; } paths.set(key, path); } }; walk(last, objectId, []); return overflow ? null : paths.size > 0 ? [...paths.values()] : undefined; }; /** A compiled collapsed group's members, each with its version and share of the scalar aggregates. */ const parseCompiledManifest = (text: string): QueryService.ManifestEntry[] => { const parsed: unknown = JSON.parse(text); if (!Array.isArray(parsed)) { return []; } return parsed.flatMap((raw: unknown): QueryService.ManifestEntry[] => { if (typeof raw !== 'object' || raw === null) { return []; } const { id, documentId, heads, position, contribution } = Object.fromEntries(Object.entries(raw)); if (typeof id !== 'string') { return []; } const version: QueryService.RowVersion | undefined = typeof documentId === 'string' && documentId !== '' && Array.isArray(heads) ? { kind: 'automerge', documentId, heads: parseStringArray(heads) } : typeof position === 'number' ? { kind: 'feed', insertionId: position } : undefined; return [{ id, ...(version && { version }), contribution: JSON.stringify(contribution ?? {}) }]; }); }; /** * Whether two working-set items would ship the same record, for reactive change detection. A * `SqlStep` item already carries its shipped form, so comparing that is comparing the record; an * item the steps built is compared on the fields `getResults` derives the record from. */ const _sameResult = (a: QueryItem, b: QueryItem): boolean => { // A client drops a hit by its paths and adjusts a group by its manifest, so stale evidence must be resent. if (evidenceKey(a) !== evidenceKey(b)) { return false; } if (a.result !== undefined || b.result !== undefined) { return ( a.result?.id === b.result?.id && a.result?.spaceId === b.result?.spaceId && a.result?.documentId === b.result?.documentId && a.result?.queueId === b.result?.queueId && a.result?.queueNamespace === b.result?.queueNamespace && a.result?.groupKey === b.result?.groupKey && a.result?.groupCount === b.result?.groupCount && a.result?.aggregates === b.result?.aggregates && a.result?.rank === b.result?.rank && // A feed row ships its indexed body, so an edit to it changes the record without moving the row. a.result?.documentJson === b.result?.documentJson ); } return ( a.objectId === b.objectId && a.spaceId === b.spaceId && a.documentId === b.documentId && a.queueId === b.queueId && a.queueNamespace === b.queueNamespace && // A feed item read from the store has no record yet; a new block for it moves its version. (a.queueId === null || (a.position === b.position && a.updatedAt === b.updatedAt)) && // A property edit can move an item between groups without changing its flat position // (e.g. the last item of group A becomes the first item of group B at the same index). _serializeOptionalGroupKey(a.groupKey) === _serializeOptionalGroupKey(b.groupKey) && // A collapsed group ships only its size and aggregates, so those are what can change. _serializeCollapsed(a) === _serializeCollapsed(b) ); }; const evidenceKey = (item: QueryItem): string => item.paths === undefined && item.manifest === undefined && !item.derivationUnknown ? '' : JSON.stringify([item.derivationUnknown ?? false, item.paths ?? null, item.manifest ?? null]); const STORED_CHANGES_CONCURRENCY = 16; type BackingSource = { json: string; heads: string[] }; const withoutBacking = ({ documentJson: _documentJson, heads: _heads, bytes: _bytes, createdAt: _createdAt, updatedAt: _updatedAt, ...row }: QueryService.QueryResult): QueryService.QueryResult => row; /** * Bytes of paths, or of manifests, one answer may carry: a mailbox-scale traversal would otherwise ship a * derivation DAG per hit, and the client retains every answer for the life of its subscription. */ const DERIVATION_BUDGET_BYTES = 256 * 1024; /** Whether the derivations of one answer fit {@link DERIVATION_BUDGET_BYTES}, measured as they encode. */ const withinBudget = (derivations: readonly (readonly unknown[] | undefined)[]): boolean => { let bytes = 0; for (const derivation of derivations) { if (derivation === undefined) { continue; } bytes += JSON.stringify(derivation).length; if (bytes > DERIVATION_BUDGET_BYTES) { return false; } } return true; }; /** One traversal hop, before it is attributed to the two items it joins. */ type TraversalEdge = { kind: QueryService.PathEdge['kind']; property?: string; holder: QueryItem }; /** Derivations kept per item: enough to revalidate a hit, bounded for a hub that every anchor reaches. */ const MAX_PATHS_PER_ITEM = 16; const itemKey = (item: QueryItem): string => `${item.spaceId}:${item.queueId ?? ''}:${item.objectId}`; const itemsById = (items: readonly QueryItem[]): Map => new Map(items.map((item) => [item.objectId, item])); const entityIdOf = (raw: string | null): EntityId | undefined => { const eid = raw ? EID.tryParse(raw) : undefined; return eid ? EID.getEntityId(eid) : undefined; }; /** * One item per object reached, carrying every derivation that reached it: each path of the item it was * reached from, extended by the hop. A derivation that cannot be stated, or one past the per-item bound, * leaves the item's derivation unknown, since a client that saw only some paths could drop a hit an * unlisted path still reaches. */ const mergeReached = ( reached: readonly { item: QueryItem; from: QueryItem; edge: TraversalEdge | undefined }[], ): QueryItem[] => { const merged = new Map; unknown: boolean }>(); for (const { item, from, edge } of reached) { const key = itemKey(item); let entry = merged.get(key); if (!entry) { entry = { item, paths: new Map(), unknown: false }; merged.set(key, entry); } if (!edge || from.derivationUnknown) { entry.unknown = true; continue; } const hop: QueryService.PathEdge = { from: from.objectId, to: item.objectId, kind: edge.kind, ...(edge.property !== undefined && { property: edge.property }), holder: edge.holder.objectId, ...(edge.holder.heads && { holderHeads: [...edge.holder.heads] }), }; for (const prefix of from.paths ?? [[]]) { const path = [...prefix, hop]; const pathKey = path.map(({ from, to, kind, property }) => `${from}>${to}:${kind}:${property ?? ''}`).join('|'); if (!entry.paths.has(pathKey) && entry.paths.size >= MAX_PATHS_PER_ITEM) { entry.unknown = true; break; } entry.paths.set(pathKey, path); } } return [...merged.values()].map(({ item, paths, unknown }) => unknown ? { ...item, paths: undefined, derivationUnknown: true } : { ...item, paths: [...paths.values()] }, ); }; /** * Attaches to each collapsed group the members it stands for, each with its share of the group's scalar * aggregates, so a client holding a member can swap the share for its local value. A group built from bare * index rows, whose values were never read, ships without one. */ const withManifests = ( collapsed: readonly QueryItem[], members: readonly QueryItem[], aggregates: readonly QueryAST.GroupAggregate[], ): QueryItem[] => { const scalar = aggregates.filter( (aggregate): aggregate is Extract => aggregate.kind === 'count' || aggregate.kind === 'sum' || aggregate.kind === 'min' || aggregate.kind === 'max', ); // A count needs no member values, so a group of bare index rows can still list its members. const readsValues = scalar.some((aggregate) => aggregate.kind !== 'count'); if (scalar.length === 0 || (readsValues && members.some((member) => !member.doc && !member.data))) { return [...collapsed]; } const byGroup = new Map(); for (const member of members) { const key = serializeItemGroupKey(member); const contribution: Record = {}; for (const aggregate of scalar) { contribution[aggregate.name] = aggregate.kind === 'count' ? 1 : GroupBy.coerceKeyComponent(QueryItem.getAggregateProperty(member, aggregate.property)); } const version = QueryItem.getVersion(member); const list = byGroup.get(key) ?? []; list.push({ id: member.objectId, ...(version && { version }), contribution: JSON.stringify(contribution) }); byGroup.set(key, list); } return collapsed.map((item) => ({ ...item, manifest: byGroup.get(serializeItemGroupKey(item)) })); };