{"version":3,"file":"chunk-query-planner.mjs","names":["__dxlog_file"],"sources":["../../src/query/group-by.ts","../../src/query/errors.ts","../../src/query/plan.ts","../../src/query/query-planner.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\nimport { QueryAST } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\n\nconst { isGroupKeyAggregate } = QueryAST;\n\n/**\n * A (possibly composite) group key: one coerced scalar component per grouped property.\n * Missing/undefined/non-scalar property values coerce to `null`.\n */\nexport type GroupKeyValue = Record<string, string | number | boolean | null>;\n\n/** Scalar result of a `max`/`min` aggregate (`null` when the group has no scalar values). */\nexport type AggregateValue = string | number | boolean | null;\n\n/** Named aggregate values computed for one group, keyed by the aggregate's result name. */\nexport type GroupAggregates = Record<string, AggregateValue>;\n\n/**\n * Execution helpers for the `aggregate` query clause, shared by the host `QueryExecutor` and the\n * client `WorkingSetQueryExecutor`. The clause itself is declared in `QueryPlan.AggregateStep`; this\n * module holds the runtime grouping/pagination algorithms that the executors apply.\n */\nconst HOUR_MS = 3_600_000;\n\nconst DAY_MS = 86_400_000;\n\n/**\n * Code-unit order, the collation SQLite's `BINARY` applies. Both executors order strings through\n * this so a compiled plan and an in-memory one return the same rows — under `limit` the collation\n * decides which rows are cut, not just their order.\n */\nexport const compareCodeUnits = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nexport const GroupBy = Object.freeze({\n  /**\n   * The start of the UTC hour or day a unix-ms `value` falls in, or `null` when it is not a finite\n   * number: the key of a `timestamp` or `time` aggregate.\n   */\n  truncateTime: (value: unknown, unit: 'hour' | 'day'): number | null => {\n    if (typeof value !== 'number' || !Number.isFinite(value)) {\n      return null;\n    }\n    const size = unit === 'hour' ? HOUR_MS : DAY_MS;\n    return Math.floor(value / size) * size;\n  },\n\n  /**\n   * Coerces a raw property value into a group-key component.\n   * `typeof value` must be `string`, `number`, or `boolean`; anything else (missing,\n   * `undefined`, `null`, objects, arrays, refs) collapses to `null`.\n   */\n  coerceKeyComponent: (value: unknown): string | number | boolean | null =>\n    typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? value : null,\n\n  /**\n   * Resolves one `group` entry's key component from its fallback chain: the first property with a\n   * scalar value wins (`a ?? b`), `null` when none do. Shared by both executors and the aggregate\n   * stamping below so a group's key and its result field can never disagree.\n   */\n  resolveKeyComponent: (\n    properties: readonly string[],\n    getValue: (property: string) => unknown,\n  ): string | number | boolean | null => {\n    for (const property of properties) {\n      const value = GroupBy.coerceKeyComponent(getValue(property));\n      if (value !== null) {\n        return value;\n      }\n    }\n    return null;\n  },\n\n  /**\n   * Stable serialization of a composite group key (component order matters).\n   * Used for wire encoding, group identity, and synthetic entry ids.\n   */\n  serializeGroupKey: (key: GroupKeyValue): string => JSON.stringify(key),\n\n  /**\n   * Partitions `items` into contiguous groups by `getKey`, preserving relative order within\n   * each group. Groups are ordered by the first occurrence of their key in `items`.\n   */\n  partitionByGroupKey: <T>(items: readonly T[], getKey: (item: T) => string): T[] => {\n    const buckets = new Map<string, T[]>();\n    for (const item of items) {\n      const key = getKey(item);\n      let bucket = buckets.get(key);\n      if (!bucket) {\n        bucket = [];\n        buckets.set(key, bucket);\n      }\n      bucket.push(item);\n    }\n\n    return Array.from(buckets.values()).flat();\n  },\n\n  /**\n   * Returns the items belonging to the first `count` distinct groups (group-level limit).\n   * Assumes `items` are already partitioned into contiguous groups (see {@link partitionByGroupKey}).\n   */\n  takeGroups: <T>(items: readonly T[], count: number, getKey: (item: T) => string): T[] => {\n    if (count <= 0) {\n      return [];\n    }\n    const result: T[] = [];\n    let seenGroups = 0;\n    let currentKey: string | undefined;\n    for (const item of items) {\n      const key = getKey(item);\n      if (key !== currentKey) {\n        seenGroups += 1;\n        currentKey = key;\n        if (seenGroups > count) {\n          break;\n        }\n      }\n      result.push(item);\n    }\n    return result;\n  },\n\n  /**\n   * Returns the items after dropping the first `count` distinct groups (group-level skip).\n   * Assumes `items` are already partitioned into contiguous groups (see {@link partitionByGroupKey}).\n   */\n  dropGroups: <T>(items: readonly T[], count: number, getKey: (item: T) => string): T[] => {\n    if (count <= 0) {\n      return items.slice();\n    }\n    let seenGroups = 0;\n    let currentKey: string | undefined;\n    for (let index = 0; index < items.length; index++) {\n      const key = getKey(items[index]);\n      if (key !== currentKey) {\n        seenGroups += 1;\n        currentKey = key;\n        if (seenGroups > count) {\n          return items.slice(index);\n        }\n      }\n    }\n    return [];\n  },\n\n  /**\n   * Compares two scalar aggregate/property values. `null` sorts last (largest), mirroring the\n   * executors' own property comparison so aggregate ordering is consistent with member ordering.\n   */\n  compareScalar: (a: AggregateValue, b: AggregateValue): number => {\n    if (a == null && b == null) {\n      return 0;\n    }\n    if (a == null) {\n      return 1;\n    }\n    if (b == null) {\n      return -1;\n    }\n    if (typeof a === 'string' && typeof b === 'string') {\n      return compareCodeUnits(a, b);\n    }\n    if (typeof a === 'number' && typeof b === 'number') {\n      return a - b;\n    }\n    if (typeof a === 'boolean' && typeof b === 'boolean') {\n      return a === b ? 0 : a ? 1 : -1;\n    }\n    return compareCodeUnits(String(a), String(b));\n  },\n\n  /** Members a group stands for: an item carrying a `weight` (an index bucket) counts that many times. */\n  countMembers: (members: readonly { weight?: number }[]): number =>\n    members.reduce((total, member) => total + (member.weight ?? 1), 0),\n\n  /** Adds the numeric values of a `sum` aggregate; anything else counts as 0. */\n  sum: (values: readonly unknown[]): number =>\n    values.reduce<number>(\n      (total, value) => (typeof value === 'number' && Number.isFinite(value) ? total + value : total),\n      0,\n    ),\n\n  /**\n   * Reduces a group's member values under a `max`/`min` aggregate. Ignores `null`s (values missing\n   * or non-scalar); a group with no scalar values yields `null`.\n   */\n  reduceAggregate: (values: readonly AggregateValue[], kind: 'max' | 'min'): AggregateValue => {\n    let result: AggregateValue = null;\n    for (const value of values) {\n      if (value == null) {\n        continue;\n      }\n      if (result == null) {\n        result = value;\n        continue;\n      }\n      const comparison = GroupBy.compareScalar(value, result);\n      if ((kind === 'max' && comparison > 0) || (kind === 'min' && comparison < 0)) {\n        result = value;\n      }\n    }\n    return result;\n  },\n\n  /**\n   * Computes each group's scalar aggregates (`group`/`max`/`min`/`count`) and returns the same items\n   * with those values stamped on every member (all members of a group share them), so a following\n   * group-level `OrderStep` can order by them — including by a `group` field whose result name differs\n   * from its source property. Assumes `items` are already partitioned into contiguous groups\n   * (see {@link partitionByGroupKey}).\n   *\n   * If an `items`-kind aggregate declares its own `order`, each group's members are stably\n   * re-sorted by it (via `compareByOrder`) before scalar aggregates are stamped — this ordering is\n   * local to that aggregate's member selection, independent of whatever order the input stream\n   * arrived in. `items` itself is not stamped: it is materialised (and capped to `limit`) at result\n   * assembly, from the (possibly now re-sorted) member order this function returns.\n   *\n   * All members of a group share a single member order, so at most one distinct `order` may be\n   * requested across the group's `items`-kind aggregates — two conflicting orders are rejected\n   * rather than silently honoring only one of them.\n   */\n  withGroupAggregates: <T extends { groupKey?: GroupKeyValue; aggregates?: GroupAggregates; weight?: number }>(\n    items: readonly T[],\n    getKey: (item: T) => string,\n    aggregates: readonly QueryAST.GroupAggregate[],\n    getProperty: (item: T, property: string) => unknown,\n    compareByOrder?: (a: T, b: T, order: QueryAST.Order) => number,\n  ): T[] => {\n    const itemsOrders = aggregates.flatMap((aggregate) =>\n      aggregate.kind === 'items' && aggregate.order?.length ? [aggregate.order] : [],\n    );\n    if (itemsOrders.length > 1) {\n      const serialized = new Set(itemsOrders.map((order) => JSON.stringify(order)));\n      invariant(serialized.size === 1, 'Multiple `items` aggregates with different `order`s are not supported.');\n    }\n    const itemsOrder = itemsOrders[0];\n    const needsStamping = aggregates.some((aggregate) => aggregate.kind !== 'items');\n    // Only group/max/min/count are stamped for ordering; `items` collects members at result assembly.\n    if (!needsStamping && !itemsOrder) {\n      return items.slice();\n    }\n    const result: T[] = [];\n    let index = 0;\n    while (index < items.length) {\n      const key = getKey(items[index]);\n      let end = index;\n      while (end < items.length && getKey(items[end]) === key) {\n        end += 1;\n      }\n      const members = items.slice(index, end);\n      if (itemsOrder && compareByOrder) {\n        members.sort((a, b) => {\n          for (const order of itemsOrder) {\n            const comparison = compareByOrder(a, b, order);\n            if (comparison !== 0) {\n              return comparison;\n            }\n          }\n          return 0;\n        });\n      }\n      if (!needsStamping) {\n        result.push(...members);\n        index = end;\n        continue;\n      }\n      const computed: GroupAggregates = {};\n      for (const aggregate of aggregates) {\n        if (aggregate.kind === 'items') {\n          continue;\n        }\n        computed[aggregate.name] =\n          aggregate.kind === 'count'\n            ? GroupBy.countMembers(members)\n            : aggregate.kind === 'sum'\n              ? GroupBy.sum(members.map((member) => getProperty(member, aggregate.property)))\n              : isGroupKeyAggregate(aggregate)\n                ? // All members of a group share the key, so read the component off any member.\n                  (members[0].groupKey?.[aggregate.name] ?? null)\n                : GroupBy.reduceAggregate(\n                    members.map((member) => coerceScalar(getProperty(member, aggregate.property))),\n                    aggregate.kind,\n                  );\n      }\n      for (const member of members) {\n        result.push({ ...member, aggregates: computed });\n      }\n      index = end;\n    }\n    return result;\n  },\n\n  /**\n   * Keeps one member per group as its stand-in, recording the group size. Used when the query asks\n   * for no members, so nothing downstream has to carry or ship the objects.\n   * Assumes `items` are already partitioned into contiguous groups (see {@link partitionByGroupKey}).\n   */\n  collapseGroups: <T extends { collapsed?: { size: number }; weight?: number }>(\n    items: readonly T[],\n    getKey: (item: T) => string,\n  ): T[] => {\n    const result: T[] = [];\n    let index = 0;\n    while (index < items.length) {\n      const key = getKey(items[index]);\n      let end = index;\n      while (end < items.length && getKey(items[end]) === key) {\n        end += 1;\n      }\n      result.push({ ...items[index], collapsed: { size: GroupBy.countMembers(items.slice(index, end)) } });\n      index = end;\n    }\n    return result;\n  },\n\n  /**\n   * Reorders whole groups by `compareGroups` (applied to each group's first member, since all\n   * members share the group's key/aggregates), preserving within-group order and contiguity.\n   * Stable: groups comparing equal keep their incoming relative order. Assumes `items` are already\n   * partitioned into contiguous groups (see {@link partitionByGroupKey}).\n   */\n  orderGroups: <T>(items: readonly T[], getKey: (item: T) => string, compareGroups: (a: T, b: T) => number): T[] => {\n    const groups: T[][] = [];\n    let currentKey: string | undefined;\n    for (const item of items) {\n      const key = getKey(item);\n      if (groups.length === 0 || key !== currentKey) {\n        groups.push([]);\n        currentKey = key;\n      }\n      groups[groups.length - 1].push(item);\n    }\n    return groups\n      .map((group, index) => ({ group, index }))\n      .sort((a, b) => {\n        const comparison = compareGroups(a.group[0], b.group[0]);\n        return comparison !== 0 ? comparison : a.index - b.index;\n      })\n      .flatMap(({ group }) => group);\n  },\n});\n\n/** Coerces a raw property value to the scalar aggregate domain (non-scalars → `null`). */\nconst coerceScalar = (value: unknown): AggregateValue =>\n  typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? value : null;\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\nexport class QueryError extends BaseError.extend('QueryError') {}\n\nexport class InvalidQueryError extends QueryError.extend('InvalidQueryError') {}\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type { EscapedPropPath, QueryAST } from '@dxos/echo-protocol';\nimport type { EID, EntityId, URI } from '@dxos/keys';\n\nexport namespace QueryPlan {\n  export type TextSearchKind = 'full-text' | 'vector' | 'hybrid';\n\n  /**\n   * A series of linear steps to execute a query.\n   * Steps can potentially contain sub-plans in case of unions.\n   *\n   * The query executor will execute each step in sequence.\n   * The plans start with a select step, which adds objects to the current working set.\n   * Then the next steps will act on the current working set, preforming filters, traversals, etc.\n   */\n  export type Plan = {\n    steps: Step[];\n  };\n\n  export const Plan = Object.freeze({\n    make: (steps: Step[]): Plan => ({ steps }),\n  });\n\n  export type Step =\n    | ClearWorkingSetStep\n    | SelectStep\n    | FilterStep\n    | FilterDeletedStep\n    | TraverseStep\n    | UnionStep\n    | SetDifferenceStep\n    | OrderStep\n    | LimitStep\n    | SkipStep\n    | AggregateStep\n    | SqlStep;\n\n  /**\n   * A contiguous run of steps compiled into a single SQLite statement over the index tables.\n   * Emitted by `SqlPlanCompiler` in place of the steps it stands for, so the compiled path runs a\n   * plan like any other rather than a separate execution mode.\n   */\n  export type SqlStep = {\n    _tag: 'SqlStep';\n    /** Statement text with placeholders. */\n    sql: string;\n    /** Values bound to the statement's placeholders, in order. */\n    params: readonly unknown[];\n    /** The steps the statement stands for, kept so traces and scope analysis still see them. */\n    steps: readonly Step[];\n  };\n\n  /**\n   * Clear the current working set.\n   */\n  export type ClearWorkingSetStep = {\n    _tag: 'ClearWorkingSetStep';\n  };\n\n  /**\n   * Select objects based on id, typename, or other predicates.\n   * Specifies the spaces and/or queues to select from.\n   * The results from spaces and queues are unioned together.\n   */\n  export type SelectStep = {\n    _tag: 'SelectStep';\n\n    /**\n     * What to select from the scope.\n     */\n    selector: Selector;\n\n    /**\n     * Where to select from.\n     */\n    scope: readonly QueryAST.Scope[];\n\n    /**\n     * Optional limit on the number of results to select.\n     * When set, the index scan can be optimized to stop early.\n     */\n    limit?: number;\n\n    /**\n     * Cursor range from a `feed-cursor` filter, both bounds exclusive. The scan returns only blocks\n     * positioned inside it, in position order, so resuming a feed costs what is new rather than the\n     * whole feed. Present (possibly with no bounds set) whenever the filter was, since a cursor read\n     * covers positioned blocks only.\n     */\n    feedCursorRange?: { begin?: string; end?: string; positions?: 'local' | 'edge' };\n\n    /**\n     * Set when the planner has proved the step's {@link limit} can be applied by the feed scan\n     * itself — see `feedScanForLimit`. Absent means the limit must be applied downstream, after the\n     * steps that would otherwise slice candidates out of an already-capped page.\n     */\n    feedScan?: FeedScan;\n\n    /**\n     * Build bare items from index rows, carrying no document. Set by the planner only when no later\n     * step reads anything but index fields: type, timestamps, deletion, parent and relation endpoints.\n     */\n    bare?: boolean;\n  };\n\n  /**\n   * How a feed scan must run for a `limit` pushed into it to keep the same rows the unpushed plan\n   * would have returned.\n   */\n  export type FeedScan = {\n    /** Natural order the scan produces, matching the plan's `OrderStep`. */\n    direction: 'asc' | 'desc';\n\n    /** Deleted state the scan filters to, folding in the plan's `FilterDeletedStep`. */\n    deleted?: boolean;\n\n    /** Rows the scan drops ahead of the step's `limit`, folding in the plan's `SkipStep`s. */\n    skip?: number;\n  };\n\n  /**\n   * Specifier to scan the database for objects.\n   * Optimized to utilize database indexes.\n   */\n  export type Selector =\n    | WildcardSelector\n    | IdSelector\n    | TypeSelector\n    | TextSelector\n    | TimestampSelector\n    | IncomingReferenceSelector\n    | ChangesSelector;\n\n  /**\n   * Select Automerge changes (`Filter.changes`) rather than objects. The working set holds change\n   * records, so only ordering, paging and aggregation may follow.\n   */\n  export type ChangesSelector = {\n    _tag: 'ChangesSelector';\n\n    /** Entities whose documents to read; every document in scope when absent. */\n    targets?: readonly EID.EID[];\n\n    /**\n     * `index` reads hourly buckets from the activity index, valid only for the aggregates it can\n     * answer; `replay` lists each target document's change history.\n     */\n    source: 'index' | 'replay';\n  };\n\n  export type WildcardSelector = {\n    _tag: 'WildcardSelector';\n  };\n\n  export type IdSelector = {\n    _tag: 'IdSelector';\n\n    objectIds: readonly EntityId[];\n  };\n\n  /**\n   * Select objects by typename.\n   * Supports passing an array of typenames and an optional inverse flag to optimize for index implementation.\n   */\n  export type TypeSelector = {\n    _tag: 'TypeSelector';\n\n    typename: URI.URI[];\n    /**\n     * If true, select objects that do not match the typename.\n     */\n    inverted: boolean;\n  };\n\n  /**\n   * Select the objects holding a reference to `targetDXN`, straight off the reverse-reference index.\n   *\n   * Unlike an incoming {@link ReferenceTraversal} this needs no anchor in the working set, so it can\n   * name an entity that is absent from the graph — a named entity, or one a migration has renamed away.\n   */\n  export type IncomingReferenceSelector = {\n    _tag: 'IncomingReferenceSelector';\n\n    targetDXN: URI.URI;\n\n    /**\n     * Property path where the reference is located; null matches any property.\n     */\n    property: EscapedPropPath | null;\n  };\n\n  /**\n   * Select objects by preforming a full-text or vector search.\n   */\n  export type TextSelector = {\n    _tag: 'TextSelector';\n\n    text: string;\n    searchKind: TextSearchKind;\n\n    /**\n     * Optionally select only objects of the given typenames.\n     */\n    typename: URI.URI[] | null;\n  };\n\n  /**\n   * Select objects by timestamp range (createdAt / updatedAt).\n   * Uses the EntityMetaIndex timestamp columns.\n   */\n  export type TimestampSelector = {\n    _tag: 'TimestampSelector';\n\n    updatedAfter?: number;\n    updatedBefore?: number;\n    createdAfter?: number;\n    createdBefore?: number;\n  };\n\n  /**\n   * Filter objects in the current working set based on a predicate.\n   */\n  export type FilterStep = {\n    _tag: 'FilterStep';\n\n    filter: QueryAST.Filter;\n  };\n\n  export const FilterStep = Object.freeze({\n    isNoop: (step: FilterStep): boolean => {\n      switch (step.filter.type) {\n        case 'object': {\n          // TODO(dmaretskyi): This is error-prone, it could easily break if we add more clauses.\n          return (\n            step.filter.typename === null &&\n            (step.filter.id === undefined || step.filter.id.length === 0) &&\n            (step.filter.props === undefined || Object.keys(step.filter.props).length === 0) &&\n            (step.filter.foreignKeys === undefined || step.filter.foreignKeys.length === 0) &&\n            step.filter.metaKey === undefined\n          );\n        }\n        default:\n          return false;\n      }\n    },\n  });\n\n  /**\n   * Filter objects in the current working set based on the deleted state.\n   */\n  export type FilterDeletedStep = {\n    _tag: 'FilterDeletedStep';\n\n    mode: 'only-deleted' | 'only-non-deleted';\n  };\n\n  /**\n   * Traverse the object graph, starting from objects in the current working set.\n   */\n  export type TraverseStep = {\n    _tag: 'TraverseStep';\n\n    traversal: Traversal;\n  };\n\n  /**\n   * Describes a traversal of the object graph.\n   */\n  export type Traversal = ReferenceTraversal | RelationTraversal | HierarchyTraversal;\n\n  /**\n   * Traverse a reference connection.\n   */\n  export type ReferenceTraversal = {\n    _tag: 'ReferenceTraversal';\n\n    /**\n     * Property path where the reference is located.\n     * If null, matches references from any property (only valid for incoming direction).\n     */\n    property: EscapedPropPath | null;\n\n    /**\n     * outgoing: the reference points from the anchor object to the target.\n     * incoming: the reference points to the anchor object from the target.\n     */\n    direction: 'outgoing' | 'incoming';\n  };\n\n  /**\n   * Traverse a relation.\n   */\n  export type RelationTraversal = {\n    _tag: 'RelationTraversal';\n\n    /**\n     * The direction of the traversal.\n     * There are for variants since each relation has two connectors (source & target) and there are two directions to traverse each.\n     */\n    direction: 'source-to-relation' | 'relation-to-source' | 'target-to-relation' | 'relation-to-target';\n  };\n\n  /**\n   * Traverse parent-child hierarchy.\n   */\n  export type HierarchyTraversal = {\n    _tag: 'HierarchyTraversal';\n\n    /**\n     * to-parent: traverse from child to parent.\n     * to-children: traverse from parent to children.\n     */\n    direction: 'to-parent' | 'to-children';\n  };\n\n  /**\n   * Combine results from multiple plans.\n   * Each of the plans starts with a copy of the current working set.\n   * This supports plans where we first perform a selection, then traverse in different directions, and then combine the results.\n   */\n  export type UnionStep = {\n    _tag: 'UnionStep';\n\n    plans: Plan[];\n  };\n\n  /**\n   * Subtract the results of one plan from another.\n   */\n  export type SetDifferenceStep = {\n    _tag: 'SetDifferenceStep';\n\n    source: Plan;\n    exclude: Plan;\n  };\n\n  /**\n   * Order the results of the plan.\n   */\n  export type OrderStep = {\n    _tag: 'OrderStep';\n\n    // Defaults to natural order if empty.\n    order: readonly QueryAST.Order[];\n\n    /**\n     * Optional limit on the number of results to return after ordering.\n     * When set, the sorting can be optimized to only track the top N elements.\n     */\n    // TODO(dmaretskyi): Remove. This doesn't belong here.\n    limit?: number;\n  };\n\n  /**\n   * Limit the number of results.\n   */\n  export type LimitStep = {\n    _tag: 'LimitStep';\n\n    limit: number;\n  };\n\n  /**\n   * Skip a number of results (offset).\n   */\n  export type SkipStep = {\n    _tag: 'SkipStep';\n\n    skip: number;\n  };\n\n  /**\n   * Aggregate the working set. `group`-kind entries partition it into contiguous groups by scalar\n   * property values (with none, the whole set forms one group), ordered by the first occurrence of\n   * their key in the incoming (already-ordered) working set — this lets a preceding `OrderStep` also\n   * control group order. Non-`group` aggregates are stamped on each member so a following group-level\n   * `OrderStep` can order by them.\n   *\n   * The runtime grouping/pagination algorithms live in `./group-by` (executor-side), not here.\n   */\n  export type AggregateStep = {\n    _tag: 'AggregateStep';\n\n    /** Aggregate declarations; `group`-kind entries define the grouping keys. */\n    aggregates: readonly QueryAST.GroupAggregate[];\n  };\n}\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { Order, Query } from '@dxos/echo';\nimport { QueryAST } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { DXN, type URI } from '@dxos/keys';\n\nimport { QueryError } from './errors.ts';\nimport { QueryPlan } from './plan.ts';\n\n/**\n * Creates a QueryError with \"Query too complex\" message and includes the prettified query in the context.\n */\nconst queryTooComplexError = (query: QueryAST.Query | null): QueryError => {\n  if (query === null) {\n    return new QueryError({\n      message: 'Query too complex',\n      context: { query: null },\n    });\n  }\n  const prettyQuery = Query.pretty(Query.fromAst(query));\n  return new QueryError({\n    message: `Query too complex: ${prettyQuery}`,\n    context: { query, prettyQuery },\n  });\n};\n\nexport type QueryPlannerOptions = {\n  defaultTextSearchKind: QueryPlan.TextSearchKind;\n  /**\n   * When true, downgrade index-backed selectors to WildcardSelector + FilterStep.\n   * Use when executing against an in-memory working set without SQL index access.\n   * TextSelector and TimestampSelector remain as-is so the caller can detect them and bail.\n   */\n  noIndexes?: boolean;\n};\n\nconst DEFAULT_OPTIONS: QueryPlannerOptions = {\n  defaultTextSearchKind: 'full-text',\n};\n\n/**\n * Constructs an optimized query plan.\n */\n// TODO(dmaretskyi): Implement inefficient versions of complex queries.\nexport class QueryPlanner {\n  private readonly _options: QueryPlannerOptions;\n\n  constructor(options?: Partial<QueryPlannerOptions>) {\n    this._options = {\n      ...DEFAULT_OPTIONS,\n      ...options,\n    };\n  }\n\n  /** The uncompiled steps. Pure, so the SQL compiler recurses through it for `in-query` subqueries. */\n  createPlan(query: QueryAST.Query): QueryPlan.Plan {\n    this._validateQueryScoped(query);\n    this._validateAggregatePlacement(query);\n    const selectsChanges = queryContainsChanges(query);\n    if (selectsChanges) {\n      this._validateChangesFilters(query);\n    }\n    let plan = this._generate(query, { ...DEFAULT_CONTEXT, originalQuery: query });\n    plan = this._optimizeEmptyFilters(plan);\n    plan = this._optimizeSoloUnions(plan);\n    plan = this._ensureOrderStep(plan);\n    if (selectsChanges) {\n      return this._routeChanges(plan, query);\n    }\n    plan = this._optimizeLimits(plan);\n    plan = this._optimizeBareAggregate(plan);\n    return plan;\n  }\n\n  private _validateChangesFilters(query: QueryAST.Query): void {\n    QueryAST.visit(query, (node) => {\n      if (\n        (node.type === 'filter' && filterContainsChanges(node.filter)) ||\n        (node.type === 'select' && node.filter.type !== 'changes' && filterContainsChanges(node.filter))\n      ) {\n        throw new QueryError({\n          message: 'Filter.changes() cannot be combined with other filters, traversals or unions.',\n          context: { query: Query.pretty(Query.fromAst(query)) },\n        });\n      }\n    });\n  }\n\n  private _routeChanges(plan: QueryPlan.Plan, query: QueryAST.Query): QueryPlan.Plan {\n    const fail = (message: string): never => {\n      throw new QueryError({ message, context: { query: Query.pretty(Query.fromAst(query)) } });\n    };\n    const [select, ...rest] = plan.steps;\n    if (select?._tag !== 'SelectStep' || select.selector._tag !== 'ChangesSelector') {\n      return fail('Filter.changes() cannot be combined with other filters, traversals or unions.');\n    }\n    if (!select.scope.every((scope) => scope._tag === 'space')) {\n      return fail('Filter.changes() selects from spaces, not feeds.');\n    }\n    for (const step of rest) {\n      switch (step._tag) {\n        case 'LimitStep':\n        case 'SkipStep':\n          break;\n        case 'OrderStep':\n          if (!step.order.every((order) => order.kind === 'natural' || order.kind === 'property')) {\n            return fail('Changes can only be ordered by a property or naturally (by time).');\n          }\n          break;\n        case 'AggregateStep': {\n          const unsupported = step.aggregates.find(\n            (aggregate) => aggregate.kind === 'items' || aggregate.kind === 'type' || aggregate.kind === 'timestamp',\n          );\n          if (unsupported) {\n            const name =\n              unsupported.kind === 'timestamp'\n                ? unsupported.field === 'updatedAt'\n                  ? 'updated'\n                  : 'created'\n                : unsupported.kind;\n            return fail(`Aggregate.${name}() does not apply to changes.`);\n          }\n          break;\n        }\n        default:\n          return fail('Filter.changes() cannot be combined with other filters, traversals or unions.');\n      }\n    }\n\n    const indexAnswers = activityIndexAnswers(rest);\n    if (!indexAnswers && select.selector.targets === undefined) {\n      return fail(\n        \"A space-wide Filter.changes() query must aggregate with only Aggregate.time('time', …), \" +\n          \"Aggregate.group('source'), Aggregate.count() and Aggregate.sum('ops'); pass targets to Filter.changes() \" +\n          'for anything else.',\n      );\n    }\n    return QueryPlan.Plan.make([\n      { ...select, selector: { ...select.selector, source: indexAnswers ? 'index' : 'replay' } },\n      ...rest,\n    ]);\n  }\n\n  /**\n   * Marks the select of a plan that only counts objects by index fields as {@link QueryPlan.SelectStep.bare},\n   * so the executor groups index rows instead of loading documents. Eligible shape: a space-scoped\n   * wildcard, type or timestamp select, then deleted handling, a plain typename re-check and natural\n   * ordering in any order, ending in an aggregate of `count`, `type` and `timestamp` only.\n   */\n  private _optimizeBareAggregate(plan: QueryPlan.Plan): QueryPlan.Plan {\n    if (this._options.noIndexes) {\n      return plan;\n    }\n    const [select, ...rest] = plan.steps;\n    const aggregate = rest.at(-1);\n    if (\n      select?._tag !== 'SelectStep' ||\n      aggregate?._tag !== 'AggregateStep' ||\n      select.limit !== undefined ||\n      select.feedCursorRange !== undefined ||\n      !select.scope.every((scope) => scope._tag === 'space' && !scope.includeAllFeeds) ||\n      (select.selector._tag !== 'WildcardSelector' &&\n        select.selector._tag !== 'TimestampSelector' &&\n        (select.selector._tag !== 'TypeSelector' || select.selector.inverted)) ||\n      !aggregate.aggregates.every(\n        (entry) => entry.kind === 'count' || entry.kind === 'type' || entry.kind === 'timestamp',\n      )\n    ) {\n      return plan;\n    }\n    const readsOnlyIndexFields = rest.slice(0, -1).every(\n      (step) =>\n        step._tag === 'FilterDeletedStep' ||\n        // A metadata predicate reads keys an index row does not carry, so it has to load documents.\n        (step._tag === 'FilterStep' &&\n          isTrivialTypenameFilter(step.filter) &&\n          step.filter.type === 'object' &&\n          step.filter.metaKey === undefined) ||\n        (step._tag === 'OrderStep' &&\n          step.limit === undefined &&\n          step.order.every((order) => order.kind === 'natural')),\n    );\n    if (!readsOnlyIndexFields) {\n      return plan;\n    }\n    return QueryPlan.Plan.make([{ ...select, bare: true }, ...rest]);\n  }\n\n  private _generate(query: QueryAST.Query, context: GenerationContext): QueryPlan.Plan {\n    switch (query.type) {\n      case 'options':\n        return this._generateOptionsClause(query, context);\n      case 'select':\n        return this._generateSelectClause(query, context);\n      case 'filter':\n        return this._generateFilterClause(query, context);\n      case 'incoming-references':\n        return this._generateIncomingReferencesClause(query, context);\n      case 'relation':\n        return this._generateRelationClause(query, context);\n      case 'relation-traversal':\n        return this._generateRelationTraversalClause(query, context);\n      case 'reference-traversal':\n        return this._generateReferenceTraversalClause(query, context);\n      case 'hierarchy-traversal':\n        return this._generateHierarchyTraversalClause(query, context);\n      case 'union':\n        return this._generateUnionClause(query, context);\n      case 'set-difference':\n        return this._generateSetDifferenceClause(query, context);\n      case 'order':\n        return this._generateOrderClause(query, context);\n      case 'limit':\n        return this._generateLimitClause(query, context);\n      case 'skip':\n        return this._generateSkipClause(query, context);\n      case 'aggregate':\n        return this._generateAggregateClause(query, context);\n      case 'from':\n        return this._generateFromClause(query, context);\n      default:\n        throw new QueryError({\n          message: `Unsupported query type: ${(query as any).type}`,\n          context: { query: context.originalQuery },\n        });\n    }\n  }\n\n  private _generateOptionsClause(query: QueryAST.QueryOptionsClause, context: GenerationContext): QueryPlan.Plan {\n    const newContext = {\n      ...context,\n    };\n    if (query.options.deleted) {\n      newContext.deletedHandling = query.options.deleted;\n    }\n    return this._generate(query.query, newContext);\n  }\n\n  private _generateFromClause(query: QueryAST.QueryFromClause, context: GenerationContext): QueryPlan.Plan {\n    if (query.from._tag === 'scope') {\n      return this._generate(query.query, { ...context, scope: query.from.scopes });\n    }\n\n    // Subquery from: flatten by rewriting the outer query's leaf select into a filter on the subquery.\n    const subquery = query.from.query;\n    const rewritten = QueryAST.map(query.query, (node) =>\n      node.type === 'select' ? { type: 'filter', selection: subquery, filter: node.filter } : node,\n    );\n    return this._generate(rewritten, context);\n  }\n\n  private _generateSelectClause(query: QueryAST.QuerySelectClause, context: GenerationContext): QueryPlan.Plan {\n    return this._generateSelectionFromFilter(query.filter, context);\n  }\n\n  // TODO(dmaretskyi): This can be rewritten as a function of (filter[]) -> (selection ? undefined, rest: filter[]) that recurses onto itself.\n  // TODO(dmaretskyi): If the tip of the query ast is a [select, ...filter] shape we can reorder the filters so the query is most efficient.\n  private _generateSelectionFromFilter(filter: QueryAST.Filter, context: GenerationContext): QueryPlan.Plan {\n    // A feed cursor bounds the scan rather than describing an object, so it is lifted out of the\n    // filter tree and onto the select step it bounds; what remains plans exactly as it would\n    // without it.\n    const { range, rest } = _splitFeedCursor(filter, context);\n    if (range !== undefined) {\n      // Checked here rather than where the bound is applied, so the start sentinel — which bounds\n      // nothing and so reaches no window — is refused over a space's documents just the same. An\n      // automerge object has no position for any cursor to name.\n      if (!context.scope.every((scope) => scope._tag === 'feed')) {\n        throw new QueryError({\n          message: 'A feed cursor filter can only be used with a feed scope.',\n          context: { query: context.originalQuery },\n        });\n      }\n      const plan = this._generateSelectionFromFilter(rest ?? { type: 'object', typename: null, props: {} }, context);\n      const selectIdx = plan.steps.findIndex((step) => step._tag === 'SelectStep');\n      invariant(selectIdx !== -1, 'expected a select step to bound');\n      const steps = [...plan.steps];\n      steps[selectIdx] = { ...(steps[selectIdx] as QueryPlan.SelectStep), feedCursorRange: range };\n      return QueryPlan.Plan.make(steps);\n    }\n\n    switch (filter.type) {\n      // Props\n      case 'object': {\n        if (\n          context.selectionInverted &&\n          filter.id === undefined &&\n          filter.typename === null &&\n          Object.keys(filter.props).length === 0\n        ) {\n          // filter of nothing -> clear working set.\n          return QueryPlan.Plan.make([\n            {\n              _tag: 'ClearWorkingSetStep',\n            },\n            ...this._generateDeletedHandlingSteps(context),\n          ]);\n        }\n        if (context.selectionInverted && isTrivialTypenameFilter(filter)) {\n          invariant(filter.typename !== null);\n          // Negated plain type filter (e.g. `Filter.not(Filter.type(Foo))`) — mirrors the trivial-OR\n          // handling below: select via an inverted TypeSelector when indexed, or a WildcardSelector\n          // when working from the in-memory set, then re-check the negation in the FilterStep.\n          const selector: QueryPlan.Selector = this._options.noIndexes\n            ? { _tag: 'WildcardSelector' }\n            : { _tag: 'TypeSelector', typename: [filter.typename], inverted: true };\n          return QueryPlan.Plan.make([\n            {\n              _tag: 'SelectStep',\n              scope: context.scope,\n              selector,\n            },\n            ...this._generateDeletedHandlingSteps(context),\n            {\n              _tag: 'FilterStep',\n              filter: { type: 'not', filter: { ...filter } },\n            },\n          ]);\n        }\n        if (context.selectionInverted) {\n          throw queryTooComplexError(context.originalQuery);\n        }\n\n        // Try to utilize indexes during selection, prioritizing selecting by id, then by typename.\n        // After selection, filter out using the remaining predicates.\n        if (filter.id && filter.id?.length > 0) {\n          return QueryPlan.Plan.make([\n            {\n              _tag: 'SelectStep',\n              scope: context.scope,\n              selector: {\n                _tag: 'IdSelector',\n                objectIds: filter.id,\n              },\n            },\n            ...this._generateDeletedHandlingSteps(context),\n            {\n              _tag: 'FilterStep',\n              filter: { ...filter, id: undefined },\n            },\n          ]);\n        } else if (filter.typename) {\n          // When noIndexes is set, use WildcardSelector so all loaded cores are scanned;\n          // the type predicate is enforced by the FilterStep that already follows.\n          const selector: QueryPlan.Selector = this._options.noIndexes\n            ? { _tag: 'WildcardSelector' }\n            : { _tag: 'TypeSelector', typename: [filter.typename], inverted: false };\n          return QueryPlan.Plan.make([\n            {\n              _tag: 'SelectStep',\n              scope: context.scope,\n              selector,\n            },\n            ...this._generateDeletedHandlingSteps(context),\n            // TODO(dmaretskyi): Normally we could skip filtering by typename here, but since the index does not separate schema versions, we need to do additional filter to only select the correct version.\n            {\n              _tag: 'FilterStep',\n              filter: { ...filter },\n            },\n          ]);\n        } else {\n          return QueryPlan.Plan.make([\n            {\n              _tag: 'SelectStep',\n              scope: context.scope,\n              selector: {\n                _tag: 'WildcardSelector',\n              },\n            },\n            ...this._generateDeletedHandlingSteps(context),\n            {\n              _tag: 'FilterStep',\n              filter: { ...filter },\n            },\n          ]);\n        }\n      }\n\n      // Tag\n      case 'tag': {\n        return QueryPlan.Plan.make([\n          {\n            _tag: 'SelectStep',\n            scope: context.scope,\n            selector: {\n              _tag: 'WildcardSelector',\n            },\n          },\n          ...this._generateDeletedHandlingSteps(context),\n          {\n            _tag: 'FilterStep',\n            filter: { ...filter },\n          },\n        ]);\n      }\n\n      // Text\n      case 'text-search': {\n        return QueryPlan.Plan.make([\n          {\n            _tag: 'SelectStep',\n            scope: context.scope,\n            selector: {\n              _tag: 'TextSelector',\n              text: filter.text,\n              searchKind: filter.searchKind ?? this._options.defaultTextSearchKind,\n              typename: null,\n            },\n          },\n          ...this._generateDeletedHandlingSteps(context),\n        ]);\n      }\n\n      // Feed cursor — always lifted out above, so reaching here means the tree changed shape.\n      case 'feed-cursor':\n        throw queryTooComplexError(context.originalQuery);\n\n      // Timestamp\n      case 'timestamp': {\n        if (context.selectionInverted) {\n          throw new QueryError({\n            message:\n              'Negated timestamp filters are not supported. Use Filter.updated/Filter.created with the inverted range instead.',\n            context: { query: context.originalQuery },\n          });\n        }\n        return QueryPlan.Plan.make([\n          {\n            _tag: 'SelectStep',\n            scope: context.scope,\n            selector: _timestampFilterToSelector(filter),\n          },\n          ...this._generateDeletedHandlingSteps(context),\n        ]);\n      }\n\n      // ChildOf\n      case 'child-of': {\n        return QueryPlan.Plan.make([\n          {\n            _tag: 'SelectStep',\n            scope: context.scope,\n            selector: {\n              _tag: 'WildcardSelector',\n            },\n          },\n          ...this._generateDeletedHandlingSteps(context),\n          {\n            _tag: 'FilterStep',\n            filter: { ...filter },\n          },\n        ]);\n      }\n\n      case 'changes': {\n        if (context.selectionInverted) {\n          throw queryTooComplexError(context.originalQuery);\n        }\n        return QueryPlan.Plan.make([\n          {\n            _tag: 'SelectStep',\n            scope: context.scope,\n            selector: { _tag: 'ChangesSelector', targets: filter.targets, source: 'replay' },\n          },\n        ]);\n      }\n\n      // Mnemonic and annotation — local predicates on the object's own id or meta, so they run as a\n      // filter step over a wildcard select. Inversion cannot fold into the value, so it is re-wrapped as `not`.\n      case 'annotation':\n      case 'mnemonic': {\n        const planned: QueryAST.Filter = context.selectionInverted ? { type: 'not', filter } : filter;\n        return QueryPlan.Plan.make([\n          {\n            _tag: 'SelectStep',\n            scope: context.scope,\n            selector: {\n              _tag: 'WildcardSelector',\n            },\n          },\n          ...this._generateDeletedHandlingSteps(context),\n          {\n            _tag: 'FilterStep',\n            filter: planned,\n          },\n        ]);\n      }\n\n      // HasParent — a local predicate on the object's own parent slot, so inversion folds into\n      // the value rather than costing a negated plan.\n      case 'has-parent': {\n        const planned: QueryAST.Filter = context.selectionInverted\n          ? { ...filter, value: !filter.value }\n          : { ...filter };\n        return QueryPlan.Plan.make([\n          {\n            _tag: 'SelectStep',\n            scope: context.scope,\n            selector: {\n              _tag: 'WildcardSelector',\n            },\n          },\n          ...this._generateDeletedHandlingSteps(context),\n          {\n            _tag: 'FilterStep',\n            filter: planned,\n          },\n        ]);\n      }\n\n      // Compare\n      case 'compare':\n        throw queryTooComplexError(context.originalQuery);\n      case 'in':\n        throw queryTooComplexError(context.originalQuery);\n      case 'in-query':\n        throw queryTooComplexError(context.originalQuery);\n      case 'range':\n        throw queryTooComplexError(context.originalQuery);\n\n      // Boolean\n      case 'not':\n        return this._generateSelectionFromFilter(filter.filter, {\n          ...context,\n          selectionInverted: !context.selectionInverted,\n        });\n      case 'and': {\n        const flatFilters = _flattenAnd(filter.filters);\n        const timestampFilters = flatFilters.filter((f): f is QueryAST.FilterTimestamp => f.type === 'timestamp');\n        const childOfFilters = flatFilters.filter((f): f is QueryAST.FilterChildOf => f.type === 'child-of');\n        // has-parent and (negated) annotation predicates are local checks, planned as post-filters.\n        const localFilters = flatFilters.filter((f) => f.type === 'has-parent' || _isAnnotationPredicate(f));\n        const otherFilters = flatFilters.filter(\n          (f) => f.type !== 'timestamp' && f.type !== 'child-of' && !localFilters.includes(f),\n        );\n\n        if (timestampFilters.length > 0 && context.selectionInverted) {\n          throw new QueryError({\n            message:\n              'Negated timestamp filters are not supported. Use Filter.updated/Filter.created with the inverted range instead.',\n            context: { query: context.originalQuery },\n          });\n        }\n\n        if (\n          timestampFilters.length > 0 &&\n          otherFilters.length <= 1 &&\n          childOfFilters.length === 0 &&\n          localFilters.length === 0\n        ) {\n          const innerFilter = otherFilters[0];\n          const innerPlan = innerFilter\n            ? this._generateSelectionFromFilter(innerFilter, context)\n            : QueryPlan.Plan.make([\n                {\n                  _tag: 'SelectStep',\n                  scope: context.scope,\n                  selector: { _tag: 'WildcardSelector' },\n                },\n                ...this._generateDeletedHandlingSteps(context),\n              ]);\n\n          const selectIdx = innerPlan.steps.findIndex((s) => s._tag === 'SelectStep');\n          if (selectIdx !== -1) {\n            const newSteps = [...innerPlan.steps];\n            newSteps.splice(selectIdx + 1, 0, {\n              _tag: 'FilterStep',\n              filter: { type: 'and', filters: timestampFilters },\n            });\n            return QueryPlan.Plan.make(newSteps);\n          }\n\n          const selector = _mergeTimestampSelectors(timestampFilters.map(_timestampFilterToSelector));\n          return QueryPlan.Plan.make([\n            {\n              _tag: 'SelectStep',\n              scope: context.scope,\n              selector,\n            },\n            ...this._generateDeletedHandlingSteps(context),\n          ]);\n        }\n\n        if (timestampFilters.length > 0 && childOfFilters.length === 0 && localFilters.length === 0) {\n          throw new QueryError({\n            message:\n              'Timestamp filters can only be combined with a single type or property filter via AND. Split complex filters into a subquery.',\n            context: { query: context.originalQuery },\n          });\n        }\n\n        // child-of and the local filters plan as post-filters appended to the remaining filters'\n        // plan, so `and(type(X), hasParent(false))` keeps its type-indexed select.\n        if (childOfFilters.length > 0 || localFilters.length > 0) {\n          // A negated conjunction cannot distribute over its conjuncts (`not(and(a, b))` is not\n          // `not(a) && b`), so under inversion the WHOLE negated AND becomes one post-filter —\n          // possible only when every conjunct is root-executable (child-of is not).\n          if (context.selectionInverted) {\n            if (childOfFilters.length > 0 || !flatFilters.every(isRootExecutable)) {\n              throw queryTooComplexError(context.originalQuery);\n            }\n            return QueryPlan.Plan.make([\n              {\n                _tag: 'SelectStep',\n                scope: context.scope,\n                selector: { _tag: 'WildcardSelector' },\n              },\n              ...this._generateDeletedHandlingSteps(context),\n              {\n                _tag: 'FilterStep',\n                filter: { type: 'not', filter: { type: 'and', filters: flatFilters } },\n              },\n            ]);\n          }\n          const remainingFilters: QueryAST.Filter[] = [...otherFilters, ...timestampFilters];\n          const innerPlan =\n            remainingFilters.length === 1\n              ? this._generateSelectionFromFilter(remainingFilters[0], context)\n              : remainingFilters.length > 1\n                ? this._generateSelectionFromFilter({ type: 'and', filters: remainingFilters }, context)\n                : QueryPlan.Plan.make([\n                    {\n                      _tag: 'SelectStep',\n                      scope: context.scope,\n                      selector: { _tag: 'WildcardSelector' },\n                    },\n                    ...this._generateDeletedHandlingSteps(context),\n                  ]);\n\n          const postFilterSteps: QueryPlan.Step[] = [...childOfFilters, ...localFilters].map((f) => ({\n            _tag: 'FilterStep' as const,\n            filter: f,\n          }));\n\n          return QueryPlan.Plan.make([...innerPlan.steps, ...postFilterSteps]);\n        }\n\n        // Simple AND: all filters are root-executable against in-memory objects after a wildcard select.\n        // The text search must drive the selection — the in-memory matcher cannot evaluate one —\n        // and inverting it would need objects outside the FTS hits, which the index cannot produce.\n        const textFilters = flatFilters.filter((f): f is QueryAST.FilterTextSearch => f.type === 'text-search');\n        if (textFilters.length === 1 && !context.selectionInverted) {\n          const [textFilter] = textFilters;\n          const rest = flatFilters.filter((f) => f.type !== 'text-search');\n          if (rest.length === 0) {\n            return this._generateSelectionFromFilter(textFilter, context);\n          }\n          if (rest.every(isRootExecutable)) {\n            const typename = rest.map(_extractFilterTypenames).find((list) => list !== null) ?? null;\n            return QueryPlan.Plan.make([\n              {\n                _tag: 'SelectStep',\n                scope: context.scope,\n                selector: {\n                  _tag: 'TextSelector',\n                  text: textFilter.text,\n                  searchKind: textFilter.searchKind ?? this._options.defaultTextSearchKind,\n                  typename,\n                },\n              },\n              ...this._generateDeletedHandlingSteps(context),\n              // The selector's typename narrowing is an over-approximation (it cannot distinguish\n              // schema versions), so the residual filters are always re-checked here.\n              {\n                _tag: 'FilterStep',\n                filter: rest.length === 1 ? { ...rest[0] } : { type: 'and', filters: rest },\n              },\n            ]);\n          }\n        }\n        if (textFilters.length > 0) {\n          throw queryTooComplexError(context.originalQuery);\n        }\n\n        if (flatFilters.every(isRootExecutable)) {\n          const innerFilter: QueryAST.Filter = { type: 'and', filters: flatFilters };\n          const plannedFilter: QueryAST.Filter = context.selectionInverted\n            ? { type: 'not', filter: innerFilter }\n            : innerFilter;\n          return QueryPlan.Plan.make([\n            {\n              _tag: 'SelectStep',\n              scope: context.scope,\n              selector: { _tag: 'WildcardSelector' },\n            },\n            ...this._generateDeletedHandlingSteps(context),\n            {\n              _tag: 'FilterStep',\n              filter: plannedFilter,\n            },\n          ]);\n        }\n\n        throw queryTooComplexError(context.originalQuery);\n      }\n      case 'or':\n        // Optimized case\n        if (filter.filters.every(isTrivialTypenameFilter)) {\n          const typenames = filter.filters.map((filter) => {\n            invariant(filter.type === 'object' && filter.typename !== null);\n            return filter.typename;\n          });\n\n          // When noIndexes is set, use WildcardSelector so all loaded cores are scanned; a WildcardSelector\n          // carries no inversion, so the FilterStep below must apply the negation instead of the selector.\n          const orSelector: QueryPlan.Selector = this._options.noIndexes\n            ? { _tag: 'WildcardSelector' }\n            : { _tag: 'TypeSelector', typename: typenames, inverted: context.selectionInverted };\n          // The FilterStep re-checks the selector's predicate (it also disambiguates same-named schema\n          // versions the index doesn't distinguish), so it must encode the same inversion as the selector.\n          const orFilter: QueryAST.Filter = context.selectionInverted\n            ? { type: 'not', filter: { ...filter } }\n            : { ...filter };\n          return QueryPlan.Plan.make([\n            {\n              _tag: 'SelectStep',\n              scope: context.scope,\n              selector: orSelector,\n            },\n            ...this._generateDeletedHandlingSteps(context),\n            {\n              _tag: 'FilterStep',\n              filter: orFilter,\n            },\n          ]);\n        } else {\n          throw queryTooComplexError(context.originalQuery);\n        }\n\n      default:\n        throw new QueryError({\n          message: `Unsupported filter type: ${(filter as any).type}`,\n          context: { query: context.originalQuery },\n        });\n    }\n  }\n\n  private _generateDeletedHandlingSteps(context: GenerationContext): QueryPlan.Step[] {\n    switch (context.deletedHandling) {\n      case 'include':\n        return [];\n      case 'exclude':\n        return [\n          {\n            _tag: 'FilterDeletedStep',\n            mode: 'only-non-deleted',\n          },\n        ];\n      case 'only':\n        return [\n          {\n            _tag: 'FilterDeletedStep',\n            mode: 'only-deleted',\n          },\n        ];\n    }\n  }\n\n  private _generateUnionClause(query: QueryAST.QueryUnionClause, context: GenerationContext): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      {\n        _tag: 'UnionStep',\n        plans: query.queries.map((query) => this._generate(query, context)),\n      },\n    ]);\n  }\n\n  private _generateSetDifferenceClause(\n    query: QueryAST.QuerySetDifferenceClause,\n    context: GenerationContext,\n  ): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      {\n        _tag: 'SetDifferenceStep',\n        source: this._generate(query.source, context),\n        exclude: this._generate(query.exclude, context),\n      },\n    ]);\n  }\n\n  private _generateReferenceTraversalClause(\n    query: QueryAST.QueryReferenceTraversalClause,\n    context: GenerationContext,\n  ): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      ...this._generate(query.anchor, context).steps,\n      {\n        _tag: 'TraverseStep',\n        traversal: {\n          _tag: 'ReferenceTraversal',\n          direction: 'outgoing',\n          property: query.property,\n        },\n      },\n      ...this._generateDeletedHandlingSteps(context),\n    ]);\n  }\n\n  private _generateIncomingReferencesClause(\n    query: QueryAST.QueryIncomingReferencesClause,\n    context: GenerationContext,\n  ): QueryPlan.Plan {\n    // `Query.select(Filter.key(dxn)).referencedBy()` collapses to a single index lookup. Evaluating\n    // the anchor would be both a scan (a meta-key filter is matched in memory, not indexed) and\n    // empty for the case this exists to serve: a named entity, which is never in the graph.\n    const namedAnchor = namedEntityAnchor(query.anchor);\n    if (namedAnchor !== undefined) {\n      return QueryPlan.Plan.make([\n        {\n          _tag: 'SelectStep',\n          selector: {\n            _tag: 'IncomingReferenceSelector',\n            targetDXN: namedAnchor,\n            property: query.property ?? null,\n          },\n          scope: context.scope,\n        },\n        ...this._generateDeletedHandlingSteps(context),\n        {\n          _tag: 'FilterStep',\n          filter: {\n            type: 'object',\n            typename: query.typename,\n            props: {},\n          },\n        },\n      ]);\n    }\n\n    return QueryPlan.Plan.make([\n      ...this._generate(query.anchor, context).steps,\n      {\n        _tag: 'TraverseStep',\n        traversal: {\n          _tag: 'ReferenceTraversal',\n          direction: 'incoming',\n          property: query.property ?? null,\n        },\n      },\n      ...this._generateDeletedHandlingSteps(context),\n      {\n        _tag: 'FilterStep',\n        filter: {\n          type: 'object',\n          typename: query.typename,\n          props: {},\n        },\n      },\n    ]);\n  }\n\n  private _generateRelationTraversalClause(\n    query: QueryAST.QueryRelationTraversalClause,\n    context: GenerationContext,\n  ): QueryPlan.Plan {\n    switch (query.direction) {\n      case 'source': {\n        return QueryPlan.Plan.make([\n          ...this._generate(query.anchor, context).steps,\n          createRelationTraversalStep('relation-to-source'),\n          ...this._generateDeletedHandlingSteps(context),\n        ]);\n      }\n      case 'target': {\n        return QueryPlan.Plan.make([\n          ...this._generate(query.anchor, context).steps,\n          createRelationTraversalStep('relation-to-target'),\n          ...this._generateDeletedHandlingSteps(context),\n        ]);\n      }\n      case 'both': {\n        const anchorPlan = this._generate(query.anchor, context);\n        return QueryPlan.Plan.make([\n          ...anchorPlan.steps,\n          {\n            _tag: 'UnionStep',\n            plans: [\n              QueryPlan.Plan.make([createRelationTraversalStep('relation-to-source')]),\n              QueryPlan.Plan.make([createRelationTraversalStep('relation-to-target')]),\n            ],\n          },\n          ...this._generateDeletedHandlingSteps(context),\n        ]);\n      }\n    }\n  }\n\n  private _generateRelationClause(query: QueryAST.QueryRelationClause, context: GenerationContext): QueryPlan.Plan {\n    switch (query.direction) {\n      case 'outgoing': {\n        return QueryPlan.Plan.make([\n          ...this._generate(query.anchor, context).steps,\n          createRelationTraversalStep('source-to-relation'),\n          ...this._generateDeletedHandlingSteps(context),\n          {\n            _tag: 'FilterStep',\n            filter: query.filter ?? NOOP_FILTER,\n          },\n        ]);\n      }\n      case 'incoming': {\n        return QueryPlan.Plan.make([\n          ...this._generate(query.anchor, context).steps,\n          createRelationTraversalStep('target-to-relation'),\n          ...this._generateDeletedHandlingSteps(context),\n          {\n            _tag: 'FilterStep',\n            filter: query.filter ?? NOOP_FILTER,\n          },\n        ]);\n      }\n      case 'both': {\n        const anchorPlan = this._generate(query.anchor, context);\n        return QueryPlan.Plan.make([\n          ...anchorPlan.steps,\n          {\n            _tag: 'UnionStep',\n            plans: [\n              QueryPlan.Plan.make([createRelationTraversalStep('source-to-relation')]),\n              QueryPlan.Plan.make([createRelationTraversalStep('target-to-relation')]),\n            ],\n          },\n          ...this._generateDeletedHandlingSteps(context),\n          {\n            _tag: 'FilterStep',\n            filter: query.filter ?? NOOP_FILTER,\n          },\n        ]);\n      }\n    }\n  }\n\n  private _generateFilterClause(query: QueryAST.QueryFilterClause, context: GenerationContext): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      ...this._generate(query.selection, context).steps,\n      {\n        _tag: 'FilterStep',\n        filter: query.filter,\n      },\n    ]);\n  }\n\n  private _generateHierarchyTraversalClause(\n    query: QueryAST.QueryHierarchyTraversalClause,\n    context: GenerationContext,\n  ): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      ...this._generate(query.anchor, context).steps,\n      {\n        _tag: 'TraverseStep',\n        traversal: {\n          _tag: 'HierarchyTraversal',\n          direction: query.direction,\n        },\n      },\n      ...this._generateDeletedHandlingSteps(context),\n    ]);\n  }\n\n  private _validateQueryScoped(query: QueryAST.Query): void {\n    let hasScope = false;\n    QueryAST.visit(query, (node) => {\n      if (node.type === 'from') {\n        hasScope = true;\n      }\n    });\n    if (!hasScope) {\n      throw new QueryError({\n        message: 'Query must be scoped with a from() clause',\n        context: { query },\n      });\n    }\n  }\n\n  /**\n   * `aggregate` must be the outermost data clause: only `from()`/`options()` and the group-level\n   * pagination clauses `limit()`/`skip()` may wrap it. At most one `aggregate` may appear anywhere\n   * in the tree — including inside a `.from(subquery)` source, which the planner flattens (so an\n   * aggregated subquery would otherwise produce an unsupported double-`aggregate`). The DSL's types\n   * can't enforce this (`Query<RecordResult & ...>` still exposes `orderBy`/`select`/etc.), so\n   * it's validated here at plan time.\n   *\n   * `limit`/`skip` above an `aggregate` page over whole groups (see the group-aware `LimitStep`/\n   * `SkipStep` execution); a `limit`/`skip` below it windows the flat object stream before aggregating.\n   */\n  private _validateAggregatePlacement(query: QueryAST.Query): void {\n    // Count every aggregate anywhere in the tree. `QueryAST.visit` recurses through `from` sources,\n    // so this also sees aggregated subqueries that flattening would merge in.\n    let aggregateCount = 0;\n    QueryAST.visit(query, (node) => {\n      if (node.type === 'aggregate') {\n        aggregateCount += 1;\n      }\n    });\n    if (aggregateCount === 0) {\n      return;\n    }\n    if (aggregateCount > 1) {\n      throw new QueryError({\n        message: 'Only one aggregate clause is supported per query',\n        context: { query },\n      });\n    }\n\n    // Exactly one aggregate: it must sit at the outermost data position (only from/options/order/\n    // limit/skip may wrap it). A wrapping `order` reorders whole groups; an `order` inside the\n    // aggregate's own query orders members within each group. Unwrap the permitted wrappers and\n    // require the aggregate to be what remains.\n    let root = query;\n    while (\n      root.type === 'options' ||\n      root.type === 'from' ||\n      root.type === 'order' ||\n      root.type === 'limit' ||\n      root.type === 'skip'\n    ) {\n      root = root.query;\n    }\n    if (root.type !== 'aggregate') {\n      throw new QueryError({\n        message:\n          'aggregate must be the outermost query clause — only from(), options(), orderBy(), limit() and skip() may follow it',\n        context: { query },\n      });\n    }\n  }\n\n  /**\n   * Removes filter steps that have no predicates.\n   */\n  private _optimizeEmptyFilters(plan: QueryPlan.Plan): QueryPlan.Plan {\n    return QueryPlan.Plan.make(\n      plan.steps\n        .filter((step) => {\n          if (step._tag === 'FilterStep') {\n            return !QueryPlan.FilterStep.isNoop(step);\n          } else {\n            return true;\n          }\n        })\n        .map((step) => {\n          if (step._tag === 'UnionStep') {\n            return {\n              _tag: 'UnionStep',\n              plans: step.plans.map((plan) => this._optimizeEmptyFilters(plan)),\n            };\n          } else {\n            return step;\n          }\n        }),\n    );\n  }\n\n  /**\n   * Removes union steps that have only one child.\n   */\n  private _optimizeSoloUnions(plan: QueryPlan.Plan): QueryPlan.Plan {\n    // TODO(dmaretskyi): Implement this.\n    return plan;\n  }\n\n  private _generateOrderClause(query: QueryAST.QueryOrderClause, context: GenerationContext): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      ...this._generate(query.query, context).steps,\n      {\n        _tag: 'OrderStep',\n        order: query.order,\n      },\n    ]);\n  }\n\n  private _generateLimitClause(query: QueryAST.QueryLimitClause, context: GenerationContext): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      ...this._generate(query.query, context).steps,\n      {\n        _tag: 'LimitStep',\n        limit: query.limit,\n      },\n    ]);\n  }\n\n  private _generateSkipClause(query: QueryAST.QuerySkipClause, context: GenerationContext): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      ...this._generate(query.query, context).steps,\n      {\n        _tag: 'SkipStep',\n        skip: query.skip,\n      },\n    ]);\n  }\n\n  private _generateAggregateClause(query: QueryAST.QueryAggregateClause, context: GenerationContext): QueryPlan.Plan {\n    return QueryPlan.Plan.make([\n      ...this._generate(query.query, context).steps,\n      {\n        _tag: 'AggregateStep',\n        aggregates: query.aggregates,\n      },\n    ]);\n  }\n\n  // After complete plan is built, inspect it from the end:\n  //   - Walk backwards until hitting an object set changer.\n  //   - If an order step is found, skip.\n  //   - Otherwise insert natural order before any limit steps (since limit should be applied after ordering).\n  // This method is recursive and also processes sub-plans in unions and set differences.\n  private _ensureOrderStep(plan: QueryPlan.Plan): QueryPlan.Plan {\n    // First, recursively process any sub-plans.\n    const processedSteps = plan.steps.map((step): QueryPlan.Step => {\n      if (step._tag === 'UnionStep') {\n        return {\n          _tag: 'UnionStep',\n          plans: step.plans.map((subPlan) => this._ensureOrderStep(subPlan)),\n        };\n      } else if (step._tag === 'SetDifferenceStep') {\n        return {\n          _tag: 'SetDifferenceStep',\n          source: this._ensureOrderStep(step.source),\n          exclude: this._ensureOrderStep(step.exclude),\n        };\n      }\n      return step;\n    });\n\n    const processedPlan = QueryPlan.Plan.make(processedSteps);\n\n    const OBJECT_SET_CHANGERS = new Set(['SelectStep', 'TraverseStep', 'UnionStep', 'SetDifferenceStep']);\n    for (let i = processedPlan.steps.length - 1; i >= 0; i--) {\n      const step = processedPlan.steps[i];\n      if (step._tag === 'OrderStep') {\n        return processedPlan;\n      }\n      if (OBJECT_SET_CHANGERS.has(step._tag)) {\n        // An outgoing reference traversal emits each anchor's refs in array order, which is the only\n        // order a ref array has. Order the anchors instead, so the result stays deterministic.\n        if (isOutgoingReferenceTraversal(step)) {\n          const anchor = this._ensureOrderStep(QueryPlan.Plan.make(processedPlan.steps.slice(0, i)));\n          return QueryPlan.Plan.make([...anchor.steps, ...processedPlan.steps.slice(i)]);\n        }\n        break;\n      }\n    }\n\n    // Find the position to insert the order step (before any trailing limit/skip/aggregate steps —\n    // aggregation must see the intended order already applied, both within and between groups).\n    let insertIndex = processedPlan.steps.length;\n    for (let i = processedPlan.steps.length - 1; i >= 0; i--) {\n      const tag = processedPlan.steps[i]._tag;\n      if (tag === 'LimitStep' || tag === 'SkipStep' || tag === 'AggregateStep') {\n        insertIndex = i;\n      } else {\n        break;\n      }\n    }\n\n    const newSteps = [...processedPlan.steps];\n    newSteps.splice(insertIndex, 0, {\n      _tag: 'OrderStep',\n      order: [Order.natural().ast],\n    });\n\n    return QueryPlan.Plan.make(newSteps);\n  }\n\n  /**\n   * Propagates limits from LimitStep to SelectStep and OrderStep when possible.\n   * Limits can only be propagated if there are no unions or traversals between the LimitStep and SelectStep/OrderStep.\n   */\n  private _optimizeLimits(plan: QueryPlan.Plan): QueryPlan.Plan {\n    // First, recursively process any sub-plans.\n    const processedSteps = plan.steps.map((step): QueryPlan.Step => {\n      if (step._tag === 'UnionStep') {\n        return {\n          _tag: 'UnionStep',\n          plans: step.plans.map((subPlan) => this._optimizeLimits(subPlan)),\n        };\n      } else if (step._tag === 'SetDifferenceStep') {\n        return {\n          _tag: 'SetDifferenceStep',\n          source: this._optimizeLimits(step.source),\n          exclude: this._optimizeLimits(step.exclude),\n        };\n      }\n      return step;\n    });\n\n    // Find if there's a LimitStep at the end (possibly after OrderStep).\n    let limitStepIndex = -1;\n    let limitValue: number | undefined;\n\n    for (let i = processedSteps.length - 1; i >= 0; i--) {\n      const step = processedSteps[i];\n      if (step._tag === 'LimitStep') {\n        limitStepIndex = i;\n        limitValue = step.limit;\n        break;\n      }\n      // Only allow OrderStep after LimitStep when looking backwards.\n      if (step._tag !== 'OrderStep') {\n        break;\n      }\n    }\n\n    if (limitStepIndex === -1 || limitValue === undefined) {\n      return QueryPlan.Plan.make(processedSteps);\n    }\n\n    // Check if we can propagate the limit to a SelectStep and/or OrderStep.\n    // We can only do this if there are no unions, traversals, or set differences between them.\n    // AggregateStep is also a blocker: a limit above it counts whole groups, so it must not be\n    // pushed down into the flat SelectStep/OrderStep scan (that would slice objects, not groups).\n    const BLOCKERS = new Set(['UnionStep', 'TraverseStep', 'SetDifferenceStep', 'AggregateStep']);\n\n    let selectStepIndex = -1;\n    let orderStepIndex = -1;\n    for (let i = 0; i < limitStepIndex; i++) {\n      const step = processedSteps[i];\n      if (step._tag === 'SelectStep') {\n        selectStepIndex = i;\n      }\n      if (step._tag === 'OrderStep') {\n        orderStepIndex = i;\n      }\n      if (BLOCKERS.has(step._tag)) {\n        // Found a blocker after the select/order step - can't propagate.\n        selectStepIndex = -1;\n        orderStepIndex = -1;\n      }\n      // A child-of/has-parent FilterStep prunes results in-memory after the SelectStep, so pushing\n      // the limit into the SelectStep would slice candidates before the filter runs and starve\n      // the result set (e.g. wildcard select of 10 random objects, then child-of leaves 0).\n      if (step._tag === 'FilterStep' && _filterContainsPostSelectPrune(step.filter)) {\n        selectStepIndex = -1;\n        orderStepIndex = -1;\n      }\n      // Same reasoning for a nested subquery-membership predicate (`Filter.in(query.project(...))`):\n      // it prunes results in-memory after the SelectStep based on a set resolved at execution time,\n      // so pushing the limit earlier would slice candidates before the semi-join runs and starve\n      // the result set.\n      if (step._tag === 'FilterStep' && filterContainsInQuery(step.filter)) {\n        selectStepIndex = -1;\n        orderStepIndex = -1;\n      }\n    }\n\n    if (selectStepIndex === -1 && orderStepIndex === -1) {\n      return QueryPlan.Plan.make(processedSteps);\n    }\n\n    // A feed scan can be ordered and capped by the storage layer itself, so it takes the limit in\n    // either natural direction — which is the point: a bounded feed query must read bounded work.\n    const feedScan =\n      selectStepIndex !== -1\n        ? feedScanForLimit(processedSteps, selectStepIndex, orderStepIndex, limitStepIndex)\n        : undefined;\n\n    // Pushing the limit into the SelectStep is only sound when the scan enumerates candidates in the\n    // requested order, so that the first N of the scan are the first N of the result. Absent a feed\n    // scan the select runs in ascending natural order (by id / queue position). A content-based\n    // reorder (property, annotation or system timestamp) or a descending natural order does not match that scan\n    // order, so slicing at select time would keep the wrong N; those need the FULL candidate set and\n    // only the OrderStep may apply the limit. Ascending natural and rank (the FTS scan already\n    // returns by rank) stay consistent with the scan, so keep optimizing those.\n    if (orderStepIndex !== -1 && feedScan === undefined) {\n      const orderStep = processedSteps[orderStepIndex];\n      const scanOrderMismatch =\n        orderStep._tag === 'OrderStep' &&\n        orderStep.order.some(\n          (order) =>\n            order.kind === 'property' ||\n            order.kind === 'annotation' ||\n            order.kind === 'timestamp' ||\n            (order.kind === 'natural' && order.direction === 'desc'),\n        );\n      if (scanOrderMismatch) {\n        selectStepIndex = -1;\n      }\n    }\n\n    // A SkipStep between a propagation target and the LimitStep drops items after the limit\n    // would be applied. Since the LimitStep is removed, the limit pushed into the earlier step\n    // must also cover the skipped prefix — otherwise `skip(k).limit(n)` yields only `n - k` items.\n    // A feed scan drops the prefix itself, before any document loads, so it takes the SkipSteps instead.\n    const skipBetween = (fromIndex: number): number => {\n      if (feedScan !== undefined) {\n        return 0;\n      }\n      let total = 0;\n      for (let i = fromIndex + 1; i < limitStepIndex; i++) {\n        const step = processedSteps[i];\n        if (step._tag === 'SkipStep') {\n          total += step.skip;\n        }\n      }\n      return total;\n    };\n\n    // Create a mutable copy of steps to modify.\n    const newSteps = [...processedSteps];\n\n    // Propagate the limit to the SelectStep if found.\n    if (selectStepIndex !== -1) {\n      const selectStep = newSteps[selectStepIndex] as QueryPlan.SelectStep;\n      newSteps[selectStepIndex] = {\n        ...selectStep,\n        limit: limitValue + skipBetween(selectStepIndex),\n        ...(feedScan ? { feedScan } : {}),\n      };\n    }\n\n    // Propagate the limit to the OrderStep if found.\n    if (orderStepIndex !== -1) {\n      const orderStep = newSteps[orderStepIndex] as QueryPlan.OrderStep;\n      newSteps[orderStepIndex] = {\n        ...orderStep,\n        limit: limitValue + skipBetween(orderStepIndex),\n      };\n    }\n\n    // Remove the LimitStep since limit is now propagated, and the SkipSteps a feed scan applies.\n    return QueryPlan.Plan.make(\n      newSteps.filter(\n        (step, index) =>\n          index !== limitStepIndex &&\n          !(feedScan !== undefined && step._tag === 'SkipStep' && index > selectStepIndex && index < limitStepIndex),\n      ),\n    );\n  }\n}\n\n/**\n * Context for query planning.\n */\n/**\n * The DXN named by a `Query.select(Filter.key(dxn))` anchor, or undefined when the anchor is any\n * other shape. A version-constrained key is excluded: the reverse-reference index keys a named\n * entity without its version, so the range could not be honoured.\n */\nconst namedEntityAnchor = (anchor: QueryAST.Query): URI.URI | undefined => {\n  if (anchor.type !== 'select' || anchor.filter.type !== 'object') {\n    return undefined;\n  }\n  const filter = anchor.filter;\n  if (\n    filter.metaKey === undefined ||\n    filter.metaVersion !== undefined ||\n    filter.typename !== null ||\n    (filter.id !== undefined && filter.id.length > 0) ||\n    Object.keys(filter.props).length > 0 ||\n    (filter.foreignKeys !== undefined && filter.foreignKeys.length > 0)\n  ) {\n    return undefined;\n  }\n  // `Filter.key` takes a bare NSID, but a caller holding a DXN passes it through unchanged.\n  return DXN.isDXN(filter.metaKey) ? DXN.tryMake(filter.metaKey) : DXN.tryMake(`dxn:${filter.metaKey}`);\n};\n\ntype GenerationContext = {\n  /**\n   * The original query.\n   */\n  originalQuery: QueryAST.Query | null;\n\n  /**\n   * The scope to select from (space IDs, queues, etc.).\n   */\n  scope: readonly QueryAST.Scope[];\n\n  /**\n   * How to handle deleted objects.\n   */\n  deletedHandling: 'include' | 'exclude' | 'only';\n\n  /**\n   * When generating a selection clause, whether to invert the filter.\n   */\n  selectionInverted: boolean;\n};\n\nconst DEFAULT_CONTEXT: GenerationContext = {\n  originalQuery: null,\n  scope: [],\n  deletedHandling: 'exclude',\n  selectionInverted: false,\n};\n\nconst NOOP_FILTER: QueryAST.Filter = {\n  type: 'object',\n  typename: null,\n  id: [],\n  props: {},\n};\n\nconst isOutgoingReferenceTraversal = (step: QueryPlan.Step): boolean =>\n  step._tag === 'TraverseStep' &&\n  step.traversal._tag === 'ReferenceTraversal' &&\n  step.traversal.direction === 'outgoing';\n\nconst createRelationTraversalStep = (direction: QueryPlan.RelationTraversal['direction']): QueryPlan.Step => ({\n  _tag: 'TraverseStep',\n  traversal: {\n    _tag: 'RelationTraversal',\n    direction,\n  },\n});\n\n/**\n * The scan shape that lets a feed-only SelectStep apply the query's `limit` itself, or `undefined`\n * when it may not: a bounded feed query is the whole point of pushing the limit into storage, but\n * a page capped before a step that prunes it would come back short of what the caller asked for.\n *\n * Sound only when every step between the select and the limit is one the scan reproduces:\n * the deleted filter and any skip (both folded into the returned scan), a residual filter the\n * selector already enforces, and the order step the scan matches.\n */\nconst feedScanForLimit = (\n  steps: readonly QueryPlan.Step[],\n  selectStepIndex: number,\n  orderStepIndex: number,\n  limitStepIndex: number,\n): QueryPlan.FeedScan | undefined => {\n  const selectStep = steps[selectStepIndex];\n  if (selectStep._tag !== 'SelectStep') {\n    return undefined;\n  }\n  // Only a feed scan orders and caps its own rows; a space scan has no ordering to cap against,\n  // and a mixed scope has no single ordering at all.\n  if (selectStep.scope.length === 0 || !selectStep.scope.every((scope) => scope._tag === 'feed')) {\n    return undefined;\n  }\n  // A cursor read is already windowed by position, and a walk by its path: both are different orderings.\n  if (\n    selectStep.feedCursorRange !== undefined ||\n    selectStep.scope.some((scope) => scope._tag === 'feed' && scope.walk)\n  ) {\n    return undefined;\n  }\n  // The index seeks by id or type; every other selector reaches rows the window cannot order.\n  if (selectStep.selector._tag !== 'WildcardSelector' && selectStep.selector._tag !== 'TypeSelector') {\n    return undefined;\n  }\n\n  const direction = feedScanDirection(steps, orderStepIndex);\n  if (direction === undefined) {\n    return undefined;\n  }\n\n  let deleted: boolean | undefined;\n  let skip = 0;\n  for (let index = selectStepIndex + 1; index < limitStepIndex; index++) {\n    const step = steps[index];\n    switch (step._tag) {\n      case 'FilterDeletedStep':\n        deleted = step.mode === 'only-deleted';\n        break;\n      case 'FilterStep':\n        if (!isSelectorResidualFilter(step.filter, selectStep.selector)) {\n          return undefined;\n        }\n        break;\n      case 'OrderStep':\n        // Only the step `direction` was derived from; a second one would reorder the capped page.\n        if (index !== orderStepIndex) {\n          return undefined;\n        }\n        break;\n      case 'SkipStep':\n        // A skip below the order composes the other way round: the plan drops rows in scan order\n        // and orders what is left, where the scan orders first and drops from that.\n        if (orderStepIndex !== -1 && index < orderStepIndex) {\n          return undefined;\n        }\n        skip += step.skip;\n        break;\n      default:\n        return undefined;\n    }\n  }\n\n  return {\n    direction,\n    ...(deleted !== undefined ? { deleted } : {}),\n    ...(skip > 0 ? { skip } : {}),\n  };\n};\n\n/**\n * The natural direction a feed scan must run to satisfy the plan's ordering, or `undefined` when\n * the ordering is not one the scan can produce (a content-based reorder needs the full candidate\n * set). An absent order step means natural ascending, which is what the planner inserts.\n */\nconst feedScanDirection = (\n  steps: readonly QueryPlan.Step[],\n  orderStepIndex: number,\n): QueryPlan.FeedScan['direction'] | undefined => {\n  if (orderStepIndex === -1) {\n    return 'asc';\n  }\n  const orderStep = steps[orderStepIndex];\n  if (orderStep._tag !== 'OrderStep') {\n    return undefined;\n  }\n  if (orderStep.order.length === 0) {\n    return 'asc';\n  }\n  // Entity ids are unique, so a secondary order could only break ties the scan never produces.\n  if (orderStep.order.length !== 1 || orderStep.order[0].kind !== 'natural') {\n    return undefined;\n  }\n  return orderStep.order[0].direction === 'desc' ? 'desc' : 'asc';\n};\n\n/**\n * Whether a residual FilterStep can only re-check what the selector already enforced, so capping\n * the scan before it cannot drop a row it would have kept. True for the empty filter, and for the\n * typename re-check `_generateSelectionFromFilter` emits alongside a TypeSelector — the index\n * matches the same typenames, versioned or not, that `compareTypenameStrings` accepts.\n */\nconst isSelectorResidualFilter = (filter: QueryAST.Filter, selector: QueryPlan.Selector): boolean => {\n  if (filter.type !== 'object') {\n    return false;\n  }\n  const hasOnlyTypename =\n    (filter.id === undefined || filter.id.length === 0) &&\n    (filter.props === undefined || Object.keys(filter.props).length === 0) &&\n    (filter.foreignKeys === undefined || filter.foreignKeys.length === 0) &&\n    filter.metaKey === undefined;\n  if (!hasOnlyTypename) {\n    return false;\n  }\n  if (filter.typename === null) {\n    return true;\n  }\n  return (\n    selector._tag === 'TypeSelector' &&\n    !selector.inverted &&\n    selector.typename.length === 1 &&\n    selector.typename[0] === filter.typename\n  );\n};\n\nconst _isAnnotationPredicate = (filter: QueryAST.Filter): boolean =>\n  filter.type === 'annotation' || (filter.type === 'not' && filter.filter.type === 'annotation');\n\n/**\n * Returns true if the filter is `annotation`, `child-of`, `has-parent` or `mnemonic` — the post-select pruning filters —\n * or composes one via `and` / `or` / `not`. Their FilterSteps genuinely subtract from the\n * SelectStep's candidates (the step is not a re-check of the selector's own predicate), so a\n * limit must never be pushed past them.\n */\nconst _filterContainsPostSelectPrune = (filter: QueryAST.Filter): boolean => {\n  switch (filter.type) {\n    case 'annotation':\n    case 'child-of':\n    case 'has-parent':\n    case 'mnemonic':\n      return true;\n    case 'not':\n      return _filterContainsPostSelectPrune(filter.filter);\n    case 'and':\n    case 'or':\n      return filter.filters.some(_filterContainsPostSelectPrune);\n    default:\n      return false;\n  }\n};\n\n/** Whether hourly activity buckets answer the steps after a changes select as individual changes would. */\nconst activityIndexAnswers = (steps: readonly QueryPlan.Step[]): boolean => {\n  const aggregateIndex = steps.findIndex((step) => step._tag === 'AggregateStep');\n  const aggregate = steps[aggregateIndex];\n  return (\n    aggregate?._tag === 'AggregateStep' &&\n    steps.slice(0, aggregateIndex).every(isNaturalOrderStep) &&\n    aggregate.aggregates.every(readsOnlyBucketFields)\n  );\n};\n\nconst isNaturalOrderStep = (step: QueryPlan.Step): boolean =>\n  step._tag === 'OrderStep' && step.order.every((order) => order.kind === 'natural');\n\nconst readsOnlyBucketFields = (aggregate: QueryAST.GroupAggregate): boolean =>\n  aggregate.kind === 'count' ||\n  (aggregate.kind === 'sum' && aggregate.property === 'ops') ||\n  (aggregate.kind === 'time' && aggregate.property === 'time') ||\n  (aggregate.kind === 'group' && aggregate.properties.length === 1 && aggregate.properties[0] === 'source');\n\nconst filterContainsChanges = (filter: QueryAST.Filter): boolean => {\n  switch (filter.type) {\n    case 'changes':\n      return true;\n    case 'not':\n      return filterContainsChanges(filter.filter);\n    case 'and':\n    case 'or':\n      return filter.filters.some(filterContainsChanges);\n    default:\n      return false;\n  }\n};\n\nexport const queryContainsChanges = (query: QueryAST.Query): boolean => {\n  let found = false;\n  QueryAST.visit(query, (node) => {\n    if ((node.type === 'select' || node.type === 'filter') && filterContainsChanges(node.filter)) {\n      found = true;\n    }\n  });\n  return found;\n};\n\n/**\n * Returns true if the filter is a subquery-membership predicate (`Filter.in(query.project(...))`,\n * AST type `in-query`) or composes one via `and` / `or` / `not` / a nested `object` prop. Unlike\n * `child-of`, which is only ever a root filter, `in-query` is always nested inside an `object`\n * filter's `props` — the residual FilterStep produced by `_generateSelectionFromFilter`'s `object`\n * case (above) is always `type: 'object'`, so this must recurse into `props` to find it.\n *\n * Exported (unlike the sibling `_filterContains*` helpers) so `query-executor.ts`'s `extractScopes`\n * can reuse it — a bare `filter.type === 'in-query'` check there would miss the common case.\n */\nexport const filterContainsInQuery = (filter: QueryAST.Filter): boolean => {\n  switch (filter.type) {\n    case 'in-query':\n      return true;\n    case 'object':\n      return Object.values(filter.props).some(filterContainsInQuery);\n    case 'not':\n      return filterContainsInQuery(filter.filter);\n    case 'and':\n    case 'or':\n      return filter.filters.some(filterContainsInQuery);\n    default:\n      return false;\n  }\n};\n\n/**\n * Recursively flattens nested `and` filters into a single list.\n */\n/**\n * Lift a `feed-cursor` filter out of the top level of a filter tree, returning the bound and\n * whatever else the tree selects.\n *\n * A cursor is a scan bound, not a predicate over an object, so it composes with AND and with\n * nothing else: negating or OR-ing one has no scan to bound, and two of them have no single bound.\n * Those are rejected rather than silently dropped, which would return the whole feed.\n */\nconst _splitFeedCursor = (\n  filter: QueryAST.Filter,\n  context: GenerationContext,\n): { range?: { begin?: string; end?: string }; rest?: QueryAST.Filter } => {\n  const reject = () => {\n    throw new QueryError({\n      message: 'A feed cursor filter can only be combined with other filters via AND.',\n      context: { query: context.originalQuery },\n    });\n  };\n\n  if (filter.type === 'feed-cursor') {\n    if (context.selectionInverted) {\n      reject();\n    }\n    return { range: _feedCursorRange(filter) };\n  }\n\n  if (filter.type !== 'and') {\n    if (_containsFeedCursor(filter)) {\n      reject();\n    }\n    return {};\n  }\n\n  const flat = _flattenAnd(filter.filters);\n  const cursors = flat.filter((f): f is QueryAST.FilterFeedCursor => f.type === 'feed-cursor');\n  const rest = flat.filter((f) => f.type !== 'feed-cursor');\n  if (cursors.length === 0) {\n    if (rest.some(_containsFeedCursor)) {\n      reject();\n    }\n    return {};\n  }\n  if (cursors.length > 1 || context.selectionInverted || rest.some(_containsFeedCursor)) {\n    reject();\n  }\n\n  return {\n    range: _feedCursorRange(cursors[0]),\n    rest: rest.length === 0 ? undefined : rest.length === 1 ? rest[0] : { type: 'and', filters: rest },\n  };\n};\n\nconst _feedCursorRange = (\n  filter: QueryAST.FilterFeedCursor,\n): { begin?: string; end?: string; positions?: 'local' | 'edge' } => ({\n  ...(filter.begin !== undefined ? { begin: filter.begin } : {}),\n  ...(filter.end !== undefined ? { end: filter.end } : {}),\n  ...(filter.positions !== undefined ? { positions: filter.positions } : {}),\n});\n\nconst _containsFeedCursor = (filter: QueryAST.Filter): boolean => {\n  switch (filter.type) {\n    case 'feed-cursor':\n      return true;\n    case 'not':\n      return _containsFeedCursor(filter.filter);\n    case 'and':\n    case 'or':\n      return filter.filters.some(_containsFeedCursor);\n    default:\n      return false;\n  }\n};\n\nconst _flattenAnd = (filters: readonly QueryAST.Filter[]): QueryAST.Filter[] => {\n  const result: QueryAST.Filter[] = [];\n  for (const f of filters) {\n    if (f.type === 'and') {\n      result.push(..._flattenAnd(f.filters));\n    } else {\n      result.push(f);\n    }\n  }\n  return result;\n};\n\nconst _timestampFilterToSelector = (filter: QueryAST.FilterTimestamp): QueryPlan.TimestampSelector => {\n  const selector: QueryPlan.TimestampSelector = { _tag: 'TimestampSelector' };\n  const key =\n    filter.field === 'updatedAt'\n      ? filter.operator === 'gte' || filter.operator === 'gt'\n        ? 'updatedAfter'\n        : 'updatedBefore'\n      : filter.operator === 'gte' || filter.operator === 'gt'\n        ? 'createdAfter'\n        : 'createdBefore';\n  selector[key] = filter.value;\n  return selector;\n};\n\nconst _mergeTimestampSelectors = (selectors: QueryPlan.TimestampSelector[]): QueryPlan.TimestampSelector => {\n  const merged: QueryPlan.TimestampSelector = { _tag: 'TimestampSelector' };\n  for (const selector of selectors) {\n    if (selector.updatedAfter != null) {\n      merged.updatedAfter = Math.max(merged.updatedAfter ?? 0, selector.updatedAfter);\n    }\n    if (selector.updatedBefore != null) {\n      merged.updatedBefore = Math.min(merged.updatedBefore ?? Infinity, selector.updatedBefore);\n    }\n    if (selector.createdAfter != null) {\n      merged.createdAfter = Math.max(merged.createdAfter ?? 0, selector.createdAfter);\n    }\n    if (selector.createdBefore != null) {\n      merged.createdBefore = Math.min(merged.createdBefore ?? Infinity, selector.createdBefore);\n    }\n  }\n  return merged;\n};\n\n/**\n * Root-executable: the filter can run against in-memory objects after a wildcard select.\n * Covers true root selectors (`object`, `tag`) plus negations / unions of those.\n * Property-level filters (`compare`, `in`, `range`, `contains`) are intentionally excluded because\n * `filterMatchDoc` only handles them as nested predicates inside an `object` filter, not at the root.\n */\nconst isRootExecutable = (filter: QueryAST.Filter): boolean => {\n  switch (filter.type) {\n    case 'object':\n    case 'tag':\n    case 'annotation':\n    case 'has-parent':\n    case 'mnemonic':\n      return true;\n    case 'not':\n      return isRootExecutable(filter.filter);\n    case 'or':\n      return filter.filters.every(isRootExecutable);\n    default:\n      return false;\n  }\n};\n\n/**\n * Typenames a filter constrains its matches to, or null when it admits objects of any type\n * (so no narrowing is possible). Used to narrow an index selector; the full filter is still\n * re-checked in memory, so returning null is always sound.\n */\nconst _extractFilterTypenames = (filter: QueryAST.Filter): NonNullable<QueryAST.FilterObject['typename']>[] | null => {\n  switch (filter.type) {\n    case 'object':\n      return filter.typename !== null ? [filter.typename] : null;\n    case 'or': {\n      const combined: NonNullable<QueryAST.FilterObject['typename']>[] = [];\n      for (const inner of filter.filters) {\n        const list = _extractFilterTypenames(inner);\n        if (list === null) {\n          return null;\n        }\n        combined.push(...list);\n      }\n      return combined;\n    }\n    default:\n      return null;\n  }\n};\n\nconst isTrivialTypenameFilter = (filter: QueryAST.Filter): boolean => {\n  return (\n    filter.type === 'object' &&\n    filter.typename !== null &&\n    Object.keys(filter.props).length === 0 &&\n    (filter.id === undefined || filter.id.length === 0) &&\n    (filter.foreignKeys === undefined || filter.foreignKeys.length === 0)\n  );\n};\n"],"mappings":";;;;;;;AAOA,IAAM,EAAE,wBAAwB;;;;;;AAmBhC,IAAM,UAAU;AAEhB,IAAM,SAAS;;;;;;AAOf,IAAa,oBAAoB,GAAW,MAAuB,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAE5F,IAAa,UAAU,OAAO,OAAO;;;;;CAKnC,eAAe,OAAgB,SAAwC;EACrE,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GACrD,OAAO;EAET,MAAM,OAAO,SAAS,SAAS,UAAU;EACzC,OAAO,KAAK,MAAM,QAAQ,IAAI,IAAI;CACpC;;;;;;CAOA,qBAAqB,UACnB,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,QAAQ;;;;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