@nicia-ai/typegraph 0.38.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend/postgres/index.cjs +16 -16
- package/dist/backend/postgres/index.js +3 -3
- package/dist/backend/postgres/pglite-store.cjs +11 -11
- package/dist/backend/postgres/pglite-store.d.cts +1 -1
- package/dist/backend/postgres/pglite-store.d.ts +1 -1
- package/dist/backend/postgres/pglite-store.js +8 -8
- package/dist/backend/postgres/pglite.cjs +5 -5
- package/dist/backend/postgres/pglite.js +4 -4
- package/dist/backend/sqlite/index.cjs +6 -6
- package/dist/backend/sqlite/index.js +3 -3
- package/dist/backend/sqlite/libsql.cjs +5 -5
- package/dist/backend/sqlite/libsql.js +3 -3
- package/dist/backend/sqlite/local-store.cjs +11 -11
- package/dist/backend/sqlite/local-store.d.cts +1 -1
- package/dist/backend/sqlite/local-store.d.ts +1 -1
- package/dist/backend/sqlite/local-store.js +9 -9
- package/dist/backend/sqlite/local.cjs +6 -6
- package/dist/backend/sqlite/local.js +4 -4
- package/dist/{chunk-UPXDVI3T.js → chunk-3SK4SVTW.js} +3 -3
- package/dist/{chunk-UPXDVI3T.js.map → chunk-3SK4SVTW.js.map} +1 -1
- package/dist/{chunk-NU23DUSJ.cjs → chunk-3YFDFOYB.cjs} +7 -7
- package/dist/{chunk-NU23DUSJ.cjs.map → chunk-3YFDFOYB.cjs.map} +1 -1
- package/dist/{chunk-NWYCOFEZ.cjs → chunk-5ELKD2FQ.cjs} +4 -4
- package/dist/chunk-5ELKD2FQ.cjs.map +1 -0
- package/dist/{chunk-2SL7OGPR.cjs → chunk-6SRLCSAV.cjs} +478 -338
- package/dist/chunk-6SRLCSAV.cjs.map +1 -0
- package/dist/{chunk-A2FGSWMQ.js → chunk-CBK2IVI2.js} +167 -27
- package/dist/chunk-CBK2IVI2.js.map +1 -0
- package/dist/{chunk-TE5ZA4VX.js → chunk-DOKUXLFH.js} +14 -10
- package/dist/chunk-DOKUXLFH.js.map +1 -0
- package/dist/{chunk-KCLZHYPU.cjs → chunk-E2Q7SP2K.cjs} +52 -52
- package/dist/{chunk-KCLZHYPU.cjs.map → chunk-E2Q7SP2K.cjs.map} +1 -1
- package/dist/{chunk-YLINFV7Z.cjs → chunk-GKQU44SQ.cjs} +67 -63
- package/dist/chunk-GKQU44SQ.cjs.map +1 -0
- package/dist/{chunk-O5H62ZWJ.cjs → chunk-HP6LWBLB.cjs} +14 -2
- package/dist/chunk-HP6LWBLB.cjs.map +1 -0
- package/dist/{chunk-7VLCN3JB.cjs → chunk-HTQOBY75.cjs} +59 -59
- package/dist/{chunk-7VLCN3JB.cjs.map → chunk-HTQOBY75.cjs.map} +1 -1
- package/dist/{chunk-RQPRCEIO.js → chunk-IFDXG2YJ.js} +3 -3
- package/dist/chunk-IFDXG2YJ.js.map +1 -0
- package/dist/{chunk-YJDSPA5E.js → chunk-IFRPHG7O.js} +4 -4
- package/dist/{chunk-YJDSPA5E.js.map → chunk-IFRPHG7O.js.map} +1 -1
- package/dist/{chunk-LZ3TVJY4.cjs → chunk-JD2YC62H.cjs} +17 -17
- package/dist/{chunk-LZ3TVJY4.cjs.map → chunk-JD2YC62H.cjs.map} +1 -1
- package/dist/{chunk-XD6X7O5R.js → chunk-KAFXPB2L.js} +4 -4
- package/dist/{chunk-XD6X7O5R.js.map → chunk-KAFXPB2L.js.map} +1 -1
- package/dist/{chunk-ZHX4KEM7.cjs → chunk-KIZSHRUI.cjs} +7 -7
- package/dist/{chunk-ZHX4KEM7.cjs.map → chunk-KIZSHRUI.cjs.map} +1 -1
- package/dist/{chunk-G32AO634.js → chunk-KXFUQNF2.js} +3 -3
- package/dist/{chunk-G32AO634.js.map → chunk-KXFUQNF2.js.map} +1 -1
- package/dist/{chunk-E6YZRKMM.js → chunk-NQBYTLPW.js} +4 -4
- package/dist/{chunk-E6YZRKMM.js.map → chunk-NQBYTLPW.js.map} +1 -1
- package/dist/{chunk-VBH7ZXSZ.js → chunk-SU7VQOJ3.js} +3 -3
- package/dist/{chunk-VBH7ZXSZ.js.map → chunk-SU7VQOJ3.js.map} +1 -1
- package/dist/{chunk-KFLXWVUJ.js → chunk-UUIBACKJ.js} +14 -3
- package/dist/chunk-UUIBACKJ.js.map +1 -0
- package/dist/{chunk-CQC6VBAF.cjs → chunk-VXAFOF6Z.cjs} +5 -5
- package/dist/{chunk-CQC6VBAF.cjs.map → chunk-VXAFOF6Z.cjs.map} +1 -1
- package/dist/{chunk-XFY73JWD.cjs → chunk-Y6UA55YS.cjs} +5 -5
- package/dist/{chunk-XFY73JWD.cjs.map → chunk-Y6UA55YS.cjs.map} +1 -1
- package/dist/{chunk-6G5CQ6JX.js → chunk-YPUNPG2T.js} +4 -4
- package/dist/{chunk-6G5CQ6JX.js.map → chunk-YPUNPG2T.js.map} +1 -1
- package/dist/graph-merge/index.cjs +30 -32
- package/dist/graph-merge/index.cjs.map +1 -1
- package/dist/graph-merge/index.d.cts +10 -5
- package/dist/graph-merge/index.d.ts +10 -5
- package/dist/graph-merge/index.js +9 -11
- package/dist/graph-merge/index.js.map +1 -1
- package/dist/index.cjs +68 -68
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/interchange/index.cjs +23 -23
- package/dist/interchange/index.d.cts +1 -1
- package/dist/interchange/index.d.ts +1 -1
- package/dist/interchange/index.js +4 -4
- package/dist/profiler/index.d.cts +1 -1
- package/dist/profiler/index.d.ts +1 -1
- package/dist/provenance/index.cjs +11 -11
- package/dist/provenance/index.d.cts +1 -1
- package/dist/provenance/index.d.ts +1 -1
- package/dist/provenance/index.js +2 -2
- package/dist/schema/index.cjs +22 -22
- package/dist/schema/index.js +3 -3
- package/dist/{store-view-BoHqdHjB.d.cts → store-view-BJd6Vwpt.d.cts} +39 -17
- package/dist/{store-view-Ctq-3OHy.d.ts → store-view-CLIhwMMX.d.ts} +39 -17
- package/package.json +1 -1
- package/dist/chunk-2SL7OGPR.cjs.map +0 -1
- package/dist/chunk-A2FGSWMQ.js.map +0 -1
- package/dist/chunk-KFLXWVUJ.js.map +0 -1
- package/dist/chunk-NWYCOFEZ.cjs.map +0 -1
- package/dist/chunk-O5H62ZWJ.cjs.map +0 -1
- package/dist/chunk-RQPRCEIO.js.map +0 -1
- package/dist/chunk-TE5ZA4VX.js.map +0 -1
- package/dist/chunk-YLINFV7Z.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/store/collection-surface.ts","../src/store/recorded-coordinate-guard.ts","../src/store/collections/temporal-read-params.ts","../src/store/store-view.ts","../src/query/compiler/emitter/plan-inspector.ts","../src/query/compiler/emitter/recursive.ts","../src/query/compiler/emitter/set-operations.ts","../src/query/compiler/emitter/standard.ts","../src/utils/identifier.ts","../src/query/ast.ts","../src/query/compiler/typed-json-extract.ts","../src/query/compiler/utils.ts","../src/query/compiler/emitter/standard-builders.ts","../src/query/compiler/passes/fulltext.ts","../src/query/compiler/passes/fusion.ts","../src/query/compiler/passes/recursive.ts","../src/query/compiler/passes/runner.ts","../src/query/compiler/passes/temporal.ts","../src/query/compiler/passes/vector.ts","../src/query/compiler/plan/lowering.ts","../src/query/compiler/recorded-current-index-guard.ts","../src/query/compiler/recursive.ts","../src/query/execution/value-decoder.ts","../src/store/recursive-cte.ts","../src/store/subgraph.ts","../src/query/compiler/set-operations.ts","../src/query/compiler/standard-pass-pipeline.ts","../src/query/compiler/index.ts","../src/utils/path.ts","../src/query/execution/result-mapper.ts","../src/query/cursor.ts","../src/query/execution/pagination.ts","../src/query/execution/field-tracker.ts","../src/query/execution/selective-result-mapper.ts","../src/query/builder/read-instant-template.ts","../src/query/builder/prepared-query.ts","../src/query/builder/validation.ts","../src/query/builder/ast-builder.ts","../src/query/builder/internal-context.ts","../src/query/builder/compile-options.ts","../src/query/builder/executable-query.ts","../src/query/builder/executable-aggregate-query.ts","../src/query/builder/dynamic.ts","../src/query/builder/traversal-builder.ts","../src/query/builder/query-builder.ts","../src/query/builder/unionable-query.ts","../src/query/builder/aggregates.ts","../src/query/builder/fragment.ts","../src/query/builder/index.ts","../src/query/builder.ts","../src/store/fulltext-rebuild.ts","../src/store/search.ts","../src/store/search-facade.ts","../src/backend/branded.ts","../src/graph-extension/classify.ts","../src/graph-extension/remove.ts","../src/store/algorithms/context.ts","../src/store/algorithms/degree.ts","../src/store/algorithms/iterative-graph-operation.ts","../src/store/algorithms/label-propagation.ts","../src/store/algorithms/page-rank.ts","../src/store/algorithms/breadth-first.ts","../src/store/algorithms/reachable.ts","../src/store/algorithms/shortest-path.ts","../src/store/algorithms/weakly-connected-components.ts","../src/store/algorithms/weighted-shortest-path.ts","../src/store/algorithms/index.ts","../src/store/collections/edge-collection.ts","../src/store/collections/coalesce.ts","../src/store/collections/node-collection.ts","../src/store/collection-factory.ts","../src/store/history-store-backend.ts","../src/store/introspect.ts","../src/store/materialize-shared.ts","../src/store/materialize-indexes.ts","../src/store/materialize-removals.ts","../src/store/operations/edge-operations.ts","../src/store/recorded-read-service.ts","../src/store/transaction-receipt.ts","../src/store/store.ts"],"names":["target","field","hasVariableLengthTraversal","compileKindFilter","compileRecursiveBranch","compileQuery","collectRequiredColumnsByAlias","compileSetOperation","having","nullToUndefined","jsonPointer","value","rawRows","outputName","aliasObject","NOT_COMPUTED","max","min","coordinate","entry","rank","chunk","createWorkingTable","initializeWorkingTable","runLabelPropagationRound","extractMemberships","applyNextLabels","rowToEdge","executeEdgeCreate","executeEdgeCreateNoReturnBatch","executeEdgeCreateBatch","executeEdgeUpdate","executeEdgeUpsertUpdate","executeEdgeDelete","executeEdgeHardDelete","results","rowToNode","executeNodeCreate","executeNodeCreateNoReturnBatch","executeNodeCreateBatch","executeNodeUpdate","executeNodeUpsertUpdate","executeNodeDelete","executeNodeHardDelete","result","rows","materializeOne","edge","count","options","sql","replacement"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCO,IAAM,uBAAA,GAA0B;AAAA,EACrC,kB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SAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAM,kBAAA,CAAmB,OAAA,EAAS,KAAK,CAAA;AAC3C,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,MAAA;AAAA,IACP,MAAA;AAAA,IACA,cAAA,EAAgB,sBAAsB,SAAS;AAAA,GACjD;AACF;AA+DA,eAAsB,0BAAA,CAIpB,KAAA,EACA,OAAA,EACA,OAAA,EAUA;AACA,EAAA,MAAM,QAAA,GAAW,MAAM,oBAAA,CAAqB,KAAA,EAAO,OAAO,CAAA;AAC1D,EAAA,OAAO;AAAA,IACL,qBAAA;AAAA,MACE,IAAI,0BAAA;AAAA,QACF,QAAA,CAAS,KAAA;AAAA,QACT,OAAA;AAAA,QACA,OAAA;AAAA,QACA,QAAA,CAAS;AAAA;AACX,KACF;AAAA,IACA,QAAA,CAAS;AAAA,GACX;AACF","file":"chunk-CBK2IVI2.js","sourcesContent":["import { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport type {\n EdgeCollection,\n NodeCollection,\n StoreViewEdgeCollection,\n StoreViewNodeCollection,\n} from \"./types\";\n\n/**\n * StoreView collection surface buckets.\n *\n * The live NodeCollection / EdgeCollection partition into buckets a StoreView\n * treats differently:\n *\n * - temporal reads honor the pinned coordinate;\n * - current reads have no temporal axis and are refused on temporal pins;\n * - writes are never available on a read-only view; and\n * - batch reads require store.batch() and are absent from a view.\n *\n * These arrays are the single runtime source of truth for the proxy routing and\n * the type-level source for the derived StoreView collection types. The\n * StoreView surface-classification test asserts they exactly partition the live\n * collection methods so new collection methods cannot be silently omitted.\n */\n\n/** Temporal-aware node read method names. */\nexport const NODE_TEMPORAL_READ_NAMES = [\n \"getById\",\n \"getByIds\",\n \"find\",\n \"count\",\n] as const satisfies readonly (keyof NodeCollection<NodeType, string>)[];\n\n/** Current-state-only node reads (constraint / index lookups). */\nexport const CURRENT_ONLY_READ_NAMES = [\n \"findByConstraint\",\n \"bulkFindByConstraint\",\n \"bulkFindByIndex\",\n] as const satisfies readonly (keyof NodeCollection<NodeType, string>)[];\n\n/** Node write method names: never available on a read-only StoreView. */\nexport const NODE_WRITE_NAMES = [\n \"create\",\n \"createFromRecord\",\n \"update\",\n \"delete\",\n \"hardDelete\",\n \"upsertById\",\n \"upsertByIdFromRecord\",\n \"bulkCreate\",\n \"bulkUpsertById\",\n \"bulkInsert\",\n \"bulkDelete\",\n \"getOrCreateByConstraint\",\n \"bulkGetOrCreateByConstraint\",\n] as const satisfies readonly (keyof NodeCollection<NodeType, string>)[];\n\n/** Temporal-aware edge read method names. */\nexport const EDGE_TEMPORAL_READ_NAMES = [\n \"getById\",\n \"getByIds\",\n \"find\",\n \"count\",\n \"findFrom\",\n \"findTo\",\n \"findByEndpoints\",\n] as const satisfies readonly (keyof EdgeCollection<\n AnyEdgeType,\n NodeType,\n NodeType\n>)[];\n\n/** Deferred edge batch-read method names. */\nexport const EDGE_BATCH_READ_NAMES = [\n \"batchFindFrom\",\n \"batchFindTo\",\n \"batchFindByEndpoints\",\n] as const satisfies readonly (keyof EdgeCollection<\n AnyEdgeType,\n NodeType,\n NodeType\n>)[];\n\n/** Edge write method names: never available on a read-only StoreView. */\nexport const EDGE_WRITE_NAMES = [\n \"create\",\n \"update\",\n \"delete\",\n \"hardDelete\",\n \"bulkCreate\",\n \"bulkUpsertById\",\n \"bulkInsert\",\n \"bulkDelete\",\n \"getOrCreateByEndpoints\",\n \"bulkGetOrCreateByEndpoints\",\n] as const satisfies readonly (keyof EdgeCollection<\n AnyEdgeType,\n NodeType,\n NodeType\n>)[];\n\n/** Recorded-time collection point reads that reconstruct safely by id. */\nexport const RECORDED_POINT_READ_NAMES = [\n \"getById\",\n \"getByIds\",\n] as const satisfies readonly (keyof StoreViewNodeCollection<NodeType> &\n keyof StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType>)[];\n","import { ConfigurationError } from \"../errors\";\n\ntype RecordedCoordinateGuardOptions = Readonly<{\n code: string;\n message: string;\n context?: Readonly<Record<string, unknown>>;\n suggestion?: string;\n}>;\n\ntype RecordedCoordinateOptions = Readonly<{ recordedAsOf?: unknown }>;\n\nfunction hasOwnRecordedAsOf(\n options: unknown,\n): options is RecordedCoordinateOptions {\n return (\n typeof options === \"object\" &&\n options !== null &&\n Object.hasOwn(options, \"recordedAsOf\")\n );\n}\n\nfunction ownRecordedAsOf(options: unknown): unknown {\n return hasOwnRecordedAsOf(options) ? options.recordedAsOf : undefined;\n}\n\nexport function assertNoRecordedCoordinate(\n options: unknown,\n guard: RecordedCoordinateGuardOptions,\n): void {\n const recordedAsOf = ownRecordedAsOf(options);\n if (recordedAsOf === undefined) return;\n\n throw new ConfigurationError(\n guard.message,\n {\n ...guard.context,\n code: guard.code,\n recordedAsOf,\n },\n guard.suggestion === undefined ?\n undefined\n : { suggestion: guard.suggestion },\n );\n}\n","/**\n * Shared temporal read-parameter resolution for collection reads.\n */\nimport {\n type ReadCoordinate,\n type RecordedInstant,\n resolveReadCoordinate,\n} from \"../../core/temporal\";\nimport { type TemporalMode } from \"../../core/types\";\nimport { nowIso } from \"../../utils/date\";\nimport { assertNoRecordedCoordinate } from \"../recorded-coordinate-guard\";\nimport { type QueryOptions } from \"../types\";\n\ntype ValidReadParams = Omit<QueryOptions, \"recordedAsOf\">;\n\nexport type InternalReadParams = ValidReadParams &\n Readonly<{ recordedAsOf?: RecordedInstant }>;\n\nfunction validReadParams(coordinate: ReadCoordinate): ValidReadParams {\n const { mode, asOf } = coordinate.valid;\n return asOf === undefined ?\n { temporalMode: mode }\n : { temporalMode: mode, asOf };\n}\n\nexport function withValidCoordinate(coordinate: ReadCoordinate): QueryOptions {\n assertNoRecordedCoordinate(\n coordinate.recorded === undefined ?\n undefined\n : { recordedAsOf: coordinate.recorded.asOf },\n {\n code: \"RECORDED_COLLECTION_READ_UNSUPPORTED\",\n message:\n \"Collection reads on StoreView cannot carry recorded-time coordinates.\",\n },\n );\n return validReadParams(coordinate);\n}\n\n/**\n * Flattens a {@link ReadCoordinate} into the `QueryOptions` temporal argument\n * every pinned read accepts. The single point that knows the wire shape of the\n * temporal axis: a `StoreView` injects its coordinate by passing this as a\n * read's trailing temporal argument (or spreading it into an algorithm /\n * subgraph option object). When a new axis (recorded time) is added to\n * {@link ReadCoordinate}, only this function and the backend params change —\n * never the call sites.\n */\nexport function withCoordinate(coordinate: ReadCoordinate): InternalReadParams {\n const valid = validReadParams(coordinate);\n return coordinate.recorded === undefined ?\n valid\n : { ...valid, recordedAsOf: coordinate.recorded.asOf };\n}\n\n/**\n * The temporal slice of a `findNodesByKind` / `findEdgesByKind` /\n * `count*` parameter object.\n */\nexport type TemporalReadParams = Readonly<{\n excludeDeleted: boolean;\n temporalMode: TemporalMode;\n asOf?: string;\n}>;\n\n/**\n * Resolves the temporal portion of a collection read's backend params:\n * the per-call `temporalMode` wins, falling back to the graph default;\n * soft-deletes are excluded except under `includeTombstones`. An `asOf` is\n * rejected unless the mode is `\"asOf\"` (via {@link resolveReadCoordinate}), so\n * a pinned `current + asOf` is a caller error here exactly as it is on the\n * query, subgraph, algorithm, and StoreView paths — never a silent pin. The\n * backend filter still needs a concrete instant for `current`, so this defaults\n * it to \"now\" once the coordinate is validated.\n *\n * Single source of truth for `find` / `count` / endpoint reads across the\n * node and edge collections, so the resolution rules cannot drift between\n * them.\n */\nexport function resolveTemporalReadParams(\n options: InternalReadParams | undefined,\n defaultTemporalMode: TemporalMode,\n): TemporalReadParams {\n assertNoRecordedCoordinate(options, {\n code: \"RECORDED_COLLECTION_READ_UNSUPPORTED\",\n message: \"Broad collection reads cannot honor recorded-time coordinates.\",\n suggestion:\n \"Use store.asOfRecorded(...).nodes.Kind.getById/getByIds for point reads, or query() for recorded-time scans.\",\n });\n\n const { valid } = resolveReadCoordinate(\n options?.temporalMode ?? defaultTemporalMode,\n options?.asOf,\n );\n const { mode, asOf } = valid;\n const base = {\n excludeDeleted: mode !== \"includeTombstones\",\n temporalMode: mode,\n } as const;\n if (mode === \"current\" || mode === \"asOf\") {\n return {\n ...base,\n asOf: asOf ?? nowIso(),\n };\n }\n return base;\n}\n","/**\n * StoreView — a read-only `(mode, asOf)` lens over a {@link Store}.\n *\n * A `StoreView` pins a temporal coordinate and routes every supported\n * read through it, mirroring Datomic's `(d/as-of db t)` database value\n * and SQL:2011 `FOR SYSTEM_TIME AS OF`. It is *read-only by\n * construction*: mutating \"the graph as of last Tuesday\" is incoherent,\n * so writes stay on the live `Store`.\n *\n * The view is an explicit read context, not a single default flip — the\n * temporal seam is not uniform across surfaces (the query builder\n * hardcodes `\"current\"`, `subgraph` reads `graph.defaults` directly,\n * collections apply a per-call default). The view therefore injects its\n * pinned {@link ReadCoordinate} into each surface it hands out through one\n * helper ({@link withCoordinate}), so a future temporal axis (recorded\n * time) lands on every surface at once instead of splitting by surface.\n *\n * Built on the public `Store` surface (plus one internal sealed-query\n * seam), so it composes the same reads `branch()` / `merge()` consume.\n */\nimport {\n type AllNodeTypes,\n type EdgeKinds,\n type GraphDef,\n type NodeKinds,\n} from \"../core/define-graph\";\nimport {\n coordinateContext,\n describeCoordinate,\n type ReadCoordinate,\n type RecordedInstant,\n resolveReadCoordinate,\n withRecordedCoordinate,\n} from \"../core/temporal\";\nimport {\n type AnyEdgeType,\n type NodeId,\n type NodeType,\n type TemporalMode,\n} from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { type InitialQueryBuilder } from \"../query/builder\";\nimport { requireDefined } from \"../utils/presence\";\nimport {\n type BaseTraversalOptions,\n type DegreeOptions,\n type InternalGraphAlgorithms,\n type LabelPropagationMembership,\n type LabelPropagationOptions,\n type NeighborsOptions,\n type NodeIdentifier,\n type PageRankOptions,\n type PageRankScore,\n type PersonalizedPageRankOptions,\n type ReachableNode,\n type ReachableOptions,\n type ShortestPathOptions,\n type ShortestPathResult,\n type TemporalAlgorithmOptions,\n type WeaklyConnectedComponentMembership,\n type WeaklyConnectedComponentsOptions,\n type WeightedShortestPathOptions,\n type WeightedShortestPathResult,\n} from \"./algorithms\";\nimport {\n CURRENT_ONLY_READ_NAMES,\n EDGE_BATCH_READ_NAMES,\n type EDGE_TEMPORAL_READ_NAMES,\n type NODE_TEMPORAL_READ_NAMES,\n type RECORDED_POINT_READ_NAMES,\n} from \"./collection-surface\";\nimport {\n withCoordinate,\n withValidCoordinate,\n} from \"./collections/temporal-read-params\";\nimport { storeRuntime } from \"./runtime-port\";\nimport { type StoreSearch } from \"./search-facade\";\nimport { type Store } from \"./store\";\nimport {\n type InternalSubgraphOptions,\n type SubgraphOptions,\n type SubgraphProject,\n type SubgraphResult,\n} from \"./subgraph\";\nimport {\n type EdgeCollection,\n type NodeCollection,\n type NodeCurrentReads,\n type RecordedStoreViewEdgeCollection,\n type RecordedStoreViewEdgeCollections,\n type RecordedStoreViewNodeCollection,\n type RecordedStoreViewNodeCollections,\n type StoreViewEdgeCollection,\n type StoreViewEdgeCollections,\n type StoreViewNodeCollection,\n type StoreViewNodeCollections,\n} from \"./types\";\n\n// ============================================================\n// Public coordinate + view-scoped option types\n// ============================================================\n\n/**\n * The temporal coordinate a {@link StoreView} pins. A discriminated union on\n * `mode`: `asOf` is *required* for `\"asOf\"` and *rejected* (`never`) for every\n * other mode, so the type mirrors the runtime contract. `view({ mode: \"asOf\" })`\n * (missing timestamp) and `view({ mode: \"current\", asOf })` (pinning an instant\n * outside `\"asOf\"`) are both compile errors, not merely runtime\n * `ValidationError`s.\n */\nexport type StoreViewCoordinate =\n | Readonly<{ mode: \"asOf\"; asOf: string }>\n | Readonly<{ mode: Exclude<TemporalMode, \"asOf\">; asOf?: never }>;\n\n/**\n * {@link Store.subgraph} options with the temporal axis removed — the\n * view's pinned coordinate supplies it.\n */\nexport type StoreViewSubgraphOptions<\n G extends GraphDef,\n EK extends EdgeKinds<G>,\n NK extends NodeKinds<G>,\n P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = Omit<\n SubgraphOptions<G, EK, NK, P>,\n \"temporalMode\" | \"asOf\" | \"recordedAsOf\"\n>;\n\n/** `reachable` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewReachableOptions<G extends GraphDef> = Omit<\n ReachableOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/** `shortestPath` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewShortestPathOptions<G extends GraphDef> = Omit<\n ShortestPathOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/**\n * `weightedShortestPath` options with the temporal axis removed (the pin\n * supplies it).\n */\nexport type StoreViewWeightedShortestPathOptions<G extends GraphDef> = Omit<\n WeightedShortestPathOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/** `canReach` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewCanReachOptions<G extends GraphDef> = Omit<\n BaseTraversalOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/** `neighbors` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewNeighborsOptions<G extends GraphDef> = Omit<\n NeighborsOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/** `degree` options with the temporal axis removed (the pin supplies it). */\nexport type StoreViewDegreeOptions<G extends GraphDef> = Omit<\n DegreeOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/** WCC options with the temporal axis removed (the view's pin supplies it). */\nexport type StoreViewWeaklyConnectedComponentsOptions<G extends GraphDef> =\n Omit<WeaklyConnectedComponentsOptions<G>, keyof TemporalAlgorithmOptions>;\n\n/** Label-propagation options pinned to the view's temporal coordinate. */\nexport type StoreViewLabelPropagationOptions<G extends GraphDef> = Omit<\n LabelPropagationOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/** PageRank options with the temporal axis removed (the view supplies it). */\nexport type StoreViewPageRankOptions<G extends GraphDef> = Omit<\n PageRankOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/** Personalized PageRank options pinned to the view's temporal coordinate. */\nexport type StoreViewPersonalizedPageRankOptions<G extends GraphDef> = Omit<\n PersonalizedPageRankOptions<G>,\n keyof TemporalAlgorithmOptions\n>;\n\n/** Graph-algorithm facade sealed to a {@link StoreView}'s coordinate. */\nexport type StoreViewGraphAlgorithms<G extends GraphDef> = Readonly<{\n shortestPath: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: StoreViewShortestPathOptions<G>,\n ) => Promise<ShortestPathResult | undefined>;\n weightedShortestPath: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: StoreViewWeightedShortestPathOptions<G>,\n ) => Promise<WeightedShortestPathResult | undefined>;\n reachable: (\n from: NodeIdentifier,\n options: StoreViewReachableOptions<G>,\n ) => Promise<readonly ReachableNode[]>;\n canReach: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: StoreViewCanReachOptions<G>,\n ) => Promise<boolean>;\n neighbors: (\n node: NodeIdentifier,\n options: StoreViewNeighborsOptions<G>,\n ) => Promise<readonly ReachableNode[]>;\n degree: (\n node: NodeIdentifier,\n options?: StoreViewDegreeOptions<G>,\n ) => Promise<number>;\n labelPropagation: (\n options: StoreViewLabelPropagationOptions<G>,\n ) => Promise<readonly LabelPropagationMembership[]>;\n weaklyConnectedComponents: (\n options: StoreViewWeaklyConnectedComponentsOptions<G>,\n ) => Promise<readonly WeaklyConnectedComponentMembership[]>;\n pageRank: (\n options: StoreViewPageRankOptions<G>,\n ) => Promise<readonly PageRankScore[]>;\n personalizedPageRank: (\n options: StoreViewPersonalizedPageRankOptions<G>,\n ) => Promise<readonly PageRankScore[]>;\n}>;\n\nfunction isReadCoordinate(\n coordinate: StoreViewCoordinate | ReadCoordinate,\n): coordinate is ReadCoordinate {\n return \"valid\" in coordinate;\n}\n\n// ============================================================\n// Read-only collection wrapping\n// ============================================================\n\n/**\n * Property keys that look like member access but are JS / Promise interop\n * probes, not graph kinds or collection methods. Resolving them to\n * `undefined` keeps `view.nodes` / `view.edges` (and the refusing search\n * facade) from being mistaken for a thenable when accidentally awaited,\n * and keeps inspection / serialization from tripping the unknown-kind\n * guard.\n */\nconst NON_KIND_KEYS: ReadonlySet<string> = new Set([\n \"then\",\n \"catch\",\n \"finally\",\n \"toJSON\",\n]);\n\n/**\n * Returns a function that refuses a write or unsupported-read method on a\n * read-only view with a descriptive error, rather than silently ignoring\n * the pin or failing with an opaque `undefined is not a function`.\n */\nfunction createReadOnlyRefusal(\n entity: \"node\" | \"edge\",\n method: string,\n coordinate: ReadCoordinate,\n): () => never {\n return () => {\n throw new ConfigurationError(\n `'${method}' is not available on a read-only StoreView (${describeCoordinate(coordinate)}). ` +\n `A time-pinned view is a read perspective — perform writes on the live Store.`,\n {\n code: \"STORE_VIEW_READ_ONLY\",\n entity,\n method,\n ...coordinateContext(coordinate),\n },\n );\n };\n}\n\n/**\n * Returns a function that refuses a current-state-only read (constraint /\n * index / endpoint lookup) on a *temporal* view via Promise rejection. Such\n * reads have no temporal axis — they always reflect current state — so on a\n * non-`current` pin they would silently lie. On a `current` view they are\n * delegated straight to the live collection instead of refused.\n */\nfunction createCurrentOnlyRefusal(\n entity: \"node\" | \"edge\",\n method: string,\n coordinate: ReadCoordinate,\n): () => Promise<never> {\n return () =>\n Promise.reject(\n new ConfigurationError(\n `'${method}' is not available on a StoreView (${describeCoordinate(coordinate)}). ` +\n `Constraint / index / endpoint lookups read current state only and ` +\n `cannot honor a temporal coordinate — use a current-mode view or the live Store.`,\n {\n code: \"STORE_VIEW_CURRENT_ONLY\",\n entity,\n method,\n ...coordinateContext(coordinate),\n },\n ),\n );\n}\n\n/**\n * Returns a function that refuses a deferred edge batch read\n * ({@link EDGE_BATCH_READ_NAMES}) on a read-only view. These reads are *reads*,\n * not writes, but they resolve through `store.batch(...)` — a DataLoader context\n * a view does not expose — so the view cannot honor them. The refusal is\n * synchronous because the live method returns a `BatchableQuery` synchronously\n * (it is invoked, not awaited), so a misuse fail-louds at the call site instead\n * of being routed through the write-refusal fallthrough and mislabeled a write.\n */\nfunction createBatchReadRefusal(\n entity: \"node\" | \"edge\",\n method: string,\n coordinate: ReadCoordinate,\n): () => never {\n return () => {\n throw new ConfigurationError(\n `'${method}' is not available on a read-only StoreView (${describeCoordinate(coordinate)}). ` +\n `Batch endpoint reads resolve through store.batch(...), which a view does not expose — ` +\n `use the live Store's batch loader, or the view's findFrom / findTo / findByEndpoints for single reads.`,\n {\n code: \"STORE_VIEW_BATCH_UNAVAILABLE\",\n entity,\n method,\n ...coordinateContext(coordinate),\n },\n );\n };\n}\n\nfunction createRecordedUnsupportedRefusal(\n entity: \"node\" | \"edge\",\n method: string,\n coordinate: ReadCoordinate,\n): () => Promise<never> {\n return () =>\n Promise.reject(\n new ConfigurationError(\n `'${method}' is not available on a RecordedStoreView (${describeCoordinate(coordinate)}). ` +\n `Recorded-time reads are reconstructing reads; this view exposes only query, ` +\n `subgraph, graph algorithms, and collection getById/getByIds/scan reads.`,\n {\n code: \"RECORDED_STORE_VIEW_UNSUPPORTED\",\n entity,\n method,\n ...coordinateContext(coordinate),\n },\n ),\n );\n}\n\n/**\n * Current-state-only collection reads: they take no temporal coordinate, so\n * the view delegates them on a `current` pin and refuses them on a temporal\n * pin rather than silently returning current data. Derived from the same\n * {@link CURRENT_ONLY_READ_NAMES} array that defines the `NodeCurrentReads`\n * type, so the runtime routing decision cannot drift from the type partition.\n */\nconst CURRENT_ONLY_READS: ReadonlySet<string> = new Set(\n CURRENT_ONLY_READ_NAMES,\n);\n\n/**\n * Deferred edge batch reads ({@link EDGE_BATCH_READ_NAMES}): refused on every\n * view (current or temporal) because they resolve through `store.batch(...)`,\n * which a view does not expose. Routed to {@link createBatchReadRefusal} so they\n * are categorized as reads rather than misrouted through the write fallthrough.\n */\nconst EDGE_BATCH_READS: ReadonlySet<string> = new Set(EDGE_BATCH_READ_NAMES);\n\n/**\n * Wraps a `reads` object so its supported reads pass through while any other\n * method that exists on the live collection is handled by `resolveLiveOnly` —\n * the one piece that differs between the read-only (valid-time) and recorded\n * facades. The frozen target and the rejecting `set` / `defineProperty` /\n * `deleteProperty` traps make the view read-only by construction at runtime, and\n * `Object.hasOwn` — not `in` — lets inherited `Object.prototype` members\n * (`toString`, `valueOf`, …) pass straight through so coercion / logging works.\n */\nfunction collectionReadProxy<T extends object>(\n reads: T,\n live: object,\n resolveLiveOnly: (property: string) => unknown,\n): T {\n const target = Object.freeze(reads) as T;\n return new Proxy(target, {\n get(target, property, receiver) {\n if (\n typeof property === \"string\" &&\n !Object.hasOwn(target, property) &&\n Object.hasOwn(live, property)\n ) {\n return resolveLiveOnly(property);\n }\n return Reflect.get(target, property, receiver);\n },\n has(target, property) {\n // Mirror `get`: a property is \"present\" if the proxy resolves a value for\n // it — the pinned reads (own keys of target), any live-collection method\n // (delegated or refused), or an inherited Object.prototype member. Keeps\n // `\"method\" in view.collection` consistent with property access.\n return (\n (typeof property === \"string\" && Object.hasOwn(live, property)) ||\n Reflect.has(target, property)\n );\n },\n set() {\n return false;\n },\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n });\n}\n\n/**\n * Read-only valid-time collection facade. Writes refuse synchronously\n * ({@link createReadOnlyRefusal}); current-state-only reads refuse via Promise\n * rejection on a temporal pin but are delegated to the live collection on a\n * `current` view ({@link CURRENT_ONLY_READS}).\n */\nfunction readOnlyCollectionProxy<T extends object>(\n reads: T,\n live: object,\n coordinate: ReadCoordinate,\n entity: \"node\" | \"edge\",\n): T {\n const isCurrent = coordinate.valid.mode === \"current\";\n return collectionReadProxy(reads, live, (property) => {\n if (CURRENT_ONLY_READS.has(property)) {\n return isCurrent ?\n (live as Record<string, unknown>)[property]\n : createCurrentOnlyRefusal(entity, property, coordinate);\n }\n if (EDGE_BATCH_READS.has(property)) {\n return createBatchReadRefusal(entity, property, coordinate);\n }\n return createReadOnlyRefusal(entity, property, coordinate);\n });\n}\n\n/**\n * Recorded-time collection facade: any live-collection method that is not a\n * supported reconstructing read refuses uniformly.\n */\nfunction recordedCollectionProxy<T extends object>(\n reads: T,\n live: object,\n coordinate: ReadCoordinate,\n entity: \"node\" | \"edge\",\n): T {\n return collectionReadProxy(reads, live, (property) => {\n if (EDGE_BATCH_READS.has(property)) {\n return createBatchReadRefusal(entity, property, coordinate);\n }\n return createRecordedUnsupportedRefusal(entity, property, coordinate);\n });\n}\n\nfunction pinnedNodeCollection(\n live: NodeCollection<NodeType, string>,\n coordinate: ReadCoordinate,\n): StoreViewNodeCollection<NodeType> {\n const temporal = withValidCoordinate(coordinate);\n // Only the temporal reads live in the literal; the proxy serves the\n // current-only reads (delegate on a `current` pin, refuse on a temporal pin).\n const reads: Omit<\n StoreViewNodeCollection<NodeType>,\n keyof NodeCurrentReads<NodeType>\n > &\n Readonly<{\n [\n Method in (typeof NODE_TEMPORAL_READ_NAMES)[number]\n ]: StoreViewNodeCollection<NodeType>[Method];\n }> = {\n getById: (id) => live.getById(id, temporal),\n getByIds: (ids) => live.getByIds(ids, temporal),\n find: (filter) => live.find(filter, temporal),\n count: () => live.count(temporal),\n };\n return readOnlyCollectionProxy(\n reads,\n live,\n coordinate,\n \"node\",\n ) as StoreViewNodeCollection<NodeType>;\n}\n\nfunction pinnedEdgeCollection(\n live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n coordinate: ReadCoordinate,\n): StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType> {\n const temporal = withValidCoordinate(coordinate);\n const reads: StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType> &\n Readonly<{\n [\n Method in (typeof EDGE_TEMPORAL_READ_NAMES)[number]\n ]: StoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType>[Method];\n }> = {\n getById: (id) => live.getById(id, temporal),\n getByIds: (ids) => live.getByIds(ids, temporal),\n find: (filter) => live.find(filter, temporal),\n count: (filter) => live.count(filter, temporal),\n findFrom: (from) => live.findFrom(from, temporal),\n findTo: (to) => live.findTo(to, temporal),\n findByEndpoints: (from, to, options) =>\n live.findByEndpoints(from, to, options, temporal),\n };\n return readOnlyCollectionProxy(reads, live, coordinate, \"edge\");\n}\n\n/**\n * Builds the lazy, per-kind caching proxy that fronts the pinned\n * collections. Shared by the valid-time and recorded views' `nodes` and\n * `edges`: indexing the live proxy throws `KindNotFoundError` for an unknown\n * kind, so the view refuses an unknown kind the same way the live store does —\n * while interop probes ({@link NON_KIND_KEYS}) resolve to `undefined`. `wrap`\n * receives the resolved `kind` so the recorded view can route point reads\n * through the store's recorded seams.\n */\nfunction pinnedCollections<L, W>(\n live: object,\n coordinate: ReadCoordinate,\n isKind: (kind: string) => boolean,\n wrap: (kind: string, liveCollection: L, coordinate: ReadCoordinate) => W,\n): Record<string, W> {\n const cache = new Map<string, W>();\n return new Proxy(\n {},\n {\n get(target, kind, receiver) {\n if (typeof kind !== \"string\") return;\n if (!isKind(kind)) {\n if (NON_KIND_KEYS.has(kind)) return;\n if (Object.hasOwn(Object.prototype, kind)) {\n const inheritedValue: unknown = Reflect.get(target, kind, receiver);\n return inheritedValue;\n }\n }\n const cached = cache.get(kind);\n if (cached !== undefined) return cached;\n const wrapped = wrap(\n kind,\n requireDefined((live as Record<string, L>)[kind]),\n coordinate,\n );\n cache.set(kind, wrapped);\n return wrapped;\n },\n },\n );\n}\n\nfunction pinnedNodeCollectionsFor<G extends GraphDef, W>(\n store: Store<G>,\n coordinate: ReadCoordinate,\n wrap: (\n kind: string,\n live: NodeCollection<NodeType, string>,\n coordinate: ReadCoordinate,\n ) => W,\n): Record<string, W> {\n return pinnedCollections(\n store.nodes,\n coordinate,\n (kind) => Object.hasOwn(store.graph.nodes, kind),\n wrap,\n );\n}\n\nfunction pinnedEdgeCollectionsFor<G extends GraphDef, W>(\n store: Store<G>,\n coordinate: ReadCoordinate,\n wrap: (\n kind: string,\n live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n coordinate: ReadCoordinate,\n ) => W,\n): Record<string, W> {\n return pinnedCollections(\n store.edges,\n coordinate,\n (kind) => Object.hasOwn(store.graph.edges, kind),\n wrap,\n );\n}\n\nfunction recordedNodeCollection<G extends GraphDef>(\n store: Store<G>,\n kind: string,\n live: NodeCollection<NodeType, string>,\n coordinate: ReadCoordinate,\n): RecordedStoreViewNodeCollection<NodeType> {\n const reads: RecordedStoreViewNodeCollection<NodeType> &\n Readonly<{\n [\n Method in (typeof RECORDED_POINT_READ_NAMES)[number]\n ]: RecordedStoreViewNodeCollection<NodeType>[Method];\n }> = {\n getById: (id) =>\n storeRuntime(store).recordedNodeGetById(kind, id, coordinate),\n getByIds: (ids) =>\n storeRuntime(store).recordedNodeGetByIds(kind, ids, coordinate),\n scan: (options) =>\n storeRuntime(store).recordedNodeScan(kind, coordinate, options),\n };\n return recordedCollectionProxy(reads, live, coordinate, \"node\");\n}\n\nfunction recordedEdgeCollection<G extends GraphDef>(\n store: Store<G>,\n kind: string,\n live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n coordinate: ReadCoordinate,\n): RecordedStoreViewEdgeCollection<AnyEdgeType, NodeType, NodeType> {\n const reads: RecordedStoreViewEdgeCollection<\n AnyEdgeType,\n NodeType,\n NodeType\n > &\n Readonly<{\n [\n Method in (typeof RECORDED_POINT_READ_NAMES)[number]\n ]: RecordedStoreViewEdgeCollection<\n AnyEdgeType,\n NodeType,\n NodeType\n >[Method];\n }> = {\n getById: (id) =>\n storeRuntime(store).recordedEdgeGetById(kind, id, coordinate),\n getByIds: (ids) =>\n storeRuntime(store).recordedEdgeGetByIds(kind, ids, coordinate),\n scan: (options) =>\n storeRuntime(store).recordedEdgeScan(kind, coordinate, options),\n };\n return recordedCollectionProxy(reads, live, coordinate, \"edge\");\n}\n\n// ============================================================\n// Read-only search facade\n// ============================================================\n\n/**\n * The non-mutating read methods of {@link StoreSearch}. The `satisfies`\n * constraint binds each name to a real `StoreSearch` member, so a rename or\n * removal of one of these methods is a compile error here rather than a silent\n * routing gap. (Completeness for a *newly added* read method would need a\n * StoreSearch read/write type split, mirroring the node collection's — tracked\n * separately.)\n */\nconst READ_SEARCH_METHOD_NAMES = [\n \"fulltext\",\n \"vector\",\n \"hybrid\",\n] as const satisfies readonly (keyof StoreSearch<GraphDef>)[];\nconst READ_SEARCH_METHODS: ReadonlySet<string> = new Set(\n READ_SEARCH_METHOD_NAMES,\n);\n\ntype SearchInvocation = (...args: readonly unknown[]) => unknown;\n\nfunction searchProxy<G extends GraphDef>(\n resolve: (method: string) => SearchInvocation | undefined,\n): StoreSearch<G> {\n return new Proxy({} as StoreSearch<G>, {\n get(target, method, receiver) {\n // Interop probes must resolve to `undefined` so the facade is not\n // mistaken for a thenable.\n if (typeof method !== \"string\" || NON_KIND_KEYS.has(method)) {\n return;\n }\n // Inherited Object.prototype members (toString / valueOf / …) pass\n // through so coercion / logging of the facade stays safe.\n if (Object.hasOwn(Object.prototype, method)) {\n const inheritedValue: unknown = Reflect.get(target, method, receiver);\n return inheritedValue;\n }\n return resolve(method);\n },\n has(target, method) {\n if (typeof method !== \"string\") return Reflect.has(target, method);\n if (NON_KIND_KEYS.has(method)) return false;\n if (Object.hasOwn(Object.prototype, method)) return true;\n return resolve(method) !== undefined;\n },\n });\n}\n\n/**\n * Builds the error a refused search method rejects with. A `current` view\n * still refuses the mutating maintenance op (`rebuildFulltext`) because the\n * view is read-only; a non-`current` view refuses *all* search because the\n * fulltext / vector index reflects current state only and historical\n * relevance is out of scope.\n */\nfunction searchRefusal(\n method: string,\n coordinate: ReadCoordinate,\n isCurrent: boolean,\n): ConfigurationError {\n return isCurrent ?\n new ConfigurationError(\n `store.search.${method} is a maintenance write and is not available on a ` +\n `read-only StoreView. Run it on the live Store.`,\n {\n code: \"STORE_VIEW_READ_ONLY\",\n method,\n ...coordinateContext(coordinate),\n },\n )\n : new ConfigurationError(\n `store.search.${method} is not available on a StoreView (${describeCoordinate(coordinate)}). ` +\n `The fulltext / vector index reflects current state only; historical ` +\n `relevance is out of scope for a temporal view. Use a current-mode ` +\n `view or query the live Store.`,\n {\n code: \"STORE_VIEW_SEARCH_UNSUPPORTED\",\n method,\n ...coordinateContext(coordinate),\n },\n );\n}\n\n/**\n * The view's search facade. On a `current` view the read methods\n * (`fulltext` / `vector` / `hybrid`) delegate to the live `store.search`;\n * every other case refuses via Promise rejection — `rebuildFulltext` (a\n * maintenance write) on any view, and *all* search on a non-`current`\n * view. A Proxy (not a fixed literal) so a future `StoreSearch` method is\n * refused, not silently passed through, on a temporal view.\n */\nfunction pinnedSearch<G extends GraphDef>(\n store: Store<G>,\n coordinate: ReadCoordinate,\n): StoreSearch<G> {\n const isCurrent = coordinate.valid.mode === \"current\";\n const live =\n isCurrent ?\n (store.search as unknown as Record<string, SearchInvocation>)\n : undefined;\n return searchProxy<G>((method) => {\n if (live !== undefined && READ_SEARCH_METHODS.has(method)) {\n const liveMethod = live[method];\n if (liveMethod !== undefined) {\n return (...args: readonly unknown[]) =>\n Reflect.apply(liveMethod, live, args);\n }\n }\n return () => Promise.reject(searchRefusal(method, coordinate, isCurrent));\n });\n}\n\n/**\n * Builds the error a refused {@link RecordedStoreView} search method rejects\n * with. Unlike {@link searchRefusal}, the recorded view refuses search for\n * *every* method regardless of the composed valid-time mode, so there is no\n * `current` delegating branch.\n */\nfunction recordedSearchRefusal(\n method: string,\n coordinate: ReadCoordinate,\n): ConfigurationError {\n return new ConfigurationError(\n `store.search.${method} is not available on a RecordedStoreView (${describeCoordinate(coordinate)}). ` +\n `The fulltext / vector index reflects current state only and cannot answer a ` +\n `recorded-time query. Run search on the live Store.`,\n {\n code: \"RECORDED_STORE_VIEW_SEARCH_UNSUPPORTED\",\n method,\n ...coordinateContext(coordinate),\n },\n );\n}\n\n/**\n * The recorded view's search facade: every method refuses. It never delegates\n * to the live `store.search` even when the composed valid-time mode is\n * `current` — a recorded-time read reconstructs from the history relations,\n * while the fulltext / vector index reflects current state only, so serving a\n * live hit would be a silent lie. A Proxy (not a fixed literal) so a future\n * `StoreSearch` method refuses too instead of resolving to `undefined`.\n */\nfunction recordedSearch<G extends GraphDef>(\n coordinate: ReadCoordinate,\n): StoreSearch<G> {\n return searchProxy<G>(\n (method) => () => Promise.reject(recordedSearchRefusal(method, coordinate)),\n );\n}\n\n// ============================================================\n// Coordinate-pinned view base\n// ============================================================\n\n/**\n * Shared base for the read-only views. Holds the pinned {@link ReadCoordinate}\n * and delegates the graph algorithms, `subgraph`, and `query` to the live store\n * with that coordinate flattened into each call. {@link StoreView} (valid-time)\n * and {@link RecordedStoreView} (recorded-time) extend it; only the surfaces\n * that genuinely differ — collections, search, and the coordinate-changing\n * helpers — live on the subclasses.\n */\nabstract class CoordinatePinnedView<G extends GraphDef> {\n protected readonly store: Store<G>;\n protected readonly coordinate: ReadCoordinate;\n #algorithmFacade: StoreViewGraphAlgorithms<G> | undefined;\n #internalAlgorithms: InternalGraphAlgorithms<G> | undefined;\n\n constructor(store: Store<G>, coordinate: ReadCoordinate) {\n this.store = store;\n this.coordinate = coordinate;\n }\n\n /** The temporal mode this view reads in. */\n get mode(): TemporalMode {\n return this.coordinate.valid.mode;\n }\n\n /** The pinned valid-time `asOf` timestamp, or `undefined` for other modes. */\n get asOf(): string | undefined {\n return this.coordinate.valid.asOf;\n }\n\n /**\n * A query builder pinned to this view's coordinate. The temporal axis is\n * sealed: calling `.temporal(...)` on the returned builder throws, so the\n * view's coordinate cannot be overridden on a per-query basis.\n */\n query(): InitialQueryBuilder<G, \"sealed\"> {\n return storeRuntime(this.store).sealedQuery(this.coordinate);\n }\n\n protected internalAlgorithms(): InternalGraphAlgorithms<G> {\n this.#internalAlgorithms ??= storeRuntime(\n this.store,\n ).algorithmsAtCoordinate(this.coordinate);\n return this.#internalAlgorithms;\n }\n\n /** Graph algorithms pinned to this view's immutable temporal coordinate. */\n get algorithms(): StoreViewGraphAlgorithms<G> {\n this.#algorithmFacade ??= Object.freeze({\n shortestPath: (from, to, options) => this.shortestPath(from, to, options),\n weightedShortestPath: (from, to, options) =>\n this.weightedShortestPath(from, to, options),\n reachable: (from, options) => this.reachable(from, options),\n canReach: (from, to, options) => this.canReach(from, to, options),\n neighbors: (node, options) => this.neighbors(node, options),\n degree: (node, options) => this.degree(node, options),\n labelPropagation: (options) => this.labelPropagation(options),\n weaklyConnectedComponents: (options) =>\n this.weaklyConnectedComponents(options),\n pageRank: (options) => this.pageRank(options),\n personalizedPageRank: (options) => this.personalizedPageRank(options),\n });\n return this.#algorithmFacade;\n }\n\n /** Extracts a subgraph at this view's pinned coordinate. */\n subgraph<\n const EK extends EdgeKinds<G>,\n const NK extends NodeKinds<G> = NodeKinds<G>,\n const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n >(\n rootId: NodeId<AllNodeTypes<G>>,\n options: StoreViewSubgraphOptions<G, EK, NK, P>,\n ): Promise<SubgraphResult<G, NK, EK, P>> {\n const internalOptions = {\n ...options,\n ...withCoordinate(this.coordinate),\n } as InternalSubgraphOptions<G, EK, NK, P>;\n return storeRuntime(this.store).subgraphAtCoordinate(\n rootId,\n internalOptions,\n );\n }\n\n /** Shortest path between two nodes at this view's pinned coordinate. */\n shortestPath(\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: StoreViewShortestPathOptions<G>,\n ): Promise<ShortestPathResult | undefined> {\n return this.internalAlgorithms().shortestPath(from, to, {\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** Minimum-total-weight path at this view's pinned coordinate. */\n weightedShortestPath(\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: StoreViewWeightedShortestPathOptions<G>,\n ): Promise<WeightedShortestPathResult | undefined> {\n return this.internalAlgorithms().weightedShortestPath(from, to, {\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** Nodes reachable from `from` at this view's pinned coordinate. */\n reachable(\n from: NodeIdentifier,\n options: StoreViewReachableOptions<G>,\n ): Promise<readonly ReachableNode[]> {\n return this.internalAlgorithms().reachable(from, {\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** Whether `to` is reachable from `from` at this view's pinned coordinate. */\n canReach(\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: StoreViewCanReachOptions<G>,\n ): Promise<boolean> {\n return this.internalAlgorithms().canReach(from, to, {\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** The k-hop neighborhood of `node` at this view's pinned coordinate. */\n neighbors(\n node: NodeIdentifier,\n options: StoreViewNeighborsOptions<G>,\n ): Promise<readonly ReachableNode[]> {\n return this.internalAlgorithms().neighbors(node, {\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** Counts active edges incident to `node` at this view's pinned coordinate. */\n degree(\n node: NodeIdentifier,\n options?: StoreViewDegreeOptions<G>,\n ): Promise<number> {\n return this.internalAlgorithms().degree(node, {\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** Deterministic label-propagation memberships at this view's coordinate. */\n labelPropagation(\n options: StoreViewLabelPropagationOptions<G>,\n ): Promise<readonly LabelPropagationMembership[]> {\n return this.internalAlgorithms().labelPropagation({\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** Exact WCC memberships at this view's pinned coordinate. */\n weaklyConnectedComponents(\n options: StoreViewWeaklyConnectedComponentsOptions<G>,\n ): Promise<readonly WeaklyConnectedComponentMembership[]> {\n return this.internalAlgorithms().weaklyConnectedComponents({\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** Global PageRank scores at this view's pinned coordinate. */\n pageRank(\n options: StoreViewPageRankOptions<G>,\n ): Promise<readonly PageRankScore[]> {\n return this.internalAlgorithms().pageRank({\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n\n /** Personalized PageRank scores at this view's pinned coordinate. */\n personalizedPageRank(\n options: StoreViewPersonalizedPageRankOptions<G>,\n ): Promise<readonly PageRankScore[]> {\n return this.internalAlgorithms().personalizedPageRank({\n ...options,\n ...withCoordinate(this.coordinate),\n });\n }\n}\n\n// ============================================================\n// StoreView\n// ============================================================\n\n/**\n * A read-only `(mode, asOf)` lens over a {@link Store}. Construct one via\n * {@link Store.asOf} (valid-time) or {@link Store.view} (any public\n * mode), never directly.\n *\n * @example\n * ```typescript\n * const past = store.asOf(\"2026-01-01T00:00:00.000Z\");\n * const alice = await past.nodes.Person.getById(aliceId);\n * const jobs = await past.edges.worksAt.findFrom(alice!);\n * const reach = await past.reachable(alice!, { edges: [\"knows\"] });\n * ```\n */\nexport class StoreView<G extends GraphDef> extends CoordinatePinnedView<G> {\n #nodes: StoreViewNodeCollections<G> | undefined;\n #edges: StoreViewEdgeCollections<G> | undefined;\n #search: StoreSearch<G> | undefined;\n\n constructor(\n store: Store<G>,\n coordinate: StoreViewCoordinate | ReadCoordinate,\n ) {\n super(\n store,\n isReadCoordinate(coordinate) ? coordinate : (\n resolveReadCoordinate(\n coordinate.mode,\n coordinate.asOf,\n 'Use store.asOf(\"2026-01-01T00:00:00.000Z\") or store.view({ mode: \"asOf\", asOf }).',\n )\n ),\n );\n }\n\n /** Adds a recorded-time pin, returning the narrow reconstructing view. */\n asOfRecorded(recordedAsOf: RecordedInstant): RecordedStoreView<G> {\n return new RecordedStoreView(\n this.store,\n withRecordedCoordinate(this.coordinate, recordedAsOf),\n );\n }\n\n /** Read-only node collections pinned to this view's coordinate. */\n get nodes(): StoreViewNodeCollections<G> {\n this.#nodes ??= pinnedNodeCollectionsFor(\n this.store,\n this.coordinate,\n (_kind, live: NodeCollection<NodeType, string>, coordinate) =>\n pinnedNodeCollection(live, coordinate),\n ) as unknown as StoreViewNodeCollections<G>;\n return this.#nodes;\n }\n\n /** Read-only edge collections pinned to this view's coordinate. */\n get edges(): StoreViewEdgeCollections<G> {\n this.#edges ??= pinnedEdgeCollectionsFor(\n this.store,\n this.coordinate,\n (\n _kind,\n live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n coordinate,\n ) => pinnedEdgeCollection(live, coordinate),\n ) as unknown as StoreViewEdgeCollections<G>;\n return this.#edges;\n }\n\n /**\n * Read-only search facade. On a `current` view the read methods\n * (`fulltext` / `vector` / `hybrid`) delegate to the live `store.search`,\n * while the mutating `rebuildFulltext` is refused — the view is read-only.\n * On any non-`current` pin every search method refuses: the fulltext /\n * vector index reflects current state only, so historical relevance is\n * out of scope.\n */\n get search(): StoreSearch<G> {\n this.#search ??= pinnedSearch<G>(this.store, this.coordinate);\n return this.#search;\n }\n}\n\n/**\n * A narrow recorded-time read lens. It preserves the valid-time coordinate\n * carried by the source view and adds a recorded/system-time pin. Collection\n * reads expose point reconstruction and bounded scans; broad collection\n * predicates, endpoint reads, search, and further coordinate changes are absent\n * from the typed surface and refused by the runtime proxies for JS callers.\n */\nexport class RecordedStoreView<\n G extends GraphDef,\n> extends CoordinatePinnedView<G> {\n #nodes: RecordedStoreViewNodeCollections<G> | undefined;\n #edges: RecordedStoreViewEdgeCollections<G> | undefined;\n\n constructor(store: Store<G>, coordinate: ReadCoordinate) {\n super(store, coordinate);\n if (!store.recordedReadBound) {\n throw new ConfigurationError(\n \"asOfRecorded() requires a recorded read relation.\",\n { code: \"ASOF_RECORDED_REQUIRES_BINDING\" },\n {\n suggestion:\n \"Create the store with createStore(graph, backend, { history: true }) to bind TypeGraph's built-in captured relation, or pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation.\",\n },\n );\n }\n if (coordinate.recorded === undefined) {\n throw new ConfigurationError(\n \"RecordedStoreView requires a recorded-time coordinate.\",\n { code: \"RECORDED_STORE_VIEW_MISSING_COORDINATE\" },\n );\n }\n\n // `search` is intentionally absent from the typed recorded surface (a TS\n // caller gets a compile error). It is installed here as a runtime-only\n // backstop — invisible to the class type — so a JS caller reaching past the\n // types gets a clear refusal rather than a bare `TypeError`. The fulltext /\n // vector index reflects current state only and cannot answer a\n // recorded-time query; the facade refuses every method. Mirrors the\n // per-collection runtime refusals ({@link recordedCollectionProxy}).\n let searchBackstop: StoreSearch<G> | undefined;\n Object.defineProperty(this, \"search\", {\n enumerable: false,\n get(): StoreSearch<G> {\n searchBackstop ??= recordedSearch<G>(coordinate);\n return searchBackstop;\n },\n });\n }\n\n /** The recorded/system-time timestamp this view reconstructs. */\n get asOfRecorded(): string {\n const recorded = this.coordinate.recorded;\n if (recorded === undefined) {\n throw new ConfigurationError(\n \"RecordedStoreView requires a recorded-time coordinate.\",\n { code: \"RECORDED_STORE_VIEW_MISSING_COORDINATE\" },\n );\n }\n return recorded.asOf;\n }\n\n /** Recorded-time node reconstructing-read collections. */\n get nodes(): RecordedStoreViewNodeCollections<G> {\n this.#nodes ??= pinnedNodeCollectionsFor(\n this.store,\n this.coordinate,\n (kind, live: NodeCollection<NodeType, string>, coordinate) =>\n recordedNodeCollection(this.store, kind, live, coordinate),\n ) as unknown as RecordedStoreViewNodeCollections<G>;\n return this.#nodes;\n }\n\n /** Recorded-time edge reconstructing-read collections. */\n get edges(): RecordedStoreViewEdgeCollections<G> {\n this.#edges ??= pinnedEdgeCollectionsFor(\n this.store,\n this.coordinate,\n (\n kind,\n live: EdgeCollection<AnyEdgeType, NodeType, NodeType>,\n coordinate,\n ) => recordedEdgeCollection(this.store, kind, live, coordinate),\n ) as unknown as RecordedStoreViewEdgeCollections<G>;\n return this.#edges;\n }\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport {\n type LimitOffsetPlanNode,\n type LogicalPlan,\n type LogicalPlanNode,\n type ProjectPlanNode,\n type SortPlanNode,\n} from \"../plan\";\n\nexport type ProjectPlanShape = Readonly<{\n hasAggregate: boolean;\n hasFulltextMatch: boolean;\n hasLimitOffset: boolean;\n hasRecursiveExpand: boolean;\n hasSetOperation: boolean;\n hasSort: boolean;\n hasVectorKnn: boolean;\n limitOffsetNode: LimitOffsetPlanNode | undefined;\n rootProjectNode: ProjectPlanNode;\n sortNode: SortPlanNode | undefined;\n}>;\n\nexport type SetOperationPlanShape = Readonly<{\n hasLimitOffset: boolean;\n hasSetOperation: boolean;\n hasSort: boolean;\n limitOffsetNode: LimitOffsetPlanNode | undefined;\n sortNode: SortPlanNode | undefined;\n}>;\n\nfunction collectPlanOperations(node: LogicalPlanNode, ops: Set<string>): void {\n ops.add(node.op);\n\n switch (node.op) {\n case \"aggregate\":\n case \"filter\":\n case \"fulltext_match\":\n case \"join\":\n case \"limit_offset\":\n case \"project\":\n case \"recursive_expand\":\n case \"sort\":\n case \"vector_knn\": {\n collectPlanOperations(node.input, ops);\n return;\n }\n case \"set_op\": {\n collectPlanOperations(node.left, ops);\n collectPlanOperations(node.right, ops);\n return;\n }\n case \"scan\": {\n return;\n }\n }\n}\n\nfunction findUnaryNodeInProjectChain<TNode extends LogicalPlanNode>(\n rootNode: ProjectPlanNode,\n op: TNode[\"op\"],\n): TNode | undefined {\n let currentNode: LogicalPlanNode = rootNode.input;\n\n for (;;) {\n if (currentNode.op === op) {\n return currentNode as TNode;\n }\n\n switch (currentNode.op) {\n case \"aggregate\":\n case \"filter\":\n case \"fulltext_match\":\n case \"join\":\n case \"limit_offset\":\n case \"recursive_expand\":\n case \"sort\":\n case \"vector_knn\": {\n currentNode = currentNode.input;\n continue;\n }\n case \"project\":\n case \"scan\":\n case \"set_op\": {\n return undefined;\n }\n }\n }\n}\n\nfunction inspectProjectPlan(logicalPlan: LogicalPlan): ProjectPlanShape {\n if (logicalPlan.root.op !== \"project\") {\n throw new CompilerInvariantError(\n `SQL emitter expected logical plan root to be \"project\", got \"${logicalPlan.root.op}\"`,\n { component: \"plan-inspector\" },\n );\n }\n\n const operations = new Set<string>();\n collectPlanOperations(logicalPlan.root, operations);\n\n const limitOffsetNode = findUnaryNodeInProjectChain<LimitOffsetPlanNode>(\n logicalPlan.root,\n \"limit_offset\",\n );\n const sortNode = findUnaryNodeInProjectChain<SortPlanNode>(\n logicalPlan.root,\n \"sort\",\n );\n\n return {\n hasAggregate: operations.has(\"aggregate\"),\n hasFulltextMatch: operations.has(\"fulltext_match\"),\n hasLimitOffset: operations.has(\"limit_offset\"),\n hasRecursiveExpand: operations.has(\"recursive_expand\"),\n hasSetOperation: operations.has(\"set_op\"),\n hasSort: operations.has(\"sort\"),\n hasVectorKnn: operations.has(\"vector_knn\"),\n limitOffsetNode,\n rootProjectNode: logicalPlan.root,\n sortNode,\n };\n}\n\nexport function inspectStandardProjectPlan(\n logicalPlan: LogicalPlan,\n): ProjectPlanShape {\n const shape = inspectProjectPlan(logicalPlan);\n if (shape.hasSetOperation) {\n throw new CompilerInvariantError(\n 'Standard SQL emitter does not support plans containing \"set_op\" nodes',\n { component: \"plan-inspector\" },\n );\n }\n if (shape.hasRecursiveExpand) {\n throw new CompilerInvariantError(\n 'Standard SQL emitter does not support plans containing \"recursive_expand\" nodes',\n { component: \"plan-inspector\" },\n );\n }\n return shape;\n}\n\nexport function inspectRecursiveProjectPlan(\n logicalPlan: LogicalPlan,\n): ProjectPlanShape {\n const shape = inspectProjectPlan(logicalPlan);\n if (!shape.hasRecursiveExpand) {\n throw new CompilerInvariantError(\n 'Recursive SQL emitter expected logical plan to contain a \"recursive_expand\" node',\n { component: \"plan-inspector\" },\n );\n }\n if (shape.hasSetOperation) {\n throw new CompilerInvariantError(\n 'Recursive SQL emitter does not support plans containing \"set_op\" nodes',\n { component: \"plan-inspector\" },\n );\n }\n return shape;\n}\n\nfunction findTopLevelLimitOffsetNode(\n rootNode: LogicalPlanNode,\n): LimitOffsetPlanNode | undefined {\n let currentNode: LogicalPlanNode = rootNode;\n\n for (;;) {\n if (currentNode.op === \"limit_offset\") {\n return currentNode;\n }\n\n switch (currentNode.op) {\n case \"aggregate\":\n case \"filter\":\n case \"fulltext_match\":\n case \"join\":\n case \"project\":\n case \"recursive_expand\":\n case \"sort\":\n case \"vector_knn\": {\n currentNode = currentNode.input;\n continue;\n }\n case \"scan\":\n case \"set_op\": {\n return undefined;\n }\n }\n }\n}\n\nfunction findTopLevelSortNode(\n rootNode: LogicalPlanNode,\n): SortPlanNode | undefined {\n let currentNode: LogicalPlanNode = rootNode;\n\n for (;;) {\n if (currentNode.op === \"sort\") {\n return currentNode;\n }\n\n switch (currentNode.op) {\n case \"aggregate\":\n case \"filter\":\n case \"fulltext_match\":\n case \"join\":\n case \"limit_offset\":\n case \"project\":\n case \"recursive_expand\":\n case \"vector_knn\": {\n currentNode = currentNode.input;\n continue;\n }\n case \"scan\":\n case \"set_op\": {\n return undefined;\n }\n }\n }\n}\n\nexport function inspectSetOperationPlan(\n logicalPlan: LogicalPlan,\n): SetOperationPlanShape {\n const operations = new Set<string>();\n collectPlanOperations(logicalPlan.root, operations);\n\n if (!operations.has(\"set_op\")) {\n throw new CompilerInvariantError(\n 'Set-operation SQL emitter expected logical plan to contain a \"set_op\" node',\n { component: \"plan-inspector\" },\n );\n }\n\n const limitOffsetNode = findTopLevelLimitOffsetNode(logicalPlan.root);\n const sortNode = findTopLevelSortNode(logicalPlan.root);\n\n return {\n hasLimitOffset: limitOffsetNode !== undefined,\n hasSetOperation: true,\n hasSort: sortNode !== undefined,\n limitOffsetNode,\n sortNode,\n };\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectRecursiveProjectPlan } from \"./plan-inspector\";\n\nexport type RecursiveQueryEmitterInput = Readonly<{\n depthFilter: SqlFragment;\n limitOffset?: SqlFragment;\n logicalPlan: LogicalPlan;\n orderBy?: SqlFragment;\n projection: SqlFragment;\n recursiveCte: SqlFragment;\n}>;\n\nfunction assertRecursiveEmitterClauseAlignment(\n logicalPlan: LogicalPlan,\n input: RecursiveQueryEmitterInput,\n): void {\n const planShape = inspectRecursiveProjectPlan(logicalPlan);\n if (planShape.hasSort && input.orderBy === undefined) {\n throw new CompilerInvariantError(\n \"Recursive SQL emitter expected ORDER BY clause for plan containing a sort node\",\n { component: \"recursive-emitter\" },\n );\n }\n if (!planShape.hasSort && input.orderBy !== undefined) {\n throw new CompilerInvariantError(\n \"Recursive SQL emitter received ORDER BY clause for a plan without sort nodes\",\n { component: \"recursive-emitter\" },\n );\n }\n if (planShape.hasLimitOffset && input.limitOffset === undefined) {\n throw new CompilerInvariantError(\n \"Recursive SQL emitter expected LIMIT/OFFSET clause for plan containing a limit_offset node\",\n { component: \"recursive-emitter\" },\n );\n }\n if (!planShape.hasLimitOffset && input.limitOffset !== undefined) {\n throw new CompilerInvariantError(\n \"Recursive SQL emitter received LIMIT/OFFSET clause for a plan without limit_offset nodes\",\n { component: \"recursive-emitter\" },\n );\n }\n}\n\nexport function emitRecursiveQuerySql(\n input: RecursiveQueryEmitterInput,\n): SqlFragment {\n assertRecursiveEmitterClauseAlignment(input.logicalPlan, input);\n\n const parts: SqlFragment[] = [\n sql`WITH RECURSIVE`,\n input.recursiveCte,\n sql`SELECT ${input.projection}`,\n sql`FROM recursive_cte`,\n input.depthFilter,\n ];\n\n if (input.orderBy !== undefined) {\n parts.push(input.orderBy);\n }\n if (input.limitOffset !== undefined) {\n parts.push(input.limitOffset);\n }\n\n return sql.join(parts, sql` `);\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectSetOperationPlan } from \"./plan-inspector\";\n\nexport type SetOperationQueryEmitterInput = Readonly<{\n baseQuery: SqlFragment;\n ctes?: readonly SqlFragment[];\n logicalPlan: LogicalPlan;\n suffixClauses?: readonly SqlFragment[];\n}>;\n\nfunction assertSetOperationEmitterClauseAlignment(\n logicalPlan: LogicalPlan,\n suffixClauses: readonly SqlFragment[] | undefined,\n): void {\n const shape = inspectSetOperationPlan(logicalPlan);\n const hasSuffixClauses =\n suffixClauses !== undefined && suffixClauses.length > 0;\n\n if (!shape.hasSort && !shape.hasLimitOffset && hasSuffixClauses) {\n throw new CompilerInvariantError(\n \"Set-operation SQL emitter received suffix clauses for a plan without top-level sort or limit_offset nodes\",\n { component: \"set-operation-emitter\" },\n );\n }\n\n if (!hasSuffixClauses) {\n if (shape.hasSort || shape.hasLimitOffset) {\n throw new CompilerInvariantError(\n \"Set-operation SQL emitter expected suffix clauses for plan containing top-level sort or limit_offset nodes\",\n { component: \"set-operation-emitter\" },\n );\n }\n return;\n }\n\n const limitOffsetClauseCount =\n shape.limitOffsetNode === undefined ?\n 0\n : (shape.limitOffsetNode.limit === undefined ? 0 : 1) +\n (shape.limitOffsetNode.offset === undefined ? 0 : 1);\n const expectedClauseCount =\n (shape.sortNode === undefined ? 0 : 1) + limitOffsetClauseCount;\n\n if (suffixClauses.length !== expectedClauseCount) {\n throw new CompilerInvariantError(\n `Set-operation SQL emitter expected ${String(expectedClauseCount)} top-level suffix clause(s) from logical plan, got ${String(suffixClauses.length)}`,\n { component: \"set-operation-emitter\" },\n );\n }\n}\n\nexport function emitSetOperationQuerySql(\n input: SetOperationQueryEmitterInput,\n): SqlFragment {\n assertSetOperationEmitterClauseAlignment(\n input.logicalPlan,\n input.suffixClauses,\n );\n\n const parts: SqlFragment[] = [];\n if (input.ctes !== undefined && input.ctes.length > 0) {\n parts.push(sql`WITH ${sql.join([...input.ctes], sql`, `)}`);\n }\n\n parts.push(input.baseQuery);\n\n if (input.suffixClauses !== undefined && input.suffixClauses.length > 0) {\n parts.push(...input.suffixClauses);\n }\n\n return sql.join(parts, sql` `);\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport { type LogicalPlan } from \"../plan\";\nimport { inspectStandardProjectPlan } from \"./plan-inspector\";\n\nexport type StandardQueryEmitterInput = Readonly<{\n ctes: readonly SqlFragment[];\n fromClause: SqlFragment;\n groupBy?: SqlFragment;\n having?: SqlFragment;\n limitOffset?: SqlFragment;\n logicalPlan: LogicalPlan;\n orderBy?: SqlFragment;\n projection: SqlFragment;\n}>;\n\nfunction assertStandardEmitterClauseAlignment(\n logicalPlan: LogicalPlan,\n input: StandardQueryEmitterInput,\n): void {\n const planShape = inspectStandardProjectPlan(logicalPlan);\n if (input.groupBy !== undefined && !planShape.hasAggregate) {\n throw new CompilerInvariantError(\n \"Standard SQL emitter received GROUP BY clause for a plan without aggregate nodes\",\n { component: \"standard-emitter\" },\n );\n }\n if (input.having !== undefined && !planShape.hasAggregate) {\n throw new CompilerInvariantError(\n \"Standard SQL emitter received HAVING clause for a plan without aggregate nodes\",\n { component: \"standard-emitter\" },\n );\n }\n const expectsOrderBy =\n planShape.hasSort || planShape.hasVectorKnn || planShape.hasFulltextMatch;\n if (expectsOrderBy && input.orderBy === undefined) {\n throw new CompilerInvariantError(\n \"Standard SQL emitter expected ORDER BY clause for plan containing a sort, vector_knn, or fulltext_match node\",\n { component: \"standard-emitter\" },\n );\n }\n if (!expectsOrderBy && input.orderBy !== undefined) {\n throw new CompilerInvariantError(\n \"Standard SQL emitter received ORDER BY clause for a plan without sort, vector_knn, or fulltext_match nodes\",\n { component: \"standard-emitter\" },\n );\n }\n if (planShape.hasLimitOffset && input.limitOffset === undefined) {\n throw new CompilerInvariantError(\n \"Standard SQL emitter expected LIMIT/OFFSET clause for plan containing a limit_offset node\",\n { component: \"standard-emitter\" },\n );\n }\n if (!planShape.hasLimitOffset && input.limitOffset !== undefined) {\n throw new CompilerInvariantError(\n \"Standard SQL emitter received LIMIT/OFFSET clause for a plan without limit_offset nodes\",\n { component: \"standard-emitter\" },\n );\n }\n}\n\nexport function emitStandardQuerySql(\n input: StandardQueryEmitterInput,\n): SqlFragment {\n assertStandardEmitterClauseAlignment(input.logicalPlan, input);\n\n const parts: SqlFragment[] = [];\n if (input.ctes.length > 0) {\n parts.push(sql`WITH ${sql.join([...input.ctes], sql`, `)}`);\n }\n\n parts.push(sql`SELECT ${input.projection}`, input.fromClause);\n\n if (input.groupBy !== undefined) {\n parts.push(input.groupBy);\n }\n if (input.having !== undefined) {\n parts.push(input.having);\n }\n if (input.orderBy !== undefined) {\n parts.push(input.orderBy);\n }\n if (input.limitOffset !== undefined) {\n parts.push(input.limitOffset);\n }\n\n return sql.join(parts, sql` `);\n}\n","/**\n * Bounding for generated SQL identifiers (column aliases, index names).\n *\n * PostgreSQL silently truncates any identifier longer than 63 *bytes* —\n * not characters — keeping only the leading bytes. Two distinct generated\n * identifiers that share a >63-byte prefix therefore collapse onto the same\n * physical name, producing an \"ambiguous column\" error or, worse, a\n * silently wrong value.\n *\n * `boundPgIdentifier` closes that gap: a name that already fits is returned\n * verbatim (short, human-readable identifiers stay readable and previously\n * emitted SQL is unchanged), and a name that does not is truncated by BYTE\n * length to leave room for a deterministic hash suffix computed from the\n * caller's FULL, untruncated input. Hashing the untruncated input is what\n * makes two colliding names diverge — the bytes truncation would discard\n * still shape the suffix.\n */\nimport { MAX_PG_IDENTIFIER_LENGTH } from \"../constants\";\nimport { fnv1aBase36 } from \"./hash\";\nimport { requireDefined } from \"./presence\";\n\nconst TEXT_ENCODER = new TextEncoder();\n\n/**\n * Truncates a string so its UTF-8 byte length does not exceed maxBytes.\n * Avoids splitting in the middle of a multi-byte character.\n */\nexport function truncateToBytes(value: string, maxBytes: number): string {\n const encoded = TEXT_ENCODER.encode(value);\n if (encoded.byteLength <= maxBytes) return value;\n\n // Walk backwards from the limit to find a clean character boundary.\n // UTF-8 continuation bytes have the form 10xxxxxx (0x80..0xBF).\n let end = maxBytes;\n while (\n end > 0 &&\n requireDefined(encoded[end]) >= 0x80 &&\n requireDefined(encoded[end]) < 0xc0\n ) {\n end--;\n }\n\n return new TextDecoder().decode(encoded.slice(0, end));\n}\n\n/**\n * Bounds `name` to PostgreSQL's 63-byte identifier limit.\n *\n * Returns `name` unchanged when its UTF-8 byte length already fits, so\n * short identifiers keep their exact, readable form. Otherwise the name is\n * truncated by BYTE length to leave room for `\"_\" + fnv1aBase36(hashInput)`,\n * and the hash is appended — guaranteeing the result stays within the limit\n * while distinguishing inputs that share a truncated prefix.\n *\n * `hashInput` must be the caller's full, untruncated discriminator (for\n * example `alias + \"\\0\" + field`): hashing the already-truncated `name`\n * would not disambiguate a collision.\n */\nexport function boundPgIdentifier(name: string, hashInput: string): string {\n if (TEXT_ENCODER.encode(name).byteLength <= MAX_PG_IDENTIFIER_LENGTH) {\n return name;\n }\n\n const hash = fnv1aBase36(hashInput);\n const truncated = truncateToBytes(\n name,\n MAX_PG_IDENTIFIER_LENGTH - 1 - hash.length,\n );\n return `${truncated}_${hash}`;\n}\n","/**\n * Query AST types.\n *\n * Defines the abstract syntax tree for TypeGraph queries.\n * This portable representation can be compiled to SQL (today)\n * or other query languages (Cypher, SPARQL) in the future.\n */\nimport {\n type KindEntity,\n type NullCheckOp,\n type TemporalMode,\n} from \"../core/types\";\nimport { type JsonPointer } from \"./json-pointer\";\n\n// ============================================================\n// Predicate Expressions\n// ============================================================\n\n/**\n * A field reference in a predicate.\n */\nexport type FieldRef = Readonly<{\n __type: \"field_ref\";\n alias: string;\n path: readonly string[]; // [\"props\", \"name\"] or [\"id\"]\n jsonPointer?: JsonPointer | undefined; // JSON Pointer into props\n valueType?: ValueType | undefined;\n elementType?: ValueType | undefined;\n}>;\n\n/**\n * A literal value in a predicate.\n */\nexport type LiteralValue = Readonly<{\n __type: \"literal\";\n value: string | number | boolean;\n valueType?: ValueType | undefined;\n}>;\n\n/**\n * A parameter reference for prepared queries.\n *\n * Used in place of a literal value to create parameterized queries\n * that can be executed multiple times with different bindings.\n */\nexport type ParameterRef = Readonly<{\n __type: \"parameter\";\n name: string;\n valueType?: ValueType | undefined;\n}>;\n\n/**\n * Supported value types for predicates.\n */\nexport type ValueType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"date\"\n | \"array\"\n | \"object\"\n | \"embedding\"\n | \"unknown\";\n\n/**\n * Comparison operators.\n */\nexport type ComparisonOp =\n \"eq\" | \"neq\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"in\" | \"notIn\";\n\n/**\n * String operators.\n */\nexport type StringOp =\n \"contains\" | \"startsWith\" | \"endsWith\" | \"like\" | \"ilike\";\n\n/**\n * A comparison predicate.\n */\nexport type ComparisonPredicate = Readonly<{\n __type: \"comparison\";\n op: ComparisonOp;\n left: FieldRef;\n right: LiteralValue | LiteralValue[] | ParameterRef;\n}>;\n\n/**\n * A string predicate.\n */\nexport type StringPredicate = Readonly<{\n __type: \"string_op\";\n op: StringOp;\n field: FieldRef;\n pattern: string | ParameterRef;\n}>;\n\n/**\n * A null check predicate.\n */\nexport type NullPredicate = Readonly<{\n __type: \"null_check\";\n op: NullCheckOp;\n field: FieldRef;\n}>;\n\n/**\n * A between predicate.\n */\nexport type BetweenPredicate = Readonly<{\n __type: \"between\";\n field: FieldRef;\n lower: LiteralValue | ParameterRef;\n upper: LiteralValue | ParameterRef;\n}>;\n\n// ============================================================\n// Array Predicates\n// ============================================================\n\n/**\n * Array operators.\n */\nexport type ArrayOp =\n | \"contains\" // Array contains a single value\n | \"containsAll\" // Array contains all specified values\n | \"containsAny\" // Array contains any of the specified values (overlaps)\n | \"isEmpty\" // Array is empty\n | \"isNotEmpty\" // Array is not empty\n | \"lengthEq\" // Array length equals\n | \"lengthGt\" // Array length greater than\n | \"lengthGte\" // Array length greater than or equal\n | \"lengthLt\" // Array length less than\n | \"lengthLte\"; // Array length less than or equal\n\n/**\n * An array predicate.\n */\nexport type ArrayPredicate = Readonly<{\n __type: \"array_op\";\n op: ArrayOp;\n field: FieldRef;\n values?: readonly LiteralValue[]; // For contains/containsAll/containsAny\n length?: number; // For length comparisons\n}>;\n\n// ============================================================\n// Object/JSON Predicates\n// ============================================================\n\n/**\n * Object operators.\n */\nexport type ObjectOp =\n | \"hasKey\" // Object has a specific key at root level\n | \"hasPath\" // Object has a nested path\n | \"pathEquals\" // Value at path equals\n | \"pathContains\" // Value at path contains (for nested arrays)\n | \"pathIsNull\" // Value at path is null\n | \"pathIsNotNull\"; // Value at path is not null\n\n/**\n * An object/JSON predicate.\n */\nexport type ObjectPredicate = Readonly<{\n __type: \"object_op\";\n op: ObjectOp;\n field: FieldRef;\n pointer: JsonPointer; // Relative JSON Pointer\n value?: LiteralValue; // For pathEquals, pathContains\n valueType?: ValueType;\n elementType?: ValueType;\n}>;\n\n/**\n * Logical AND predicate.\n */\ntype AndPredicate = Readonly<{\n __type: \"and\";\n predicates: readonly PredicateExpression[];\n}>;\n\n/**\n * Logical OR predicate.\n */\ntype OrPredicate = Readonly<{\n __type: \"or\";\n predicates: readonly PredicateExpression[];\n}>;\n\n/**\n * Logical NOT predicate.\n */\ntype NotPredicate = Readonly<{\n __type: \"not\";\n predicate: PredicateExpression;\n}>;\n\n/**\n * An aggregate comparison predicate (for HAVING clauses).\n */\nexport type AggregateComparisonPredicate = Readonly<{\n __type: \"aggregate_comparison\";\n op: ComparisonOp;\n aggregate: AggregateExpr;\n value: LiteralValue;\n}>;\n\n// ============================================================\n// Subquery Predicates\n// ============================================================\n\n/**\n * An EXISTS subquery predicate.\n * Tests whether the subquery returns any rows.\n */\nexport type ExistsSubquery = Readonly<{\n __type: \"exists\";\n subquery: QueryAst;\n negated: boolean; // for NOT EXISTS\n}>;\n\n/**\n * An IN subquery predicate.\n * Tests whether a field value is in the subquery results.\n */\nexport type InSubquery = Readonly<{\n __type: \"in_subquery\";\n field: FieldRef;\n subquery: QueryAst;\n negated: boolean; // for NOT IN\n}>;\n\n// ============================================================\n// Vector Predicates\n// ============================================================\n\n/**\n * Vector similarity metric types.\n */\nexport type VectorMetricType = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * A vector similarity predicate.\n * Finds nodes with embeddings similar to the query embedding.\n *\n * This predicate affects query execution by:\n * - Joining with the embeddings table\n * - Adding ORDER BY distance (ascending)\n * - Applying LIMIT (top k results)\n * - Optionally filtering by minimum score\n */\nexport type VectorSimilarityPredicate = Readonly<{\n __type: \"vector_similarity\";\n /** The embedding field reference */\n field: FieldRef;\n /** The query embedding to compare against */\n queryEmbedding: readonly number[];\n /**\n * Similarity metric. Omitted when the caller didn't pass one — the compiler\n * then uses the field's DECLARED `embedding()` metric (resolved per kind),\n * falling back to \"cosine\" only when no declaration is available.\n */\n metric?: VectorMetricType;\n /** Maximum number of results to return */\n limit: number;\n /** Optional minimum similarity score (0-1 for cosine) */\n minScore?: number;\n /**\n * Retrieve each kind's candidates via the engine's native ANN structure\n * instead of an exact distance scan (see `SimilarToOptions.approximate`).\n */\n approximate?: boolean;\n}>;\n\n// ============================================================\n// Fulltext Predicates\n// ============================================================\n\nimport type { FulltextQueryMode } from \"../backend/types\";\n\n/**\n * A fulltext MATCH predicate.\n *\n * Finds nodes whose combined searchable content matches the query. Affects\n * query execution by joining with the fulltext table, adding an ORDER BY\n * on relevance rank (descending), and applying a LIMIT (top k).\n */\nexport type FulltextMatchPredicate = Readonly<{\n __type: \"fulltext_match\";\n /**\n * Reserved for forward compatibility with per-field fulltext dispatch.\n * Today only `field.alias` is consumed: the MATCH always targets the\n * combined `content` column, so `field.path` is a synthetic\n * `[\"$fulltext\"]` marker rather than a real props path. Future\n * strategies (per-field indexes, `setweight()`-style boosts) can use\n * the full `FieldRef` without breaking the AST shape.\n */\n field: FieldRef;\n /** The user-supplied query string. */\n query: string;\n /** Parse mode for the query string. Default: \"websearch\". */\n mode: FulltextQueryMode;\n /** Language override for query parsing. */\n language?: string;\n /** Maximum number of results to return. */\n limit: number;\n /** Minimum relevance to include (backend-native units). */\n minScore?: number;\n}>;\n\n/**\n * Fusion options for hybrid (vector + fulltext) queries.\n *\n * Shared between:\n * - Query-builder path: `QueryBuilder.fuseWith()` stores this on `QueryAst`.\n * - Store path: `store.search.hybrid(kind, { fusion })` accepts the same shape.\n *\n * Only applied when the query contains both a vector and a fulltext\n * predicate. Defaults (when omitted): RRF with k=60 and equal weights.\n */\nexport type HybridFusionOptions = Readonly<{\n /** RRF is the only currently supported fusion method. */\n method?: \"rrf\";\n /** RRF constant. The classic value is 60. */\n k?: number;\n /** Per-source weights. Default: { vector: 1, fulltext: 1 }. */\n weights?: Readonly<{\n vector?: number;\n fulltext?: number;\n }>;\n}>;\n\n/**\n * Classic RRF constant. Shared by the store-level JS fusion in\n * `store.search.hybrid` and the SQL emitter — keep both paths reading\n * the same number so their top-k never drifts on ties.\n */\nexport const DEFAULT_RRF_K = 60;\n\n/** Default per-source RRF weight when none is supplied. */\nexport const DEFAULT_RRF_WEIGHT = 1;\n\n/**\n * All predicate expression types.\n */\nexport type PredicateExpression =\n | ComparisonPredicate\n | StringPredicate\n | NullPredicate\n | BetweenPredicate\n | ArrayPredicate\n | ObjectPredicate\n | AndPredicate\n | OrPredicate\n | NotPredicate\n | AggregateComparisonPredicate\n | ExistsSubquery\n | InSubquery\n | VectorSimilarityPredicate\n | FulltextMatchPredicate;\n\n// ============================================================\n// Query Start\n// ============================================================\n\n/**\n * The starting point of a query (the FROM clause).\n */\ntype QueryStart = Readonly<{\n alias: string;\n kinds: readonly string[]; // Expanded via ontology if includeSubClasses\n includeSubClasses: boolean;\n}>;\n\n// ============================================================\n// Traversals\n// ============================================================\n\n/**\n * Direction of edge traversal.\n */\nexport type TraversalDirection = \"out\" | \"in\";\n\n/**\n * Traversal ontology expansion behavior.\n *\n * - `\"none\"` — follow only the exact edge kind specified\n * - `\"implying\"` — also follow edge kinds that imply the specified kind (subClassOf)\n * - `\"inverse\"` — also follow the ontological inverse edge kind (inverseOf)\n * - `\"all\"` — follow both implying and inverse expansions\n */\nexport type TraversalExpansion = \"none\" | \"implying\" | \"inverse\" | \"all\";\n\n/**\n * Cycle handling policy for recursive traversals.\n */\nexport type RecursiveCyclePolicy = \"prevent\" | \"allow\";\n\n/**\n * Variable-length traversal specification for recursive graph traversals.\n */\nexport type VariableLengthSpec = Readonly<{\n /** Minimum number of hops before including results (default: 1) */\n minDepth: number;\n /** Maximum number of hops (-1 = unlimited, default: -1) */\n maxDepth: number;\n /**\n * Cycle handling mode.\n *\n * - \"prevent\": Track visited nodes per path and reject revisits\n * - \"allow\": Skip cycle checks (faster, may revisit nodes)\n */\n cyclePolicy: RecursiveCyclePolicy;\n /** Optional column alias for projected traversal path array */\n pathAlias?: string;\n /** Optional column alias for projected traversal depth */\n depthAlias?: string;\n}>;\n\n/**\n * A traversal step in the query.\n */\nexport type Traversal = Readonly<{\n edgeAlias: string;\n edgeKinds: readonly string[]; // Expanded via ontology based on traversal expand mode\n /**\n * Edge kinds traversed in the opposite direction.\n *\n * Populated when query options request inverse/symmetric expansion.\n */\n inverseEdgeKinds?: readonly string[];\n direction: TraversalDirection;\n nodeAlias: string;\n nodeKinds: readonly string[];\n joinFromAlias: string;\n joinEdgeField: \"from_id\" | \"to_id\";\n /** If true, use LEFT JOIN instead of INNER JOIN (optional match) */\n optional: boolean;\n /** Variable-length traversal configuration (for recursive CTEs) */\n variableLength?: VariableLengthSpec;\n}>;\n\n/**\n * Returns the full set of edge kind names for a traversal, merging\n * forward and inverse kinds with deduplication.\n */\nexport function mergeEdgeKinds(traversal: Traversal): readonly string[] {\n const inverse = traversal.inverseEdgeKinds;\n if (inverse === undefined || inverse.length === 0) return traversal.edgeKinds;\n\n return [\n ...traversal.edgeKinds,\n ...inverse.filter((kind) => !traversal.edgeKinds.includes(kind)),\n ];\n}\n\n// ============================================================\n// Aggregations\n// ============================================================\n\n/**\n * Supported aggregate functions.\n */\ntype AggregateFunction =\n \"count\" | \"countDistinct\" | \"sum\" | \"avg\" | \"min\" | \"max\";\n\n/**\n * An aggregate expression.\n */\nexport type AggregateExpr = Readonly<{\n __type: \"aggregate\";\n function: AggregateFunction;\n field: FieldRef;\n}>;\n\n/**\n * A GROUP BY specification.\n */\nexport type GroupBySpec = Readonly<{\n fields: readonly FieldRef[];\n}>;\n\n// ============================================================\n// Projections\n// ============================================================\n\n/**\n * A projected field in the SELECT clause.\n * Can be either a direct field reference or an aggregate expression.\n */\nexport type ProjectedField = Readonly<{\n outputName: string;\n source: FieldRef | AggregateExpr;\n /** Override the CTE alias for this field (used for edge fields in node CTEs) */\n cteAlias?: string;\n}>;\n\n/**\n * The projection (SELECT) clause.\n */\nexport type Projection = Readonly<{\n fields: readonly ProjectedField[];\n}>;\n\n/**\n * A selectively projected field for optimized queries.\n *\n * Used when the select callback only accesses specific fields,\n * allowing the compiler to generate optimized SQL that fetches\n * only those fields instead of the full props blob.\n */\nexport type SelectiveField = Readonly<{\n /** The alias (node or edge) this field belongs to */\n alias: string;\n /** The field name (e.g., \"email\", \"name\", \"id\") */\n field: string;\n /** The output column name in the result (e.g., \"p_email\") */\n outputName: string;\n /** True if this is a system field (id, kind, etc.), false for props */\n isSystemField: boolean;\n /**\n * Optional value type for props fields.\n *\n * When present, the compiler can use type-aware JSON extraction\n * (e.g. numeric/date casts) to better match predicate compilation\n * and enable expression index coverage.\n */\n valueType?: ValueType | undefined;\n}>;\n\n// ============================================================\n// Ordering\n// ============================================================\n\n/**\n * Null ordering preference.\n */\ntype NullOrdering = \"first\" | \"last\";\n\n/**\n * Sort direction.\n */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/**\n * An ordering specification.\n */\nexport type OrderSpec = Readonly<{\n field: FieldRef;\n direction: SortDirection;\n nulls?: NullOrdering;\n}>;\n\n/**\n * An ordering specification for aggregate queries.\n *\n * Unlike {@link OrderSpec}, this references a projected SELECT-list output\n * column by name rather than a `FieldRef` into a source table/CTE. Aggregate\n * query projections always assign an output alias to every grouped field\n * and aggregate expression (via `.aggregate({ outputName: ... })`), so\n * ordering by that alias works uniformly for both — and both SQLite and\n * PostgreSQL allow `ORDER BY` to reference a SELECT-list alias directly, so\n * no re-derivation of the underlying expression (and no dialect seam) is\n * needed.\n */\nexport type AggregateOrderSpec = Readonly<{\n outputName: string;\n direction: SortDirection;\n nulls?: NullOrdering;\n}>;\n\n// ============================================================\n// Node Predicate\n// ============================================================\n\n/**\n * A predicate applied to a specific node or edge alias.\n */\nexport type NodePredicate = Readonly<{\n targetAlias: string;\n /** Whether this predicate targets a node or edge. Defaults to \"node\". */\n targetType?: KindEntity;\n expression: PredicateExpression;\n}>;\n\n// ============================================================\n// Temporal Options\n// ============================================================\n\n/**\n * Temporal query options.\n */\ntype TemporalOptions = Readonly<{\n mode: TemporalMode;\n asOf?: string;\n}>;\n\n// ============================================================\n// Query AST\n// ============================================================\n\n/**\n * The complete query AST.\n */\nexport type QueryAst = Readonly<{\n /** The graph ID this query is for (used for subqueries) */\n graphId?: string;\n start: QueryStart;\n traversals: readonly Traversal[];\n predicates: readonly NodePredicate[];\n projection: Projection;\n temporalMode: TemporalOptions;\n /** Recorded/system-time timestamp for recorded-pinned reads. */\n recordedAsOf?: string;\n orderBy?: readonly OrderSpec[];\n limit?: number;\n offset?: number;\n /** GROUP BY specification for aggregate queries */\n groupBy?: GroupBySpec;\n /** HAVING clause - predicates applied after GROUP BY */\n having?: PredicateExpression;\n /**\n * ORDER BY specification for aggregate queries, referencing projected\n * output aliases (grouped fields or aggregate expressions) instead of\n * source-table field refs. See {@link AggregateOrderSpec}.\n */\n aggregateOrderBy?: readonly AggregateOrderSpec[];\n /**\n * Selective fields for optimized queries.\n * When present, the compiler generates SQL that only fetches these specific\n * fields instead of the full props blob, enabling covered index usage.\n */\n selectiveFields?: readonly SelectiveField[];\n /** Fusion options for hybrid queries. Ignored unless both predicates present. */\n fusion?: HybridFusionOptions;\n}>;\n\n// ============================================================\n// Set Operations\n// ============================================================\n\n/**\n * Set operation types for combining queries.\n */\nexport type SetOperationType = \"union\" | \"unionAll\" | \"intersect\" | \"except\";\n\n/**\n * A set operation combining two queries.\n */\nexport type SetOperation = Readonly<{\n __type: \"set_operation\";\n operator: SetOperationType;\n left: ComposableQuery;\n right: ComposableQuery;\n orderBy?: readonly OrderSpec[];\n limit?: number;\n offset?: number;\n}>;\n\n/**\n * A composable query - either a base query or a set operation.\n */\nexport type ComposableQuery = QueryAst | SetOperation;\n","import { type SelectiveField } from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport { type JsonPointer, jsonPointer } from \"../json-pointer\";\nimport { type SqlFragment } from \"../sql-fragment\";\n\ntype JsonExtractFallback = \"json\" | \"text\";\n\ntype TypedJsonExtractInput = Readonly<{\n column: SqlFragment;\n dialect: DialectAdapter;\n fallback?: JsonExtractFallback;\n pointer: JsonPointer;\n valueType: string | undefined;\n}>;\n\nexport function compileTypedJsonExtract(\n input: TypedJsonExtractInput,\n): SqlFragment {\n const { column, dialect, pointer, valueType } = input;\n const fallback = input.fallback ?? \"json\";\n\n switch (valueType) {\n case \"string\": {\n return dialect.jsonExtractText(column, pointer);\n }\n case \"number\": {\n return dialect.jsonExtractNumber(column, pointer);\n }\n case \"boolean\": {\n return dialect.jsonExtractBoolean(column, pointer);\n }\n case \"date\": {\n return dialect.jsonExtractDate(column, pointer);\n }\n case \"array\":\n case \"object\":\n case \"embedding\":\n case \"unknown\":\n case undefined: {\n return fallback === \"text\" ?\n dialect.jsonExtractText(column, pointer)\n : dialect.jsonExtract(column, pointer);\n }\n default: {\n return fallback === \"text\" ?\n dialect.jsonExtractText(column, pointer)\n : dialect.jsonExtract(column, pointer);\n }\n }\n}\n\n/**\n * Extracts a single top-level selective-projection field from a JSON props\n * column, typed by the field's declared value type.\n *\n * Shared by both projection shapes: the standard emitter pushes this extraction\n * into a CTE synthetic column, while the recursive emitter applies it in the\n * outer SELECT over the props carried through the recursive CTE. The two SQL\n * shapes differ by design, but they must extract identically — centralizing the\n * pointer/valueType wiring here keeps their extraction semantics from drifting.\n */\nexport function compileSelectivePropsExtraction(\n field: SelectiveField,\n column: SqlFragment,\n dialect: DialectAdapter,\n): SqlFragment {\n return compileTypedJsonExtract({\n column,\n dialect,\n pointer: jsonPointer([field.field]),\n valueType: field.valueType,\n });\n}\n","/**\n * Shared Compiler Utilities\n *\n * Functions and constants shared between the standard and recursive compilers.\n */\nimport { type AggregateExpr, type FieldRef, type SelectiveField } from \"../ast\";\nimport { parseJsonPointer } from \"../json-pointer\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { getFieldPointer } from \"./predicates\";\n\n// ============================================================\n// Constants\n// ============================================================\n\nexport const NODE_COLUMNS = [\n \"id\",\n \"kind\",\n \"props\",\n \"version\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n] as const;\n\nexport const EDGE_COLUMNS = [\n \"id\",\n \"kind\",\n \"from_id\",\n \"to_id\",\n \"props\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n] as const;\n\nexport type RequiredColumnsByAlias = ReadonlyMap<string, ReadonlySet<string>>;\nexport const EMPTY_REQUIRED_COLUMNS = new Set<string>();\n\n// ============================================================\n// SQL Helpers\n// ============================================================\n\nexport function quoteIdentifier(identifier: string): SqlFragment {\n return sql.identifier(identifier);\n}\n\n// ============================================================\n// Column Projection\n// ============================================================\n\n/**\n * Determines whether a column should be included in the projection.\n *\n * @param requiredColumns - Set of columns required by the query, or undefined to include all.\n * @param column - The column name to check.\n * @param alwaysRequiredColumns - Optional set of columns that are always projected\n * (e.g. join keys in recursive CTEs). Pass only from recursive compiler callers.\n */\nexport function shouldProjectColumn(\n requiredColumns: ReadonlySet<string> | undefined,\n column: string,\n alwaysRequiredColumns?: ReadonlySet<string>,\n): boolean {\n if (alwaysRequiredColumns?.has(column)) return true;\n if (requiredColumns === undefined) return true;\n return requiredColumns.has(column);\n}\n\n// ============================================================\n// Required Column Tracking\n// ============================================================\n\nexport function addRequiredColumn(\n requiredColumnsByAlias: Map<string, Set<string>>,\n alias: string,\n column: string,\n): void {\n const existing = requiredColumnsByAlias.get(alias);\n if (existing) {\n existing.add(column);\n return;\n }\n requiredColumnsByAlias.set(alias, new Set([column]));\n}\n\nexport function markFieldRefAsRequired(\n requiredColumnsByAlias: Map<string, Set<string>>,\n field: FieldRef,\n): void {\n const column = field.path[0];\n if (column === undefined) return;\n addRequiredColumn(requiredColumnsByAlias, field.alias, column);\n}\n\nexport function mapSelectiveSystemFieldToColumn(field: string): string {\n if (field === \"fromId\") return \"from_id\";\n if (field === \"toId\") return \"to_id\";\n if (field.startsWith(\"meta.\")) {\n return field\n .slice(5)\n .replaceAll(/([A-Z])/g, \"_$1\")\n .toLowerCase();\n }\n return field;\n}\n\nexport function markSelectiveFieldAsRequired(\n requiredColumnsByAlias: Map<string, Set<string>>,\n field: SelectiveField,\n): void {\n if (field.isSystemField) {\n addRequiredColumn(\n requiredColumnsByAlias,\n field.alias,\n mapSelectiveSystemFieldToColumn(field.field),\n );\n return;\n }\n addRequiredColumn(requiredColumnsByAlias, field.alias, \"props\");\n}\n\nfunction getTopLevelPropsFieldName(field: FieldRef): string | undefined {\n const pointer = getFieldPointer(field);\n if (pointer === undefined) return undefined;\n\n const segments = parseJsonPointer(pointer);\n return segments.length === 1 ? segments[0] : undefined;\n}\n\nexport function findSelectivePropsFieldForFieldRef(\n selectiveFields: readonly SelectiveField[] | undefined,\n field: FieldRef,\n): SelectiveField | undefined {\n if (selectiveFields === undefined || selectiveFields.length === 0) {\n return undefined;\n }\n\n const propsFieldName = getTopLevelPropsFieldName(field);\n if (propsFieldName === undefined) return undefined;\n\n return selectiveFields.find(\n (selectiveField) =>\n !selectiveField.isSystemField &&\n selectiveField.alias === field.alias &&\n selectiveField.field === propsFieldName,\n );\n}\n\n// ============================================================\n// AST Type Guards\n// ============================================================\n\nexport function isIdFieldRef(field: FieldRef): boolean {\n return (\n field.path.length === 1 &&\n field.path[0] === \"id\" &&\n field.jsonPointer === undefined\n );\n}\n\nexport function isAggregateExpr(\n source: FieldRef | AggregateExpr,\n): source is AggregateExpr {\n return \"__type\" in source && source.__type === \"aggregate\";\n}\n","import { UnsupportedPredicateError } from \"../../../errors\";\nimport { boundPgIdentifier } from \"../../../utils/identifier\";\nimport { requireDefined } from \"../../../utils/presence\";\nimport {\n type AggregateExpr,\n DEFAULT_RRF_K,\n DEFAULT_RRF_WEIGHT,\n type FieldRef,\n type FulltextMatchPredicate,\n type HybridFusionOptions,\n type QueryAst,\n type SelectiveField,\n type VectorSimilarityPredicate,\n} from \"../../ast\";\nimport { type DialectAdapter } from \"../../dialect/types\";\nimport {\n vectorMinScoreCondition,\n vectorScoreExpression,\n} from \"../../dialect/vector-strategy\";\nimport { sql, type SqlFragment } from \"../../sql-fragment\";\nimport { type TemporalFilterPass } from \"../passes\";\nimport {\n compileKindFilter,\n compilePredicateClauses,\n getHybridTargetAlias,\n getNodeKindsForAlias,\n getPredicatesForAlias,\n type PredicateIndex,\n} from \"../predicate-utils\";\nimport {\n compileFieldValue,\n compilePredicateExpression,\n type PredicateCompilerContext,\n} from \"../predicates\";\nimport {\n ALIAS_CTE_PREFIX,\n EMBEDDINGS_CTE_ALIAS,\n FULLTEXT_CTE_ALIAS,\n HYBRID_CANDIDATES_CTE_ALIAS,\n vectorSlotKey,\n} from \"../schema\";\nimport { compileSelectivePropsExtraction } from \"../typed-json-extract\";\nimport {\n EDGE_COLUMNS,\n EMPTY_REQUIRED_COLUMNS,\n findSelectivePropsFieldForFieldRef,\n isAggregateExpr,\n mapSelectiveSystemFieldToColumn,\n NODE_COLUMNS,\n quoteIdentifier,\n type RequiredColumnsByAlias,\n shouldProjectColumn,\n} from \"../utils\";\n\nexport type StandardEmitterPredicateIndex = PredicateIndex;\n\nfunction compileColumnReference(\n tableAlias: string | undefined,\n column: string,\n): SqlFragment {\n if (tableAlias === undefined) {\n return sql.raw(column);\n }\n return sql`${sql.raw(tableAlias)}.${sql.raw(column)}`;\n}\n\nfunction qualifyColumn(owner: string, name: string): SqlFragment {\n return sql`${quoteIdentifier(owner)}.${quoteIdentifier(name)}`;\n}\n\nconst SCOPED_RELEVANCE_NODES_ALIAS = \"scoped_relevance_nodes\";\n\n/**\n * Builds a synthetic CTE column name for a selectively-extracted props field.\n *\n * Length-prefixes each component (`<length>:<value>`) rather than joining\n * `alias`/`field` on a bare `_`: alias and field are both attacker/user-controlled\n * strings that may themselves contain `_`, so naive concatenation lets two distinct\n * (alias, field) pairs collide on the same column name (e.g. alias=\"p_full\",\n * field=\"name\" vs. alias=\"p\", field=\"full_name\" would otherwise both produce\n * \"__tg_p_full_name\"). The length prefix makes the encoding unambiguous regardless\n * of what characters alias/field contain.\n *\n * The encoding is unbounded, but PostgreSQL truncates identifiers at 63 bytes,\n * so `boundPgIdentifier` hash-guards long names: two pairs whose encodings share\n * a >63-byte prefix would otherwise collapse onto the same physical column.\n * Short names are returned verbatim, preserving the readable `__tg_...` form.\n */\nfunction selectivePropsCteColumnName(field: SelectiveField): string {\n const { alias, field: fieldName } = field;\n const encoded = `__tg_${alias.length}:${alias}:${fieldName.length}:${fieldName}`;\n return boundPgIdentifier(encoded, `${alias}\\0${fieldName}`);\n}\n\nfunction buildScopedNodeIdsSubquery(nodeAlias: string): SqlFragment {\n const cteAlias = `${ALIAS_CTE_PREFIX}${nodeAlias}`;\n return sql`\n (\n SELECT DISTINCT\n ${qualifyColumn(cteAlias, `${nodeAlias}_id`)} AS node_id,\n ${qualifyColumn(cteAlias, `${nodeAlias}_kind`)} AS node_kind\n FROM ${quoteIdentifier(cteAlias)}\n ) AS ${sql.raw(SCOPED_RELEVANCE_NODES_ALIAS)}\n `;\n}\n\ntype CompileSelectivePropsSelectColumnsInput = Readonly<{\n alias: string;\n dialect: DialectAdapter;\n selectiveFields: readonly SelectiveField[] | undefined;\n tableAlias: string | undefined;\n}>;\n\nfunction compileSelectivePropsSelectColumns(\n input: CompileSelectivePropsSelectColumnsInput,\n): SqlFragment[] {\n const { alias, dialect, selectiveFields, tableAlias } = input;\n const propsFields =\n selectiveFields?.filter(\n (field) => !field.isSystemField && field.alias === alias,\n ) ?? [];\n if (propsFields.length === 0) return [];\n\n const propsColumn = compileColumnReference(tableAlias, \"props\");\n return propsFields.map((field) => {\n const extracted = compileSelectivePropsExtraction(\n field,\n propsColumn,\n dialect,\n );\n return sql`${extracted} AS ${quoteIdentifier(selectivePropsCteColumnName(field))}`;\n });\n}\n\nfunction appendSelectivePropsColumns(\n baseColumns: readonly SqlFragment[],\n input: CompileSelectivePropsSelectColumnsInput,\n): SqlFragment[] {\n return [...baseColumns, ...compileSelectivePropsSelectColumns(input)];\n}\n\ntype CompileNodeSelectColumnsInput = Readonly<{\n alias: string;\n dialect: DialectAdapter;\n requiredColumns: ReadonlySet<string> | undefined;\n selectiveFields: readonly SelectiveField[] | undefined;\n tableAlias: string | undefined;\n}>;\n\nfunction compileNodeSelectColumns(\n input: CompileNodeSelectColumnsInput,\n): SqlFragment[] {\n const { alias, dialect, requiredColumns, selectiveFields, tableAlias } =\n input;\n const baseColumns = NODE_COLUMNS.filter(\n (column) =>\n column === \"id\" ||\n column === \"kind\" ||\n shouldProjectColumn(requiredColumns, column),\n ).map(\n (column) =>\n sql`${compileColumnReference(tableAlias, column)} AS ${sql.raw(`${alias}_${column}`)}`,\n );\n return appendSelectivePropsColumns(baseColumns, {\n alias,\n dialect,\n selectiveFields,\n tableAlias,\n });\n}\n\ntype CompileEdgeSelectColumnsInput = Readonly<{\n alias: string;\n dialect: DialectAdapter;\n requiredColumns: ReadonlySet<string> | undefined;\n selectiveFields: readonly SelectiveField[] | undefined;\n tableAlias: string | undefined;\n}>;\n\nfunction compileEdgeSelectColumns(\n input: CompileEdgeSelectColumnsInput,\n): SqlFragment[] {\n const { alias, dialect, requiredColumns, selectiveFields, tableAlias } =\n input;\n const baseColumns = EDGE_COLUMNS.filter((column) =>\n shouldProjectColumn(requiredColumns, column),\n ).map(\n (column) =>\n sql`${compileColumnReference(tableAlias, column)} AS ${sql.raw(`${alias}_${column}`)}`,\n );\n return appendSelectivePropsColumns(baseColumns, {\n alias,\n dialect,\n selectiveFields,\n tableAlias,\n });\n}\n\ntype BuildStandardStartCteInput = Readonly<{\n ast: QueryAst;\n ctx: PredicateCompilerContext;\n graphId: string;\n predicateIndex: StandardEmitterPredicateIndex;\n requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n temporalFilterPass: TemporalFilterPass;\n /**\n * Optional LIMIT/OFFSET to apply inside the start CTE. Used by the count\n * aggregate fast path to push limits past the GROUP BY when it's safe.\n */\n limitOffset?: Readonly<{ limit: number; offset?: number | undefined }>;\n}>;\n\nexport function buildStandardStartCte(\n input: BuildStandardStartCteInput,\n): SqlFragment {\n const { ast, ctx, graphId, predicateIndex, requiredColumnsByAlias } = input;\n const alias = ast.start.alias;\n const kinds = ast.start.kinds;\n const cteMaterialization =\n ctx.dialect.capabilities.emitNotMaterializedHint ?\n sql`NOT MATERIALIZED `\n : sql``;\n\n const kindFilter = compileKindFilter(sql.raw(\"kind\"), kinds);\n const temporalFilter = input.temporalFilterPass.forAlias();\n const cteContext: PredicateCompilerContext = { ...ctx, cteColumnPrefix: \"\" };\n const predicateClauses = compilePredicateClauses(\n getPredicatesForAlias(predicateIndex, alias, \"node\"),\n cteContext,\n );\n\n const whereClauses = [\n sql`graph_id = ${graphId}`,\n kindFilter,\n temporalFilter,\n ...predicateClauses,\n ];\n\n const effectiveRequiredColumns =\n requiredColumnsByAlias ?\n (requiredColumnsByAlias.get(alias) ?? EMPTY_REQUIRED_COLUMNS)\n : undefined;\n\n const limitClause =\n input.limitOffset === undefined ? sql``\n : input.limitOffset.offset === undefined ?\n sql`\n LIMIT ${input.limitOffset.limit}\n `\n : sql`\n LIMIT ${input.limitOffset.limit} OFFSET ${input.limitOffset.offset}\n `;\n\n return sql`\n cte_${sql.raw(alias)} AS ${cteMaterialization}(\n SELECT ${sql.join(\n compileNodeSelectColumns({\n alias,\n dialect: ctx.dialect,\n requiredColumns: effectiveRequiredColumns,\n selectiveFields: ast.selectiveFields,\n tableAlias: undefined,\n }),\n sql`, `,\n )}\n FROM ${ctx.schema.nodesTable}\n WHERE ${sql.join(whereClauses, sql` AND `)}${limitClause}\n )\n `;\n}\n\ntype BuildStandardTraversalCteInput = Readonly<{\n ast: QueryAst;\n carryForwardPreviousColumns: boolean;\n ctx: PredicateCompilerContext;\n graphId: string;\n materializeCte: boolean;\n predicateIndex: StandardEmitterPredicateIndex;\n requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n temporalFilterPass: TemporalFilterPass;\n traversalIndex: number;\n traversalLimit: number | undefined;\n}>;\n\nexport function buildStandardTraversalCte(\n input: BuildStandardTraversalCteInput,\n): SqlFragment {\n const {\n ast,\n carryForwardPreviousColumns,\n ctx,\n graphId,\n materializeCte,\n predicateIndex,\n requiredColumnsByAlias,\n temporalFilterPass,\n traversalIndex,\n traversalLimit,\n } = input;\n const traversal = requireDefined(ast.traversals[traversalIndex]);\n const traversalLimitValue =\n traversalIndex === ast.traversals.length - 1 ? traversalLimit : undefined;\n\n const previousNodeKinds = getNodeKindsForAlias(ast, traversal.joinFromAlias);\n const directEdgeKinds = [...new Set(traversal.edgeKinds)];\n const inverseEdgeKinds =\n traversal.inverseEdgeKinds === undefined ?\n []\n : [...new Set(traversal.inverseEdgeKinds)];\n\n const nodeKinds = traversal.nodeKinds;\n const nodeKindFilter = compileKindFilter(sql.raw(\"n.kind\"), nodeKinds);\n\n const edgeTemporalFilter = temporalFilterPass.forAlias(\"e\");\n const nodeTemporalFilter = temporalFilterPass.forAlias(\"n\");\n\n const nodeCteContext: PredicateCompilerContext = {\n ...ctx,\n cteColumnPrefix: \"n\",\n };\n const nodePredicateClauses = compilePredicateClauses(\n getPredicatesForAlias(predicateIndex, traversal.nodeAlias, \"node\"),\n nodeCteContext,\n );\n\n const edgeCteContext: PredicateCompilerContext = {\n ...ctx,\n cteColumnPrefix: \"e\",\n };\n const edgePredicateClauses = compilePredicateClauses(\n getPredicatesForAlias(predicateIndex, traversal.edgeAlias, \"edge\"),\n edgeCteContext,\n );\n\n const baseWhereClauses = [\n sql`e.graph_id = ${graphId}`,\n nodeKindFilter,\n edgeTemporalFilter,\n nodeTemporalFilter,\n ...nodePredicateClauses,\n ...edgePredicateClauses,\n ];\n\n const previousAlias = traversal.joinFromAlias;\n const edgeAlias = traversal.edgeAlias;\n const nodeAlias = traversal.nodeAlias;\n const requiredNodeColumns =\n requiredColumnsByAlias ?\n (requiredColumnsByAlias.get(nodeAlias) ?? EMPTY_REQUIRED_COLUMNS)\n : undefined;\n const requiredEdgeColumns =\n requiredColumnsByAlias ?\n (requiredColumnsByAlias.get(edgeAlias) ?? EMPTY_REQUIRED_COLUMNS)\n : undefined;\n const previousRowColumns =\n carryForwardPreviousColumns ?\n [sql`cte_${sql.raw(previousAlias)}.*`]\n : [\n sql`cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_id AS ${sql.raw(previousAlias)}_id`,\n sql`cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_kind AS ${sql.raw(previousAlias)}_kind`,\n ];\n const selectColumns = [\n ...previousRowColumns,\n ...compileEdgeSelectColumns({\n alias: edgeAlias,\n dialect: ctx.dialect,\n requiredColumns: requiredEdgeColumns,\n selectiveFields: ast.selectiveFields,\n tableAlias: \"e\",\n }),\n ...compileNodeSelectColumns({\n alias: nodeAlias,\n dialect: ctx.dialect,\n requiredColumns: requiredNodeColumns,\n selectiveFields: ast.selectiveFields,\n tableAlias: \"n\",\n }),\n ];\n const cteMaterialization =\n materializeCte ? sql`MATERIALIZED `\n : ctx.dialect.capabilities.emitNotMaterializedHint ? sql`NOT MATERIALIZED `\n : sql``;\n\n function compileTraversalBranch(\n branch: Readonly<{\n duplicateGuard?: SqlFragment | undefined;\n edgeKinds: readonly string[];\n joinField: \"from_id\" | \"to_id\";\n joinKindField: \"from_kind\" | \"to_kind\";\n targetField: \"from_id\" | \"to_id\";\n targetKindField: \"from_kind\" | \"to_kind\";\n }>,\n ): SqlFragment {\n const whereClauses = [\n ...baseWhereClauses,\n compileKindFilter(sql.raw(\"e.kind\"), branch.edgeKinds),\n compileKindFilter(\n sql.raw(`e.${branch.joinKindField}`),\n previousNodeKinds,\n ),\n compileKindFilter(sql.raw(`e.${branch.targetKindField}`), nodeKinds),\n ];\n\n if (branch.duplicateGuard !== undefined) {\n whereClauses.push(branch.duplicateGuard);\n }\n\n return sql`\n SELECT ${sql.join(selectColumns, sql`, `)}\n FROM cte_${sql.raw(previousAlias)}\n JOIN ${ctx.schema.edgesTable} e ON cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_id = e.${sql.raw(branch.joinField)}\n AND cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_kind = e.${sql.raw(branch.joinKindField)}\n JOIN ${ctx.schema.nodesTable} n ON n.graph_id = e.graph_id\n AND n.id = e.${sql.raw(branch.targetField)}\n AND n.kind = e.${sql.raw(branch.targetKindField)}\n WHERE ${sql.join(whereClauses, sql` AND `)}\n `;\n }\n\n const directJoinField = traversal.direction === \"out\" ? \"from_id\" : \"to_id\";\n const directTargetField = traversal.direction === \"out\" ? \"to_id\" : \"from_id\";\n const directJoinKindField =\n traversal.direction === \"out\" ? \"from_kind\" : \"to_kind\";\n const directTargetKindField =\n traversal.direction === \"out\" ? \"to_kind\" : \"from_kind\";\n\n const directBranch = compileTraversalBranch({\n edgeKinds: directEdgeKinds,\n joinField: directJoinField,\n joinKindField: directJoinKindField,\n targetField: directTargetField,\n targetKindField: directTargetKindField,\n });\n\n if (inverseEdgeKinds.length === 0) {\n if (traversalLimitValue !== undefined) {\n return sql`\n cte_${sql.raw(nodeAlias)} AS ${cteMaterialization}(\n SELECT * FROM (\n ${directBranch}\n ) AS traversal_rows\n LIMIT ${traversalLimitValue}\n )\n `;\n }\n\n return sql`\n cte_${sql.raw(nodeAlias)} AS ${cteMaterialization}(\n ${directBranch}\n )\n `;\n }\n\n const inverseJoinField = traversal.direction === \"out\" ? \"to_id\" : \"from_id\";\n const inverseTargetField =\n traversal.direction === \"out\" ? \"from_id\" : \"to_id\";\n const inverseJoinKindField =\n traversal.direction === \"out\" ? \"to_kind\" : \"from_kind\";\n const inverseTargetKindField =\n traversal.direction === \"out\" ? \"from_kind\" : \"to_kind\";\n\n const overlappingKinds = inverseEdgeKinds.filter((kind) =>\n directEdgeKinds.includes(kind),\n );\n\n const duplicateGuard =\n overlappingKinds.length > 0 ?\n sql`NOT (e.from_id = e.to_id AND ${compileKindFilter(\n sql.raw(\"e.kind\"),\n overlappingKinds,\n )})`\n : undefined;\n\n const inverseBranch = compileTraversalBranch({\n duplicateGuard,\n edgeKinds: inverseEdgeKinds,\n joinField: inverseJoinField,\n joinKindField: inverseJoinKindField,\n targetField: inverseTargetField,\n targetKindField: inverseTargetKindField,\n });\n\n if (traversalLimitValue !== undefined) {\n return sql`\n cte_${sql.raw(nodeAlias)} AS ${cteMaterialization}(\n SELECT * FROM (\n ${directBranch}\n UNION ALL\n ${inverseBranch}\n ) AS traversal_rows\n LIMIT ${traversalLimitValue}\n )\n `;\n }\n\n return sql`\n cte_${sql.raw(nodeAlias)} AS ${cteMaterialization}(\n ${directBranch}\n UNION ALL\n ${inverseBranch}\n )\n `;\n}\n\nfunction compileAggregateExprFromSource(\n expr: AggregateExpr,\n dialect: DialectAdapter,\n): SqlFragment {\n const { field } = expr;\n const fn = expr.function;\n\n switch (fn) {\n case \"count\":\n case \"countDistinct\":\n case \"sum\":\n case \"avg\":\n case \"min\":\n case \"max\": {\n const cteAlias = `cte_${field.alias}`;\n const column = compileFieldValue(\n field,\n dialect,\n field.valueType,\n cteAlias,\n );\n if (fn === \"countDistinct\") {\n return sql`COUNT(DISTINCT ${column})`;\n }\n return sql`${sql.raw(fn.toUpperCase())}(${column})`;\n }\n default: {\n throw new UnsupportedPredicateError(\n `Unknown aggregate function: ${String(fn)}`,\n );\n }\n }\n}\n\nfunction compileProjectedSource(\n field: {\n cteAlias?: string;\n source: FieldRef | AggregateExpr;\n },\n dialect: DialectAdapter,\n): SqlFragment {\n if (isAggregateExpr(field.source)) {\n return compileAggregateExprFromSource(field.source, dialect);\n }\n const cteAlias = field.cteAlias ?? `cte_${field.source.alias}`;\n return compileFieldValue(\n field.source,\n dialect,\n field.source.valueType,\n cteAlias,\n );\n}\n\ntype BuildStandardProjectionInput = Readonly<{\n ast: QueryAst;\n collapsedTraversalCteAlias?: string;\n dialect: DialectAdapter;\n}>;\n\nexport function buildStandardProjection(\n input: BuildStandardProjectionInput,\n): SqlFragment {\n const { ast, collapsedTraversalCteAlias, dialect } = input;\n if (ast.selectiveFields && ast.selectiveFields.length > 0) {\n return compileSelectiveProjection(\n ast.selectiveFields,\n ast,\n collapsedTraversalCteAlias,\n );\n }\n\n const fields = ast.projection.fields;\n if (fields.length === 0) {\n return sql.raw(\"*\");\n }\n\n const projectedFields = fields.map((field) => {\n const source = compileProjectedSource(field, dialect);\n return sql`${source} AS ${quoteIdentifier(field.outputName)}`;\n });\n return sql.join(projectedFields, sql`, `);\n}\n\n/**\n * Builds a map from query aliases (node and edge) to their CTE table names.\n * Edge aliases map to the CTE of the traversal node they are co-projected with.\n */\nfunction buildAliasToCteMap(ast: QueryAst): Map<string, string> {\n const map = new Map<string, string>([\n [ast.start.alias, `cte_${ast.start.alias}`],\n ]);\n for (const traversal of ast.traversals) {\n map.set(traversal.nodeAlias, `cte_${traversal.nodeAlias}`);\n map.set(traversal.edgeAlias, `cte_${traversal.nodeAlias}`);\n }\n return map;\n}\n\nfunction compileSelectiveProjection(\n fields: readonly SelectiveField[],\n ast: QueryAst,\n collapsedTraversalCteAlias?: string,\n): SqlFragment {\n const aliasToCte = buildAliasToCteMap(ast);\n\n const columns = fields.map((field) => {\n const cteAlias =\n collapsedTraversalCteAlias ??\n aliasToCte.get(field.alias) ??\n `cte_${field.alias}`;\n\n if (field.isSystemField) {\n const dbColumn = mapSelectiveSystemFieldToColumn(field.field);\n\n return sql`${sql.raw(cteAlias)}.${sql.raw(`${field.alias}_${dbColumn}`)} AS ${quoteIdentifier(field.outputName)}`;\n }\n\n return sql`${sql.raw(cteAlias)}.${quoteIdentifier(selectivePropsCteColumnName(field))} AS ${quoteIdentifier(field.outputName)}`;\n });\n\n return sql.join(columns, sql`, `);\n}\n\nfunction compileOrderFieldValue(\n ast: QueryAst,\n field: FieldRef,\n dialect: DialectAdapter,\n cteAlias: string,\n): SqlFragment {\n const selectiveField = findSelectivePropsFieldForFieldRef(\n ast.selectiveFields,\n field,\n );\n if (selectiveField !== undefined) {\n return sql`${sql.raw(cteAlias)}.${quoteIdentifier(selectivePropsCteColumnName(selectiveField))}`;\n }\n\n return compileFieldValue(field, dialect, field.valueType, cteAlias);\n}\n\nfunction buildRelevanceJoins(\n vectorPredicate: VectorSimilarityPredicate | undefined,\n fulltextPredicate: FulltextMatchPredicate | undefined,\n): SqlFragment[] {\n const hybridTargetAlias = getHybridTargetAlias(\n vectorPredicate,\n fulltextPredicate,\n );\n if (hybridTargetAlias !== undefined) {\n return [\n buildHybridCandidateJoin(hybridTargetAlias),\n buildRelevanceJoin(EMBEDDINGS_CTE_ALIAS, hybridTargetAlias, \"LEFT JOIN\"),\n buildRelevanceJoin(FULLTEXT_CTE_ALIAS, hybridTargetAlias, \"LEFT JOIN\"),\n ];\n }\n\n const joins: SqlFragment[] = [];\n if (vectorPredicate) {\n joins.push(\n buildRelevanceJoin(EMBEDDINGS_CTE_ALIAS, vectorPredicate.field.alias),\n );\n }\n if (fulltextPredicate) {\n joins.push(\n buildRelevanceJoin(FULLTEXT_CTE_ALIAS, fulltextPredicate.field.alias),\n );\n }\n return joins;\n}\n\nfunction buildHybridCandidateJoin(nodeAlias: string): SqlFragment {\n const candidateCte = sql.raw(HYBRID_CANDIDATES_CTE_ALIAS);\n const node = sql.raw(`${ALIAS_CTE_PREFIX}${nodeAlias}`);\n const idColumn = sql.raw(`${nodeAlias}_id`);\n const kindColumn = sql.raw(`${nodeAlias}_kind`);\n return sql`INNER JOIN ${candidateCte} ON ${candidateCte}.node_id = ${node}.${idColumn} AND ${candidateCte}.node_kind = ${node}.${kindColumn}`;\n}\n\nfunction buildRelevanceJoin(\n cteAlias: string,\n nodeAlias: string,\n joinType = \"INNER JOIN\",\n): SqlFragment {\n const cte = sql.raw(cteAlias);\n const node = sql.raw(`${ALIAS_CTE_PREFIX}${nodeAlias}`);\n const idColumn = sql.raw(`${nodeAlias}_id`);\n const kindColumn = sql.raw(`${nodeAlias}_kind`);\n return sql`${sql.raw(joinType)} ${cte} ON ${cte}.node_id = ${node}.${idColumn} AND ${cte}.node_kind = ${node}.${kindColumn}`;\n}\n\ntype BuildStandardFromClauseInput = Readonly<{\n ast: QueryAst;\n collapsedTraversalCteAlias?: string;\n fulltextPredicate?: FulltextMatchPredicate;\n vectorPredicate?: VectorSimilarityPredicate;\n}>;\n\nexport function buildStandardFromClause(\n input: BuildStandardFromClauseInput,\n): SqlFragment {\n const {\n ast,\n collapsedTraversalCteAlias,\n fulltextPredicate,\n vectorPredicate,\n } = input;\n if (collapsedTraversalCteAlias !== undefined) {\n return sql`FROM ${sql.raw(collapsedTraversalCteAlias)}`;\n }\n\n const startAlias = ast.start.alias;\n const fromClause = sql`FROM cte_${sql.raw(startAlias)}`;\n\n const joins: SqlFragment[] = [];\n for (const traversal of ast.traversals) {\n const cteAlias = `cte_${traversal.nodeAlias}`;\n const previousAlias = traversal.joinFromAlias;\n const joinType = traversal.optional ? \"LEFT JOIN\" : \"INNER JOIN\";\n joins.push(\n sql`${sql.raw(joinType)} ${sql.raw(cteAlias)} ON ${sql.raw(cteAlias)}.${sql.raw(previousAlias)}_id = cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_id AND ${sql.raw(cteAlias)}.${sql.raw(previousAlias)}_kind = cte_${sql.raw(previousAlias)}.${sql.raw(previousAlias)}_kind`,\n );\n }\n\n // Node IDs are unique only within a kind (PK is graph_id, kind, id),\n // so the relevance-CTE joins must include node_kind. Without it,\n // polymorphic queries would cross-join on user-supplied ids shared\n // across kinds.\n for (const join of buildRelevanceJoins(vectorPredicate, fulltextPredicate)) {\n joins.push(join);\n }\n\n return joins.length === 0 ?\n fromClause\n : sql`${fromClause} ${sql.join(joins, sql` `)}`;\n}\n\ntype BuildStandardOrderByInput = Readonly<{\n ast: QueryAst;\n collapsedTraversalCteAlias?: string;\n dialect: DialectAdapter;\n}>;\n\nexport function buildStandardOrderBy(\n input: BuildStandardOrderByInput,\n): SqlFragment | undefined {\n const { ast, collapsedTraversalCteAlias, dialect } = input;\n const fieldOrderBy = ast.orderBy ?? [];\n const aggregateOrderBy = ast.aggregateOrderBy ?? [];\n if (fieldOrderBy.length === 0 && aggregateOrderBy.length === 0) {\n return undefined;\n }\n\n // Only built when there's a FieldRef-based order spec to resolve against\n // a CTE — the aggregate-alias loop below references the SELECT-list\n // output alias directly and never needs it, which matters because the\n // common case for `.aggregate().orderBy(...)` has `fieldOrderBy` empty.\n const aliasToCte =\n fieldOrderBy.length > 0 ? buildAliasToCteMap(ast) : undefined;\n const parts: SqlFragment[] = [];\n for (const orderSpec of fieldOrderBy) {\n const valueType = orderSpec.field.valueType;\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n \"Ordering by JSON arrays or objects is not supported\",\n );\n }\n const cteAlias =\n collapsedTraversalCteAlias ??\n aliasToCte?.get(orderSpec.field.alias) ??\n `cte_${orderSpec.field.alias}`;\n const field = compileOrderFieldValue(\n ast,\n orderSpec.field,\n dialect,\n cteAlias,\n );\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDirection = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n parts.push(\n sql`(${field} IS NULL) ${nullsDirection}`,\n sql`${field} ${direction}`,\n );\n }\n\n // Aggregate ordering references the projected SELECT-list output alias\n // directly rather than recompiling a FieldRef/AggregateExpr — every\n // `.aggregate()` field (grouped or aggregated) is always projected with\n // an alias, and both SQLite and PostgreSQL allow ORDER BY to reference\n // it, so this needs no per-CTE or per-dialect resolution.\n //\n // Nulls ordering can't reuse the `(field IS NULL) direction, field\n // direction` trick above: unlike a source-table field reference, an\n // output alias is only resolved by either dialect when the ORDER BY term\n // is the bare identifier itself — wrapping it in `(alias IS NULL)`\n // makes both SQLite and PostgreSQL look for a real column named\n // `alias` and fail. The standard `NULLS FIRST`/`NULLS LAST` suffix\n // (supported by both dialects) sidesteps that: it attaches to the bare\n // identifier rather than embedding it in a larger expression.\n for (const orderSpec of aggregateOrderBy) {\n const column = quoteIdentifier(orderSpec.outputName);\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsKeyword = sql.raw(\n nulls === \"first\" ? \"NULLS FIRST\" : \"NULLS LAST\",\n );\n parts.push(sql`${column} ${direction} ${nullsKeyword}`);\n }\n\n return sql`ORDER BY ${sql.join(parts, sql`, `)}`;\n}\n\n// ============================================================\n// Late materialization (deferred projection)\n// ============================================================\n//\n// For an ORDER BY … LIMIT query whose projection reads columns beyond the\n// ordering/identity keys, the flat plan carries every projected column (e.g. a\n// large `content` prop) through the sorter for every candidate row and then\n// discards all but the LIMIT survivors. Late materialization sorts+limits a\n// *lean* candidate set (identity + sort keys only), then re-joins the physical\n// node table by `(graph_id, kind, id)` to fetch the deferred columns for only\n// the surviving rows. See the standard emitter's late-materialization branch\n// for the eligibility gate; these builders assume it already held.\n\nexport const LATE_MAT_TOPK_CTE_ALIAS = \"cte_lm_topk\";\nconst LATE_MAT_SORT_KEY_PREFIX = \"__lm_sk\";\nconst LATE_MAT_PHYSICAL_ALIAS_PREFIX = \"lm_\";\n\nexport function lateMaterializedPhysicalAlias(alias: string): string {\n return `${LATE_MAT_PHYSICAL_ALIAS_PREFIX}${alias}`;\n}\n\n/** Node aliases in the query: the start alias plus each traversal's node. */\nfunction lateMaterializedNodeAliases(ast: QueryAst): readonly string[] {\n return [\n ast.start.alias,\n ...ast.traversals.map((traversal) => traversal.nodeAlias),\n ];\n}\n\n/**\n * Node aliases the projection actually reads — the physical tables the outer\n * SELECT must re-join. Edge aliases are gated out upstream, so every projected\n * alias resolves to a node table here.\n */\nexport function lateMaterializedProjectedNodeAliases(\n ast: QueryAst,\n): readonly string[] {\n const referenced = new Set<string>();\n for (const field of ast.selectiveFields ?? []) {\n referenced.add(field.alias);\n }\n return lateMaterializedNodeAliases(ast).filter((alias) =>\n referenced.has(alias),\n );\n}\n\ntype BuildLateMaterializedTopKCteInput = Readonly<{\n ast: QueryAst;\n collapsedTraversalCteAlias?: string;\n dialect: DialectAdapter;\n fromClause: SqlFragment;\n limit: number;\n offset?: number | undefined;\n}>;\n\n/**\n * The topK CTE: selects each node alias's identity `(id, kind)` plus each sort\n * key value (aliased `__lm_sk{n}` so the outer SELECT can re-order the survivors\n * without re-extracting), ordered and limited on the lean candidate set.\n *\n * When the traversal rowset is collapsed onto a single CTE, every alias's\n * identity is carried into that one CTE (keyed by alias prefix), so all columns\n * resolve against `collapsedTraversalCteAlias` and the FROM references it alone.\n */\nexport function buildLateMaterializedTopKCte(\n input: BuildLateMaterializedTopKCteInput,\n): SqlFragment {\n const { ast, collapsedTraversalCteAlias, dialect, fromClause } = input;\n const aliasToCte = buildAliasToCteMap(ast);\n const cteAliasFor = (alias: string): string =>\n collapsedTraversalCteAlias ??\n aliasToCte.get(alias) ??\n `${ALIAS_CTE_PREFIX}${alias}`;\n\n const columns: SqlFragment[] = [];\n for (const alias of lateMaterializedNodeAliases(ast)) {\n const cteAlias = cteAliasFor(alias);\n columns.push(\n sql`${qualifyColumn(cteAlias, `${alias}_id`)} AS ${sql.raw(`${alias}_id`)}`,\n sql`${qualifyColumn(cteAlias, `${alias}_kind`)} AS ${sql.raw(`${alias}_kind`)}`,\n );\n }\n for (const [index, orderSpec] of (ast.orderBy ?? []).entries()) {\n const value = compileOrderFieldValue(\n ast,\n orderSpec.field,\n dialect,\n cteAliasFor(orderSpec.field.alias),\n );\n columns.push(\n sql`${value} AS ${sql.raw(`${LATE_MAT_SORT_KEY_PREFIX}${index}`)}`,\n );\n }\n\n const innerOrderBy = buildStandardOrderBy({\n ast,\n dialect,\n ...(collapsedTraversalCteAlias === undefined ?\n {}\n : { collapsedTraversalCteAlias }),\n });\n const limitOffset = buildLimitOffsetClause({\n limit: input.limit,\n offset: input.offset,\n });\n\n const parts: SqlFragment[] = [\n sql`SELECT ${sql.join(columns, sql`, `)}`,\n fromClause,\n ];\n if (innerOrderBy !== undefined) parts.push(innerOrderBy);\n if (limitOffset !== undefined) parts.push(limitOffset);\n\n return sql`${sql.raw(LATE_MAT_TOPK_CTE_ALIAS)} AS (${sql.join(parts, sql` `)})`;\n}\n\n/**\n * The outer projection: each selective field sourced from the re-joined\n * physical node table alias `lm_<alias>` rather than a candidate CTE, so the\n * deferred columns are read only for the surviving rows.\n */\nexport function buildLateMaterializedOuterProjection(\n ast: QueryAst,\n dialect: DialectAdapter,\n): SqlFragment {\n const columns = (ast.selectiveFields ?? []).map((field) => {\n const physicalAlias = lateMaterializedPhysicalAlias(field.alias);\n if (field.isSystemField) {\n const dbColumn = mapSelectiveSystemFieldToColumn(field.field);\n return sql`${compileColumnReference(physicalAlias, dbColumn)} AS ${quoteIdentifier(field.outputName)}`;\n }\n const extracted = compileSelectivePropsExtraction(\n field,\n compileColumnReference(physicalAlias, \"props\"),\n dialect,\n );\n return sql`${extracted} AS ${quoteIdentifier(field.outputName)}`;\n });\n return sql.join(columns, sql`, `);\n}\n\n/**\n * The outer ORDER BY: re-orders the LIMIT survivors by the `__lm_sk{n}` sort\n * values carried out of the topK CTE, matching `buildStandardOrderBy`'s\n * null-ordering semantics. Referencing the CTE's real columns (not bare output\n * aliases) keeps the `(x IS NULL)` null-placement trick valid on both dialects.\n */\nexport function buildLateMaterializedOuterOrderBy(\n ast: QueryAst,\n): SqlFragment | undefined {\n const orderBy = ast.orderBy ?? [];\n if (orderBy.length === 0) return undefined;\n const topk = sql.raw(LATE_MAT_TOPK_CTE_ALIAS);\n const parts: SqlFragment[] = [];\n for (const [index, orderSpec] of orderBy.entries()) {\n const column = sql`${topk}.${sql.raw(`${LATE_MAT_SORT_KEY_PREFIX}${index}`)}`;\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDirection = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n parts.push(\n sql`(${column} IS NULL) ${nullsDirection}`,\n sql`${column} ${direction}`,\n );\n }\n return sql`ORDER BY ${sql.join(parts, sql`, `)}`;\n}\n\nfunction fieldRefKey(field: FieldRef): string {\n const pointer = field.jsonPointer ?? \"\";\n return `${field.alias}:${field.path.join(\".\")}:${pointer}`;\n}\n\nfunction resolveEmbeddingFieldPath(field: FieldRef): string {\n if (\n field.jsonPointer !== undefined &&\n field.jsonPointer !== \"\" &&\n field.jsonPointer !== \"/\"\n ) {\n return field.jsonPointer.replace(/^\\//u, \"\").replaceAll(\"/\", \".\");\n }\n\n if (field.path[0] === \"props\") {\n return field.path.slice(1).join(\".\");\n }\n\n return field.path.join(\".\");\n}\n\ntype BuildStandardGroupByInput = Readonly<{\n ast: QueryAst;\n dialect: DialectAdapter;\n}>;\n\nexport function buildStandardGroupBy(\n input: BuildStandardGroupByInput,\n): SqlFragment | undefined {\n const { ast, dialect } = input;\n if (!ast.groupBy || ast.groupBy.fields.length === 0) {\n return undefined;\n }\n\n const seenKeys = new Set<string>();\n const allFields: FieldRef[] = [];\n\n for (const projectedField of ast.projection.fields) {\n if (projectedField.source.__type === \"field_ref\") {\n const key = fieldRefKey(projectedField.source);\n if (!seenKeys.has(key)) {\n seenKeys.add(key);\n allFields.push(projectedField.source);\n }\n }\n }\n\n for (const field of ast.groupBy.fields) {\n const key = fieldRefKey(field);\n if (!seenKeys.has(key)) {\n seenKeys.add(key);\n allFields.push(field);\n }\n }\n\n if (allFields.length === 0) {\n return undefined;\n }\n\n const aliasToCte = buildAliasToCteMap(ast);\n const parts = allFields.map((field) =>\n compileFieldValue(\n field,\n dialect,\n field.valueType,\n aliasToCte.get(field.alias) ?? `cte_${field.alias}`,\n ),\n );\n\n return sql`GROUP BY ${sql.join(parts, sql`, `)}`;\n}\n\ntype BuildStandardHavingInput = Readonly<{\n ast: QueryAst;\n ctx: PredicateCompilerContext;\n}>;\n\nexport function buildStandardHaving(\n input: BuildStandardHavingInput,\n): SqlFragment | undefined {\n const { ast, ctx } = input;\n if (!ast.having) {\n return undefined;\n }\n\n const condition = compilePredicateExpression(ast.having, ctx);\n return sql`HAVING ${condition}`;\n}\n\ntype BuildStandardEmbeddingsCteInput = Readonly<{\n ctx: PredicateCompilerContext;\n graphId: string;\n nodeKinds: readonly string[];\n vectorPredicate: VectorSimilarityPredicate;\n}>;\n\n/**\n * Builds the relevance CTE for a `field.similarTo(...)` predicate in the query\n * builder.\n *\n * Default (exact): splices the strategy's `distanceExpression` and scans each\n * declaring kind's per-field table (`ORDER BY distance LIMIT k`). On\n * pgvector >= 0.8 the planner can serve this shape from an HNSW index for a\n * single-kind alias; on the SQLite-family engines it is a full scan.\n *\n * Opt-in (`{ approximate: true }`): each declaring kind's branch compiles to\n * the strategy's own search SQL — the engine-native ANN form (vec0\n * `MATCH … k=`, libSQL `vector_top_k`, pgvector's index-eligible scan) —\n * scoped to the alias's candidate nodes via the same `candidates` pushdown\n * the search facade uses. Semantics become approximate (index recall); a\n * slot declared `indexType: \"none\"` degrades to the exact scan.\n */\nexport function buildStandardEmbeddingsCte(\n input: BuildStandardEmbeddingsCteInput,\n): SqlFragment {\n const { ctx, graphId, nodeKinds, vectorPredicate } = input;\n const { field, metric, minScore, queryEmbedding } = vectorPredicate;\n\n if (nodeKinds.length === 0) {\n throw new UnsupportedPredicateError(\n \"Vector predicate must resolve to at least one node kind\",\n );\n }\n\n const { vectorStrategy } = ctx;\n if (vectorStrategy === undefined) {\n throw new UnsupportedPredicateError(\n \"Vector similarity predicate requires a backend with a vector strategy\",\n );\n }\n\n const fieldPath = resolveEmbeddingFieldPath(field);\n const vectorSlots = ctx.vectorSlots;\n const scopedNodes = buildScopedNodeIdsSubquery(field.alias);\n\n // Only the kinds in this alias that actually DECLARE the embedding\n // field back a per-field table. Skipping kinds without a slot keeps\n // similarTo() from referencing a table that was never created and\n // stops rank weight leaking from kinds that happen to share a\n // field_path but don't embed it.\n const declaringKinds = nodeKinds.filter((kind) =>\n vectorSlots?.has(vectorSlotKey(kind, fieldPath)),\n );\n\n // Per-kind relevance scan against the strategy's typed per-field\n // table. The strategy owns the engine-specific distance fragment\n // (`<=>` / `vec_distance_cosine` / `vector_distance_cos`); the score\n // and minScore math around it stays shared so the OUTPUT columns\n // (node_id, node_kind, distance, score, ord) are identical across\n // engines and the hybrid RRF / vector ORDER BY paths are untouched.\n const branches = declaringKinds.map((kind) => {\n const tableName = vectorStrategy.tableName(graphId, kind, fieldPath);\n const slotDescriptor = vectorSlots?.get(vectorSlotKey(kind, fieldPath));\n // Use the predicate's explicit metric if given, else this kind's DECLARED\n // metric (the one its ANN index was built for). Resolving per kind keeps an\n // includeSubClasses union correct when subkinds declare different metrics.\n const branchMetric = metric ?? slotDescriptor?.metric ?? \"cosine\";\n\n // Approximate opt-in: retrieve this kind's candidates via the\n // strategy's own search SQL — the engine's native ANN form — scoped to\n // the alias's candidate nodes (predicates, currency, traversal\n // reachability) via the same `candidates` pushdown the search facade\n // uses. A slot declared `indexType: \"none\"` compiles to the strategy's\n // exact scan, so the opt-in degrades to today's semantics. Distance is\n // re-derived from the strategy's score convention (cosine score =\n // `1 - distance`; l2 / inner_product score = raw distance) so the\n // shared ORDER BY / ROW_NUMBER machinery below is untouched.\n //\n // The ANN path additionally requires the effective metric to MATCH the\n // slot's declared metric: every engine materializes metric-specific\n // ANN structures (vec0 bakes `distance_metric` into the virtual table,\n // libSQL's DiskANN index and pgvector's operator class are built for\n // one metric), so retrieving by the declared metric and re-scoring\n // under an overridden one would silently miss the override metric's\n // true nearest neighbors. A mismatched override falls back to the\n // exact scan below — correct for any metric, like `indexType: \"none\"`.\n // Engines whose `buildSearch` is EXACT (vec0's brute-force C KNN)\n // serve the non-approximate branch through it as well: identical\n // results to the SQL distance scan at engine speed (489ms -> 113ms\n // at 50k on the SQLite lane). The metric gate stays: the engine\n // form is built for the slot's declared metric.\n const engineFormEligible =\n vectorPredicate.approximate === true ||\n vectorStrategy.searchIsExact === true;\n const annSlot =\n engineFormEligible && branchMetric === slotDescriptor?.metric ?\n slotDescriptor\n : undefined;\n if (annSlot !== undefined) {\n ctx.annIndexTypes?.add(annSlot.indexType);\n // Membership candidates WITHOUT the scoped subquery's DISTINCT:\n // strategies embed these as `node_id IN (...)`, where duplicates\n // cannot change the result — and the DISTINCT is what kept\n // PostgreSQL off the ordered ANN index scan entirely (verified:\n // the identical statement flips from a full sort to an HNSW\n // Index Scan when the DISTINCT is dropped; even\n // `enable_seqscan = off` could not rescue the DISTINCT form).\n // The JOIN consumers (exact branch, fulltext CTE) keep\n // buildScopedNodeIdsSubquery's DISTINCT — a join DOES multiply\n // rows on duplicates.\n const candidateCte = `${ALIAS_CTE_PREFIX}${field.alias}`;\n const kindCandidates = sql`SELECT ${qualifyColumn(candidateCte, `${field.alias}_id`)} FROM ${quoteIdentifier(candidateCte)} WHERE ${qualifyColumn(candidateCte, `${field.alias}_kind`)} = ${kind}`;\n const annSql = vectorStrategy.buildSearch(\n {\n graphId,\n nodeKind: kind,\n fieldPath,\n dimensions: annSlot.dimensions,\n metric: branchMetric,\n indexType: annSlot.indexType,\n },\n {\n graphId,\n nodeKind: kind,\n fieldPath,\n queryEmbedding,\n metric: branchMetric,\n dimensions: annSlot.dimensions,\n indexType: annSlot.indexType,\n limit: vectorPredicate.limit,\n ...(minScore === undefined ? {} : { minScore }),\n },\n kindCandidates,\n );\n const distanceFromScore =\n branchMetric === \"cosine\" ? sql.raw(\"(1.0 - score)\") : sql.raw(\"score\");\n return sql`\n SELECT node_id, ${kind} AS node_kind, ${distanceFromScore} AS distance, score\n FROM (${annSql}) AS tg_ann_src\n `;\n }\n const distanceExpr = vectorStrategy.distanceExpression(\n qualifyColumn(tableName, \"embedding\"),\n queryEmbedding,\n branchMetric,\n );\n // EXACT MEANS EXACT: this branch is the non-approximate path, but on\n // pgvector any `ORDER BY embedding <=> q LIMIT k` whose expression\n // matches the ANN opclass is silently served by the HNSW/IVFFlat\n // index — approximate results with plan-dependent recall (measured\n // recall 0.980 unfiltered, 0.000 under a selective filter at 50k,\n // where the index frontier starves). `+ 0.0` makes the ordered\n // expression unmatchable to the opclass, forcing the true flat scan;\n // numerically identity, and inert on engines whose ANN forms are\n // opt-in anyway (vec0 MATCH, libSQL vector_top_k). The sanctioned\n // index path is `approximate: true` above.\n const exactDistanceExpr = sql`(${distanceExpr} + 0.0)`;\n const scoreExpr = vectorScoreExpression(distanceExpr, branchMetric);\n\n const conditions: SqlFragment[] = [\n sql`${qualifyColumn(tableName, \"graph_id\")} = ${graphId}`,\n ];\n if (minScore !== undefined) {\n // minScore validation (finiteness, cosine range) is handled by the\n // vector predicate pass in passes/vector.ts — no redundant check.\n conditions.push(\n vectorMinScoreCondition(distanceExpr, branchMetric, minScore),\n );\n }\n\n return sql`\n SELECT\n ${qualifyColumn(tableName, \"node_id\")} AS node_id,\n ${kind} AS node_kind,\n ${exactDistanceExpr} AS distance,\n ${scoreExpr} AS score\n FROM ${quoteIdentifier(tableName)}\n INNER JOIN ${scopedNodes}\n ON ${sql.raw(`${SCOPED_RELEVANCE_NODES_ALIAS}.node_id`)} =\n ${qualifyColumn(tableName, \"node_id\")}\n AND ${sql.raw(`${SCOPED_RELEVANCE_NODES_ALIAS}.node_kind`)} = ${kind}\n WHERE ${sql.join(conditions, sql` AND `)}\n `;\n });\n\n // No declaring kind → emit a CTE with the right column shape that\n // yields no rows, so the rest of the emitter (which always references\n // cte_embeddings) compiles and simply matches nothing.\n const unionBody =\n branches.length === 0 ?\n emptyEmbeddingsBody()\n : sql.join(\n branches,\n sql`\n UNION ALL\n `,\n );\n\n // Inner SELECT applies the predicate's k-cutoff, then ROW_NUMBER ranks\n // over that bounded set. Without the inner LIMIT, a hybrid query would\n // assign vector ordinals to every candidate, letting documents far\n // outside the requested top-k contribute to the RRF fused score and\n // reorder final results.\n return sql`\n ${sql.raw(EMBEDDINGS_CTE_ALIAS)} AS (\n SELECT\n node_id,\n node_kind,\n distance,\n score,\n ROW_NUMBER() OVER (ORDER BY distance ASC) AS ord\n FROM (\n ${unionBody}\n ORDER BY distance ASC\n LIMIT ${vectorPredicate.limit}\n ) AS vec_inner\n )\n `;\n}\n\n/**\n * A no-row inner body carrying the exact `(node_id, node_kind, distance,\n * score)` column contract, used when no kind in the alias declares the\n * embedding field. `WHERE 1 = 0` keeps the planner from scanning.\n */\nfunction emptyEmbeddingsBody(): SqlFragment {\n return sql`\n SELECT\n CAST(NULL AS TEXT) AS node_id,\n CAST(NULL AS TEXT) AS node_kind,\n CAST(NULL AS REAL) AS distance,\n CAST(NULL AS REAL) AS score\n WHERE 1 = 0\n `;\n}\n\n// ============================================================\n// Fulltext Search CTE\n// ============================================================\n\ntype BuildStandardFulltextCteInput = Readonly<{\n ctx: PredicateCompilerContext;\n fulltextPredicate: FulltextMatchPredicate;\n graphId: string;\n nodeKinds: readonly string[];\n}>;\n\nexport function buildStandardFulltextCte(\n input: BuildStandardFulltextCteInput,\n): SqlFragment {\n const { ctx, fulltextPredicate, graphId, nodeKinds } = input;\n const { dialect, schema } = ctx;\n const { query, mode, language, limit, minScore } = fulltextPredicate;\n\n if (nodeKinds.length === 0) {\n throw new UnsupportedPredicateError(\n \"Fulltext predicate must resolve to at least one node kind\",\n );\n }\n\n const tableName = schema.tables.fulltext;\n const scopedNodes = buildScopedNodeIdsSubquery(fulltextPredicate.field.alias);\n const fulltextStrategy = dialect.fulltext;\n if (fulltextStrategy === undefined) {\n throw new UnsupportedPredicateError(\n `Fulltext match predicates are not supported for dialect \"${dialect.name}\"`,\n );\n }\n // Parse the query with a CONSTANT language whenever possible: the\n // caller's explicit override, else the one declared language shared by\n // every kind in the alias (rows are written with their kind's declared\n // language, so this matches the stored tsv). A constant keeps the\n // tsquery plan-time-stable, so PostgreSQL's GIN index on `tsv` can\n // serve the match — the per-row `websearch_to_tsquery(\"language\", ...)`\n // fallback (mixed-language aliases only) forces a scan of the kinds'\n // rows.\n const effectiveLanguage =\n language ?? sharedDeclaredLanguage(ctx.fulltextLanguages, nodeKinds);\n const matchCondition = fulltextStrategy.matchCondition(\n tableName,\n query,\n mode,\n effectiveLanguage,\n );\n const rankExpression = fulltextStrategy.rankExpression(\n tableName,\n query,\n mode,\n effectiveLanguage,\n );\n\n const conditions: SqlFragment[] = [\n sql`${qualifyColumn(tableName, \"graph_id\")} = ${graphId}`,\n compileKindFilter(qualifyColumn(tableName, \"node_kind\"), nodeKinds),\n matchCondition,\n ];\n if (minScore !== undefined) {\n conditions.push(sql`${rankExpression} >= ${minScore}`);\n }\n\n // Inner SELECT computes the rank once into an alias, outer SELECT\n // adds the ordinal via ROW_NUMBER. Two reasons to nest:\n // (1) Postgres re-evaluates `ts_rank_cd(...)` if it's repeated across\n // SELECT/ORDER BY, so referencing the alias avoids duplicate work.\n // (2) SQLite FTS5's bm25() cannot appear inside a window function's\n // OVER clause — the auxiliary-function context is restricted.\n return sql`\n ${sql.raw(FULLTEXT_CTE_ALIAS)} AS (\n SELECT\n node_id,\n node_kind,\n rank,\n ROW_NUMBER() OVER (ORDER BY rank DESC, node_id ASC) AS ord\n FROM (\n SELECT\n ${qualifyColumn(tableName, \"node_id\")} AS node_id,\n ${qualifyColumn(tableName, \"node_kind\")} AS node_kind,\n ${rankExpression} AS rank\n FROM ${schema.fulltextTable}\n INNER JOIN ${scopedNodes}\n ON ${sql.raw(`${SCOPED_RELEVANCE_NODES_ALIAS}.node_id`)} =\n ${qualifyColumn(tableName, \"node_id\")}\n AND ${sql.raw(`${SCOPED_RELEVANCE_NODES_ALIAS}.node_kind`)} =\n ${qualifyColumn(tableName, \"node_kind\")}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY rank DESC, ${qualifyColumn(tableName, \"node_id\")} ASC\n LIMIT ${limit}\n ) AS fts_inner\n )\n `;\n}\n\n/**\n * The single declared language shared by every kind in the alias that\n * declares searchable fields, or `undefined` when they disagree (or none\n * declares any — such kinds contribute no fulltext rows either way).\n */\nfunction sharedDeclaredLanguage(\n fulltextLanguages: ReadonlyMap<string, string> | undefined,\n nodeKinds: readonly string[],\n): string | undefined {\n if (fulltextLanguages === undefined) return undefined;\n const languages = new Set<string>();\n for (const kind of nodeKinds) {\n const language = fulltextLanguages.get(kind);\n if (language !== undefined) languages.add(language);\n }\n if (languages.size !== 1) return undefined;\n return [...languages][0];\n}\n\nexport function buildStandardHybridCandidateCte(): SqlFragment {\n return sql`\n ${sql.raw(HYBRID_CANDIDATES_CTE_ALIAS)} AS (\n SELECT node_id, node_kind FROM ${sql.raw(EMBEDDINGS_CTE_ALIAS)}\n UNION\n SELECT node_id, node_kind FROM ${sql.raw(FULLTEXT_CTE_ALIAS)}\n )\n `;\n}\n\n/**\n * Compiles user-supplied `orderBy` clauses into `SqlFragment` values suitable\n * for appending after a relevance-driven primary ORDER BY (vector,\n * fulltext, or hybrid RRF).\n */\nfunction compileUserOrderBy(\n ast: QueryAst,\n dialect: DialectAdapter,\n): readonly SqlFragment[] {\n if (!ast.orderBy || ast.orderBy.length === 0) return [];\n\n const aliasToCte = buildAliasToCteMap(ast);\n const fragments: SqlFragment[] = [];\n for (const orderSpec of ast.orderBy) {\n const valueType = orderSpec.field.valueType;\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n \"Ordering by JSON arrays or objects is not supported\",\n );\n }\n const cteAlias =\n aliasToCte.get(orderSpec.field.alias) ??\n `${ALIAS_CTE_PREFIX}${orderSpec.field.alias}`;\n const field = compileOrderFieldValue(\n ast,\n orderSpec.field,\n dialect,\n cteAlias,\n );\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDirection = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n fragments.push(\n sql`(${field} IS NULL) ${nullsDirection}`,\n sql`${field} ${direction}`,\n );\n }\n return fragments;\n}\n\ntype BuildStandardFulltextOrderByInput = Readonly<{\n ast: QueryAst;\n dialect: DialectAdapter;\n}>;\n\n/**\n * ORDER BY clause when only a fulltext predicate is present.\n * Orders by rank DESC then any user-supplied ORDER BY as tiebreakers.\n */\nexport function buildStandardFulltextOrderBy(\n input: BuildStandardFulltextOrderByInput,\n): SqlFragment {\n const { ast, dialect } = input;\n const rankOrder = sql.raw(`${FULLTEXT_CTE_ALIAS}.rank DESC`);\n const userOrders = compileUserOrderBy(ast, dialect);\n return sql`ORDER BY ${sql.join([rankOrder, ...userOrders], sql`, `)}`;\n}\n\n/**\n * ORDER BY clause when BOTH vector and fulltext predicates are present.\n *\n * Reciprocal Rank Fusion at SQL level. Each CTE emits an `ord` ordinal\n * via ROW_NUMBER; the outer ORDER BY blends them as\n * `w_vec / (k + ord_vec) + w_ft / (k + ord_ft)`. NULL `ord` (a node\n * matched by only one source) makes that source's term NULL → COALESCE-to-0\n * absorbs it. User-supplied `orderBy` clauses follow as tiebreakers,\n * matching the single-source paths so pagination stays stable across\n * RRF score ties.\n *\n * Defaults: k=60, vector weight = fulltext weight = 1. Override via\n * `.fuseWith({ k, weights })` on the query builder.\n */\n\ntype BuildStandardHybridRrfOrderByInput = Readonly<{\n ast: QueryAst;\n dialect: DialectAdapter;\n fusion: HybridFusionOptions | undefined;\n}>;\n\nexport function buildStandardHybridRrfOrderBy(\n input: BuildStandardHybridRrfOrderByInput,\n): SqlFragment {\n const { ast, dialect, fusion } = input;\n const k = fusion?.k ?? DEFAULT_RRF_K;\n const vectorWeight = fusion?.weights?.vector ?? DEFAULT_RRF_WEIGHT;\n const fulltextWeight = fusion?.weights?.fulltext ?? DEFAULT_RRF_WEIGHT;\n\n // Invariant: validateHybridFusionOptions has already rejected\n // non-finite / negative values before we reach here. sql.raw on these\n // numeric constants is deliberate — they're schema-level config, not\n // user-bindable.\n const rrfOrder = sql.raw(\n `(COALESCE(${vectorWeight} / (${k} + ${EMBEDDINGS_CTE_ALIAS}.ord), 0) + ` +\n `COALESCE(${fulltextWeight} / (${k} + ${FULLTEXT_CTE_ALIAS}.ord), 0)) DESC`,\n );\n // Deterministic tiebreak on the CTE-projected node_id. At least one of\n // the two CTEs always has a non-NULL node_id for any row returned by\n // the LEFT JOIN-union shape, so COALESCE always resolves. This matches\n // `store.search.hybrid`'s JS-side code-unit `compareStrings(nodeId)`\n // tiebreak so the two paths produce identical top-k under ties (SQLite\n // BINARY collation is code-unit order for the ASCII id alphabet).\n const idTiebreak = sql.raw(\n `COALESCE(${FULLTEXT_CTE_ALIAS}.node_id, ${EMBEDDINGS_CTE_ALIAS}.node_id) ASC`,\n );\n const userOrders = compileUserOrderBy(ast, dialect);\n return sql`ORDER BY ${sql.join([rrfOrder, ...userOrders, idTiebreak], sql`, `)}`;\n}\n\ntype BuildStandardVectorOrderByInput = Readonly<{\n ast: QueryAst;\n dialect: DialectAdapter;\n}>;\n\nexport function buildStandardVectorOrderBy(\n input: BuildStandardVectorOrderByInput,\n): SqlFragment {\n const { ast, dialect } = input;\n const distanceOrder = sql.raw(`${EMBEDDINGS_CTE_ALIAS}.distance ASC`);\n const userOrders = compileUserOrderBy(ast, dialect);\n return sql`ORDER BY ${sql.join([distanceOrder, ...userOrders], sql`, `)}`;\n}\n\ntype BuildLimitOffsetClauseInput = Readonly<{\n limit: number | undefined;\n offset: number | undefined;\n}>;\n\nexport function buildLimitOffsetClause(\n input: BuildLimitOffsetClauseInput,\n): SqlFragment | undefined {\n const { limit, offset } = input;\n const parts: SqlFragment[] = [];\n\n if (limit !== undefined) {\n parts.push(sql`LIMIT ${limit}`);\n }\n if (offset !== undefined) {\n parts.push(sql`OFFSET ${offset}`);\n }\n\n return parts.length > 0 ? sql.join(parts, sql` `) : undefined;\n}\n","import { UnsupportedPredicateError } from \"../../../errors\";\nimport type { FulltextMatchPredicate, QueryAst } from \"../../ast\";\nimport type { DialectAdapter } from \"../../dialect\";\nimport { extractFulltextMatchPredicates } from \"../predicates\";\n\nexport type FulltextPredicatePassResult = Readonly<{\n fulltextPredicate: FulltextMatchPredicate | undefined;\n}>;\n\n/**\n * Validates fulltext predicate placement and cardinality.\n *\n * Invariants mirror the vector predicate pass:\n * - Fulltext predicates must not appear under OR/NOT branches.\n * - At most one fulltext predicate is allowed per query.\n * - The dialect must declare fulltext support.\n */\nexport function runFulltextPredicatePass(\n ast: QueryAst,\n dialect: DialectAdapter,\n): FulltextPredicatePassResult {\n const fulltextPredicates = extractFulltextMatchPredicates(ast.predicates);\n if (fulltextPredicates.length > 1) {\n throw new UnsupportedPredicateError(\n \"Multiple fulltext match predicates in a single query are not supported\",\n );\n }\n\n const fulltextPredicate = fulltextPredicates[0];\n if (fulltextPredicate === undefined) {\n return { fulltextPredicate: undefined };\n }\n\n if (!dialect.capabilities.supportsFulltext) {\n throw new UnsupportedPredicateError(\n `Fulltext match predicates are not supported for dialect \"${dialect.name}\"`,\n );\n }\n\n const strategy = dialect.fulltext;\n if (strategy === undefined) {\n throw new UnsupportedPredicateError(\n `Dialect \"${dialect.name}\" advertises fulltext support but has no strategy configured`,\n );\n }\n\n if (!strategy.supportedModes.includes(fulltextPredicate.mode)) {\n throw new UnsupportedPredicateError(\n `Fulltext query mode \"${fulltextPredicate.mode}\" is not supported by the \"${strategy.name}\" strategy. Supported modes: ${strategy.supportedModes.join(\", \")}.`,\n );\n }\n\n if (\n fulltextPredicate.language !== undefined &&\n !strategy.supportsLanguageOverride\n ) {\n throw new UnsupportedPredicateError(\n `Fulltext strategy \"${strategy.name}\" does not honor a per-query \\`language\\` override ` +\n `(its tokenizer is fixed at table-create time). Drop the option, or use a strategy ` +\n `that advertises \\`supportsLanguageOverride: true\\`.`,\n );\n }\n\n if (\n !Number.isFinite(fulltextPredicate.limit) ||\n fulltextPredicate.limit <= 0\n ) {\n throw new UnsupportedPredicateError(\n `Fulltext match limit must be a positive finite number, got ${String(fulltextPredicate.limit)}`,\n );\n }\n\n const { minScore } = fulltextPredicate;\n if (minScore !== undefined && !Number.isFinite(minScore)) {\n throw new UnsupportedPredicateError(\n `Fulltext minScore must be a finite number, got ${String(minScore)}`,\n );\n }\n\n return { fulltextPredicate };\n}\n\n/**\n * Resolves query LIMIT in the presence of a fulltext predicate.\n *\n * Mirrors resolveVectorAwareLimit. When a fulltext predicate is present\n * without an explicit AST limit, the predicate's own limit bounds the\n * result set; when both are present the tighter wins.\n */\nexport function resolveFulltextAwareLimit(\n astLimit?: number,\n fulltextPredicate?: FulltextMatchPredicate,\n): number | undefined {\n if (fulltextPredicate === undefined) {\n return astLimit;\n }\n if (astLimit === undefined) {\n return fulltextPredicate.limit;\n }\n return Math.min(astLimit, fulltextPredicate.limit);\n}\n","import { UnsupportedPredicateError } from \"../../../errors\";\nimport type {\n FulltextMatchPredicate,\n HybridFusionOptions,\n QueryAst,\n VectorSimilarityPredicate,\n} from \"../../ast\";\n\nexport type FusionConfigPassResult = Readonly<{\n fusion: HybridFusionOptions | undefined;\n}>;\n\n/**\n * Validates that `.fuseWith()` configuration is coherent with the query\n * shape. Runs after the vector and fulltext predicate passes.\n *\n * - When no `fusion` is configured, returns `{ fusion: undefined }`.\n * - When `fusion` is configured but either predicate is missing, throws.\n * - When the predicates target different aliases, throws.\n */\nexport function runFusionConfigPass(\n ast: QueryAst,\n vectorPredicate: VectorSimilarityPredicate | undefined,\n fulltextPredicate: FulltextMatchPredicate | undefined,\n): FusionConfigPassResult {\n const fusion = ast.fusion;\n if (fusion === undefined) return { fusion: undefined };\n\n if (vectorPredicate === undefined || fulltextPredicate === undefined) {\n throw new UnsupportedPredicateError(\n `.fuseWith() requires both a .similarTo() and a .$fulltext.matches() ` +\n `predicate in the same query. Remove .fuseWith(), or add the missing ` +\n `predicate.`,\n );\n }\n if (vectorPredicate.field.alias !== fulltextPredicate.field.alias) {\n throw new UnsupportedPredicateError(\n `.fuseWith() requires .similarTo() and .$fulltext.matches() to target ` +\n `the same node alias. Got vector=${vectorPredicate.field.alias}, ` +\n `fulltext=${fulltextPredicate.field.alias}.`,\n );\n }\n return { fusion };\n}\n","import {\n CompilerInvariantError,\n UnsupportedPredicateError,\n} from \"../../../errors\";\nimport type { QueryAst, Traversal, VariableLengthSpec } from \"../../ast\";\n\n/**\n * Traversal with required variable-length spec.\n */\nexport type VariableLengthTraversal = Traversal & {\n variableLength: VariableLengthSpec;\n};\n\n/**\n * Selects and validates the variable-length traversal target for recursive compilation.\n *\n * Invariants:\n * - Query must contain exactly one variable-length traversal.\n * - Recursive mode currently supports only a single traversal in the query.\n */\nexport function runRecursiveTraversalSelectionPass(\n ast: QueryAst,\n): VariableLengthTraversal {\n const variableLengthTraversal = ast.traversals.find(\n (traversal): traversal is VariableLengthTraversal =>\n traversal.variableLength !== undefined,\n );\n\n if (variableLengthTraversal === undefined) {\n throw new CompilerInvariantError(\"No variable-length traversal found\");\n }\n\n if (ast.traversals.length > 1) {\n throw new UnsupportedPredicateError(\n \"Variable-length traversals with multiple traversals are not yet supported. \" +\n \"Please use a single variable-length traversal.\",\n );\n }\n\n return variableLengthTraversal;\n}\n","export type CompilerPass<TState, TPassName extends string, TOutput> = Readonly<{\n name: TPassName;\n execute: (state: TState) => TOutput;\n update: (state: TState, output: TOutput) => TState;\n}>;\n\nexport type CompilerPassResult<TState> = Readonly<{\n state: TState;\n}>;\n\nexport function runCompilerPass<TState, TPassName extends string, TOutput>(\n state: TState,\n pass: CompilerPass<TState, TPassName, TOutput>,\n): CompilerPassResult<TState> {\n const output = pass.execute(state);\n return {\n state: pass.update(state, output),\n };\n}\n","import type { QueryAst } from \"../../ast\";\nimport { type SqlFragment } from \"../../sql-fragment\";\nimport {\n compileTemporalFilter,\n currentReadInstantFor,\n extractTemporalOptions,\n type ReadInstantMode,\n} from \"../temporal\";\n\nexport type TemporalFilterPass = Readonly<{\n forAlias: (tableAlias?: string) => SqlFragment;\n}>;\n\n/**\n * Creates a temporal filter pass bound to a query AST.\n *\n * Invariant: all temporal clauses for a query use the same \"current\" instant,\n * bound once here from the application clock. In `\"literal\"` mode that is a\n * concrete value; in `\"placeholder\"` mode it is the reserved read-instant\n * placeholder (filled fresh per execution by the query builder's template\n * cache) — see {@link currentReadInstantFor}.\n */\nexport function createTemporalFilterPass(\n ast: QueryAst,\n readInstant: ReadInstantMode = \"literal\",\n): TemporalFilterPass {\n const currentTimestamp = currentReadInstantFor(readInstant);\n return {\n forAlias(tableAlias?: string): SqlFragment {\n return compileTemporalFilter({\n ...extractTemporalOptions(ast, tableAlias),\n currentTimestamp,\n });\n },\n };\n}\n","import { type VectorMetric } from \"../../../backend/types\";\nimport { UnsupportedPredicateError } from \"../../../errors\";\nimport type { QueryAst, VectorSimilarityPredicate } from \"../../ast\";\nimport type { DialectAdapter } from \"../../dialect\";\nimport { type VectorStrategy } from \"../../dialect/vector-strategy\";\nimport { extractVectorSimilarityPredicates } from \"../predicates\";\n\nexport type VectorPredicatePassResult = Readonly<{\n vectorPredicate: VectorSimilarityPredicate | undefined;\n}>;\n\n/**\n * Validates vector predicate placement, cardinality, and metric support.\n *\n * Invariants:\n * - Vector predicates must not appear under OR/NOT branches.\n * - At most one vector predicate is allowed per query.\n * - The requested metric must be supported by the active vector strategy.\n *\n * `vectorStrategy` is the backend-declared strategy that will generate the\n * relevance SQL (passed by the standard compile path). When present it is the\n * authoritative source for supported metrics — a custom strategy override may\n * advertise a different metric set than the dialect's built-in default. It is\n * omitted only by the plan-lowering path (recursive / set-operation queries),\n * which has no strategy plumbed and falls back to the dialect's metric list.\n */\nexport function runVectorPredicatePass(\n ast: QueryAst,\n dialect: DialectAdapter,\n vectorStrategy?: VectorStrategy,\n): VectorPredicatePassResult {\n const vectorPredicates = extractVectorSimilarityPredicates(ast.predicates);\n if (vectorPredicates.length > 1) {\n throw new UnsupportedPredicateError(\n \"Multiple vector similarity predicates in a single query are not supported\",\n );\n }\n\n const vectorPredicate = vectorPredicates[0];\n if (vectorPredicate === undefined) {\n return { vectorPredicate: undefined };\n }\n\n const predicateStrategy = dialect.capabilities.vectorPredicateStrategy;\n if (predicateStrategy === \"unsupported\" || !dialect.supportsVectors) {\n throw new UnsupportedPredicateError(\n `Vector similarity predicates are not supported for dialect \"${dialect.name}\"`,\n );\n }\n\n // Only an EXPLICIT metric is validated here. When omitted, the compiler\n // resolves the field's declared `embedding()` metric per kind (validated\n // when the field's index was materialized), so there is nothing to check yet.\n if (vectorPredicate.metric !== undefined) {\n const supportedMetrics: readonly VectorMetric[] =\n vectorStrategy?.capabilities.metrics ??\n dialect.capabilities.vectorMetrics;\n if (!supportedMetrics.includes(vectorPredicate.metric)) {\n throw new UnsupportedPredicateError(\n vectorStrategy === undefined ?\n `Vector metric \"${vectorPredicate.metric}\" is not supported for dialect \"${dialect.name}\"`\n : `Vector metric \"${vectorPredicate.metric}\" is not supported by vector strategy \"${vectorStrategy.name}\" (supported: ${supportedMetrics.join(\", \")})`,\n );\n }\n }\n\n if (!Number.isFinite(vectorPredicate.limit) || vectorPredicate.limit <= 0) {\n throw new UnsupportedPredicateError(\n `Vector predicate limit must be a positive finite number, got ${String(vectorPredicate.limit)}`,\n );\n }\n\n const { minScore } = vectorPredicate;\n if (minScore !== undefined) {\n if (!Number.isFinite(minScore)) {\n throw new UnsupportedPredicateError(\n `Vector minScore must be a finite number, got ${String(minScore)}`,\n );\n }\n if (vectorPredicate.metric === \"cosine\" && Math.abs(minScore) > 1) {\n throw new UnsupportedPredicateError(\n `Cosine minScore must be between -1 and 1, got ${String(minScore)}`,\n );\n }\n }\n\n return { vectorPredicate };\n}\n\n/**\n * Resolves the query LIMIT in the presence of vector similarity.\n *\n * If a vector predicate is present and AST limit is omitted, use the\n * predicate's built-in limit to bound nearest-neighbor search.\n */\nexport function resolveVectorAwareLimit(\n astLimit?: number,\n vectorPredicate?: VectorSimilarityPredicate,\n): number | undefined {\n if (vectorPredicate === undefined) {\n return astLimit;\n }\n if (astLimit === undefined) {\n return vectorPredicate.limit;\n }\n return Math.min(astLimit, vectorPredicate.limit);\n}\n","import { CompilerInvariantError } from \"../../../errors\";\nimport { requireDefined } from \"../../../utils/presence\";\nimport type {\n AggregateExpr,\n ComposableQuery,\n FulltextMatchPredicate,\n NodePredicate,\n QueryAst,\n SetOperation,\n VectorSimilarityPredicate,\n} from \"../../ast\";\nimport {\n getDialect,\n type SqlDialect,\n type VectorStrategy,\n} from \"../../dialect\";\nimport {\n resolveFulltextAwareLimit,\n resolveVectorAwareLimit,\n runFulltextPredicatePass,\n runRecursiveTraversalSelectionPass,\n runVectorPredicatePass,\n type VariableLengthTraversal,\n} from \"../passes\";\nimport type {\n AggregatePlanNode,\n LimitOffsetPlanNode,\n LogicalPlan,\n LogicalPlanNode,\n ProjectPlanNode,\n} from \"./types\";\n\nexport type LowerStandardQueryToLogicalPlanInput = Readonly<{\n ast: QueryAst;\n collapsedTraversalCteAlias?: string;\n dialect: SqlDialect;\n effectiveLimit?: number;\n fulltextPredicate?: FulltextMatchPredicate;\n graphId: string;\n vectorPredicate?: VectorSimilarityPredicate;\n}>;\n\nexport type LowerRecursiveQueryToLogicalPlanInput = Readonly<{\n ast: QueryAst;\n dialect: SqlDialect;\n graphId: string;\n traversal?: VariableLengthTraversal;\n}>;\n\nexport type LowerSetOperationToLogicalPlanInput = Readonly<{\n dialect: SqlDialect;\n graphId: string;\n op: SetOperation;\n /**\n * The backend-configured vector strategy, threaded so a set-operation leaf's\n * vector predicate validates against the same metric set as standalone leaf\n * compilation (rather than only the dialect's fallback metric list).\n */\n vectorStrategy?: VectorStrategy;\n}>;\n\n/**\n * Creates a sequential plan node ID generator scoped to a single compilation invocation.\n * IDs are NOT stable across compilations — different compilations of the same query\n * may produce different IDs depending on pass execution order.\n */\nfunction createPlanNodeIdFactory(): () => string {\n let current = 0;\n return function nextPlanNodeId(): string {\n current += 1;\n return `plan_${current.toString(36)}`;\n };\n}\n\nfunction extractAggregateExpressions(ast: QueryAst): readonly AggregateExpr[] {\n const aggregates: AggregateExpr[] = [];\n\n for (const field of ast.projection.fields) {\n if (\"__type\" in field.source && field.source.__type === \"aggregate\") {\n aggregates.push(field.source);\n }\n }\n\n return aggregates;\n}\n\nfunction getAliasPredicates(\n ast: QueryAst,\n alias: string,\n predicateTargetType: \"edge\" | \"node\",\n): readonly NodePredicate[] {\n return ast.predicates.filter((predicate) => {\n const targetType = predicate.targetType ?? \"node\";\n return (\n predicate.targetAlias === alias && targetType === predicateTargetType\n );\n });\n}\n\nfunction wrapWithAliasFilterNode(\n currentNode: LogicalPlanNode,\n ast: QueryAst,\n alias: string,\n predicateTargetType: \"edge\" | \"node\",\n nextPlanNodeId: () => string,\n): LogicalPlanNode {\n const aliasPredicates = getAliasPredicates(ast, alias, predicateTargetType);\n if (aliasPredicates.length === 0) {\n return currentNode;\n }\n\n return {\n alias,\n id: nextPlanNodeId(),\n input: currentNode,\n op: \"filter\",\n predicateTargetType,\n predicates: aliasPredicates.map((predicate) => predicate.expression),\n };\n}\n\nfunction appendAggregateSortLimitAndProjectNodes(\n currentNode: LogicalPlanNode,\n ast: QueryAst,\n nextPlanNodeId: () => string,\n limit: number | undefined,\n collapsedTraversalCteAlias?: string,\n): LogicalPlanNode {\n let node = currentNode;\n\n const aggregateExpressions = extractAggregateExpressions(ast);\n if (\n aggregateExpressions.length > 0 ||\n ast.groupBy !== undefined ||\n ast.having !== undefined\n ) {\n const aggregateNode: AggregatePlanNode = {\n aggregates: aggregateExpressions,\n groupBy: ast.groupBy?.fields ?? [],\n id: nextPlanNodeId(),\n input: node,\n op: \"aggregate\",\n };\n node =\n ast.having === undefined ?\n aggregateNode\n : { ...aggregateNode, having: ast.having };\n }\n\n const hasFieldOrderBy = ast.orderBy !== undefined && ast.orderBy.length > 0;\n const hasAggregateOrderBy =\n ast.aggregateOrderBy !== undefined && ast.aggregateOrderBy.length > 0;\n if (hasFieldOrderBy || hasAggregateOrderBy) {\n // The sort node's presence (not its `orderBy` payload) is what the\n // emitter's plan-shape invariant reads — see `hasSort` in\n // emitter/plan-inspector.ts. `orderBy` here can be `[]` when only\n // `ast.aggregateOrderBy` is set; that's fine today since nothing reads\n // this field's contents, only whether the node exists.\n node = {\n id: nextPlanNodeId(),\n input: node,\n op: \"sort\",\n orderBy: ast.orderBy ?? [],\n };\n }\n\n if (limit !== undefined || ast.offset !== undefined) {\n const limitOffsetNodeBase: Omit<LimitOffsetPlanNode, \"limit\" | \"offset\"> = {\n id: nextPlanNodeId(),\n input: node,\n op: \"limit_offset\",\n };\n const hasLimit = limit !== undefined;\n const hasOffset = ast.offset !== undefined;\n\n if (hasLimit && hasOffset) {\n node = {\n ...limitOffsetNodeBase,\n limit,\n offset: ast.offset,\n };\n } else if (hasLimit) {\n node = { ...limitOffsetNodeBase, limit };\n } else if (hasOffset) {\n node = { ...limitOffsetNodeBase, offset: ast.offset };\n } else {\n throw new CompilerInvariantError(\n \"limit_offset node requires limit or offset to be present\",\n );\n }\n }\n\n const projectNodeBase: Omit<ProjectPlanNode, \"collapsedTraversalAlias\"> = {\n fields: ast.projection.fields,\n id: nextPlanNodeId(),\n input: node,\n op: \"project\",\n };\n return collapsedTraversalCteAlias === undefined ? projectNodeBase : (\n {\n ...projectNodeBase,\n collapsedTraversalAlias: collapsedTraversalCteAlias,\n }\n );\n}\n\ntype LowerStandardQueryToLogicalPlanNodeInput =\n LowerStandardQueryToLogicalPlanInput &\n Readonly<{\n nextPlanNodeId: () => string;\n }>;\n\nfunction lowerStandardQueryToLogicalPlanNode(\n input: LowerStandardQueryToLogicalPlanNodeInput,\n): LogicalPlanNode {\n const { ast, nextPlanNodeId } = input;\n\n let currentNode: LogicalPlanNode = {\n alias: ast.start.alias,\n graphId: input.graphId,\n id: nextPlanNodeId(),\n kinds: ast.start.kinds,\n op: \"scan\",\n source: \"nodes\",\n };\n\n currentNode = wrapWithAliasFilterNode(\n currentNode,\n ast,\n ast.start.alias,\n \"node\",\n nextPlanNodeId,\n );\n\n for (const traversal of ast.traversals) {\n currentNode = {\n direction: traversal.direction,\n edgeAlias: traversal.edgeAlias,\n edgeKinds: traversal.edgeKinds,\n id: nextPlanNodeId(),\n input: currentNode,\n inverseEdgeKinds: traversal.inverseEdgeKinds ?? [],\n joinFromAlias: traversal.joinFromAlias,\n joinType: traversal.optional ? \"left\" : \"inner\",\n nodeAlias: traversal.nodeAlias,\n nodeKinds: traversal.nodeKinds,\n op: \"join\",\n };\n\n currentNode = wrapWithAliasFilterNode(\n currentNode,\n ast,\n traversal.edgeAlias,\n \"edge\",\n nextPlanNodeId,\n );\n currentNode = wrapWithAliasFilterNode(\n currentNode,\n ast,\n traversal.nodeAlias,\n \"node\",\n nextPlanNodeId,\n );\n }\n\n if (input.vectorPredicate !== undefined) {\n currentNode = {\n id: nextPlanNodeId(),\n input: currentNode,\n op: \"vector_knn\",\n predicate: input.vectorPredicate,\n };\n }\n\n if (input.fulltextPredicate !== undefined) {\n currentNode = {\n id: nextPlanNodeId(),\n input: currentNode,\n op: \"fulltext_match\",\n predicate: input.fulltextPredicate,\n };\n }\n\n return appendAggregateSortLimitAndProjectNodes(\n currentNode,\n ast,\n nextPlanNodeId,\n input.effectiveLimit,\n input.collapsedTraversalCteAlias,\n );\n}\n\ntype LowerRecursiveQueryToLogicalPlanNodeInput =\n LowerRecursiveQueryToLogicalPlanInput &\n Readonly<{\n nextPlanNodeId: () => string;\n }>;\n\nfunction lowerRecursiveQueryToLogicalPlanNode(\n input: LowerRecursiveQueryToLogicalPlanNodeInput,\n): LogicalPlanNode {\n const { ast, nextPlanNodeId } = input;\n const traversal =\n input.traversal ?? runRecursiveTraversalSelectionPass(input.ast);\n\n let currentNode: LogicalPlanNode = {\n alias: ast.start.alias,\n graphId: input.graphId,\n id: nextPlanNodeId(),\n kinds: ast.start.kinds,\n op: \"scan\",\n source: \"nodes\",\n };\n\n currentNode = wrapWithAliasFilterNode(\n currentNode,\n ast,\n ast.start.alias,\n \"node\",\n nextPlanNodeId,\n );\n\n currentNode = {\n edgeAlias: traversal.edgeAlias,\n edgeKinds: traversal.edgeKinds,\n id: nextPlanNodeId(),\n input: currentNode,\n inverseEdgeKinds: traversal.inverseEdgeKinds ?? [],\n nodeAlias: traversal.nodeAlias,\n nodeKinds: traversal.nodeKinds,\n op: \"recursive_expand\",\n traversal: traversal.variableLength,\n };\n\n currentNode = wrapWithAliasFilterNode(\n currentNode,\n ast,\n traversal.edgeAlias,\n \"edge\",\n nextPlanNodeId,\n );\n currentNode = wrapWithAliasFilterNode(\n currentNode,\n ast,\n traversal.nodeAlias,\n \"node\",\n nextPlanNodeId,\n );\n\n return appendAggregateSortLimitAndProjectNodes(\n currentNode,\n ast,\n nextPlanNodeId,\n ast.limit,\n );\n}\n\nfunction lowerComposableQueryToLogicalPlanNode(\n query: ComposableQuery,\n dialect: SqlDialect,\n graphId: string,\n nextPlanNodeId: () => string,\n vectorStrategy: VectorStrategy | undefined,\n): LogicalPlanNode {\n if (\"__type\" in query) {\n return lowerSetOperationToLogicalPlanNode(\n query,\n graphId,\n dialect,\n nextPlanNodeId,\n vectorStrategy,\n );\n }\n\n const hasVariableLengthTraversal = query.traversals.some(\n (traversal) => traversal.variableLength !== undefined,\n );\n if (hasVariableLengthTraversal) {\n return lowerRecursiveQueryToLogicalPlanNode({\n ast: query,\n dialect,\n graphId,\n nextPlanNodeId,\n });\n }\n\n const dialectAdapter = getDialect(dialect);\n const vectorPredicate = runVectorPredicatePass(\n query,\n dialectAdapter,\n vectorStrategy,\n ).vectorPredicate;\n const fulltextPredicate = runFulltextPredicatePass(\n query,\n dialectAdapter,\n ).fulltextPredicate;\n const limitAfterVector = resolveVectorAwareLimit(\n query.limit,\n vectorPredicate,\n );\n const effectiveLimit = resolveFulltextAwareLimit(\n limitAfterVector,\n fulltextPredicate,\n );\n const loweringInput = {\n ast: query,\n dialect,\n graphId,\n nextPlanNodeId,\n ...(effectiveLimit === undefined ? {} : { effectiveLimit }),\n ...(vectorPredicate === undefined ? {} : { vectorPredicate }),\n ...(fulltextPredicate === undefined ? {} : { fulltextPredicate }),\n };\n return lowerStandardQueryToLogicalPlanNode(loweringInput);\n}\n\nfunction lowerSetOperationToLogicalPlanNode(\n op: SetOperation,\n graphId: string,\n dialect: SqlDialect,\n nextPlanNodeId: () => string,\n vectorStrategy: VectorStrategy | undefined,\n): LogicalPlanNode {\n let currentNode: LogicalPlanNode = {\n id: nextPlanNodeId(),\n left: lowerComposableQueryToLogicalPlanNode(\n op.left,\n dialect,\n graphId,\n nextPlanNodeId,\n vectorStrategy,\n ),\n op: \"set_op\",\n operator: op.operator,\n right: lowerComposableQueryToLogicalPlanNode(\n op.right,\n dialect,\n graphId,\n nextPlanNodeId,\n vectorStrategy,\n ),\n };\n\n if (op.orderBy !== undefined && op.orderBy.length > 0) {\n currentNode = {\n id: nextPlanNodeId(),\n input: currentNode,\n op: \"sort\",\n orderBy: op.orderBy,\n };\n }\n\n if (op.limit !== undefined || op.offset !== undefined) {\n const limitOffsetBase = {\n id: nextPlanNodeId(),\n input: currentNode,\n op: \"limit_offset\" as const,\n };\n if (op.limit !== undefined && op.offset !== undefined) {\n currentNode = { ...limitOffsetBase, limit: op.limit, offset: op.offset };\n } else if (op.limit === undefined) {\n currentNode = { ...limitOffsetBase, offset: requireDefined(op.offset) };\n } else {\n currentNode = { ...limitOffsetBase, limit: op.limit };\n }\n }\n\n return currentNode;\n}\n\nexport function lowerStandardQueryToLogicalPlan(\n input: LowerStandardQueryToLogicalPlanInput,\n): LogicalPlan {\n const nextPlanNodeId = createPlanNodeIdFactory();\n return {\n metadata: {\n dialect: input.dialect,\n graphId: input.graphId,\n },\n root: lowerStandardQueryToLogicalPlanNode({\n ...input,\n nextPlanNodeId,\n }),\n };\n}\n\nexport function lowerRecursiveQueryToLogicalPlan(\n input: LowerRecursiveQueryToLogicalPlanInput,\n): LogicalPlan {\n const nextPlanNodeId = createPlanNodeIdFactory();\n return {\n metadata: {\n dialect: input.dialect,\n graphId: input.graphId,\n },\n root: lowerRecursiveQueryToLogicalPlanNode({\n ...input,\n nextPlanNodeId,\n }),\n };\n}\n\nexport function lowerSetOperationToLogicalPlan(\n input: LowerSetOperationToLogicalPlanInput,\n): LogicalPlan {\n const nextPlanNodeId = createPlanNodeIdFactory();\n return {\n metadata: {\n dialect: input.dialect,\n graphId: input.graphId,\n },\n root: lowerSetOperationToLogicalPlanNode(\n input.op,\n input.graphId,\n input.dialect,\n nextPlanNodeId,\n input.vectorStrategy,\n ),\n };\n}\n","import { UnsupportedPredicateError } from \"../../errors\";\nimport type {\n FulltextMatchPredicate,\n QueryAst,\n VectorSimilarityPredicate,\n} from \"../ast\";\nimport {\n extractFulltextMatchPredicates,\n extractVectorSimilarityPredicates,\n} from \"./predicates\";\n\ntype CurrentIndexUsage = Readonly<{\n usesVectorPredicate: boolean;\n usesFulltextPredicate: boolean;\n}>;\n\nexport function assertRecordedQueryDoesNotUseCurrentIndexes(\n ast: QueryAst,\n vectorPredicate: VectorSimilarityPredicate | undefined,\n fulltextPredicate: FulltextMatchPredicate | undefined,\n): void {\n assertRecordedQueryHasNoCurrentIndexUsage(ast, {\n usesVectorPredicate: vectorPredicate !== undefined,\n usesFulltextPredicate: fulltextPredicate !== undefined,\n });\n}\n\nexport function assertRecordedQueryAstDoesNotUseCurrentIndexes(\n ast: QueryAst,\n): void {\n if (ast.recordedAsOf === undefined) return;\n const vectorPredicates = extractVectorSimilarityPredicates(ast.predicates);\n const fulltextPredicates = extractFulltextMatchPredicates(ast.predicates);\n assertRecordedQueryHasNoCurrentIndexUsage(ast, {\n usesVectorPredicate: vectorPredicates.length > 0,\n usesFulltextPredicate: fulltextPredicates.length > 0,\n });\n}\n\nfunction assertRecordedQueryHasNoCurrentIndexUsage(\n ast: QueryAst,\n usage: CurrentIndexUsage,\n): void {\n if (ast.recordedAsOf === undefined) return;\n if (!usage.usesVectorPredicate && !usage.usesFulltextPredicate) return;\n\n throwRecordedCurrentIndexError(ast.recordedAsOf, usage);\n}\n\nfunction throwRecordedCurrentIndexError(\n recordedAsOf: string,\n usage: CurrentIndexUsage,\n): never {\n throw new UnsupportedPredicateError(\n \"Recorded-time queries cannot use vector or fulltext predicates because those indexes reflect current state.\",\n {\n recordedAsOf,\n ...usage,\n },\n {\n suggestion:\n \"Use ordinary property predicates on the recorded view, or run vector/fulltext predicates against the live Store.\",\n },\n );\n}\n","/**\n * Recursive CTE Compilation\n *\n * Compiles variable-length path traversals using WITH RECURSIVE.\n * Handles cycle detection and depth limiting using dialect-specific operations.\n */\nimport {\n CompilerInvariantError,\n UnsupportedPredicateError,\n} from \"../../errors\";\nimport { type QueryAst, type SelectiveField } from \"../ast\";\nimport {\n type DialectAdapter,\n type DialectRecursiveQueryStrategy,\n} from \"../dialect\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { emitRecursiveQuerySql } from \"./emitter\";\nimport {\n createTemporalFilterPass,\n runCompilerPass,\n runRecursiveTraversalSelectionPass,\n type TemporalFilterPass,\n type VariableLengthTraversal,\n} from \"./passes\";\nimport { type LogicalPlan, lowerRecursiveQueryToLogicalPlan } from \"./plan\";\nimport { compileKindFilter as sharedCompileKindFilter } from \"./predicate-utils\";\nimport {\n compileFieldValue,\n compilePredicateExpression,\n type PredicateCompilerContext,\n} from \"./predicates\";\nimport { assertRecordedQueryAstDoesNotUseCurrentIndexes } from \"./recorded-current-index-guard\";\nimport { compileSelectivePropsExtraction } from \"./typed-json-extract\";\nimport {\n addRequiredColumn,\n EMPTY_REQUIRED_COLUMNS,\n mapSelectiveSystemFieldToColumn,\n markFieldRefAsRequired,\n markSelectiveFieldAsRequired,\n NODE_COLUMNS,\n quoteIdentifier,\n type RequiredColumnsByAlias,\n shouldProjectColumn,\n} from \"./utils\";\n\n// ============================================================\n// Constants\n// ============================================================\n\n/**\n * Maximum depth for recursive CTE queries when maxDepth is unlimited (-1).\n *\n * Graphs with branching factor B produce O(B^depth) rows before cycle\n * detection can prune them. A default of 10 covers typical neighborhood,\n * shortest-path, and hierarchy use-cases without risking exponential blowup\n * on dense graphs. Users who need deeper traversals should call .maxHops(N)\n * explicitly (up to MAX_EXPLICIT_RECURSIVE_DEPTH).\n */\nexport const MAX_RECURSIVE_DEPTH = 10;\n\n/**\n * Maximum depth for explicit maxDepth traversals.\n *\n * Explicit traversal bounds are opt-in and safe to allow at a higher ceiling\n * for stress testing and long-path workloads.\n */\nexport const MAX_EXPLICIT_RECURSIVE_DEPTH = 1000;\n\nconst NO_ALWAYS_REQUIRED_COLUMNS = new Set<string>();\n\ntype RecursiveQueryPassState = Readonly<{\n ast: QueryAst;\n ctx: PredicateCompilerContext;\n graphId: string;\n logicalPlan: LogicalPlan | undefined;\n requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n temporalFilterPass: TemporalFilterPass | undefined;\n traversal: VariableLengthTraversal | undefined;\n}>;\n\nfunction runRecursiveQueryPassPipeline(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): RecursiveQueryPassState {\n let state: RecursiveQueryPassState = {\n ast,\n ctx,\n graphId,\n logicalPlan: undefined,\n requiredColumnsByAlias: undefined,\n temporalFilterPass: undefined,\n traversal: undefined,\n };\n\n const recursiveTraversalPass = runCompilerPass(state, {\n name: \"recursive_traversal\",\n execute(currentState): VariableLengthTraversal {\n return runRecursiveTraversalSelectionPass(currentState.ast);\n },\n update(currentState, traversal): RecursiveQueryPassState {\n return {\n ...currentState,\n traversal,\n };\n },\n });\n state = recursiveTraversalPass.state;\n\n const temporalPass = runCompilerPass(state, {\n name: \"temporal_filters\",\n execute(currentState): TemporalFilterPass {\n return createTemporalFilterPass(\n currentState.ast,\n currentState.ctx.readInstant,\n );\n },\n update(currentState, temporalFilterPass): RecursiveQueryPassState {\n return {\n ...currentState,\n temporalFilterPass,\n };\n },\n });\n state = temporalPass.state;\n\n assertRecordedQueryAstDoesNotUseCurrentIndexes(state.ast);\n\n const columnPruningPass = runCompilerPass(state, {\n name: \"column_pruning\",\n execute(currentState): RequiredColumnsByAlias | undefined {\n const traversal = currentState.traversal;\n if (traversal === undefined) {\n throw new CompilerInvariantError(\n \"Recursive traversal pass did not select traversal\",\n );\n }\n return collectRequiredColumnsByAlias(currentState.ast, traversal);\n },\n update(currentState, requiredColumnsByAlias): RecursiveQueryPassState {\n return {\n ...currentState,\n requiredColumnsByAlias,\n };\n },\n });\n state = columnPruningPass.state;\n\n const logicalPlanPass = runCompilerPass(state, {\n name: \"logical_plan\",\n execute(currentState): LogicalPlan {\n const loweringInput = {\n ast: currentState.ast,\n dialect: currentState.ctx.dialect.name,\n graphId: currentState.graphId,\n ...(currentState.traversal === undefined ?\n {}\n : { traversal: currentState.traversal }),\n };\n return lowerRecursiveQueryToLogicalPlan(loweringInput);\n },\n update(currentState, logicalPlan): RecursiveQueryPassState {\n return {\n ...currentState,\n logicalPlan,\n };\n },\n });\n state = logicalPlanPass.state;\n\n return state;\n}\n\n// ============================================================\n// Main Compiler\n// ============================================================\n\n/**\n * Compiles a variable-length query using recursive CTEs.\n *\n * @param ast - The query AST\n * @param graphId - The graph ID\n * @param ctx - Predicate compiler context\n * @returns `SqlFragment` for the recursive query\n */\nexport function compileVariableLengthQuery(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): SqlFragment {\n const strategy = ctx.dialect.capabilities.recursiveQueryStrategy;\n const handler = RECURSIVE_QUERY_STRATEGY_HANDLERS[strategy];\n return handler(ast, graphId, ctx);\n}\n\ntype RecursiveQueryStrategyHandler = (\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n) => SqlFragment;\n\nconst RECURSIVE_QUERY_STRATEGY_HANDLERS: Record<\n DialectRecursiveQueryStrategy,\n RecursiveQueryStrategyHandler\n> = {\n recursive_cte: compileVariableLengthQueryWithRecursiveCteStrategy,\n};\n\nfunction compileVariableLengthQueryWithRecursiveCteStrategy(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): SqlFragment {\n const passState = runRecursiveQueryPassPipeline(ast, graphId, ctx);\n\n const { dialect } = ctx;\n const {\n logicalPlan,\n requiredColumnsByAlias,\n temporalFilterPass,\n traversal: vlTraversal,\n } = passState;\n\n if (temporalFilterPass === undefined) {\n throw new CompilerInvariantError(\n \"Temporal filter pass did not initialize temporal state\",\n );\n }\n if (logicalPlan === undefined) {\n throw new CompilerInvariantError(\n \"Logical plan pass did not initialize plan state\",\n );\n }\n if (vlTraversal === undefined) {\n throw new CompilerInvariantError(\n \"Recursive traversal pass did not select traversal\",\n );\n }\n\n // Build the recursive CTE\n const recursiveCte = compileRecursiveCte(\n ast,\n vlTraversal,\n graphId,\n ctx,\n requiredColumnsByAlias,\n temporalFilterPass,\n );\n\n // Build projection\n const projection = compileRecursiveProjection(ast, vlTraversal, dialect);\n\n // Build final SELECT\n const minDepth = vlTraversal.variableLength.minDepth;\n const depthFilter =\n minDepth > 0 ? sql`WHERE depth >= ${minDepth}` : sql.raw(\"\");\n\n // Order by and limit/offset\n const orderBy = compileRecursiveOrderBy(ast, dialect);\n const limitOffset = compileLimitOffset(ast);\n\n return emitRecursiveQuerySql({\n depthFilter,\n ...(limitOffset === undefined ? {} : { limitOffset }),\n logicalPlan,\n ...(orderBy === undefined ? {} : { orderBy }),\n projection,\n recursiveCte,\n });\n}\n\n/**\n * Checks if a query contains variable-length traversals.\n */\nexport function hasVariableLengthTraversal(ast: QueryAst): boolean {\n return ast.traversals.some((t) => t.variableLength !== undefined);\n}\n\n// ============================================================\n// Recursive CTE Generation\n// ============================================================\n\n/**\n * Compiles the recursive CTE for variable-length traversal.\n */\nfunction compileRecursiveCte(\n ast: QueryAst,\n traversal: VariableLengthTraversal,\n graphId: string,\n ctx: PredicateCompilerContext,\n requiredColumnsByAlias: RequiredColumnsByAlias | undefined,\n temporalFilterPass: TemporalFilterPass,\n): SqlFragment {\n const { dialect } = ctx;\n const startAlias = ast.start.alias;\n const startKinds = ast.start.kinds;\n const nodeAlias = traversal.nodeAlias;\n const directEdgeKinds = [...new Set(traversal.edgeKinds)];\n const inverseEdgeKinds =\n traversal.inverseEdgeKinds === undefined ?\n []\n : [...new Set(traversal.inverseEdgeKinds)];\n const forceWorktableOuterJoinOrder =\n dialect.capabilities.forceRecursiveWorktableOuterJoinOrder;\n const nodeKinds = traversal.nodeKinds;\n const previousNodeKinds = [...new Set([...startKinds, ...nodeKinds])];\n const direction = traversal.direction;\n const vl = traversal.variableLength;\n const shouldEnforceCycleCheck = vl.cyclePolicy !== \"allow\";\n const shouldTrackPath = shouldEnforceCycleCheck || vl.pathAlias !== undefined;\n const recursiveJoinRequiredColumns = new Set<string>([\"id\"]);\n if (previousNodeKinds.length > 1) {\n recursiveJoinRequiredColumns.add(\"kind\");\n }\n const requiredStartColumns =\n requiredColumnsByAlias ?\n (requiredColumnsByAlias.get(startAlias) ?? EMPTY_REQUIRED_COLUMNS)\n : undefined;\n const requiredNodeColumns =\n requiredColumnsByAlias ?\n (requiredColumnsByAlias.get(nodeAlias) ?? EMPTY_REQUIRED_COLUMNS)\n : undefined;\n const startColumnsFromBase = compileNodeSelectColumnsFromTable(\n \"n0\",\n startAlias,\n requiredStartColumns,\n NO_ALWAYS_REQUIRED_COLUMNS,\n );\n const startColumnsFromRecursive = compileNodeSelectColumnsFromRecursiveRow(\n startAlias,\n requiredStartColumns,\n NO_ALWAYS_REQUIRED_COLUMNS,\n );\n const nodeColumnsFromBase = compileNodeSelectColumnsFromTable(\n \"n0\",\n nodeAlias,\n requiredNodeColumns,\n recursiveJoinRequiredColumns,\n );\n const nodeColumnsFromRecursive = compileNodeSelectColumnsFromTable(\n \"n\",\n nodeAlias,\n requiredNodeColumns,\n recursiveJoinRequiredColumns,\n );\n\n const startKindFilter = compileKindFilter(startKinds, \"n0.kind\");\n const nodeKindFilter = compileKindFilter(nodeKinds, \"n.kind\");\n\n const startTemporalFilter = temporalFilterPass.forAlias(\"n0\");\n const edgeTemporalFilter = temporalFilterPass.forAlias(\"e\");\n const nodeTemporalFilter = temporalFilterPass.forAlias(\"n\");\n\n // Start predicates (with cteColumnPrefix \"\" for raw n0 columns)\n const startContext = { ...ctx, cteColumnPrefix: \"\" };\n const startPredicates = compileNodePredicates(ast, startAlias, startContext);\n\n // Edge predicates (with cteColumnPrefix \"e\" for e.props)\n const edgeContext = { ...ctx, cteColumnPrefix: \"e\" };\n const edgePredicates = compileEdgePredicates(\n ast,\n traversal.edgeAlias,\n edgeContext,\n );\n\n // Target node predicates (with cteColumnPrefix \"n\" for n.props)\n const targetContext = { ...ctx, cteColumnPrefix: \"n\" };\n const targetNodePredicates = compileNodePredicates(\n ast,\n nodeAlias,\n targetContext,\n );\n\n // Max depth condition:\n // - unlimited traversals are capped at MAX_RECURSIVE_DEPTH\n // - explicit maxDepth traversals must not exceed MAX_EXPLICIT_RECURSIVE_DEPTH\n if (vl.maxDepth > MAX_EXPLICIT_RECURSIVE_DEPTH) {\n throw new UnsupportedPredicateError(\n `Recursive traversal maxHops(${vl.maxDepth}) exceeds maximum explicit depth of ${MAX_EXPLICIT_RECURSIVE_DEPTH}`,\n );\n }\n const effectiveMaxDepth = vl.maxDepth > 0 ? vl.maxDepth : MAX_RECURSIVE_DEPTH;\n const maxDepthCondition = sql`r.depth < ${effectiveMaxDepth}`;\n\n const cycleCheck =\n shouldEnforceCycleCheck ?\n dialect.cycleCheck(sql.raw(\"n.id\"), sql.raw(\"r.path\"))\n : undefined;\n const initialPath =\n shouldTrackPath ? dialect.initializePath(sql.raw(\"n0.id\")) : undefined;\n const pathExtension =\n shouldTrackPath ?\n dialect.extendPath(sql.raw(\"r.path\"), sql.raw(\"n.id\"))\n : undefined;\n\n // Base case WHERE clauses\n const baseWhereClauses = [\n sql`n0.graph_id = ${graphId}`,\n startKindFilter,\n startTemporalFilter,\n ...startPredicates,\n ];\n\n const recursiveBaseWhereClauses: SqlFragment[] = [\n sql`e.graph_id = ${graphId}`,\n nodeKindFilter,\n edgeTemporalFilter,\n nodeTemporalFilter,\n maxDepthCondition,\n ];\n if (cycleCheck !== undefined) {\n recursiveBaseWhereClauses.push(cycleCheck);\n }\n recursiveBaseWhereClauses.push(...edgePredicates, ...targetNodePredicates);\n\n function compileRecursiveBranch(\n branch: Readonly<{\n joinField: \"from_id\" | \"to_id\";\n targetField: \"from_id\" | \"to_id\";\n joinKindField: \"from_kind\" | \"to_kind\";\n targetKindField: \"from_kind\" | \"to_kind\";\n edgeKinds: readonly string[];\n duplicateGuard?: SqlFragment | undefined;\n }>,\n ): SqlFragment {\n const recursiveFilterClauses = [\n ...recursiveBaseWhereClauses,\n compileKindFilter(branch.edgeKinds, \"e.kind\"),\n compileKindFilter(previousNodeKinds, `e.${branch.joinKindField}`),\n compileKindFilter(nodeKinds, `e.${branch.targetKindField}`),\n ];\n\n if (branch.duplicateGuard !== undefined) {\n recursiveFilterClauses.push(branch.duplicateGuard);\n }\n\n const recursiveSelectColumns = [\n ...startColumnsFromRecursive,\n ...nodeColumnsFromRecursive,\n sql`r.depth + 1 AS depth`,\n ];\n if (pathExtension !== undefined) {\n recursiveSelectColumns.push(sql`${pathExtension} AS path`);\n }\n const recursiveJoinClauses: SqlFragment[] = [\n sql`e.${sql.raw(branch.joinField)} = r.${sql.raw(nodeAlias)}_id`,\n ];\n if (previousNodeKinds.length > 1) {\n recursiveJoinClauses.push(\n sql`e.${sql.raw(branch.joinKindField)} = r.${sql.raw(nodeAlias)}_kind`,\n );\n }\n\n if (forceWorktableOuterJoinOrder) {\n const recursiveWhereClauses = [\n ...recursiveJoinClauses,\n ...recursiveFilterClauses,\n ];\n\n return sql`\n SELECT ${sql.join(recursiveSelectColumns, sql`, `)}\n FROM recursive_cte r\n CROSS JOIN ${ctx.schema.edgesTable} e\n JOIN ${ctx.schema.nodesTable} n ON n.graph_id = e.graph_id\n AND n.id = e.${sql.raw(branch.targetField)}\n AND n.kind = e.${sql.raw(branch.targetKindField)}\n WHERE ${sql.join(recursiveWhereClauses, sql` AND `)}\n `;\n }\n\n return sql`\n SELECT ${sql.join(recursiveSelectColumns, sql`, `)}\n FROM recursive_cte r\n JOIN ${ctx.schema.edgesTable} e ON ${sql.join(recursiveJoinClauses, sql` AND `)}\n JOIN ${ctx.schema.nodesTable} n ON n.graph_id = e.graph_id\n AND n.id = e.${sql.raw(branch.targetField)}\n AND n.kind = e.${sql.raw(branch.targetKindField)}\n WHERE ${sql.join(recursiveFilterClauses, sql` AND `)}\n `;\n }\n\n const directJoinField = direction === \"out\" ? \"from_id\" : \"to_id\";\n const directTargetField = direction === \"out\" ? \"to_id\" : \"from_id\";\n const directJoinKindField = direction === \"out\" ? \"from_kind\" : \"to_kind\";\n const directTargetKindField = direction === \"out\" ? \"to_kind\" : \"from_kind\";\n\n const directBranch = compileRecursiveBranch({\n joinField: directJoinField,\n targetField: directTargetField,\n joinKindField: directJoinKindField,\n targetKindField: directTargetKindField,\n edgeKinds: directEdgeKinds,\n });\n\n function compileInverseRecursiveBranch(): SqlFragment {\n const inverseJoinField = direction === \"out\" ? \"to_id\" : \"from_id\";\n const inverseTargetField = direction === \"out\" ? \"from_id\" : \"to_id\";\n const inverseJoinKindField = direction === \"out\" ? \"to_kind\" : \"from_kind\";\n const inverseTargetKindField =\n direction === \"out\" ? \"from_kind\" : \"to_kind\";\n const overlappingKinds = inverseEdgeKinds.filter((kind) =>\n directEdgeKinds.includes(kind),\n );\n\n const duplicateGuard =\n overlappingKinds.length > 0 ?\n sql`NOT (e.from_id = e.to_id AND ${compileKindFilter(overlappingKinds, \"e.kind\")})`\n : undefined;\n\n const inverseBranch = compileRecursiveBranch({\n joinField: inverseJoinField,\n targetField: inverseTargetField,\n joinKindField: inverseJoinKindField,\n targetKindField: inverseTargetKindField,\n edgeKinds: inverseEdgeKinds,\n duplicateGuard,\n });\n\n return sql`\n ${directBranch}\n UNION ALL\n ${inverseBranch}\n `;\n }\n\n const recursiveBranchSql =\n inverseEdgeKinds.length === 0 ?\n directBranch\n : compileInverseRecursiveBranch();\n const baseSelectColumns = [\n ...startColumnsFromBase,\n ...nodeColumnsFromBase,\n sql`0 AS depth`,\n ];\n if (initialPath !== undefined) {\n baseSelectColumns.push(sql`${initialPath} AS path`);\n }\n\n return sql`\n recursive_cte AS (\n -- Base case: starting nodes\n SELECT ${sql.join(baseSelectColumns, sql`, `)}\n FROM ${ctx.schema.nodesTable} n0\n WHERE ${sql.join(baseWhereClauses, sql` AND `)}\n\n UNION ALL\n\n -- Recursive case: follow edges\n ${recursiveBranchSql}\n )\n `;\n}\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\n/**\n * Compiles a kind filter for IN clause.\n * Delegates to the shared compileKindFilter from predicate-utils\n * with a raw SQL column expression.\n */\nfunction compileKindFilter(\n kinds: readonly string[],\n columnExpr: string,\n): SqlFragment {\n return sharedCompileKindFilter(sql.raw(columnExpr), kinds);\n}\n\n/**\n * Compiles node predicates for a specific alias.\n * Filters by alias and excludes edge predicates (targetType !== \"edge\").\n */\nfunction compileNodePredicates(\n ast: QueryAst,\n alias: string,\n ctx: PredicateCompilerContext,\n): SqlFragment[] {\n return ast.predicates\n .filter((p) => p.targetAlias === alias && p.targetType !== \"edge\")\n .map((p) => compilePredicateExpression(p.expression, ctx));\n}\n\n/**\n * Compiles edge predicates for a specific edge alias.\n * Filters by alias and only includes edge predicates (targetType === \"edge\").\n */\nfunction compileEdgePredicates(\n ast: QueryAst,\n edgeAlias: string,\n ctx: PredicateCompilerContext,\n): SqlFragment[] {\n return ast.predicates\n .filter((p) => p.targetAlias === edgeAlias && p.targetType === \"edge\")\n .map((p) => compilePredicateExpression(p.expression, ctx));\n}\n\nfunction collectRequiredColumnsByAlias(\n ast: QueryAst,\n traversal: VariableLengthTraversal,\n): RequiredColumnsByAlias | undefined {\n const selectiveFields = ast.selectiveFields;\n if (selectiveFields === undefined || selectiveFields.length === 0) {\n return undefined;\n }\n\n const requiredColumnsByAlias = new Map<string, Set<string>>();\n const previousNodeKinds = [\n ...new Set([...ast.start.kinds, ...traversal.nodeKinds]),\n ];\n\n // Recursive expansion always needs node alias id for joins/cycle checks.\n addRequiredColumn(requiredColumnsByAlias, traversal.nodeAlias, \"id\");\n if (previousNodeKinds.length > 1) {\n addRequiredColumn(requiredColumnsByAlias, traversal.nodeAlias, \"kind\");\n }\n\n for (const field of selectiveFields) {\n markSelectiveFieldAsRequired(requiredColumnsByAlias, field);\n }\n\n if (ast.orderBy) {\n for (const orderSpec of ast.orderBy) {\n markFieldRefAsRequired(requiredColumnsByAlias, orderSpec.field);\n }\n }\n\n return requiredColumnsByAlias;\n}\n\nfunction compileNodeSelectColumnsFromTable(\n tableAlias: string,\n alias: string,\n requiredColumns: ReadonlySet<string> | undefined,\n alwaysRequiredColumns: ReadonlySet<string>,\n): SqlFragment[] {\n return NODE_COLUMNS.filter((column) =>\n shouldProjectColumn(requiredColumns, column, alwaysRequiredColumns),\n ).map(\n (column) =>\n sql`${sql.raw(tableAlias)}.${sql.raw(column)} AS ${sql.raw(`${alias}_${column}`)}`,\n );\n}\n\nfunction compileNodeSelectColumnsFromRecursiveRow(\n alias: string,\n requiredColumns: ReadonlySet<string> | undefined,\n alwaysRequiredColumns: ReadonlySet<string>,\n): SqlFragment[] {\n return NODE_COLUMNS.filter((column) =>\n shouldProjectColumn(requiredColumns, column, alwaysRequiredColumns),\n ).map((column) => {\n const projected = `${alias}_${column}`;\n return sql`r.${sql.raw(projected)} AS ${sql.raw(projected)}`;\n });\n}\n\n/**\n * Compiles projection for recursive query results.\n */\nfunction compileRecursiveProjection(\n ast: QueryAst,\n traversal: VariableLengthTraversal,\n dialect: DialectAdapter,\n): SqlFragment {\n if (ast.selectiveFields && ast.selectiveFields.length > 0) {\n return compileRecursiveSelectiveProjection(\n ast.selectiveFields,\n ast,\n traversal,\n dialect,\n );\n }\n\n const startAlias = ast.start.alias;\n const nodeAlias = traversal.nodeAlias;\n const vl = traversal.variableLength;\n\n const fields: SqlFragment[] = [\n // Start alias fields with metadata\n sql`${sql.raw(startAlias)}_id`,\n sql`${sql.raw(startAlias)}_kind`,\n sql`${sql.raw(startAlias)}_props`,\n sql`${sql.raw(startAlias)}_version`,\n sql`${sql.raw(startAlias)}_valid_from`,\n sql`${sql.raw(startAlias)}_valid_to`,\n sql`${sql.raw(startAlias)}_created_at`,\n sql`${sql.raw(startAlias)}_updated_at`,\n sql`${sql.raw(startAlias)}_deleted_at`,\n // Node alias fields with metadata\n sql`${sql.raw(nodeAlias)}_id`,\n sql`${sql.raw(nodeAlias)}_kind`,\n sql`${sql.raw(nodeAlias)}_props`,\n sql`${sql.raw(nodeAlias)}_version`,\n sql`${sql.raw(nodeAlias)}_valid_from`,\n sql`${sql.raw(nodeAlias)}_valid_to`,\n sql`${sql.raw(nodeAlias)}_created_at`,\n sql`${sql.raw(nodeAlias)}_updated_at`,\n sql`${sql.raw(nodeAlias)}_deleted_at`,\n ];\n\n if (vl.depthAlias !== undefined) {\n fields.push(sql`depth AS ${quoteIdentifier(vl.depthAlias)}`);\n }\n\n if (vl.pathAlias !== undefined) {\n fields.push(sql`path AS ${quoteIdentifier(vl.pathAlias)}`);\n }\n\n return sql.join(fields, sql`, `);\n}\n\nfunction compileRecursiveSelectiveProjection(\n fields: readonly SelectiveField[],\n ast: QueryAst,\n traversal: VariableLengthTraversal,\n dialect: DialectAdapter,\n): SqlFragment {\n const allowedAliases = new Set([ast.start.alias, traversal.nodeAlias]);\n\n const columns: SqlFragment[] = fields.map((field) => {\n if (!allowedAliases.has(field.alias)) {\n throw new UnsupportedPredicateError(\n `Selective projection for recursive traversals does not support alias \"${field.alias}\"`,\n );\n }\n\n if (field.isSystemField) {\n const dbColumn = mapSelectiveSystemFieldToColumn(field.field);\n return sql`${sql.raw(`${field.alias}_${dbColumn}`)} AS ${quoteIdentifier(field.outputName)}`;\n }\n\n const column = sql.raw(`${field.alias}_props`);\n const extracted = compileSelectivePropsExtraction(field, column, dialect);\n return sql`${extracted} AS ${quoteIdentifier(field.outputName)}`;\n });\n\n // Include recursive depth/path columns when present\n const vl = traversal.variableLength;\n if (vl.depthAlias !== undefined) {\n columns.push(sql`depth AS ${quoteIdentifier(vl.depthAlias)}`);\n }\n if (vl.pathAlias !== undefined) {\n columns.push(sql`path AS ${quoteIdentifier(vl.pathAlias)}`);\n }\n\n return sql.join(columns, sql`, `);\n}\n\n/**\n * Compiles ORDER BY for recursive query.\n */\nfunction compileRecursiveOrderBy(\n ast: QueryAst,\n dialect: DialectAdapter,\n): SqlFragment | undefined {\n if (!ast.orderBy || ast.orderBy.length === 0) {\n return undefined;\n }\n\n const parts: SqlFragment[] = [];\n\n for (const orderSpec of ast.orderBy) {\n const valueType = orderSpec.field.valueType;\n if (valueType === \"array\" || valueType === \"object\") {\n throw new UnsupportedPredicateError(\n \"Ordering by JSON arrays or objects is not supported\",\n );\n }\n const field = compileFieldValue(orderSpec.field, dialect, valueType);\n const direction = sql.raw(orderSpec.direction.toUpperCase());\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDirection = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n\n parts.push(\n sql`(${field} IS NULL) ${nullsDirection}`,\n sql`${field} ${direction}`,\n );\n }\n\n return sql`ORDER BY ${sql.join(parts, sql`, `)}`;\n}\n\n/**\n * Compiles LIMIT and OFFSET clauses.\n */\nfunction compileLimitOffset(ast: QueryAst): SqlFragment | undefined {\n const parts: SqlFragment[] = [];\n\n if (ast.limit !== undefined) {\n parts.push(sql`LIMIT ${ast.limit}`);\n }\n if (ast.offset !== undefined) {\n parts.push(sql`OFFSET ${ast.offset}`);\n }\n\n return parts.length > 0 ? sql.join(parts, sql` `) : undefined;\n}\n","/**\n * Value decoding utilities for query execution.\n *\n * Selective projection queries return values extracted directly from JSON\n * columns. Some dialects return booleans/numbers as different JS types, and\n * arrays/objects may be returned as JSON text. This module normalizes those\n * values based on schema type information.\n */\n\nimport { type ValueType } from \"../ast\";\nimport { type FieldTypeInfo } from \"../schema-introspector\";\n\nexport function nullToUndefined(value: unknown): unknown {\n return value === null ? undefined : value;\n}\n\nexport function decodeSelectedValue(\n value: unknown,\n typeInfo: FieldTypeInfo | undefined,\n): unknown {\n const normalized = nullToUndefined(value);\n if (normalized === undefined) return undefined;\n\n if (typeInfo === undefined) {\n return normalized;\n }\n\n return decodeByValueType(normalized, typeInfo.valueType);\n}\n\nfunction decodeByValueType(value: unknown, valueType: ValueType): unknown {\n switch (valueType) {\n case \"boolean\": {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return value !== 0;\n if (typeof value === \"string\") {\n if (value === \"0\") return false;\n if (value === \"1\") return true;\n if (value.toLowerCase() === \"true\") return true;\n if (value.toLowerCase() === \"false\") return false;\n }\n return Boolean(value);\n }\n case \"number\": {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\") {\n const parsed = Number(value);\n return Number.isNaN(parsed) ? value : parsed;\n }\n return value;\n }\n case \"array\":\n case \"object\":\n case \"embedding\": {\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n const looksJson = trimmed.startsWith(\"[\") || trimmed.startsWith(\"{\");\n if (!looksJson) return value;\n try {\n return JSON.parse(trimmed) as unknown;\n } catch {\n return value;\n }\n }\n case \"string\":\n case \"date\":\n case \"unknown\": {\n return value;\n }\n default: {\n const _exhaustive: never = valueType;\n void _exhaustive;\n return value;\n }\n }\n}\n","import { type RecordedInstant } from \"../core/temporal\";\nimport { type TemporalMode } from \"../core/types\";\nimport { type RecursiveCyclePolicy } from \"../query/ast\";\nimport { compileKindFilter } from \"../query/compiler/predicate-utils\";\nimport {\n type RecordedReadBinding,\n recordedReadSchemaFor,\n type SqlSchema,\n} from \"../query/compiler/schema\";\nimport {\n compileTemporalFilter,\n currentReadInstant,\n} from \"../query/compiler/temporal\";\nimport { type DialectAdapter } from \"../query/dialect/types\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { type TraversalDirection } from \"./algorithms/types\";\n\ntype BuildReachableCteOptions = Readonly<{\n graphId: string;\n sourceId: string;\n edgeKinds: readonly string[];\n maxHops: number;\n direction: TraversalDirection;\n cyclePolicy: RecursiveCyclePolicy;\n includePath: boolean;\n /**\n * Temporal mode applied to both nodes and edges along the traversal.\n * Callers that want the pre-temporal behavior (soft-delete only) should\n * pass `\"includeEnded\"`.\n */\n temporalMode: TemporalMode;\n /** ISO-8601 timestamp used when `temporalMode === \"asOf\"`. */\n asOf?: string;\n /** Recorded/system-time timestamp for recorded-pinned reads. */\n recordedAsOf?: RecordedInstant;\n dialect: DialectAdapter;\n /**\n * The base (live-table) schema. The recorded-relation swap is derived here\n * from `recordedAsOf`, so the table source and the recorded interval predicate\n * cannot drift — callers pass their base schema and need not pre-resolve it.\n */\n schema: SqlSchema;\n recordedReadBinding?: RecordedReadBinding;\n}>;\n\nexport function buildReachableCte(\n options: BuildReachableCteOptions,\n): SqlFragment {\n const trackPath = options.cyclePolicy === \"prevent\" || options.includePath;\n const edgeKindFilter = compileKindFilter(\n sql.raw(\"e.kind\"),\n options.edgeKinds,\n );\n const currentTimestamp = currentReadInstant();\n const nodeTemporalFilter = compileTemporalFilter({\n mode: options.temporalMode,\n asOf: options.asOf,\n recordedAsOf: options.recordedAsOf,\n tableAlias: \"n\",\n currentTimestamp,\n });\n const edgeTemporalFilter = compileTemporalFilter({\n mode: options.temporalMode,\n asOf: options.asOf,\n recordedAsOf: options.recordedAsOf,\n tableAlias: \"e\",\n currentTimestamp,\n });\n // Derive the read schema from the same `recordedAsOf` that drives the temporal\n // filters above: when a recorded pin is set the node/edge sources become the\n // recorded relations, matching the `recorded_from/to` interval predicate. One\n // derivation means the table source and the predicate cannot disagree.\n const schema = recordedReadSchemaFor(\n options.schema,\n options.recordedAsOf,\n options.recordedReadBinding,\n \"recorded-recursive-cte\",\n );\n\n const initialPath =\n trackPath ? options.dialect.initializePath(sql.raw(\"n.id\")) : undefined;\n const pathExtension =\n trackPath ?\n options.dialect.extendPath(sql.raw(\"r.path\"), sql.raw(\"n.id\"))\n : undefined;\n const cycleCheck =\n options.cyclePolicy === \"prevent\" ?\n options.dialect.cycleCheck(sql.raw(\"n.id\"), sql.raw(\"r.path\"))\n : undefined;\n\n const baseColumns: SqlFragment[] = [sql`n.id`, sql`n.kind`, sql`0 AS depth`];\n if (initialPath !== undefined) {\n baseColumns.push(sql`${initialPath} AS path`);\n }\n\n const baseCase = sql`SELECT ${sql.join(baseColumns, sql`, `)} FROM ${schema.nodesTable} n WHERE n.graph_id = ${options.graphId} AND n.id = ${options.sourceId} AND ${nodeTemporalFilter}`;\n\n const recursiveColumns: SqlFragment[] = [\n sql`n.id`,\n sql`n.kind`,\n sql`r.depth + 1 AS depth`,\n ];\n if (pathExtension !== undefined) {\n recursiveColumns.push(sql`${pathExtension} AS path`);\n }\n\n const recursiveWhere: SqlFragment[] = [\n sql`e.graph_id = ${options.graphId}`,\n edgeKindFilter,\n edgeTemporalFilter,\n nodeTemporalFilter,\n sql`r.depth < ${options.maxHops}`,\n ];\n if (cycleCheck !== undefined) recursiveWhere.push(cycleCheck);\n\n const forceWorktableOuterJoinOrder =\n options.dialect.capabilities.forceRecursiveWorktableOuterJoinOrder;\n\n const recursiveCase = compileRecursiveBranch({\n recursiveColumns,\n whereClauses: recursiveWhere,\n direction: options.direction,\n forceWorktableOuterJoinOrder,\n schema,\n });\n\n return sql`WITH RECURSIVE reachable AS (${baseCase} UNION ALL ${recursiveCase})`;\n}\n\ntype CompileRecursiveBranchOptions = Readonly<{\n recursiveColumns: readonly SqlFragment[];\n whereClauses: readonly SqlFragment[];\n direction: TraversalDirection;\n forceWorktableOuterJoinOrder: boolean;\n schema: SqlSchema;\n}>;\n\nfunction compileRecursiveBranch(\n options: CompileRecursiveBranchOptions,\n): SqlFragment {\n const selectClause = sql`SELECT ${sql.join([...options.recursiveColumns], sql`, `)}`;\n\n switch (options.direction) {\n case \"out\": {\n return buildDirectionalBranch({\n selectClause,\n whereClauses: options.whereClauses,\n joinField: \"from_id\",\n targetField: \"to_id\",\n targetKindField: \"to_kind\",\n forceWorktableOuterJoinOrder: options.forceWorktableOuterJoinOrder,\n schema: options.schema,\n });\n }\n case \"in\": {\n return buildDirectionalBranch({\n selectClause,\n whereClauses: options.whereClauses,\n joinField: \"to_id\",\n targetField: \"from_id\",\n targetKindField: \"from_kind\",\n forceWorktableOuterJoinOrder: options.forceWorktableOuterJoinOrder,\n schema: options.schema,\n });\n }\n case \"both\": {\n return buildBidirectionalBranch({\n selectClause,\n whereClauses: options.whereClauses,\n forceWorktableOuterJoinOrder: options.forceWorktableOuterJoinOrder,\n schema: options.schema,\n });\n }\n }\n}\n\ntype DirectionalBranchOptions = Readonly<{\n selectClause: SqlFragment;\n whereClauses: readonly SqlFragment[];\n joinField: \"from_id\" | \"to_id\";\n targetField: \"from_id\" | \"to_id\";\n targetKindField: \"from_kind\" | \"to_kind\";\n forceWorktableOuterJoinOrder: boolean;\n schema: SqlSchema;\n}>;\n\nfunction buildDirectionalBranch(\n options: DirectionalBranchOptions,\n): SqlFragment {\n const nodeJoin = sql`JOIN ${options.schema.nodesTable} n ON n.graph_id = e.graph_id AND n.id = e.${sql.raw(options.targetField)} AND n.kind = e.${sql.raw(options.targetKindField)}`;\n\n if (options.forceWorktableOuterJoinOrder) {\n const allWhere = [\n ...options.whereClauses,\n sql`e.${sql.raw(options.joinField)} = r.id`,\n ];\n return sql`${options.selectClause} FROM reachable r CROSS JOIN ${options.schema.edgesTable} e ${nodeJoin} WHERE ${sql.join(allWhere, sql` AND `)}`;\n }\n\n return sql`${options.selectClause} FROM reachable r JOIN ${options.schema.edgesTable} e ON e.${sql.raw(options.joinField)} = r.id ${nodeJoin} WHERE ${sql.join([...options.whereClauses], sql` AND `)}`;\n}\n\ntype BidirectionalBranchOptions = Readonly<{\n selectClause: SqlFragment;\n whereClauses: readonly SqlFragment[];\n forceWorktableOuterJoinOrder: boolean;\n schema: SqlSchema;\n}>;\n\nfunction buildBidirectionalBranch(\n options: BidirectionalBranchOptions,\n): SqlFragment {\n // PostgreSQL rejects multiple non-recursive terms, so both directions are\n // folded into a single UNION ALL branch via an OR on the join condition.\n const nodeJoin = sql`JOIN ${options.schema.nodesTable} n ON n.graph_id = e.graph_id AND ((e.to_id = r.id AND n.id = e.from_id AND n.kind = e.from_kind) OR (e.from_id = r.id AND n.id = e.to_id AND n.kind = e.to_kind))`;\n\n if (options.forceWorktableOuterJoinOrder) {\n const allWhere = [\n ...options.whereClauses,\n sql`(e.from_id = r.id OR e.to_id = r.id)`,\n ];\n return sql`${options.selectClause} FROM reachable r CROSS JOIN ${options.schema.edgesTable} e ${nodeJoin} WHERE ${sql.join(allWhere, sql` AND `)}`;\n }\n\n return sql`${options.selectClause} FROM reachable r JOIN ${options.schema.edgesTable} e ON (e.from_id = r.id OR e.to_id = r.id) ${nodeJoin} WHERE ${sql.join([...options.whereClauses], sql` AND `)}`;\n}\n","/**\n * Subgraph Extraction\n *\n * Extracts a typed subgraph from a root node by traversing a set of edge kinds.\n * Uses a recursive CTE for BFS traversal with cycle detection, then hydrates\n * the reachable nodes and connecting edges in two parallel queries.\n */\nimport type { GraphBackend } from \"../backend/types\";\nimport { MAX_PG_IDENTIFIER_LENGTH } from \"../constants\";\nimport type {\n AllNodeTypes,\n EdgeKinds,\n GraphDef,\n NodeKinds,\n} from \"../core/define-graph\";\nimport { type RecordedInstant, resolveReadCoordinate } from \"../core/temporal\";\nimport type { KindEntity } from \"../core/types\";\nimport type {\n AnyEdgeType,\n NodeId,\n NodeType,\n TemporalMode,\n} from \"../core/types\";\nimport type { RecursiveCyclePolicy } from \"../query/ast\";\nimport { compileKindFilter } from \"../query/compiler/predicate-utils\";\nimport { MAX_EXPLICIT_RECURSIVE_DEPTH } from \"../query/compiler/recursive\";\nimport {\n DEFAULT_SQL_SCHEMA,\n type RecordedReadBinding,\n recordedReadSchemaFor,\n type SqlSchema,\n} from \"../query/compiler/schema\";\nimport {\n compileTemporalFilter,\n currentReadInstant,\n} from \"../query/compiler/temporal\";\nimport { compileTypedJsonExtract } from \"../query/compiler/typed-json-extract\";\nimport { quoteIdentifier } from \"../query/compiler/utils\";\nimport type { DialectAdapter } from \"../query/dialect/types\";\nimport { decodeSelectedValue } from \"../query/execution/value-decoder\";\nimport { jsonPointer } from \"../query/json-pointer\";\nimport {\n createSchemaIntrospector,\n type FieldTypeInfo,\n type SchemaIntrospector,\n} from \"../query/schema-introspector\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, markForceCustomPlan } from \"../query/sql-intent\";\nimport { fnv1aBase36 } from \"../utils/hash\";\nimport { truncateToBytes } from \"../utils/identifier\";\nimport { buildReachableCte } from \"./recursive-cte\";\nimport { validateProjectionField } from \"./reserved-keys\";\nimport {\n type EdgeRow,\n type NodeRow,\n rowToEdge,\n rowToEdgeMeta,\n rowToNode,\n rowToNodeMeta,\n} from \"./row-mappers\";\nimport type { Edge, EdgeMeta, Node, NodeMeta } from \"./types\";\n\n// ============================================================\n// Constants\n// ============================================================\n\nconst DEFAULT_SUBGRAPH_MAX_DEPTH = 10;\n\n/**\n * Generates a short, deterministic column alias safe for PostgreSQL.\n *\n * Format: `sg_{n|e}_{truncatedKind}_{hash}`\n * The hash is computed from the full `kind + field` to prevent collisions\n * when truncation would make two different identifiers identical.\n *\n * PostgreSQL truncates identifiers at 63 *bytes*, not characters.\n * The kind portion is truncated by byte length to stay under the limit\n * even with multibyte characters.\n */\nfunction projectionAlias(\n entityPrefix: KindEntity,\n kind: string,\n field: string,\n): string {\n const prefix = entityPrefix === \"node\" ? \"sg_n\" : \"sg_e\";\n const hash = fnv1aBase36(`${kind}\\0${field}`);\n // prefix + \"_\" + kind_trunc + \"_\" + hash must fit in 63 bytes.\n // prefix and hash are ASCII, so byte length === string length.\n const fixedBytes = prefix.length + 1 + 1 + hash.length;\n const maxKindBytes = MAX_PG_IDENTIFIER_LENGTH - fixedBytes;\n const truncatedKind = truncateToBytes(kind, maxKindBytes);\n return `${prefix}_${truncatedKind}_${hash}`;\n}\n\n/**\n * Normalizes a JSON column value to a string.\n * PostgreSQL JSONB columns return parsed objects; SQLite returns strings.\n */\nfunction normalizeProps(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value ?? {});\n}\n\n// ============================================================\n// Type Utilities\n// ============================================================\n\n/**\n * Discriminated union of all Node runtime types in a graph.\n *\n * Unlike `AllNodeTypes<G>` which gives the union of *type definitions*,\n * `AnyNode<G>` gives the union of *runtime node instances*.\n */\nexport type AnyNode<G extends GraphDef> = {\n [K in NodeKinds<G>]: Node<G[\"nodes\"][K][\"type\"]>;\n}[NodeKinds<G>];\n\n/**\n * Discriminated union of all Edge runtime types in a graph.\n */\nexport type AnyEdge<G extends GraphDef> = {\n [K in EdgeKinds<G>]: Edge<G[\"edges\"][K][\"type\"]>;\n}[EdgeKinds<G>];\n\n/**\n * Discriminated union of Node runtime types narrowed to a subset of kinds.\n */\nexport type SubsetNode<G extends GraphDef, K extends NodeKinds<G>> = {\n [Kind in K]: Node<G[\"nodes\"][Kind][\"type\"]>;\n}[K];\n\n/**\n * Discriminated union of Edge runtime types narrowed to a subset of kinds.\n */\nexport type SubsetEdge<G extends GraphDef, K extends EdgeKinds<G>> = {\n [Kind in K]: Edge<G[\"edges\"][Kind][\"type\"]>;\n}[K];\n\ntype EmptyShape = Readonly<Record<never, never>>;\n\ntype NodeProjectionPropertyKey<N extends NodeType> = Exclude<\n keyof Node<N>,\n \"id\" | \"kind\" | \"meta\"\n> &\n string;\n\ntype EdgeProjectionPropertyKey<E extends AnyEdgeType> = Exclude<\n keyof Edge<E>,\n \"id\" | \"kind\" | \"fromKind\" | \"fromId\" | \"toKind\" | \"toId\" | \"meta\"\n> &\n string;\n\ntype SubgraphNodeProjectionField<N extends NodeType = NodeType> =\n NodeProjectionPropertyKey<N> | \"meta\";\n\ntype SubgraphEdgeProjectionField<E extends AnyEdgeType = AnyEdgeType> =\n EdgeProjectionPropertyKey<E> | \"meta\";\n\ntype SubgraphNodeProjectionMap<\n G extends GraphDef,\n NK extends NodeKinds<G> = NodeKinds<G>,\n> = Readonly<{\n [K in NodeKinds<G>]?: K extends NK ?\n readonly SubgraphNodeProjectionField<G[\"nodes\"][K][\"type\"]>[]\n : never;\n}>;\n\ntype SubgraphEdgeProjectionMap<\n G extends GraphDef,\n EK extends EdgeKinds<G> = EdgeKinds<G>,\n> = Readonly<{\n [K in EdgeKinds<G>]?: K extends EK ?\n readonly SubgraphEdgeProjectionField<G[\"edges\"][K][\"type\"]>[]\n : never;\n}>;\n\nexport type SubgraphProject<\n G extends GraphDef,\n NK extends NodeKinds<G> = NodeKinds<G>,\n EK extends EdgeKinds<G> = EdgeKinds<G>,\n> = Readonly<{\n /**\n * Node fields to keep per kind.\n *\n * Projected nodes always retain `kind` and `id`.\n * Use `\"meta\"` to include the full metadata object; omit it to exclude metadata entirely.\n * Only kinds present in `includeKinds` (or all node kinds when omitted) are valid keys.\n */\n nodes?: SubgraphNodeProjectionMap<G, NK>;\n /**\n * Edge fields to keep per kind.\n *\n * Projected edges always retain `id`, `kind`, `fromKind`, `fromId`,\n * `toKind`, and `toId`.\n * Use `\"meta\"` to include the full metadata object; omit it to exclude metadata entirely.\n * Only edge kinds listed in `edges` are valid keys.\n */\n edges?: SubgraphEdgeProjectionMap<G, EK>;\n}>;\n\n/**\n * Identity function that preserves literal types for reusable projection configs.\n *\n * Without this helper, storing a projection in a typed variable widens the\n * field arrays to `string[]`, defeating compile-time narrowing on results.\n *\n * @example\n * ```ts\n * const project = defineSubgraphProject(graph)({\n * nodes: { Task: [\"title\", \"meta\"] },\n * edges: { uses_skill: [] },\n * });\n * const result = await store.subgraph(rootId, { edges: [\"uses_skill\"], project });\n * // result.nodes narrowed correctly — task.status is a type error\n * ```\n */\nexport function defineSubgraphProject<G extends GraphDef>(\n _graph: G,\n): <const P extends SubgraphProject<G>>(project: P) => P {\n return <const P extends SubgraphProject<G>>(project: P): P => project;\n}\n\ntype HasMeta<Selection extends readonly string[] | undefined> =\n Selection extends readonly string[] ?\n \"meta\" extends Selection[number] ?\n true\n : false\n : false;\n\ntype SelectedNodeProps<\n N extends NodeType,\n Selection extends readonly string[] | undefined,\n> =\n Selection extends readonly string[] ?\n Pick<Node<N>, Extract<Selection[number], NodeProjectionPropertyKey<N>>>\n : EmptyShape;\n\ntype SelectedEdgeProps<\n E extends AnyEdgeType,\n Selection extends readonly string[] | undefined,\n> =\n Selection extends readonly string[] ?\n Pick<Edge<E>, Extract<Selection[number], EdgeProjectionPropertyKey<E>>>\n : EmptyShape;\n\ntype ProjectedNodeResult<\n N extends NodeType,\n Selection extends readonly string[] | undefined,\n> = Readonly<Pick<Node<N>, \"id\" | \"kind\">> &\n Readonly<SelectedNodeProps<N, Selection>> &\n (HasMeta<Selection> extends true ? Readonly<{ meta: NodeMeta }> : EmptyShape);\n\ntype ProjectedEdgeResult<\n E extends AnyEdgeType,\n Selection extends readonly string[] | undefined,\n> = Readonly<\n Pick<Edge<E>, \"id\" | \"kind\" | \"fromKind\" | \"fromId\" | \"toKind\" | \"toId\">\n> &\n Readonly<SelectedEdgeProps<E, Selection>> &\n (HasMeta<Selection> extends true ? Readonly<{ meta: EdgeMeta }> : EmptyShape);\n\ntype ProjectionSelection<\n P,\n Key extends \"nodes\" | \"edges\",\n Kind extends string,\n> =\n // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style -- mapped type needed for conditional inference on Key\n P extends Readonly<{ [K in Key]?: infer Map }> ?\n Map extends Readonly<Record<string, readonly string[] | undefined>> ?\n Kind extends keyof Map ?\n Map[Kind]\n : undefined\n : undefined\n : undefined;\n\ntype SubgraphNodeResultForKind<\n G extends GraphDef,\n Kind extends NodeKinds<G>,\n P,\n> =\n ProjectionSelection<P, \"nodes\", Kind> extends readonly string[] ?\n ProjectedNodeResult<\n G[\"nodes\"][Kind][\"type\"],\n ProjectionSelection<P, \"nodes\", Kind>\n >\n : Node<G[\"nodes\"][Kind][\"type\"]>;\n\ntype SubgraphEdgeResultForKind<\n G extends GraphDef,\n Kind extends EdgeKinds<G>,\n P,\n> =\n ProjectionSelection<P, \"edges\", Kind> extends readonly string[] ?\n ProjectedEdgeResult<\n G[\"edges\"][Kind][\"type\"],\n ProjectionSelection<P, \"edges\", Kind>\n >\n : Edge<G[\"edges\"][Kind][\"type\"]>;\n\n// ============================================================\n// Options & Result Types\n// ============================================================\n\nexport type SubgraphOptions<\n G extends GraphDef,\n EK extends EdgeKinds<G>,\n NK extends NodeKinds<G>,\n P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = Readonly<{\n /** Edge kinds to follow during traversal. Edges not listed are not traversed. */\n edges: readonly EK[];\n /** Maximum traversal depth from root (default: 10). */\n maxDepth?: number;\n /**\n * Node kinds to include in the result. Nodes of other kinds are still\n * traversed through but omitted from the output. When omitted, all\n * reachable node kinds are included.\n */\n includeKinds?: readonly NK[];\n /** Exclude the root node from the result (default: false). */\n excludeRoot?: boolean;\n /**\n * Edge direction policy (default: \"out\").\n * - \"out\": follow edges in their defined direction only\n * - \"both\": follow edges in both directions (undirected traversal)\n */\n direction?: \"out\" | \"both\";\n /** Cycle policy — reuse RecursiveCyclePolicy (default: \"prevent\"). */\n cyclePolicy?: RecursiveCyclePolicy;\n /**\n * Temporal mode applied to both nodes and edges along the traversal and in\n * the hydrated result. Defaults to `graph.defaults.temporalMode`.\n */\n temporalMode?: TemporalMode;\n /** ISO-8601 timestamp used when `temporalMode === \"asOf\"`. */\n asOf?: string;\n /** @internal Recorded coordinates are supplied by StoreView only. */\n recordedAsOf?: never;\n /**\n * Optional field-level projection per node/edge kind.\n *\n * Projected nodes keep `kind` and `id`; projected edges keep their structural\n * endpoint fields. Kinds omitted from `project` remain fully hydrated.\n * Projection applies to every returned entity, including the root node.\n *\n * Only kinds present in `includeKinds` (nodes) or `edges` (edges) are valid\n * projection keys. Specifying a kind outside those sets is a compile-time error.\n */\n project?: P;\n}>;\n\n/**\n * Subgraph options as seen by the internal executor: identical to the public\n * {@link SubgraphOptions} except the recorded/system-time pin is a branded\n * instant the StoreView seam supplies. The public surface keeps\n * `recordedAsOf?: never`;\n * recorded reads reach the executor only through `store.subgraphAtCoordinate`.\n */\nexport type InternalSubgraphOptions<\n G extends GraphDef,\n EK extends EdgeKinds<G>,\n NK extends NodeKinds<G>,\n P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = Omit<SubgraphOptions<G, EK, NK, P>, \"recordedAsOf\"> &\n Readonly<{\n recordedAsOf?: RecordedInstant;\n }>;\n\n/**\n * Union of all node result types in a subgraph, respecting projection.\n */\nexport type SubgraphNodeResult<\n G extends GraphDef,\n NK extends NodeKinds<G> = NodeKinds<G>,\n P = undefined,\n> = {\n [Kind in NK]: SubgraphNodeResultForKind<G, Kind, P>;\n}[NK];\n\n/**\n * Union of all edge result types in a subgraph, respecting projection.\n */\nexport type SubgraphEdgeResult<\n G extends GraphDef,\n EK extends EdgeKinds<G> = EdgeKinds<G>,\n P = undefined,\n> = {\n [Kind in EK]: SubgraphEdgeResultForKind<G, Kind, P>;\n}[EK];\n\nexport type SubgraphResult<\n G extends GraphDef,\n NK extends NodeKinds<G> = NodeKinds<G>,\n EK extends EdgeKinds<G> = EdgeKinds<G>,\n P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n> = Readonly<{\n /** The root node, or undefined if the root was not found or excluded. */\n root: SubgraphNodeResult<G, NK, P> | undefined;\n nodes: ReadonlyMap<string, SubgraphNodeResult<G, NK, P>>;\n /** Forward adjacency: fromId → edgeKind → edges to targets. */\n adjacency: ReadonlyMap<\n string,\n ReadonlyMap<EK, readonly SubgraphEdgeResult<G, EK, P>[]>\n >;\n /** Reverse adjacency: toId → edgeKind → edges from sources. */\n reverseAdjacency: ReadonlyMap<\n string,\n ReadonlyMap<EK, readonly SubgraphEdgeResult<G, EK, P>[]>\n >;\n}>;\n\n// ============================================================\n// Execution Context\n// ============================================================\n\ntype SubgraphContext = Readonly<{\n graphId: string;\n rootId: string;\n edgeKinds: readonly string[];\n maxDepth: number;\n includeKinds: readonly string[] | undefined;\n excludeRoot: boolean;\n direction: \"out\" | \"both\";\n cyclePolicy: RecursiveCyclePolicy;\n temporalMode: TemporalMode;\n asOf: string | undefined;\n recordedAsOf: RecordedInstant | undefined;\n dialect: DialectAdapter;\n schema: SqlSchema;\n recordedReadBinding: RecordedReadBinding | undefined;\n backend: GraphBackend;\n}>;\n\ntype SubgraphNodeFetchRow = Readonly<\n Omit<NodeRow, \"props\"> & { props: unknown } & Record<string, unknown>\n>;\n\ntype SubgraphEdgeFetchRow = Readonly<\n Omit<EdgeRow, \"props\"> & { props: unknown } & Record<string, unknown>\n>;\n\ntype ProjectionPropertyFieldPlan = Readonly<{\n field: string;\n outputName: string;\n typeInfo: FieldTypeInfo | undefined;\n}>;\n\ntype KindProjectionPlan = Readonly<{\n includeMeta: boolean;\n propertyFields: readonly ProjectionPropertyFieldPlan[];\n}>;\n\ntype ProjectionPlan = Readonly<{\n fullKinds: readonly string[];\n projectedKinds: ReadonlyMap<string, KindProjectionPlan>;\n}>;\n\n// ============================================================\n// Public API\n// ============================================================\n\nexport async function executeSubgraph<\n G extends GraphDef,\n EK extends EdgeKinds<G>,\n NK extends NodeKinds<G>,\n P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n>(params: {\n graph: G;\n graphId: string;\n rootId: NodeId<AllNodeTypes<G>>;\n backend: GraphBackend;\n dialect: DialectAdapter;\n schema: SqlSchema | undefined;\n recordedReadBinding: RecordedReadBinding | undefined;\n options: InternalSubgraphOptions<G, EK, NK, P>;\n}): Promise<SubgraphResult<G, NK, EK, P>> {\n const { options } = params;\n const { valid: coordinate } = resolveReadCoordinate(\n options.temporalMode ?? params.graph.defaults.temporalMode,\n options.asOf,\n );\n const temporalMode = coordinate.mode;\n // `recordedAsOf` reaches here only via the internal `subgraphAtCoordinate`\n // seam; the public `store.subgraph` rejects it (typed `never`, runtime-guarded\n // for JS callers) before this executor is reached.\n const recordedAsOf = options.recordedAsOf;\n const baseSchema = params.schema ?? DEFAULT_SQL_SCHEMA;\n\n const maxDepth = Math.min(\n options.maxDepth ?? DEFAULT_SUBGRAPH_MAX_DEPTH,\n MAX_EXPLICIT_RECURSIVE_DEPTH,\n );\n\n const ctx: SubgraphContext = {\n graphId: params.graphId,\n rootId: params.rootId,\n edgeKinds: options.edges,\n maxDepth,\n includeKinds: options.includeKinds,\n excludeRoot: options.excludeRoot ?? false,\n direction: options.direction ?? \"out\",\n cyclePolicy: options.cyclePolicy ?? \"prevent\",\n temporalMode,\n asOf: coordinate.asOf,\n recordedAsOf,\n dialect: params.dialect,\n schema: recordedReadSchemaFor(\n baseSchema,\n recordedAsOf,\n params.recordedReadBinding,\n \"recorded-subgraph\",\n ),\n recordedReadBinding: params.recordedReadBinding,\n backend: params.backend,\n };\n\n const schemaIntrospector = getSubgraphSchemaIntrospector(params.graph);\n const nodeProjectionPlan = buildProjectionPlan(\n getIncludedNodeKinds(params.graph, options.includeKinds),\n options.project?.nodes,\n (kind, field) => schemaIntrospector.getFieldTypeInfo(kind, field),\n \"node\",\n );\n const edgeProjectionPlan = buildProjectionPlan(\n dedupeStrings(options.edges),\n options.project?.edges,\n (kind, field) => schemaIntrospector.getEdgeFieldTypeInfo(kind, field),\n \"edge\",\n );\n\n const reachableCte = buildReachableCte({\n graphId: ctx.graphId,\n sourceId: ctx.rootId,\n edgeKinds: ctx.edgeKinds,\n maxHops: ctx.maxDepth,\n direction: ctx.direction,\n cyclePolicy: ctx.cyclePolicy,\n includePath: false,\n temporalMode: ctx.temporalMode,\n ...(ctx.asOf !== undefined && { asOf: ctx.asOf }),\n ...(ctx.recordedAsOf !== undefined && { recordedAsOf: ctx.recordedAsOf }),\n dialect: ctx.dialect,\n // Base schema: buildReachableCte derives the recorded swap from recordedAsOf.\n schema: baseSchema,\n ...(ctx.recordedReadBinding === undefined ?\n {}\n : { recordedReadBinding: ctx.recordedReadBinding }),\n });\n const includedIdsCte = buildIncludedIdsCte(ctx);\n\n // The node and edge fetches both need the traversal closure. Embedding\n // the recursive CTE in each statement runs the BFS twice; on Postgres\n // the closure ids are fetched ONCE and passed to both fetches as a\n // single text[] parameter, filtered via a hashed semi-join\n // (EXISTS over unnest — measured faster than `= ANY` on the same\n // closure). SQLite keeps the embedded form: its in-process traversal\n // is cheap, an id list would bind one parameter per id (bind-budget\n // pressure), and per-count SQL texts would churn the prepared-statement\n // cache.\n let membership: SubgraphMembership;\n const dialect = ctx.dialect.name;\n switch (dialect) {\n case \"postgres\": {\n const includedIds = await fetchIncludedIds(\n ctx,\n reachableCte,\n includedIdsCte,\n );\n const idsArray = textArrayParam(includedIds);\n membership = {\n prefix: sql``,\n idFilter: (column) =>\n sql`EXISTS (SELECT 1 FROM unnest(${idsArray}) AS tg_included(id) WHERE tg_included.id = ${column})`,\n parameterDependentPlan: true,\n };\n break;\n }\n case \"sqlite\": {\n membership = {\n prefix: sql`${reachableCte}${includedIdsCte} `,\n // SQLite: `column IN (subquery)` evaluates via a transient index —\n // optimal as-is. (Postgres takes the parameterized text[] form above.)\n idFilter: (column) => sql`${column} IN (SELECT id FROM included_ids)`,\n parameterDependentPlan: false,\n };\n break;\n }\n default: {\n dialect satisfies never;\n throw new Error(`Unsupported SQL dialect: ${String(dialect)}`);\n }\n }\n\n const [nodeRows, edgeRows] = await Promise.all([\n fetchSubgraphNodes(ctx, membership, nodeProjectionPlan),\n fetchSubgraphEdges(ctx, membership, edgeProjectionPlan),\n ]);\n\n const nodesMap = new Map<string, Node>();\n for (const row of nodeRows) {\n const node = mapSubgraphNodeRow(row, nodeProjectionPlan);\n nodesMap.set(node.id, node);\n }\n\n const adjacency = new Map<string, Map<string, Edge[]>>();\n const reverseAdjacency = new Map<string, Map<string, Edge[]>>();\n for (const row of edgeRows) {\n const edge = mapSubgraphEdgeRow(row, edgeProjectionPlan);\n insertAdjacencyEntry(adjacency, edge.fromId, edge.kind, edge);\n insertAdjacencyEntry(reverseAdjacency, edge.toId, edge.kind, edge);\n }\n\n const root = nodesMap.get(ctx.rootId);\n\n return {\n root,\n nodes: nodesMap,\n adjacency,\n reverseAdjacency,\n } as unknown as SubgraphResult<G, NK, EK, P>;\n}\n\n// ============================================================\n// Projection Planning\n// ============================================================\n\ntype FieldTypeResolver = (\n kind: string,\n field: string,\n) => FieldTypeInfo | undefined;\n\nconst introspectorCache = new WeakMap<GraphDef, SchemaIntrospector>();\n\nfunction getSubgraphSchemaIntrospector<G extends GraphDef>(\n graph: G,\n): SchemaIntrospector {\n const cached = introspectorCache.get(graph);\n if (cached !== undefined) return cached;\n\n const nodeKinds = new Map(\n Object.entries(graph.nodes).map(([kind, definition]) => [\n kind,\n { schema: definition.type.schema },\n ]),\n );\n const edgeKinds = new Map(\n Object.entries(graph.edges).map(([kind, definition]) => [\n kind,\n { schema: definition.type.schema },\n ]),\n );\n\n const introspector = createSchemaIntrospector(nodeKinds, edgeKinds);\n introspectorCache.set(graph, introspector);\n return introspector;\n}\n\nfunction buildProjectionPlan(\n kinds: readonly string[],\n projectionMap:\n Readonly<Record<string, readonly string[] | undefined>> | undefined,\n resolveFieldType: FieldTypeResolver,\n entityPrefix: KindEntity,\n): ProjectionPlan {\n const projectedKinds = new Map<string, KindProjectionPlan>();\n const fullKinds: string[] = [];\n\n for (const kind of kinds) {\n const selection = projectionMap?.[kind];\n if (selection === undefined) {\n fullKinds.push(kind);\n continue;\n }\n\n projectedKinds.set(\n kind,\n buildKindProjectionPlan(kind, selection, resolveFieldType, entityPrefix),\n );\n }\n\n return { fullKinds, projectedKinds };\n}\n\nfunction buildKindProjectionPlan(\n kind: string,\n selection: readonly string[],\n resolveFieldType: FieldTypeResolver,\n entityPrefix: KindEntity,\n): KindProjectionPlan {\n const propertyFields = new Map<string, ProjectionPropertyFieldPlan>();\n let includeMeta = false;\n\n for (const field of selection) {\n if (field === \"meta\") {\n includeMeta = true;\n continue;\n }\n\n validateProjectionField(field, entityPrefix, kind);\n\n if (!propertyFields.has(field)) {\n propertyFields.set(field, {\n field,\n outputName: projectionAlias(entityPrefix, kind, field),\n typeInfo: resolveFieldType(kind, field),\n });\n }\n }\n\n return {\n includeMeta,\n propertyFields: [...propertyFields.values()],\n };\n}\n\nfunction getIncludedNodeKinds<G extends GraphDef>(\n graph: G,\n includeKinds: readonly NodeKinds<G>[] | undefined,\n): readonly string[] {\n if (includeKinds === undefined || includeKinds.length === 0) {\n return Object.keys(graph.nodes);\n }\n\n return dedupeStrings(includeKinds);\n}\n\nfunction dedupeStrings(values: readonly string[]): readonly string[] {\n return [...new Set(values)];\n}\n\n// ============================================================\n// SQL Generation\n// ============================================================\n\nfunction buildIncludedIdsCte(ctx: SubgraphContext): SqlFragment {\n const filters: SqlFragment[] = [];\n\n if (ctx.includeKinds !== undefined && ctx.includeKinds.length > 0) {\n filters.push(compileKindFilter(sql.raw(\"kind\"), ctx.includeKinds));\n }\n\n if (ctx.excludeRoot) {\n filters.push(sql`id != ${ctx.rootId}`);\n }\n\n const whereClause =\n filters.length > 0 ? sql` WHERE ${sql.join(filters, sql` AND `)}` : sql``;\n\n return sql`, included_ids AS (SELECT DISTINCT id FROM reachable${whereClause})`;\n}\n\n/**\n * How the node/edge fetches restrict rows to the traversal closure:\n * either a statement prefix re-declaring the recursive CTE with an\n * `included_ids` membership subquery (SQLite), or an empty prefix with a\n * pre-fetched id-array filter (Postgres).\n */\ntype SubgraphMembership = Readonly<{\n prefix: SqlFragment;\n idFilter: (column: SqlFragment) => SqlFragment;\n /**\n * True in id-array mode: the fetch plans depend on the array\n * cardinality, so the statements must never fall onto a prepared\n * generic plan (see markForceCustomPlan).\n */\n parameterDependentPlan: boolean;\n}>;\n\n/**\n * Binds a string list as ONE text parameter in Postgres array-literal\n * form, cast to text[]. A single parameter keeps the statement text\n * constant across id counts, and the fetch statements semi-join against\n * `unnest` of the array. (Drizzle would otherwise serialize a JS array\n * param as JSON text.)\n */\nfunction textArrayParam(values: readonly string[]): SqlFragment {\n const elements = values.map(\n (value) =>\n `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', String.raw`\\\"`)}\"`,\n );\n return sql`${`{${elements.join(\",\")}}`}::text[]`;\n}\n\n/** Runs the traversal once and returns the closure's node ids. */\nasync function fetchIncludedIds(\n ctx: SubgraphContext,\n reachableCte: SqlFragment,\n includedIdsCte: SqlFragment,\n): Promise<readonly string[]> {\n const rows = await ctx.backend.execute<{ id: string }>(\n asCompiledRowsSql(\n sql`${reachableCte}${includedIdsCte} SELECT id FROM included_ids`,\n ),\n );\n return rows.map((row) => row.id);\n}\n\nasync function fetchSubgraphNodes(\n ctx: SubgraphContext,\n membership: SubgraphMembership,\n projectionPlan: ProjectionPlan,\n): Promise<SubgraphNodeFetchRow[]> {\n const nodeTemporalFilter = compileTemporalFilter({\n mode: ctx.temporalMode,\n asOf: ctx.asOf,\n recordedAsOf: ctx.recordedAsOf,\n tableAlias: \"n\",\n currentTimestamp: currentReadInstant(),\n });\n const columns: SqlFragment[] = [\n sql`n.kind`,\n sql`n.id`,\n buildFullPropsColumn(\"n\", projectionPlan),\n ...buildMetadataColumns(\"n\", projectionPlan, [\n \"version\",\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n ]),\n ...buildProjectedPropertyColumns(\"n\", projectionPlan, ctx.dialect),\n ];\n\n const query = sql`${membership.prefix}SELECT ${sql.join(columns, sql`, `)} FROM ${ctx.schema.nodesTable} n WHERE n.graph_id = ${ctx.graphId} AND ${nodeTemporalFilter} AND ${membership.idFilter(sql.raw(\"n.id\"))}`;\n if (membership.parameterDependentPlan) markForceCustomPlan(query);\n\n return ctx.backend.execute<SubgraphNodeFetchRow>(\n asCompiledRowsSql(query),\n ) as Promise<SubgraphNodeFetchRow[]>;\n}\n\nasync function fetchSubgraphEdges(\n ctx: SubgraphContext,\n membership: SubgraphMembership,\n projectionPlan: ProjectionPlan,\n): Promise<SubgraphEdgeFetchRow[]> {\n const edgeKindFilter = compileKindFilter(sql.raw(\"e.kind\"), ctx.edgeKinds);\n const edgeTemporalFilter = compileTemporalFilter({\n mode: ctx.temporalMode,\n asOf: ctx.asOf,\n recordedAsOf: ctx.recordedAsOf,\n tableAlias: \"e\",\n currentTimestamp: currentReadInstant(),\n });\n const columns: SqlFragment[] = [\n sql`e.id`,\n sql`e.kind`,\n sql`e.from_kind`,\n sql`e.from_id`,\n sql`e.to_kind`,\n sql`e.to_id`,\n buildFullPropsColumn(\"e\", projectionPlan),\n ...buildMetadataColumns(\"e\", projectionPlan, [\n \"valid_from\",\n \"valid_to\",\n \"created_at\",\n \"updated_at\",\n \"deleted_at\",\n ]),\n ...buildProjectedPropertyColumns(\"e\", projectionPlan, ctx.dialect),\n ];\n\n const query = sql`${membership.prefix}SELECT ${sql.join(columns, sql`, `)} FROM ${ctx.schema.edgesTable} e WHERE e.graph_id = ${ctx.graphId} AND ${edgeKindFilter} AND ${edgeTemporalFilter} AND ${membership.idFilter(sql.raw(\"e.from_id\"))} AND ${membership.idFilter(sql.raw(\"e.to_id\"))}`;\n if (membership.parameterDependentPlan) markForceCustomPlan(query);\n\n return ctx.backend.execute<SubgraphEdgeFetchRow>(\n asCompiledRowsSql(query),\n ) as Promise<SubgraphEdgeFetchRow[]>;\n}\n\nfunction buildMetadataColumns(\n alias: \"n\" | \"e\",\n plan: ProjectionPlan,\n columns: readonly string[],\n): readonly SqlFragment[] {\n if (plan.projectedKinds.size === 0) {\n return columns.map((col) => sql`${sql.raw(`${alias}.${col}`)}`);\n }\n\n const metaKinds: string[] = [...plan.fullKinds];\n for (const [kind, kindPlan] of plan.projectedKinds) {\n if (kindPlan.includeMeta) metaKinds.push(kind);\n }\n\n if (metaKinds.length === 0) {\n return columns.map((col) => sql`NULL AS ${sql.raw(col)}`);\n }\n\n // All kinds need meta — no CASE needed\n if (metaKinds.length === plan.fullKinds.length + plan.projectedKinds.size) {\n return columns.map((col) => sql`${sql.raw(`${alias}.${col}`)}`);\n }\n\n const filter = compileKindFilter(sql.raw(`${alias}.kind`), metaKinds);\n return columns.map(\n (col) =>\n sql`CASE WHEN ${filter} THEN ${sql.raw(`${alias}.${col}`)} ELSE NULL END AS ${sql.raw(col)}`,\n );\n}\n\nfunction buildFullPropsColumn(\n alias: \"n\" | \"e\",\n plan: ProjectionPlan,\n): SqlFragment {\n if (plan.projectedKinds.size === 0) {\n return sql`${sql.raw(`${alias}.props`)} AS props`;\n }\n\n if (plan.fullKinds.length === 0) {\n return sql`NULL AS props`;\n }\n\n const filter = compileKindFilter(sql.raw(`${alias}.kind`), plan.fullKinds);\n return sql`CASE WHEN ${filter} THEN ${sql.raw(`${alias}.props`)} ELSE NULL END AS props`;\n}\n\nfunction buildProjectedPropertyColumns(\n alias: \"n\" | \"e\",\n plan: ProjectionPlan,\n dialect: DialectAdapter,\n): readonly SqlFragment[] {\n const columns: SqlFragment[] = [];\n\n for (const [kind, kindPlan] of plan.projectedKinds.entries()) {\n for (const fieldPlan of kindPlan.propertyFields) {\n const extracted = compileTypedJsonExtract({\n column: sql.raw(`${alias}.props`),\n dialect,\n pointer: jsonPointer([fieldPlan.field]),\n valueType: fieldPlan.typeInfo?.valueType,\n });\n\n columns.push(\n sql`CASE WHEN ${sql.raw(alias)}.kind = ${kind} THEN ${extracted} ELSE NULL END AS ${quoteIdentifier(fieldPlan.outputName)}`,\n );\n }\n }\n\n return columns;\n}\n\n// ============================================================\n// Adjacency Index Builder\n// ============================================================\n\nfunction insertAdjacencyEntry(\n index: Map<string, Map<string, Edge[]>>,\n nodeId: string,\n edgeKind: string,\n edge: Edge,\n): void {\n let kindMap = index.get(nodeId);\n if (kindMap === undefined) {\n kindMap = new Map();\n index.set(nodeId, kindMap);\n }\n const edges = kindMap.get(edgeKind);\n if (edges === undefined) {\n kindMap.set(edgeKind, [edge]);\n } else {\n edges.push(edge);\n }\n}\n\n// ============================================================\n// Result Mapping\n// ============================================================\n\nfunction applyProjectedFields(\n target: Record<string, unknown>,\n row: Readonly<Record<string, unknown>>,\n kindPlan: KindProjectionPlan,\n): void {\n for (const fieldPlan of kindPlan.propertyFields) {\n target[fieldPlan.field] = decodeSelectedValue(\n row[fieldPlan.outputName],\n fieldPlan.typeInfo,\n );\n }\n}\n\nfunction mapSubgraphNodeRow(\n row: SubgraphNodeFetchRow,\n projectionPlan: ProjectionPlan,\n): Node {\n const kindPlan = projectionPlan.projectedKinds.get(row.kind);\n if (kindPlan === undefined) {\n return rowToNode({\n ...row,\n props: normalizeProps(row.props),\n });\n }\n\n const projectedNode: Record<string, unknown> = {\n kind: row.kind,\n id: row.id,\n };\n\n if (kindPlan.includeMeta) {\n projectedNode[\"meta\"] = rowToNodeMeta(row);\n }\n\n applyProjectedFields(projectedNode, row, kindPlan);\n return projectedNode as Node;\n}\n\nfunction mapSubgraphEdgeRow(\n row: SubgraphEdgeFetchRow,\n projectionPlan: ProjectionPlan,\n): Edge {\n const kindPlan = projectionPlan.projectedKinds.get(row.kind);\n if (kindPlan === undefined) {\n return rowToEdge({\n ...row,\n props: normalizeProps(row.props),\n });\n }\n\n const projectedEdge: Record<string, unknown> = {\n id: row.id,\n kind: row.kind,\n fromKind: row.from_kind,\n fromId: row.from_id,\n toKind: row.to_kind,\n toId: row.to_id,\n };\n\n if (kindPlan.includeMeta) {\n projectedEdge[\"meta\"] = rowToEdgeMeta(row);\n }\n\n applyProjectedFields(projectedEdge, row, kindPlan);\n return projectedEdge as Edge;\n}\n","/**\n * Set Operation Compilation\n *\n * Compiles UNION, INTERSECT, and EXCEPT operations to SQL.\n *\n * Both dialects compile each leaf with the full query compiler and combine\n * the results with the requested operator. The only dialect-specific concern\n * is how each operand is wrapped so the compound statement stays valid:\n *\n * - PostgreSQL allows a complete SELECT (including its own WITH clause) to be\n * parenthesized as a compound operand: `(SELECT ...) UNION (SELECT ...)`.\n * - SQLite forbids parentheses around compound operands, but it does allow a\n * `WITH` clause inside a FROM-subquery, so each operand is wrapped as\n * `SELECT * FROM (SELECT ...)`. This keeps every leaf's CTEs (traversals,\n * vector/fulltext joins, recursive expansions) scoped to its own subquery\n * and lets per-leaf ORDER BY/LIMIT/OFFSET live inside the wrap.\n *\n * Nested set operations are wrapped the same way, which preserves the AST's\n * grouping regardless of the dialect's native compound-operator associativity.\n */\nimport {\n CompilerInvariantError,\n ConfigurationError,\n UnsupportedPredicateError,\n} from \"../../errors\";\nimport type { SetOperationType } from \"../ast\";\nimport {\n type ComposableQuery,\n type FieldRef,\n type ProjectedField,\n type Projection,\n type QueryAst,\n type SetOperation,\n} from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport { type VectorStrategy } from \"../dialect/vector-strategy\";\nimport { type JsonPointer, jsonPointer } from \"../json-pointer\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport { emitSetOperationQuerySql } from \"./emitter\";\nimport { runCompilerPass } from \"./passes\";\nimport { type LogicalPlan, lowerSetOperationToLogicalPlan } from \"./plan\";\n\n/**\n * Type for the query compiler function.\n */\nexport type QueryCompilerFunction = (\n ast: QueryAst,\n graphId: string,\n) => SqlFragment;\n\n/**\n * Operator mapping for set operations.\n */\nconst OPERATOR_MAP: Record<SetOperationType, string> = {\n union: \"UNION\",\n unionAll: \"UNION ALL\",\n intersect: \"INTERSECT\",\n except: \"EXCEPT\",\n};\n\ntype SetOperationPassState = Readonly<{\n dialect: DialectAdapter;\n graphId: string;\n logicalPlan: LogicalPlan | undefined;\n op: SetOperation;\n}>;\n\ntype RecordedCoordinateKey = string;\n\nfunction queryRecordedCoordinateKey(ast: QueryAst): RecordedCoordinateKey {\n return ast.recordedAsOf ?? \"live\";\n}\n\nfunction collectQueryRecordedCoordinateKeys(\n query: ComposableQuery,\n keys: Set<RecordedCoordinateKey>,\n): void {\n if (\"__type\" in query) {\n collectQueryRecordedCoordinateKeys(query.left, keys);\n collectQueryRecordedCoordinateKeys(query.right, keys);\n return;\n }\n keys.add(queryRecordedCoordinateKey(query));\n}\n\nfunction assertUniformSetOperationRecordedCoordinates(op: SetOperation): void {\n const keys = new Set<RecordedCoordinateKey>();\n collectQueryRecordedCoordinateKeys(op, keys);\n if (keys.size <= 1) return;\n throw new ConfigurationError(\n \"Cannot combine queries with different recorded-time coordinates in a set \" +\n \"operation: each operand reads either the live tables or the recorded \" +\n \"relation at one instant, so mixing live with recorded (or two different \" +\n \"recorded instants) is rejected. Valid-time differences are allowed.\",\n { code: \"SET_OPERATION_RECORDED_COORDINATE_MISMATCH\" },\n {\n suggestion:\n \"Build every operand from the same Store or recorded StoreView coordinate before calling union/intersect/except.\",\n },\n );\n}\n\nfunction runSetOperationPassPipeline(\n op: SetOperation,\n graphId: string,\n dialect: DialectAdapter,\n vectorStrategy: VectorStrategy | undefined,\n): SetOperationPassState {\n let state: SetOperationPassState = {\n dialect,\n graphId,\n logicalPlan: undefined,\n op,\n };\n\n const logicalPlanPass = runCompilerPass(state, {\n name: \"logical_plan\",\n execute(currentState): LogicalPlan {\n return lowerSetOperationToLogicalPlan({\n dialect: currentState.dialect.name,\n graphId: currentState.graphId,\n op: currentState.op,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n });\n },\n update(currentState, logicalPlan): SetOperationPassState {\n return {\n ...currentState,\n logicalPlan,\n };\n },\n });\n state = logicalPlanPass.state;\n\n return state;\n}\n\n// ============================================================\n// Main Entry Point\n// ============================================================\n\n/**\n * Compiles a set operation to SQL.\n *\n * Each leaf is compiled by the full query compiler, so set operations support\n * exactly the same query features as standalone queries (traversals, EXISTS/IN\n * subqueries, vector/fulltext predicates, GROUP BY/HAVING, and per-leaf\n * ORDER BY/LIMIT/OFFSET) on every dialect.\n *\n * @param op - The set operation AST\n * @param graphId - The graph ID\n * @param dialect - The dialect adapter\n * @param compileQuery - Function to compile regular (leaf) queries\n * @param vectorStrategy - The backend-configured vector strategy, if any, used\n * to validate leaf vector predicates against the strategy's metric set\n * @returns `SqlFragment` for the set operation\n */\nexport function compileSetOperation(\n op: SetOperation,\n graphId: string,\n dialect: DialectAdapter,\n compileQuery: QueryCompilerFunction,\n vectorStrategy?: VectorStrategy,\n): SqlFragment {\n assertUniformSetOperationRecordedCoordinates(op);\n const passState = runSetOperationPassPipeline(\n op,\n graphId,\n dialect,\n vectorStrategy,\n );\n const { logicalPlan } = passState;\n if (logicalPlan === undefined) {\n throw new CompilerInvariantError(\n \"Logical plan pass did not initialize plan state\",\n );\n }\n\n const coreSql = compileSetOperationCore(op, graphId, compileQuery, dialect);\n\n const suffixClauses = buildSetOperationSuffixClauses(op, dialect);\n return emitSetOperationQuerySql({\n baseQuery: coreSql,\n logicalPlan,\n ...(suffixClauses.length === 0 ? {} : { suffixClauses }),\n });\n}\n\n/**\n * Compiles a set operation node into a compound SELECT by wrapping each side\n * with the dialect's operand wrapper and joining them with the operator.\n */\nfunction compileSetOperationCore(\n op: SetOperation,\n graphId: string,\n compileQuery: QueryCompilerFunction,\n dialect: DialectAdapter,\n): SqlFragment {\n const left = compileComposableQuery(op.left, graphId, compileQuery, dialect);\n const right = compileComposableQuery(\n op.right,\n graphId,\n compileQuery,\n dialect,\n );\n\n const opSql = sql.raw(OPERATOR_MAP[op.operator]);\n\n return sql`${dialect.wrapSetOperationOperand(left)} ${opSql} ${dialect.wrapSetOperationOperand(right)}`;\n}\n\n/**\n * Compiles a composable query operand. Leaves are compiled by the full query\n * compiler; nested set operations recurse into a complete compound SELECT\n * (including their own ORDER BY/LIMIT/OFFSET) before the parent wraps them.\n */\nfunction compileComposableQuery(\n query: ComposableQuery,\n graphId: string,\n compileQuery: QueryCompilerFunction,\n dialect: DialectAdapter,\n): SqlFragment {\n if (\"__type\" in query) {\n return compileSetOperationCompound(query, graphId, compileQuery, dialect);\n }\n return compileQuery(query, graphId);\n}\n\n/**\n * Compiles a set operation into a complete compound SELECT, including its own\n * ORDER BY/LIMIT/OFFSET suffix clauses. Used for nested operands: a nested\n * compound carries suffix clauses that belong inside the operand, not on the\n * outer statement. The top-level entry (compileSetOperation) layers the\n * logical-plan emitter invariant on top of these same core + suffix clauses.\n */\nfunction compileSetOperationCompound(\n op: SetOperation,\n graphId: string,\n compileQuery: QueryCompilerFunction,\n dialect: DialectAdapter,\n): SqlFragment {\n const core = compileSetOperationCore(op, graphId, compileQuery, dialect);\n const suffixClauses = buildSetOperationSuffixClauses(op, dialect);\n if (suffixClauses.length === 0) return core;\n return sql.join([core, ...suffixClauses], sql` `);\n}\n\n// ============================================================\n// Suffix Clauses (ORDER BY / LIMIT / OFFSET)\n// ============================================================\n\n/**\n * Gets the leftmost leaf's projection from a set operation.\n * The leftmost leaf defines the output column names for the compound query.\n */\nfunction getLeftmostProjection(op: SetOperation): Projection {\n let current: ComposableQuery = op.left;\n while (\"__type\" in current) {\n // current is a SetOperation, traverse left\n current = current.left;\n }\n // current is now a QueryAst (the leftmost leaf)\n return current.projection;\n}\n\n/**\n * Normalizes a FieldRef to a canonical key for comparison.\n *\n * Handles equivalent representations:\n * - path: [\"props\", \"name\"] (no jsonPointer) → \"alias:props:/name\"\n * - path: [\"props\"], jsonPointer: \"/name\" → \"alias:props:/name\"\n *\n * This matches the normalization logic in compileFieldValue/getFieldPointer.\n */\nfunction normalizeFieldRefKey(field: FieldRef): string {\n // Derive JSON pointer from path if not explicitly set (same logic as predicates.ts getFieldPointer)\n let pointer: JsonPointer | undefined = field.jsonPointer;\n if (\n pointer === undefined &&\n field.path.length > 1 &&\n field.path[0] === \"props\"\n ) {\n pointer = jsonPointer(field.path.slice(1));\n }\n\n // Normalize base path: for JSON fields, always use [\"props\"]\n const basePath =\n field.path.length > 0 && field.path[0] === \"props\" ?\n \"props\"\n : field.path.join(\".\");\n\n return `${field.alias}:${basePath}:${pointer ?? \"\"}`;\n}\n\n/**\n * Matches a FieldRef from ORDER BY to a ProjectedField in the projection.\n * Returns the matching ProjectedField or undefined if no match.\n *\n * Uses normalized keys to handle equivalent field representations.\n */\nfunction matchFieldToProjection(\n field: FieldRef,\n projection: Projection,\n): ProjectedField | undefined {\n const targetKey = normalizeFieldRefKey(field);\n\n for (const projected of projection.fields) {\n const source = projected.source;\n\n // Only match against FieldRef sources (not aggregates)\n if (!(\"__type\" in source) || source.__type !== \"field_ref\") continue;\n\n // Compare normalized keys\n if (normalizeFieldRefKey(source) === targetKey) {\n return projected;\n }\n }\n return undefined;\n}\n\n/**\n * Builds ORDER BY, LIMIT, OFFSET clauses for set operations.\n *\n * For set operations, ORDER BY must reference output column names from\n * the compound result, not internal CTE columns. This function:\n * 1. Maps each ORDER BY field to its output name from the leftmost projection\n * 2. Uses IS NULL emulation for consistent NULLS FIRST/LAST across dialects\n * 3. Throws a descriptive error if an ORDER BY field isn't in the projection\n */\nfunction buildSetOperationSuffixClauses(\n op: SetOperation,\n dialect: DialectAdapter,\n): SqlFragment[] {\n const clauses: SqlFragment[] = [];\n\n // Handle ORDER BY if present\n if (op.orderBy && op.orderBy.length > 0) {\n const projection = getLeftmostProjection(op);\n\n // Check for SELECT * (empty projection) - can't order by named columns\n if (projection.fields.length === 0) {\n throw new UnsupportedPredicateError(\n \"Set operation ORDER BY requires explicit field projection. \" +\n \"SELECT * does not provide stable output column names for ordering. \" +\n \"Use .select() to specify which fields to project.\",\n );\n }\n\n const orderParts: SqlFragment[] = [];\n\n for (const orderSpec of op.orderBy) {\n const projected = matchFieldToProjection(orderSpec.field, projection);\n\n if (!projected) {\n // Build a descriptive error message\n const fieldDesc =\n orderSpec.field.jsonPointer ?\n `${orderSpec.field.alias}.props${orderSpec.field.jsonPointer}`\n : `${orderSpec.field.alias}.${orderSpec.field.path.join(\".\")}`;\n const availableFields = projection.fields\n .map((f) => f.outputName)\n .join(\", \");\n throw new UnsupportedPredicateError(\n `Set operation ORDER BY field \"${fieldDesc}\" is not in the projection. ` +\n `ORDER BY for UNION/INTERSECT/EXCEPT must reference projected columns. ` +\n `Available columns: ${availableFields}`,\n );\n }\n\n // Use output column name with proper quoting\n const columnRef = sql.raw(dialect.quoteIdentifier(projected.outputName));\n const dir = sql.raw(orderSpec.direction.toUpperCase());\n\n // Handle nulls with IS NULL emulation for cross-dialect consistency\n // Default: ASC → NULLS LAST, DESC → NULLS FIRST\n const nulls =\n orderSpec.nulls ?? (orderSpec.direction === \"asc\" ? \"last\" : \"first\");\n const nullsDir = sql.raw(nulls === \"first\" ? \"DESC\" : \"ASC\");\n\n // Emulate NULLS FIRST/LAST: (col IS NULL) ASC/DESC, col DIR\n orderParts.push(\n sql`(${columnRef} IS NULL) ${nullsDir}`,\n sql`${columnRef} ${dir}`,\n );\n }\n\n clauses.push(sql`ORDER BY ${sql.join(orderParts, sql`, `)}`);\n }\n\n // Handle LIMIT\n if (op.limit !== undefined) {\n clauses.push(sql`LIMIT ${op.limit}`);\n }\n\n // Handle OFFSET\n if (op.offset !== undefined) {\n clauses.push(sql`OFFSET ${op.offset}`);\n }\n\n return clauses;\n}\n","import type {\n FulltextMatchPredicate,\n HybridFusionOptions,\n PredicateExpression,\n QueryAst,\n VectorSimilarityPredicate,\n} from \"../ast\";\nimport { type DialectAdapter } from \"../dialect/types\";\nimport {\n createTemporalFilterPass,\n resolveFulltextAwareLimit,\n resolveVectorAwareLimit,\n runCompilerPass,\n runFulltextPredicatePass,\n runFusionConfigPass,\n runVectorPredicatePass,\n type TemporalFilterPass,\n} from \"./passes\";\nimport { type LogicalPlan, lowerStandardQueryToLogicalPlan } from \"./plan\";\nimport {\n buildPredicateIndex,\n getPredicatesForAlias,\n type PredicateIndex,\n} from \"./predicate-utils\";\nimport { type PredicateCompilerContext } from \"./predicates\";\nimport { assertRecordedQueryDoesNotUseCurrentIndexes } from \"./recorded-current-index-guard\";\nimport {\n addRequiredColumn,\n findSelectivePropsFieldForFieldRef,\n isIdFieldRef,\n mapSelectiveSystemFieldToColumn,\n markFieldRefAsRequired,\n type RequiredColumnsByAlias,\n} from \"./utils\";\n\n/**\n * Heuristics for pushing LIMIT into traversal CTEs to cap intermediate row counts.\n * - 8x multiplier accounts for edge fan-out (each node may connect to multiple edges).\n * - 10K cap prevents runaway memory allocation for large intermediate result sets.\n */\nconst TRAVERSAL_LIMIT_PUSHDOWN_MULTIPLIER = 8;\nconst TRAVERSAL_LIMIT_PUSHDOWN_MAX = 10_000;\n\nfunction isColumnPruningEnabled(ast: QueryAst): boolean {\n if (ast.selectiveFields && ast.selectiveFields.length > 0) {\n return true;\n }\n if (ast.groupBy || ast.having) {\n return true;\n }\n return ast.projection.fields.some(\n (field) => field.source.__type === \"aggregate\",\n );\n}\n\nfunction markPredicateFieldsAsRequired(\n requiredColumnsByAlias: Map<string, Set<string>>,\n expression: PredicateExpression,\n): void {\n switch (expression.__type) {\n case \"comparison\": {\n markFieldRefAsRequired(requiredColumnsByAlias, expression.left);\n return;\n }\n case \"string_op\":\n case \"null_check\":\n case \"between\":\n case \"array_op\":\n case \"object_op\": {\n markFieldRefAsRequired(requiredColumnsByAlias, expression.field);\n return;\n }\n case \"and\":\n case \"or\": {\n for (const predicate of expression.predicates) {\n markPredicateFieldsAsRequired(requiredColumnsByAlias, predicate);\n }\n return;\n }\n case \"not\": {\n markPredicateFieldsAsRequired(\n requiredColumnsByAlias,\n expression.predicate,\n );\n return;\n }\n case \"aggregate_comparison\": {\n markFieldRefAsRequired(\n requiredColumnsByAlias,\n expression.aggregate.field,\n );\n return;\n }\n case \"in_subquery\": {\n markFieldRefAsRequired(requiredColumnsByAlias, expression.field);\n return;\n }\n case \"vector_similarity\": {\n markFieldRefAsRequired(requiredColumnsByAlias, expression.field);\n return;\n }\n case \"fulltext_match\": {\n markFieldRefAsRequired(requiredColumnsByAlias, expression.field);\n return;\n }\n case \"exists\": {\n return;\n }\n }\n}\n\n/**\n * Collects the columns each alias must carry out of its CTE.\n *\n * `includeProjection` (default true) folds in the SELECT-list fields. The late\n * materialization path passes `false` to build a *lean* candidate CTE that\n * carries only identity, ordering, and predicate columns — the projection-only\n * columns (e.g. a large `content` prop) are deferred and re-fetched by identity\n * for the surviving rows, not materialized for every candidate.\n */\nexport function collectRequiredColumnsByAlias(\n ast: QueryAst,\n options?: Readonly<{ includeProjection?: boolean }>,\n): RequiredColumnsByAlias {\n const includeProjection = options?.includeProjection ?? true;\n const requiredColumnsByAlias = new Map<string, Set<string>>();\n\n addRequiredColumn(requiredColumnsByAlias, ast.start.alias, \"id\");\n for (const traversal of ast.traversals) {\n addRequiredColumn(requiredColumnsByAlias, traversal.nodeAlias, \"id\");\n }\n\n const hasSelectiveFields = (ast.selectiveFields?.length ?? 0) > 0;\n\n if (includeProjection) {\n if (hasSelectiveFields) {\n for (const field of ast.selectiveFields ?? []) {\n if (field.isSystemField) {\n addRequiredColumn(\n requiredColumnsByAlias,\n field.alias,\n mapSelectiveSystemFieldToColumn(field.field),\n );\n }\n }\n } else {\n for (const projectedField of ast.projection.fields) {\n const source = projectedField.source;\n if (source.__type === \"field_ref\") {\n markFieldRefAsRequired(requiredColumnsByAlias, source);\n } else {\n addRequiredColumn(requiredColumnsByAlias, source.field.alias, \"id\");\n markFieldRefAsRequired(requiredColumnsByAlias, source.field);\n }\n }\n }\n }\n\n if (ast.groupBy) {\n for (const field of ast.groupBy.fields) {\n markFieldRefAsRequired(requiredColumnsByAlias, field);\n }\n }\n\n if (ast.orderBy) {\n for (const orderSpec of ast.orderBy) {\n if (\n findSelectivePropsFieldForFieldRef(\n ast.selectiveFields,\n orderSpec.field,\n ) !== undefined\n ) {\n continue;\n }\n markFieldRefAsRequired(requiredColumnsByAlias, orderSpec.field);\n }\n }\n\n if (ast.having) {\n markPredicateFieldsAsRequired(requiredColumnsByAlias, ast.having);\n }\n\n if (!hasSelectiveFields) {\n for (const predicate of ast.predicates) {\n markPredicateFieldsAsRequired(\n requiredColumnsByAlias,\n predicate.expression,\n );\n }\n }\n\n return requiredColumnsByAlias;\n}\n\nfunction hasIdEqualityPredicate(\n expression: PredicateExpression,\n alias: string,\n): boolean {\n switch (expression.__type) {\n case \"comparison\": {\n return (\n expression.op === \"eq\" &&\n expression.left.alias === alias &&\n isIdFieldRef(expression.left)\n );\n }\n case \"and\": {\n return expression.predicates.some((predicate) =>\n hasIdEqualityPredicate(predicate, alias),\n );\n }\n case \"or\":\n case \"not\":\n case \"string_op\":\n case \"null_check\":\n case \"between\":\n case \"array_op\":\n case \"object_op\":\n case \"aggregate_comparison\":\n case \"exists\":\n case \"in_subquery\":\n case \"vector_similarity\":\n case \"fulltext_match\": {\n return false;\n }\n }\n}\n\nfunction isStartAliasBoundToSingleId(\n ast: QueryAst,\n predicateIndex: PredicateIndex,\n): boolean {\n return getPredicatesForAlias(predicateIndex, ast.start.alias, \"node\").some(\n (predicate) =>\n hasIdEqualityPredicate(predicate.expression, ast.start.alias),\n );\n}\n\nfunction resolveTraversalCteLimit(\n ast: QueryAst,\n predicateIndex: PredicateIndex,\n): number | undefined {\n if (ast.limit === undefined) {\n return undefined;\n }\n\n if (ast.offset !== undefined) {\n return undefined;\n }\n\n if (ast.limit <= 0) {\n return 0;\n }\n\n if (ast.groupBy || ast.having) {\n return undefined;\n }\n\n if (ast.orderBy && ast.orderBy.length > 0) {\n return undefined;\n }\n\n if (ast.traversals.length < 2) {\n return undefined;\n }\n\n if (ast.traversals.some((traversal) => traversal.optional)) {\n return undefined;\n }\n\n if (!isStartAliasBoundToSingleId(ast, predicateIndex)) {\n return undefined;\n }\n\n const pushdownLimit = Math.min(\n ast.limit * TRAVERSAL_LIMIT_PUSHDOWN_MULTIPLIER,\n TRAVERSAL_LIMIT_PUSHDOWN_MAX,\n );\n\n return Math.max(ast.limit, pushdownLimit);\n}\n\nfunction canCollapseSelectiveTraversalRowset(\n ast: QueryAst,\n vectorPredicate: VectorSimilarityPredicate | undefined,\n fulltextPredicate: FulltextMatchPredicate | undefined,\n): boolean {\n if (vectorPredicate !== undefined) {\n return false;\n }\n\n if (fulltextPredicate !== undefined) {\n return false;\n }\n\n if (ast.traversals.length === 0) {\n return false;\n }\n\n if (ast.traversals.some((traversal) => traversal.optional)) {\n return false;\n }\n\n let expectedJoinFromAlias = ast.start.alias;\n for (const traversal of ast.traversals) {\n if (traversal.joinFromAlias !== expectedJoinFromAlias) {\n return false;\n }\n expectedJoinFromAlias = traversal.nodeAlias;\n }\n\n if (!ast.selectiveFields || ast.selectiveFields.length === 0) {\n return false;\n }\n\n if (ast.groupBy || ast.having) {\n return false;\n }\n\n if (\n ast.projection.fields.some((field) => field.source.__type === \"aggregate\")\n ) {\n return false;\n }\n\n return true;\n}\n\nexport function shouldMaterializeTraversalCte(\n dialect: DialectAdapter,\n traversalCount: number,\n traversalIndex: number,\n): boolean {\n if (!dialect.capabilities.materializeIntermediateTraversalCtes) {\n return false;\n }\n\n if (traversalCount <= 1) {\n return false;\n }\n\n return traversalIndex < traversalCount - 1;\n}\n\ntype StandardQueryPassState = Readonly<{\n ast: QueryAst;\n collapsedTraversalCteAlias: string | undefined;\n ctx: PredicateCompilerContext;\n effectiveLimit: number | undefined;\n fulltextPredicate: FulltextMatchPredicate | undefined;\n fusion: HybridFusionOptions | undefined;\n logicalPlan: LogicalPlan | undefined;\n predicateIndex: PredicateIndex;\n requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n shouldCollapseSelectiveTraversalRowset: boolean;\n temporalFilterPass: TemporalFilterPass | undefined;\n traversalCteLimit: number | undefined;\n vectorPredicate: VectorSimilarityPredicate | undefined;\n}>;\n\nexport function runStandardQueryPassPipeline(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): StandardQueryPassState {\n let state: StandardQueryPassState = {\n ast,\n collapsedTraversalCteAlias: undefined,\n ctx,\n effectiveLimit: undefined,\n fulltextPredicate: undefined,\n fusion: undefined,\n logicalPlan: undefined,\n predicateIndex: buildPredicateIndex(ast),\n requiredColumnsByAlias: undefined,\n shouldCollapseSelectiveTraversalRowset: false,\n temporalFilterPass: undefined,\n traversalCteLimit: undefined,\n vectorPredicate: undefined,\n };\n\n const vectorPass = runCompilerPass(state, {\n name: \"vector_predicate\",\n execute(currentState): VectorSimilarityPredicate | undefined {\n return runVectorPredicatePass(\n currentState.ast,\n currentState.ctx.dialect,\n currentState.ctx.vectorStrategy,\n ).vectorPredicate;\n },\n update(currentState, vectorPredicate): StandardQueryPassState {\n return {\n ...currentState,\n vectorPredicate,\n };\n },\n });\n state = vectorPass.state;\n\n const fulltextPass = runCompilerPass(state, {\n name: \"fulltext_predicate\",\n execute(currentState): FulltextMatchPredicate | undefined {\n return runFulltextPredicatePass(\n currentState.ast,\n currentState.ctx.dialect,\n ).fulltextPredicate;\n },\n update(currentState, fulltextPredicate): StandardQueryPassState {\n return {\n ...currentState,\n fulltextPredicate,\n };\n },\n });\n state = fulltextPass.state;\n\n assertRecordedQueryDoesNotUseCurrentIndexes(\n state.ast,\n state.vectorPredicate,\n state.fulltextPredicate,\n );\n\n const fusionPass = runCompilerPass(state, {\n name: \"fusion_config\",\n execute(currentState): HybridFusionOptions | undefined {\n return runFusionConfigPass(\n currentState.ast,\n currentState.vectorPredicate,\n currentState.fulltextPredicate,\n ).fusion;\n },\n update(currentState, fusion): StandardQueryPassState {\n return {\n ...currentState,\n fusion,\n };\n },\n });\n state = fusionPass.state;\n\n const temporalPass = runCompilerPass(state, {\n name: \"temporal_filters\",\n execute(currentState): TemporalFilterPass {\n return createTemporalFilterPass(currentState.ast, ctx.readInstant);\n },\n update(currentState, temporalFilterPass): StandardQueryPassState {\n return {\n ...currentState,\n temporalFilterPass,\n };\n },\n });\n state = temporalPass.state;\n\n const columnPruningPass = runCompilerPass(state, {\n name: \"column_pruning\",\n execute(currentState): RequiredColumnsByAlias | undefined {\n return isColumnPruningEnabled(currentState.ast) ?\n collectRequiredColumnsByAlias(currentState.ast)\n : undefined;\n },\n update(currentState, requiredColumnsByAlias): StandardQueryPassState {\n return {\n ...currentState,\n requiredColumnsByAlias,\n };\n },\n });\n state = columnPruningPass.state;\n\n const selectiveTraversalRowsetPass = runCompilerPass(state, {\n name: \"selective_traversal_rowset\",\n execute(currentState): Readonly<{\n collapsedTraversalCteAlias: string | undefined;\n shouldCollapseSelectiveTraversalRowset: boolean;\n }> {\n const shouldCollapseSelectiveTraversalRowset =\n canCollapseSelectiveTraversalRowset(\n currentState.ast,\n currentState.vectorPredicate,\n currentState.fulltextPredicate,\n );\n const lastTraversal = currentState.ast.traversals.at(-1);\n const collapsedTraversalCteAlias =\n shouldCollapseSelectiveTraversalRowset && lastTraversal !== undefined ?\n `cte_${lastTraversal.nodeAlias}`\n : undefined;\n\n return {\n collapsedTraversalCteAlias,\n shouldCollapseSelectiveTraversalRowset,\n };\n },\n update(\n currentState,\n { collapsedTraversalCteAlias, shouldCollapseSelectiveTraversalRowset },\n ): StandardQueryPassState {\n return {\n ...currentState,\n collapsedTraversalCteAlias,\n shouldCollapseSelectiveTraversalRowset,\n };\n },\n });\n state = selectiveTraversalRowsetPass.state;\n\n const traversalLimitPass = runCompilerPass(state, {\n name: \"traversal_limit\",\n execute(currentState): number | undefined {\n return resolveTraversalCteLimit(\n currentState.ast,\n currentState.predicateIndex,\n );\n },\n update(currentState, traversalCteLimit): StandardQueryPassState {\n return {\n ...currentState,\n traversalCteLimit,\n };\n },\n });\n state = traversalLimitPass.state;\n\n // Compute effectiveLimit once — used by both logical plan lowering and SQL LIMIT/OFFSET.\n // Both vector and fulltext predicates carry their own LIMITs; the tightest wins.\n state = {\n ...state,\n effectiveLimit: resolveFulltextAwareLimit(\n resolveVectorAwareLimit(state.ast.limit, state.vectorPredicate),\n state.fulltextPredicate,\n ),\n };\n\n const logicalPlanPass = runCompilerPass(state, {\n name: \"logical_plan\",\n execute(currentState): LogicalPlan {\n const loweringInput = {\n ast: currentState.ast,\n dialect: currentState.ctx.dialect.name,\n graphId,\n };\n\n return lowerStandardQueryToLogicalPlan({\n ...loweringInput,\n ...(currentState.collapsedTraversalCteAlias === undefined ?\n {}\n : {\n collapsedTraversalCteAlias: currentState.collapsedTraversalCteAlias,\n }),\n ...(currentState.effectiveLimit === undefined ?\n {}\n : { effectiveLimit: currentState.effectiveLimit }),\n ...(currentState.vectorPredicate === undefined ?\n {}\n : { vectorPredicate: currentState.vectorPredicate }),\n ...(currentState.fulltextPredicate === undefined ?\n {}\n : { fulltextPredicate: currentState.fulltextPredicate }),\n });\n },\n update(currentState, logicalPlan): StandardQueryPassState {\n return {\n ...currentState,\n logicalPlan,\n };\n },\n });\n state = logicalPlanPass.state;\n\n return state;\n}\n","import { requireDefined } from \"../../utils/presence\";\n/**\n * Query Compiler Module\n *\n * Main entry point for compiling query ASTs to SQL.\n * Re-exports individual compiler modules and provides the main compile functions.\n */\n\n// Re-export sub-modules\nexport {\n type LogicalPlan,\n type LogicalPlanNode,\n lowerRecursiveQueryToLogicalPlan,\n lowerSetOperationToLogicalPlan,\n lowerStandardQueryToLogicalPlan,\n} from \"./plan\";\nexport {\n compileAggregateExpr,\n compileFieldColumn,\n compileFieldValue,\n compilePredicateExpression,\n type PredicateCompilerContext,\n} from \"./predicates\";\nexport {\n compileVariableLengthQuery,\n hasVariableLengthTraversal,\n MAX_EXPLICIT_RECURSIVE_DEPTH,\n MAX_RECURSIVE_DEPTH,\n} from \"./recursive\";\nexport {\n createSqlSchema,\n DEFAULT_SQL_SCHEMA,\n type ExternalRecordedReadSource,\n recordedRelation,\n type RecordedRelationOptions,\n type ResolvedSqlTableNames,\n type SqlSchema,\n type SqlTableNames,\n} from \"./schema\";\nexport {\n compileTemporalFilter,\n extractTemporalOptions,\n type TemporalFilterOptions,\n} from \"./temporal\";\nimport { type ReadInstantMode, withPinnedReadInstant } from \"./temporal\";\n\n// Re-export dialect helpers and types\nexport { getDialect } from \"../dialect\";\nexport { type DialectAdapter, type SqlDialect } from \"../dialect/types\";\n\nimport { CompilerInvariantError, ConfigurationError } from \"../../errors\";\nimport {\n type AggregateExpr,\n type FulltextMatchPredicate,\n type HybridFusionOptions,\n type QueryAst,\n type SelectiveField,\n type SetOperation,\n type VectorSimilarityPredicate,\n} from \"../ast\";\nimport { getDialect } from \"../dialect\";\nimport { type FulltextStrategy } from \"../dialect/fulltext-strategy\";\nimport {\n type DialectAdapter,\n type DialectStandardQueryStrategy,\n type SqlDialect,\n} from \"../dialect/types\";\nimport { type VectorStrategy } from \"../dialect/vector-strategy\";\nimport { sql, type SqlFragment } from \"../sql-fragment\";\nimport {\n annIndexScanTypes,\n asCompiledSelectSql,\n type CompiledSelectSql,\n markAnnIndexScan,\n} from \"../sql-intent\";\nimport { emitStandardQuerySql } from \"./emitter\";\nimport {\n buildLateMaterializedOuterOrderBy,\n buildLateMaterializedOuterProjection,\n buildLateMaterializedTopKCte,\n buildLimitOffsetClause,\n buildStandardEmbeddingsCte,\n buildStandardFromClause,\n buildStandardFulltextCte,\n buildStandardFulltextOrderBy,\n buildStandardGroupBy,\n buildStandardHaving,\n buildStandardHybridCandidateCte,\n buildStandardHybridRrfOrderBy,\n buildStandardOrderBy,\n buildStandardProjection,\n buildStandardStartCte,\n buildStandardTraversalCte,\n buildStandardVectorOrderBy,\n LATE_MAT_TOPK_CTE_ALIAS,\n lateMaterializedPhysicalAlias,\n lateMaterializedProjectedNodeAliases,\n} from \"./emitter\";\nimport { type TemporalFilterPass } from \"./passes\";\nimport { type LogicalPlan, type LogicalPlanNode } from \"./plan\";\nimport {\n compileKindFilter,\n compilePredicateClauses,\n getHybridTargetAlias,\n getNodeKindsForAlias,\n getPredicatesForAlias,\n type PredicateIndex,\n} from \"./predicate-utils\";\nimport { compileFieldValue, type PredicateCompilerContext } from \"./predicates\";\nimport {\n compileVariableLengthQuery,\n hasVariableLengthTraversal,\n} from \"./recursive\";\nimport {\n DEFAULT_SQL_SCHEMA,\n type RecordedReadBinding,\n recordedReadSchemaFor,\n requireSqlSchema,\n type SqlSchema,\n type VectorSlotMap,\n} from \"./schema\";\nimport { compileSetOperation as compileSetOp } from \"./set-operations\";\nimport {\n collectRequiredColumnsByAlias,\n runStandardQueryPassPipeline,\n shouldMaterializeTraversalCte,\n} from \"./standard-pass-pipeline\";\nimport {\n findSelectivePropsFieldForFieldRef,\n isAggregateExpr,\n isIdFieldRef,\n mapSelectiveSystemFieldToColumn,\n quoteIdentifier,\n type RequiredColumnsByAlias,\n} from \"./utils\";\n\n// ============================================================\n// Main Query Compiler\n// ============================================================\n\n/**\n * Options for query compilation.\n */\nexport type CompileQueryOptions = Readonly<{\n /** SQL dialect (\"sqlite\" or \"postgres\"). Defaults to \"sqlite\". */\n dialect?: SqlDialect | undefined;\n /** SQL schema configuration from createSqlSchema(...). Defaults to standard names. */\n schema?: SqlSchema | undefined;\n /**\n * Fulltext strategy override. When set, overrides the dialect's\n * default fulltext strategy for `$fulltext.matches()` compilation.\n * Callers typically read this from `backend.fulltextStrategy` so a\n * backend-declared strategy (e.g. ParadeDB) wins over the dialect\n * default (tsvector).\n */\n fulltextStrategy?: FulltextStrategy | undefined;\n /**\n * Vector strategy override. When set, `field.similarTo(...)`\n * predicates compile against the strategy's per-`(kind, field)`\n * tables and distance expression. Callers read it from\n * `backend.vectorStrategy` so a backend-declared strategy (pgvector,\n * libsql-native, sqlite-vec) drives the per-field relevance scan.\n */\n vectorStrategy?: VectorStrategy | undefined;\n /**\n * Whether the active backend supports SQL window functions such as\n * `ROW_NUMBER()`. Defaults to true for direct compiler callers.\n */\n windowFunctions?: boolean | undefined;\n /**\n * Declared embedding slots `(kind, fieldPath) -> descriptor` used by\n * the `field.similarTo(...)` CTE to know which kinds in an alias\n * declare the field. Callers build it from the graph's node schemas.\n */\n vectorSlots?: VectorSlotMap | undefined;\n /** Per-kind declared fulltext language (see buildFulltextLanguages). */\n fulltextLanguages?: ReadonlyMap<string, string> | undefined;\n /**\n * Recorded read relation to use when the AST carries `recordedAsOf`.\n * Supplying a recorded timestamp without this binding is rejected so the\n * compiler never silently swaps to TypeGraph's built-in history tables when\n * the store was only configured for live/valid-time reads.\n */\n recordedReadBinding?: RecordedReadBinding | undefined;\n /**\n * How the \"current\" valid-time read instant is emitted. Defaults to\n * `\"literal\"` (a value frozen at compile time). The query builder's\n * compiled template cache passes `\"placeholder\"` so the instant is a\n * reserved execution-time slot, letting one compiled statement be reused\n * across executions with a fresh \"now\" each call. See {@link ReadInstantMode}.\n */\n readInstant?: ReadInstantMode | undefined;\n}>;\n\n/**\n * Compiles a query AST to SQL.\n *\n * This is the main entry point for query compilation. It dispatches to\n * the appropriate compiler based on the query type (standard, recursive,\n * or set operation).\n *\n * @param ast - The query AST to compile\n * @param graphId - The graph ID for filtering\n * @param options - Compilation options (dialect, schema)\n * @returns TypeGraph `SqlFragment` ready for backend execution\n *\n * @example\n * ```typescript\n * const ast = query.toAst();\n * const sql = compileQuery(ast, \"my_graph\", { dialect: \"postgres\" });\n * const results = await db.execute(sql);\n * ```\n *\n * @example\n * ```typescript\n * // With custom table names\n * const schema = createSqlSchema({ nodes: \"myapp_nodes\", edges: \"myapp_edges\" });\n * const sql = compileQuery(ast, \"my_graph\", { dialect: \"postgres\", schema });\n * ```\n */\nexport function compileQuery(\n ast: QueryAst,\n graphId: string,\n options: CompileQueryOptions | SqlDialect = \"sqlite\",\n): CompiledSelectSql {\n // Support legacy signature: compileQuery(ast, graphId, dialect)\n const options_: CompileQueryOptions =\n typeof options === \"string\" ? { dialect: options } : options;\n const dialect = options_.dialect ?? \"sqlite\";\n const baseSchema =\n options_.schema === undefined ?\n DEFAULT_SQL_SCHEMA\n : requireSqlSchema(options_.schema, \"compileQuery schema\");\n const schema = recordedReadSchemaFor(\n baseSchema,\n ast.recordedAsOf,\n options_.recordedReadBinding,\n \"recorded-query\",\n );\n\n const adapter = resolveDialectAdapter(dialect, options_.fulltextStrategy);\n // Collects the ANN slot index types the emitter compiles engine-form\n // branches for; a non-empty set brands the finished statement so the\n // backend applies the pgvector iterative-scan GUCs around execution.\n // (Sub-compiled correlated queries brand their own `SqlFragment` objects, which\n // are embedded by text — an ANN branch inside a subquery therefore\n // does not surface the brand; the inline vector predicate compiles at\n // the top level, so this is theoretical today.)\n const annIndexTypes = new Set<string>();\n const ctx: PredicateCompilerContext = {\n dialect: adapter,\n schema,\n annIndexTypes,\n readInstant: options_.readInstant ?? \"literal\",\n compileQuery: (subAst, subGraphId) =>\n compileQuery(\n inheritRecordedAsOf(subAst, ast.recordedAsOf),\n subGraphId,\n propagateOptions(options_),\n ),\n ...(options_.vectorStrategy === undefined ?\n {}\n : { vectorStrategy: options_.vectorStrategy }),\n windowFunctions: options_.windowFunctions ?? true,\n ...(options_.vectorSlots === undefined ?\n {}\n : { vectorSlots: options_.vectorSlots }),\n ...(options_.fulltextLanguages === undefined ?\n {}\n : { fulltextLanguages: options_.fulltextLanguages }),\n };\n\n function finish(compiled: SqlFragment): CompiledSelectSql {\n if (annIndexTypes.size > 0) {\n markAnnIndexScan(compiled, [...annIndexTypes]);\n }\n return asCompiledSelectSql(compiled);\n }\n\n // Check for variable-length traversals\n if (hasVariableLengthTraversal(ast)) {\n const lowered = tryLowerSingleHopRecursiveTraversal(ast);\n if (lowered !== undefined) {\n return finish(compileStandardQuery(lowered, graphId, ctx));\n }\n return finish(compileVariableLengthQuery(ast, graphId, ctx));\n }\n\n // Standard query compilation\n return finish(compileStandardQuery(ast, graphId, ctx));\n}\n\nfunction tryLowerSingleHopRecursiveTraversal(\n ast: QueryAst,\n): QueryAst | undefined {\n if (ast.traversals.length !== 1) {\n return undefined;\n }\n\n const traversal = requireDefined(ast.traversals[0]);\n const variableLength = traversal.variableLength;\n if (!variableLength) {\n return undefined;\n }\n\n if (variableLength.minDepth !== 1 || variableLength.maxDepth !== 1) {\n return undefined;\n }\n if (\n variableLength.pathAlias !== undefined ||\n variableLength.depthAlias !== undefined\n ) {\n return undefined;\n }\n\n const { variableLength: _vl, ...nonRecursiveTraversal } = traversal;\n\n return {\n ...ast,\n traversals: [nonRecursiveTraversal],\n };\n}\n\n/**\n * Compiles a set operation (UNION/INTERSECT/EXCEPT) to SQL.\n *\n * @param op - The set operation AST\n * @param graphId - The graph ID for filtering\n * @param options - Compilation options (dialect, schema)\n * @returns TypeGraph `SqlFragment`\n */\nexport function compileSetOperation(\n op: SetOperation,\n graphId: string,\n options: CompileQueryOptions | SqlDialect = \"sqlite\",\n): CompiledSelectSql {\n // Support legacy signature: compileSetOperation(op, graphId, dialect)\n const options_: CompileQueryOptions =\n typeof options === \"string\" ? { dialect: options } : options;\n const dialect = options_.dialect ?? \"sqlite\";\n\n const adapter = resolveDialectAdapter(dialect, options_.fulltextStrategy);\n // Operand statements carry their own ANN brand, but the set-operation\n // wrapper is a fresh `SqlFragment` object and the backend only inspects the\n // object it executes — so operand brands are merged onto the final\n // statement here, or a union with an approximate operand would skip\n // the pgvector GUC wrapper.\n const annIndexTypes = new Set<string>();\n const compileOperand = (ast: QueryAst, gid: string): CompiledSelectSql => {\n const compiled = compileQuery(ast, gid, propagateOptions(options_));\n for (const indexType of annIndexScanTypes(compiled) ?? []) {\n annIndexTypes.add(indexType);\n }\n return compiled;\n };\n // One statement, one \"current\" instant. Each operand compiles its own\n // temporal filter, so without this pin an INTERSECT/EXCEPT could bind two\n // clock samples microseconds apart and disagree about a row created between\n // them.\n const combined = withPinnedReadInstant(() =>\n compileSetOp(op, graphId, adapter, compileOperand, options_.vectorStrategy),\n );\n if (annIndexTypes.size > 0) {\n markAnnIndexScan(combined, [...annIndexTypes]);\n }\n return asCompiledSelectSql(combined);\n}\n\n/**\n * Builds the dialect adapter the compiler actually runs against,\n * applying a caller-supplied fulltext strategy override on top of the\n * dialect default. Returns the unmodified adapter when the override is\n * absent or identical to the dialect default — shipped backends always\n * set `fulltextStrategy`, so this short-circuit keeps the common path\n * from allocating a fresh adapter on every compile.\n */\nfunction resolveDialectAdapter(\n dialect: SqlDialect,\n fulltextStrategy: FulltextStrategy | undefined,\n): DialectAdapter {\n const baseAdapter = getDialect(dialect);\n if (\n fulltextStrategy === undefined ||\n fulltextStrategy === baseAdapter.fulltext\n ) {\n return baseAdapter;\n }\n return { ...baseAdapter, fulltext: fulltextStrategy };\n}\n\n/**\n * Reconciles the enclosing query's recorded-time pin with an EXISTS/IN\n * subquery's so the whole statement reads one coordinate, never a silent mix\n * of recorded and live tables. Symmetric with the uniformity guard on set\n * operations ({@link assertUniformSetOperationRecordedCoordinates}):\n *\n * - **Recorded outer, unpinned subquery** — propagate the outer pin so the\n * subquery reads the recorded relations as of the same instant (a subquery\n * built from the live store carries none and would otherwise cross the axis\n * and skip the current-index guard).\n * - **Recorded outer, differently-pinned subquery** — coordinate mismatch,\n * rejected.\n * - **Live outer, recorded subquery** — also a mismatch: the subquery would\n * read the recorded relations while the outer reads live tables. Rejected\n * rather than silently honored, the same way the set-operation guard rejects\n * a live ∪ recorded mix.\n */\nfunction inheritRecordedAsOf(\n subAst: QueryAst,\n recordedAsOf: string | undefined,\n): QueryAst {\n if (recordedAsOf === undefined) {\n if (subAst.recordedAsOf !== undefined) {\n throw recordedSubqueryCoordinateMismatch(\n \"Cannot nest a recorded-time subquery inside a live query without a recorded-time coordinate.\",\n );\n }\n return subAst;\n }\n if (subAst.recordedAsOf === undefined) return { ...subAst, recordedAsOf };\n if (subAst.recordedAsOf !== recordedAsOf) {\n throw recordedSubqueryCoordinateMismatch(\n \"Cannot nest a subquery with a different recorded-time coordinate than the enclosing query.\",\n );\n }\n return subAst;\n}\n\nfunction recordedSubqueryCoordinateMismatch(\n message: string,\n): ConfigurationError {\n return new ConfigurationError(\n message,\n { code: \"SUBQUERY_TEMPORAL_COORDINATE_MISMATCH\" },\n {\n suggestion:\n \"Build the subquery from the same Store or StoreView coordinate as the enclosing query.\",\n },\n );\n}\n\n/** Forwards compile options into recursive sub-compile calls. */\nfunction propagateOptions(options_: CompileQueryOptions): CompileQueryOptions {\n return {\n dialect: options_.dialect ?? \"sqlite\",\n ...(options_.schema === undefined ? {} : { schema: options_.schema }),\n ...(options_.fulltextStrategy === undefined ?\n {}\n : { fulltextStrategy: options_.fulltextStrategy }),\n ...(options_.vectorStrategy === undefined ?\n {}\n : { vectorStrategy: options_.vectorStrategy }),\n windowFunctions: options_.windowFunctions ?? true,\n ...(options_.vectorSlots === undefined ?\n {}\n : { vectorSlots: options_.vectorSlots }),\n ...(options_.fulltextLanguages === undefined ?\n {}\n : { fulltextLanguages: options_.fulltextLanguages }),\n ...(options_.recordedReadBinding === undefined ?\n {}\n : { recordedReadBinding: options_.recordedReadBinding }),\n ...(options_.readInstant === undefined ?\n {}\n : { readInstant: options_.readInstant }),\n };\n}\n\n// ============================================================\n// Standard Query Compilation\n// ============================================================\n\ntype CountAggregateFastPathPlan = Readonly<{\n traversal: QueryAst[\"traversals\"][number];\n /** Aggregate references `traversal.nodeAlias` (count of live target nodes). */\n requiresNodeCount: boolean;\n /** countDistinct over `traversal.nodeAlias`. */\n requiresNodeCountDistinct: boolean;\n /** Aggregate references `traversal.edgeAlias` (count of live edges). */\n requiresEdgeCount: boolean;\n /** countDistinct over `traversal.edgeAlias`. */\n requiresEdgeCountDistinct: boolean;\n}>;\n\nfunction resolveCountAggregateFastPath(\n ast: QueryAst,\n): CountAggregateFastPathPlan | undefined {\n if (ast.traversals.length !== 1) {\n return undefined;\n }\n\n if (ast.groupBy?.fields.length !== 1) {\n return undefined;\n }\n\n if (ast.having !== undefined) {\n return undefined;\n }\n\n if (\n ast.orderBy?.some((orderSpec) => orderSpec.field.alias !== ast.start.alias)\n ) {\n return undefined;\n }\n\n const traversal = requireDefined(ast.traversals[0]);\n if ((traversal.inverseEdgeKinds?.length ?? 0) > 0) {\n return undefined;\n }\n\n const groupField = requireDefined(ast.groupBy.fields[0]);\n if (groupField.alias !== ast.start.alias || !isIdFieldRef(groupField)) {\n return undefined;\n }\n\n let requiresNodeCount = false;\n let requiresNodeCountDistinct = false;\n let requiresEdgeCount = false;\n let requiresEdgeCountDistinct = false;\n\n for (const projectedField of ast.projection.fields) {\n const source = projectedField.source;\n\n if (!isAggregateExpr(source)) {\n if (source.alias !== ast.start.alias) {\n return undefined;\n }\n continue;\n }\n\n if (!isIdFieldRef(source.field)) {\n return undefined;\n }\n\n const isNodeTarget = source.field.alias === traversal.nodeAlias;\n const isEdgeTarget = source.field.alias === traversal.edgeAlias;\n if (!isNodeTarget && !isEdgeTarget) {\n return undefined;\n }\n\n if (source.function === \"count\") {\n if (isNodeTarget) requiresNodeCount = true;\n else requiresEdgeCount = true;\n continue;\n }\n\n if (source.function === \"countDistinct\") {\n if (isNodeTarget) requiresNodeCountDistinct = true;\n else requiresEdgeCountDistinct = true;\n continue;\n }\n\n return undefined;\n }\n\n if (\n !requiresNodeCount &&\n !requiresNodeCountDistinct &&\n !requiresEdgeCount &&\n !requiresEdgeCountDistinct\n ) {\n return undefined;\n }\n\n return {\n traversal,\n requiresNodeCount,\n requiresNodeCountDistinct,\n requiresEdgeCount,\n requiresEdgeCountDistinct,\n };\n}\n\nfunction compileCountAggregateFastPath(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n logicalPlan: LogicalPlan,\n requiredColumnsByAlias: RequiredColumnsByAlias | undefined,\n predicateIndex: PredicateIndex,\n temporalFilterPass: TemporalFilterPass,\n): SqlFragment | undefined {\n const plan = resolveCountAggregateFastPath(ast);\n if (!plan) {\n return undefined;\n }\n\n const {\n traversal,\n requiresNodeCount,\n requiresNodeCountDistinct,\n requiresEdgeCount,\n requiresEdgeCountDistinct,\n } = plan;\n const { dialect } = ctx;\n const startAlias = ast.start.alias;\n const previousAlias = traversal.joinFromAlias;\n const previousAliasIdColumn = `${previousAlias}_id`;\n const previousAliasKindColumn = `${previousAlias}_kind`;\n const countCteAlias = `cte_${traversal.nodeAlias}_counts`;\n const nodeCountColumn = `${traversal.nodeAlias}_count`;\n const nodeCountDistinctColumn = `${traversal.nodeAlias}_count_distinct`;\n const edgeCountColumn = `${traversal.edgeAlias}_count`;\n const edgeCountDistinctColumn = `${traversal.edgeAlias}_count_distinct`;\n\n const previousNodeKinds = getNodeKindsForAlias(ast, traversal.joinFromAlias);\n const edgeKinds = [...new Set(traversal.edgeKinds)];\n const nodeKinds = traversal.nodeKinds;\n\n const edgeTemporalFilter = temporalFilterPass.forAlias(\"e\");\n const nodeTemporalFilter = temporalFilterPass.forAlias(\"n\");\n\n const nodePredicateContext: PredicateCompilerContext = {\n ...ctx,\n cteColumnPrefix: \"n\",\n };\n const nodePredicateClauses = compilePredicateClauses(\n getPredicatesForAlias(predicateIndex, traversal.nodeAlias, \"node\"),\n nodePredicateContext,\n );\n\n const edgePredicateContext: PredicateCompilerContext = {\n ...ctx,\n cteColumnPrefix: \"e\",\n };\n const edgePredicateClauses = compilePredicateClauses(\n getPredicatesForAlias(predicateIndex, traversal.edgeAlias, \"edge\"),\n edgePredicateContext,\n );\n\n const joinField = traversal.direction === \"out\" ? \"from_id\" : \"to_id\";\n const targetField = traversal.direction === \"out\" ? \"to_id\" : \"from_id\";\n const joinKindField = traversal.direction === \"out\" ? \"from_kind\" : \"to_kind\";\n const targetKindField =\n traversal.direction === \"out\" ? \"to_kind\" : \"from_kind\";\n\n // The target-node join is only needed when an aggregate actually counts\n // live target nodes. For edge-only counts (countEdges / countDistinctEdges)\n // the edge row alone is sufficient: the edge's own deleted_at and valid_*\n // columns already constrain \"live edge,\" and target-kind validation is\n // enforced via the edge's to_kind filter (which the store's write path\n // keeps consistent with the target node's kind at insert time).\n const hasNodePredicates = nodePredicateClauses.length > 0;\n const requiresNodeJoin =\n requiresNodeCount || requiresNodeCountDistinct || hasNodePredicates;\n\n // Join style depends on how the target-node join interacts with the\n // aggregates:\n //\n // - INNER JOIN when the user applied a predicate to the target alias\n // (whereNode on the target). Predicates should constrain every\n // aggregate in the query — including countEdges — so they live in\n // WHERE and the JOIN filters edges whose targets fail to match.\n // With INNER JOIN, a group where every edge's target fails the\n // predicate produces no rows; GROUP BY omits it, and required\n // traversals correctly drop that start row.\n //\n // - LEFT JOIN when only temporal/deleted filters apply (no caller\n // predicates). This lets mixed aggregates differ: countEdges\n // counts all live edges (including edges to expired targets)\n // while count(target) only counts edges to live targets.\n const useInnerJoin = hasNodePredicates;\n\n const whereClauses = [\n sql`e.graph_id = ${graphId}`,\n compileKindFilter(sql.raw(\"e.kind\"), edgeKinds),\n compileKindFilter(sql.raw(`e.${joinKindField}`), previousNodeKinds),\n compileKindFilter(sql.raw(`e.${targetKindField}`), nodeKinds),\n edgeTemporalFilter,\n ...edgePredicateClauses,\n // INNER JOIN mode: node-side filters in WHERE constrain every aggregate.\n ...(requiresNodeJoin && useInnerJoin ?\n [\n compileKindFilter(sql.raw(\"n.kind\"), nodeKinds),\n nodeTemporalFilter,\n ...nodePredicateClauses,\n ]\n : []),\n ];\n\n const nodeJoinOnClauses =\n requiresNodeJoin ?\n useInnerJoin ?\n // INNER JOIN: only the key conditions; filters live in WHERE.\n [\n sql`n.graph_id = e.graph_id`,\n sql`n.id = e.${sql.raw(targetField)}`,\n sql`n.kind = e.${sql.raw(targetKindField)}`,\n ]\n // LEFT JOIN: temporal/kind filters gate the join, so countEdges\n // still sees the full edge set while count(target) excludes edges\n // to expired targets (via COUNT ignoring NULLs).\n : [\n sql`n.graph_id = e.graph_id`,\n sql`n.id = e.${sql.raw(targetField)}`,\n sql`n.kind = e.${sql.raw(targetKindField)}`,\n compileKindFilter(sql.raw(\"n.kind\"), nodeKinds),\n nodeTemporalFilter,\n ]\n : [];\n\n const aggregateColumns: SqlFragment[] = [];\n if (requiresNodeCount) {\n aggregateColumns.push(sql`COUNT(n.id) AS ${sql.raw(nodeCountColumn)}`);\n }\n if (requiresNodeCountDistinct) {\n aggregateColumns.push(\n sql`COUNT(DISTINCT n.id) AS ${sql.raw(nodeCountDistinctColumn)}`,\n );\n }\n if (requiresEdgeCount) {\n aggregateColumns.push(sql`COUNT(e.id) AS ${sql.raw(edgeCountColumn)}`);\n }\n if (requiresEdgeCountDistinct) {\n aggregateColumns.push(\n sql`COUNT(DISTINCT e.id) AS ${sql.raw(edgeCountDistinctColumn)}`,\n );\n }\n\n // LIMIT push-down: when the outer SELECT applies LIMIT/OFFSET that do not\n // depend on aggregate results, we can reduce the start CTE to just the\n // required rows before aggregation. This turns an O(|start|) GROUP BY\n // into an O(limit) GROUP BY.\n //\n // Safe when:\n // - The traversal is optional (LEFT JOIN outer). For INNER JOIN we can't\n // push down without potentially dropping rows the original query would\n // have kept.\n // - No ORDER BY of either kind. ORDER BY over the full result requires\n // the full result. `ast.orderBy` is FieldRef-based row ordering (the\n // fast path already restricts it to the start alias, but we still\n // need every row to sort correctly); `ast.aggregateOrderBy` is\n // output-alias-based ordering added via `ExecutableAggregateQuery\n // .orderBy()` — sorting by an aggregate value (e.g. `employeeCount`)\n // needs every start row counted first, so pushing LIMIT into the\n // start CTE before aggregation would pick an arbitrary subset of\n // rows to count rather than the true top-N.\n // - LIMIT is defined. OFFSET is carried with it.\n const startCteLimit =\n (\n traversal.optional &&\n ast.orderBy === undefined &&\n ast.aggregateOrderBy === undefined &&\n ast.limit !== undefined\n ) ?\n { limit: ast.limit, offset: ast.offset }\n : undefined;\n\n const startCte = buildStandardStartCte({\n ast,\n ctx,\n graphId,\n predicateIndex,\n requiredColumnsByAlias,\n temporalFilterPass,\n ...(startCteLimit === undefined ? {} : { limitOffset: startCteLimit }),\n });\n\n const targetNodeJoinKeyword = useInnerJoin ? \"JOIN\" : \"LEFT JOIN\";\n const targetNodeJoin =\n requiresNodeJoin ?\n sql`\n ${sql.raw(targetNodeJoinKeyword)} ${ctx.schema.nodesTable} n ON ${sql.join(nodeJoinOnClauses, sql` AND `)}\n `\n : sql``;\n\n const countCte = sql`\n ${sql.raw(countCteAlias)} AS (\n SELECT\n cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasIdColumn)} AS ${sql.raw(previousAliasIdColumn)},\n cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasKindColumn)} AS ${sql.raw(previousAliasKindColumn)},\n ${sql.join(aggregateColumns, sql`, `)}\n FROM cte_${sql.raw(previousAlias)}\n JOIN ${ctx.schema.edgesTable} e ON cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasIdColumn)} = e.${sql.raw(joinField)}\n AND cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasKindColumn)} = e.${sql.raw(joinKindField)}${targetNodeJoin}\n WHERE ${sql.join(whereClauses, sql` AND `)}\n GROUP BY\n cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasIdColumn)},\n cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasKindColumn)}\n )\n `;\n\n function resolveCountColumn(source: AggregateExpr): string {\n const isEdge = source.field.alias === traversal.edgeAlias;\n if (source.function === \"countDistinct\") {\n return isEdge ? edgeCountDistinctColumn : nodeCountDistinctColumn;\n }\n return isEdge ? edgeCountColumn : nodeCountColumn;\n }\n\n const projection = sql.join(\n ast.projection.fields.map((projectedField) => {\n const source = projectedField.source;\n\n if (!isAggregateExpr(source)) {\n const value = compileFieldValue(\n source,\n dialect,\n source.valueType,\n `cte_${source.alias}`,\n );\n return sql`${value} AS ${quoteIdentifier(projectedField.outputName)}`;\n }\n\n const projectedCountColumn = resolveCountColumn(source);\n const countValue = sql`${sql.raw(countCteAlias)}.${sql.raw(projectedCountColumn)}`;\n const aggregateValue =\n traversal.optional ? sql`COALESCE(${countValue}, 0)` : countValue;\n\n return sql`${aggregateValue} AS ${quoteIdentifier(projectedField.outputName)}`;\n }),\n sql`, `,\n );\n\n const joinType = traversal.optional ? \"LEFT JOIN\" : \"INNER JOIN\";\n const fromClause = sql`\n FROM cte_${sql.raw(startAlias)}\n ${sql.raw(joinType)} ${sql.raw(countCteAlias)}\n ON ${sql.raw(countCteAlias)}.${sql.raw(previousAliasIdColumn)} = cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasIdColumn)}\n AND ${sql.raw(countCteAlias)}.${sql.raw(previousAliasKindColumn)} = cte_${sql.raw(previousAlias)}.${sql.raw(previousAliasKindColumn)}\n `;\n\n // Also picks up `ast.aggregateOrderBy` (ORDER BY output-alias entries\n // added via `ExecutableAggregateQuery.orderBy()`) with no extra handling\n // here: the fast path's projection above always re-aliases every\n // projected column to its final output name, so an alias reference\n // resolves the same way it would on the general query path.\n const orderBy = buildStandardOrderBy({ ast, dialect });\n // When the LIMIT/OFFSET was pushed into the start CTE, the outer SELECT\n // must not re-apply it — the start CTE already produced exactly the\n // requested page, and the outer LEFT JOIN preserves its cardinality.\n // Re-applying would double-offset and produce an empty page. Rewrite\n // the logical plan to match: the emitter asserts plan shape aligns\n // with emitted SQL, so dropping the clause and leaving the plan's\n // `limit_offset` node behind would trip an invariant.\n const emittedLogicalPlan =\n startCteLimit === undefined ? logicalPlan : (\n stripLimitOffsetFromPlan(logicalPlan)\n );\n const limitOffset =\n startCteLimit === undefined ?\n buildLimitOffsetClause({ limit: ast.limit, offset: ast.offset })\n : undefined;\n\n return emitStandardQuerySql({\n ctes: [startCte, countCte],\n fromClause,\n ...(orderBy === undefined ? {} : { orderBy }),\n ...(limitOffset === undefined ? {} : { limitOffset }),\n logicalPlan: emittedLogicalPlan,\n projection,\n });\n}\n\n/**\n * Returns a copy of the logical plan with every `limit_offset` node\n * elided. Used when the count aggregate fast path pushes LIMIT/OFFSET\n * into the start CTE — the outer SELECT then carries no LIMIT/OFFSET,\n * so the logical plan must not either or the emitter invariant check\n * will disagree with the emitted SQL.\n */\nfunction stripLimitOffsetFromPlan(plan: LogicalPlan): LogicalPlan {\n return { ...plan, root: stripLimitOffsetFromPlanNode(plan.root) };\n}\n\nfunction stripLimitOffsetFromPlanNode(node: LogicalPlanNode): LogicalPlanNode {\n if (node.op === \"limit_offset\") {\n return stripLimitOffsetFromPlanNode(node.input);\n }\n if (\"input\" in node) {\n return { ...node, input: stripLimitOffsetFromPlanNode(node.input) };\n }\n return node;\n}\n\n/**\n * The start CTE followed by one CTE per traversal — the candidate-set prefix\n * shared by the flat plan and the late-materialization plan (which feeds it a\n * lean AST/column set and no per-traversal limit).\n */\nfunction buildStandardStartAndTraversalCtes(\n input: Readonly<{\n ast: QueryAst;\n carryForwardPreviousColumns: boolean;\n ctx: PredicateCompilerContext;\n graphId: string;\n predicateIndex: PredicateIndex;\n requiredColumnsByAlias: RequiredColumnsByAlias | undefined;\n temporalFilterPass: TemporalFilterPass;\n traversalLimit: number | undefined;\n }>,\n): SqlFragment[] {\n const {\n ast,\n carryForwardPreviousColumns,\n ctx,\n graphId,\n predicateIndex,\n requiredColumnsByAlias,\n temporalFilterPass,\n traversalLimit,\n } = input;\n const ctes: SqlFragment[] = [\n buildStandardStartCte({\n ast,\n ctx,\n graphId,\n predicateIndex,\n requiredColumnsByAlias,\n temporalFilterPass,\n }),\n ];\n for (let index = 0; index < ast.traversals.length; index++) {\n ctes.push(\n buildStandardTraversalCte({\n ast,\n carryForwardPreviousColumns,\n ctx,\n graphId,\n materializeCte: shouldMaterializeTraversalCte(\n ctx.dialect,\n ast.traversals.length,\n index,\n ),\n predicateIndex,\n requiredColumnsByAlias,\n temporalFilterPass,\n traversalIndex: index,\n traversalLimit,\n }),\n );\n }\n return ctes;\n}\n\ntype LateMaterializationPlan = Readonly<{\n leanAst: QueryAst;\n limit: number;\n offset: number | undefined;\n}>;\n\n/**\n * A selective field that resolves to a node's identity (`id`/`kind`) — already\n * carried in the topK CTE, so it needs no deferred re-fetch.\n */\nfunction selectiveFieldIsIdentity(field: SelectiveField): boolean {\n if (!field.isSystemField) {\n return false;\n }\n const column = mapSelectiveSystemFieldToColumn(field.field);\n return column === \"id\" || column === \"kind\";\n}\n\n/**\n * Decides whether a query is eligible for late materialization and, if so,\n * produces the lean AST whose CTEs carry only identity, ordering, and predicate\n * columns. Returns undefined (fall back to the flat plan) for anything outside\n * the v1 envelope — see the inline gates.\n */\nfunction resolveLateMaterializationPlan(\n ast: QueryAst,\n): LateMaterializationPlan | undefined {\n // Recorded-time reads swap `ctx.schema.nodesTable` to the recorded history\n // relation (see `recordedReadSchemaFor`), where `(graph_id, kind, id)` is\n // NOT unique — one row per recorded interval. The outer re-fetch joins on\n // exactly that key with no temporal predicate, so it would match every\n // historical version of each survivor (duplicate rows, stale props).\n if (ast.recordedAsOf !== undefined) {\n return undefined;\n }\n\n // v1 targets the selective `.select()` path. The non-selective path would\n // have to carry the full `props` blob into the lean CTE to order by a prop,\n // which defeats the deferral — left to a follow-up.\n const selectiveFields = ast.selectiveFields;\n if (selectiveFields === undefined || selectiveFields.length === 0) {\n return undefined;\n }\n\n // The transform only pays off when rows past the LIMIT are discarded before\n // their deferred columns are materialized — so both ORDER BY and a positive\n // LIMIT must be present.\n const orderBy = ast.orderBy;\n if (orderBy === undefined || orderBy.length === 0) {\n return undefined;\n }\n if (ast.limit === undefined || ast.limit <= 0) {\n return undefined;\n }\n\n // Aggregation owns the count fast path / group-by shape, not this transform.\n if (ast.groupBy !== undefined || ast.having !== undefined) {\n return undefined;\n }\n if (ast.aggregateOrderBy !== undefined && ast.aggregateOrderBy.length > 0) {\n return undefined;\n }\n\n // Optional (LEFT JOIN) traversals yield NULL-identity candidate rows that the\n // outer identity re-join would drop. Out of v1 scope.\n if (ast.traversals.some((traversal) => traversal.optional)) {\n return undefined;\n }\n\n const nodeAliases = new Set<string>([\n ast.start.alias,\n ...ast.traversals.map((traversal) => traversal.nodeAlias),\n ]);\n\n // Every projected and ordered field must resolve to a node alias — edge\n // fields live in the traversal CTE keyed differently, a follow-up.\n for (const field of selectiveFields) {\n if (!nodeAliases.has(field.alias)) {\n return undefined;\n }\n }\n for (const orderSpec of orderBy) {\n if (!nodeAliases.has(orderSpec.field.alias)) {\n return undefined;\n }\n }\n\n // Sort-key props fields must stay in the lean CTE so the topK can order by\n // them; everything else non-identity is deferred to the outer re-fetch.\n const orderReferenced = new Set<SelectiveField>();\n for (const orderSpec of orderBy) {\n const matched = findSelectivePropsFieldForFieldRef(\n selectiveFields,\n orderSpec.field,\n );\n if (matched !== undefined) {\n orderReferenced.add(matched);\n }\n }\n\n // Worth doing only if some projected column is genuinely deferrable: a\n // non-identity field that isn't already carried as a sort key.\n const hasDeferredColumn = selectiveFields.some(\n (field) => !selectiveFieldIsIdentity(field) && !orderReferenced.has(field),\n );\n if (!hasDeferredColumn) {\n return undefined;\n }\n\n const prunedSelectiveFields = selectiveFields.filter(\n (field) => field.isSystemField || orderReferenced.has(field),\n );\n\n return {\n leanAst: { ...ast, selectiveFields: prunedSelectiveFields },\n limit: ast.limit,\n offset: ast.offset,\n };\n}\n\n/**\n * The outer FROM clause: the topK CTE joined to the physical node table for each\n * projected alias, keyed on `(graph_id, kind, id)`. Sound only because that key\n * is the live nodes PK (one row per identity, the exact row the topK already\n * validated for temporal/soft-delete visibility). Recorded-time reads are gated\n * out in `resolveLateMaterializationPlan` — under a recorded pin `nodesTable`\n * is the history relation where this key matches every version.\n */\nfunction buildLateMaterializedOuterFromClause(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): SqlFragment {\n const topk = sql.raw(LATE_MAT_TOPK_CTE_ALIAS);\n const joins = lateMaterializedProjectedNodeAliases(ast).map((alias) => {\n const physical = sql.raw(lateMaterializedPhysicalAlias(alias));\n return sql`JOIN ${ctx.schema.nodesTable} ${physical} ON ${physical}.graph_id = ${graphId} AND ${physical}.kind = ${topk}.${sql.raw(`${alias}_kind`)} AND ${physical}.id = ${topk}.${sql.raw(`${alias}_id`)}`;\n });\n return joins.length === 0 ?\n sql`FROM ${topk}`\n : sql`FROM ${topk} ${sql.join(joins, sql` `)}`;\n}\n\nfunction compileLateMaterializedQuery(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n logicalPlan: LogicalPlan,\n predicateIndex: PredicateIndex,\n temporalFilterPass: TemporalFilterPass,\n collapsedTraversalCteAlias: string | undefined,\n shouldCollapseSelectiveTraversalRowset: boolean,\n): SqlFragment | undefined {\n const plan = resolveLateMaterializationPlan(ast);\n if (plan === undefined) {\n return undefined;\n }\n\n const { leanAst, limit, offset } = plan;\n const { dialect } = ctx;\n const leanRequiredColumns = collectRequiredColumnsByAlias(leanAst, {\n includeProjection: false,\n });\n\n const ctes = buildStandardStartAndTraversalCtes({\n ast: leanAst,\n carryForwardPreviousColumns: shouldCollapseSelectiveTraversalRowset,\n ctx,\n graphId,\n predicateIndex,\n requiredColumnsByAlias: leanRequiredColumns,\n temporalFilterPass,\n traversalLimit: undefined,\n });\n ctes.push(\n buildLateMaterializedTopKCte({\n ast: leanAst,\n dialect,\n fromClause: buildStandardFromClause({\n ast: leanAst,\n ...(collapsedTraversalCteAlias === undefined ?\n {}\n : { collapsedTraversalCteAlias }),\n }),\n limit,\n offset,\n ...(collapsedTraversalCteAlias === undefined ?\n {}\n : { collapsedTraversalCteAlias }),\n }),\n );\n\n const orderBy = buildLateMaterializedOuterOrderBy(ast);\n return emitStandardQuerySql({\n ctes,\n fromClause: buildLateMaterializedOuterFromClause(ast, graphId, ctx),\n ...(orderBy === undefined ? {} : { orderBy }),\n logicalPlan: stripLimitOffsetFromPlan(logicalPlan),\n projection: buildLateMaterializedOuterProjection(ast, dialect),\n });\n}\n\n/**\n * Compiles a standard (non-recursive) query to SQL using CTEs.\n */\ntype StandardQueryStrategyHandler = (\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n) => SqlFragment;\n\nconst STANDARD_QUERY_STRATEGY_HANDLERS: Record<\n DialectStandardQueryStrategy,\n StandardQueryStrategyHandler\n> = {\n cte_project: compileStandardQueryWithCteStrategy,\n};\n\nfunction compileStandardQuery(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): SqlFragment {\n const strategy = ctx.dialect.capabilities.standardQueryStrategy;\n const handler = STANDARD_QUERY_STRATEGY_HANDLERS[strategy];\n return handler(ast, graphId, ctx);\n}\n\ntype SelectStandardOrderByInput = Readonly<{\n ast: QueryAst;\n collapsedTraversalCteAlias: string | undefined;\n dialect: DialectAdapter;\n fulltextPredicate: FulltextMatchPredicate | undefined;\n fusion: HybridFusionOptions | undefined;\n vectorPredicate: VectorSimilarityPredicate | undefined;\n}>;\n\nfunction selectStandardOrderBy(\n input: SelectStandardOrderByInput,\n): SqlFragment | undefined {\n const {\n ast,\n collapsedTraversalCteAlias,\n dialect,\n fulltextPredicate,\n fusion,\n vectorPredicate,\n } = input;\n if (vectorPredicate && fulltextPredicate) {\n return buildStandardHybridRrfOrderBy({ ast, dialect, fusion });\n }\n if (vectorPredicate) {\n return buildStandardVectorOrderBy({ ast, dialect });\n }\n if (fulltextPredicate) {\n return buildStandardFulltextOrderBy({ ast, dialect });\n }\n return buildStandardOrderBy({\n ast,\n ...(collapsedTraversalCteAlias === undefined ?\n {}\n : { collapsedTraversalCteAlias }),\n dialect,\n });\n}\n\nfunction selectWindowFunctionOperation(\n vectorPredicate: VectorSimilarityPredicate | undefined,\n fulltextPredicate: FulltextMatchPredicate | undefined,\n): string {\n if (vectorPredicate !== undefined && fulltextPredicate !== undefined) {\n return \"hybrid relevance ranking\";\n }\n if (vectorPredicate !== undefined) return \"vector relevance ranking\";\n return \"fulltext relevance ranking\";\n}\n\nfunction assertWindowFunctionsSupported(\n ctx: PredicateCompilerContext,\n operation: string,\n): void {\n if (ctx.windowFunctions) return;\n\n throw new ConfigurationError(\n `${operation} requires SQL window functions, but this backend profile declares windowFunctions: false.`,\n {\n capability: \"windowFunctions\",\n operation,\n windowFunctions: false,\n },\n {\n suggestion:\n \"Use a backend profile that supports SQL window functions, or avoid this query shape.\",\n },\n );\n}\n\nfunction compileStandardQueryWithCteStrategy(\n ast: QueryAst,\n graphId: string,\n ctx: PredicateCompilerContext,\n): SqlFragment {\n const { dialect } = ctx;\n const {\n collapsedTraversalCteAlias,\n effectiveLimit,\n fulltextPredicate,\n fusion,\n logicalPlan,\n predicateIndex,\n requiredColumnsByAlias,\n shouldCollapseSelectiveTraversalRowset,\n temporalFilterPass,\n traversalCteLimit,\n vectorPredicate,\n } = runStandardQueryPassPipeline(ast, graphId, ctx);\n\n if (temporalFilterPass === undefined) {\n throw new CompilerInvariantError(\n \"Temporal filter pass did not initialize temporal state\",\n { phase: \"standard-pass-pipeline\" },\n );\n }\n if (logicalPlan === undefined) {\n throw new CompilerInvariantError(\n \"Logical plan pass did not initialize plan state\",\n { phase: \"standard-pass-pipeline\" },\n );\n }\n\n if (vectorPredicate !== undefined || fulltextPredicate !== undefined) {\n assertWindowFunctionsSupported(\n ctx,\n selectWindowFunctionOperation(vectorPredicate, fulltextPredicate),\n );\n }\n\n if (!vectorPredicate && !fulltextPredicate) {\n const fastPathSql = compileCountAggregateFastPath(\n ast,\n graphId,\n ctx,\n logicalPlan,\n requiredColumnsByAlias,\n predicateIndex,\n temporalFilterPass,\n );\n if (fastPathSql) {\n return fastPathSql;\n }\n\n const lateMaterializedSql = compileLateMaterializedQuery(\n ast,\n graphId,\n ctx,\n logicalPlan,\n predicateIndex,\n temporalFilterPass,\n collapsedTraversalCteAlias,\n shouldCollapseSelectiveTraversalRowset,\n );\n if (lateMaterializedSql) {\n return lateMaterializedSql;\n }\n }\n\n // Start + traversal candidate CTEs\n const ctes = buildStandardStartAndTraversalCtes({\n ast,\n carryForwardPreviousColumns: shouldCollapseSelectiveTraversalRowset,\n ctx,\n graphId,\n predicateIndex,\n requiredColumnsByAlias,\n temporalFilterPass,\n traversalLimit: traversalCteLimit,\n });\n\n // Add embeddings CTE if vector similarity is used\n if (vectorPredicate) {\n const nodeKinds = getNodeKindsForAlias(ast, vectorPredicate.field.alias);\n ctes.push(\n buildStandardEmbeddingsCte({\n ctx,\n graphId,\n nodeKinds,\n vectorPredicate,\n }),\n );\n }\n\n // Add fulltext CTE if a matches() predicate is used\n if (fulltextPredicate) {\n const nodeKinds = getNodeKindsForAlias(ast, fulltextPredicate.field.alias);\n ctes.push(\n buildStandardFulltextCte({\n ctx,\n fulltextPredicate,\n graphId,\n nodeKinds,\n }),\n );\n }\n\n if (getHybridTargetAlias(vectorPredicate, fulltextPredicate) !== undefined) {\n ctes.push(buildStandardHybridCandidateCte());\n }\n\n // Build main SELECT\n const projection = buildStandardProjection({\n ast,\n ...(collapsedTraversalCteAlias === undefined ?\n {}\n : { collapsedTraversalCteAlias }),\n dialect,\n });\n const fromClause = buildStandardFromClause({\n ast,\n ...(collapsedTraversalCteAlias === undefined ?\n {}\n : { collapsedTraversalCteAlias }),\n ...(vectorPredicate === undefined ? {} : { vectorPredicate }),\n ...(fulltextPredicate === undefined ? {} : { fulltextPredicate }),\n });\n const groupBy = buildStandardGroupBy({ ast, dialect });\n const having = buildStandardHaving({ ast, ctx });\n\n const orderBy = selectStandardOrderBy({\n ast,\n collapsedTraversalCteAlias,\n dialect,\n fulltextPredicate,\n fusion,\n vectorPredicate,\n });\n\n const limitOffset = buildLimitOffsetClause({\n limit: effectiveLimit,\n offset: ast.offset,\n });\n\n return emitStandardQuerySql({\n ctes,\n fromClause,\n ...(groupBy === undefined ? {} : { groupBy }),\n ...(having === undefined ? {} : { having }),\n ...(orderBy === undefined ? {} : { orderBy }),\n ...(limitOffset === undefined ? {} : { limitOffset }),\n logicalPlan,\n projection,\n });\n}\n","/**\n * Path utilities for variable-length traversal results.\n *\n * SQLite doesn't support native arrays, so paths are stored as pipe-delimited\n * strings: \"|id1|id2|id3|\". PostgreSQL returns native arrays.\n */\nimport {\n PG_ARRAY_END,\n PG_ARRAY_START,\n PG_PATH_ELEMENT_SEPARATOR,\n SQLITE_PATH_DELIMITER,\n} from \"../constants\";\n\n/**\n * Parses a SQLite path string into an array of node IDs.\n *\n * @param path - Pipe-delimited path string like \"|id1|id2|id3|\"\n * @returns Array of node IDs like [\"id1\", \"id2\", \"id3\"]\n *\n * @example\n * parseSqlitePath(\"|abc|def|ghi|\") // [\"abc\", \"def\", \"ghi\"]\n * parseSqlitePath(\"|single|\") // [\"single\"]\n * parseSqlitePath(\"||\") // []\n */\nexport function parseSqlitePath(path: string): readonly string[] {\n const emptyPath = `${SQLITE_PATH_DELIMITER}${SQLITE_PATH_DELIMITER}`;\n if (!path || path === emptyPath) return [];\n\n // Remove leading and trailing pipes, then split\n const trimmed = path.slice(1, -1);\n if (trimmed === \"\") return [];\n\n return trimmed.split(SQLITE_PATH_DELIMITER);\n}\n\n/**\n * Type guard to check if a value is a SQLite path string.\n * SQLite paths start and end with \"|\".\n */\nexport function isSqlitePath(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.startsWith(SQLITE_PATH_DELIMITER) &&\n value.endsWith(SQLITE_PATH_DELIMITER)\n );\n}\n\n/**\n * Normalizes a path value to an array.\n * - If already an array (PostgreSQL native), returns as-is\n * - If a SQLite path string (|id1|id2|), parses it\n * - If a PostgreSQL text array ({id1,id2}), parses it\n * - Otherwise returns empty array\n */\nexport function normalizePath(value: unknown): readonly string[] {\n if (Array.isArray(value)) {\n return value as string[];\n }\n if (isSqlitePath(value)) {\n return parseSqlitePath(value);\n }\n if (isPostgresTextArray(value)) {\n return parsePostgresTextArray(value);\n }\n return [];\n}\n\n/**\n * Type guard for PostgreSQL text array format: {id1,id2,id3}\n */\nfunction isPostgresTextArray(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.startsWith(PG_ARRAY_START) &&\n value.endsWith(PG_ARRAY_END)\n );\n}\n\n/**\n * Parses a PostgreSQL text array string into an array of strings.\n * Input format: {id1,id2,id3} or {} for empty.\n */\nfunction parsePostgresTextArray(value: string): readonly string[] {\n const inner = value.slice(1, -1);\n if (inner === \"\") return [];\n return inner.split(PG_PATH_ELEMENT_SEPARATOR);\n}\n","/**\n * Result mapping utilities for query execution.\n *\n * Transforms raw database rows into typed SelectContext and result objects.\n */\nimport { type NodeType } from \"../../core/types\";\nimport { normalizePath } from \"../../utils\";\nimport { type Traversal } from \"../ast\";\nimport type {\n AliasMap,\n EdgeAliasMap,\n QueryBuilderState,\n RecursiveAliasMap,\n SelectableEdge,\n SelectableNode,\n SelectContext,\n} from \"../builder/types\";\nimport { type SqlDialect } from \"../dialect/types\";\n\n/**\n * Transforms SQLite path columns from pipe-delimited strings to arrays.\n * PostgreSQL returns native arrays, so no transformation needed.\n */\nexport function transformPathColumns(\n rows: readonly Record<string, unknown>[],\n state: QueryBuilderState,\n _dialect: SqlDialect,\n): readonly Record<string, unknown>[] {\n // Find path columns from variable-length traversals\n const pathAliases: string[] = [];\n for (const traversal of state.traversals) {\n if (traversal.variableLength?.pathAlias !== undefined) {\n pathAliases.push(traversal.variableLength.pathAlias);\n }\n }\n\n if (pathAliases.length === 0) return rows;\n\n const result: Record<string, unknown>[] = [];\n let changed = false;\n for (const row of rows) {\n let transformed: Record<string, unknown> | undefined;\n for (const alias of pathAliases) {\n const value = row[alias];\n if (value !== undefined && !Array.isArray(value)) {\n transformed ??= { ...row };\n transformed[alias] = normalizePath(value);\n }\n }\n if (transformed === undefined) {\n result.push(row);\n } else {\n changed = true;\n result.push(transformed);\n }\n }\n // Preserve reference identity when no rows were transformed\n return changed ? result : rows;\n}\n\n// Reserved keys that cannot be overwritten by user props\nconst RESERVED_NODE_KEYS = new Set([\"id\", \"kind\", \"meta\"]);\nconst RESERVED_EDGE_KEYS = new Set([\"id\", \"kind\", \"fromId\", \"toId\", \"meta\"]);\n\n/**\n * Converts null to undefined for consistent typing.\n * Database backends return null for missing values, but our types use undefined.\n */\nfunction nullToUndefined<T>(value: T | null | undefined): T | undefined {\n return value === null ? undefined : value;\n}\n\n/**\n * Assigns props to a target object, excluding reserved keys to prevent runtime\n * collisions with system fields (id, kind, meta, etc).\n */\nfunction assignPropsExcludingReserved(\n target: Record<string, unknown>,\n props: Record<string, unknown>,\n reservedKeys: Set<string>,\n): void {\n for (const [key, value] of Object.entries(props)) {\n if (!reservedKeys.has(key)) {\n target[key] = value;\n }\n }\n}\n\n/**\n * Builds a SelectableNode from row data for a given alias.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys (id, kind, meta) in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n */\nexport function buildSelectableNode(\n row: Record<string, unknown>,\n alias: string,\n): SelectableNode<NodeType> {\n const id = row[`${alias}_id`] as string;\n const kind = row[`${alias}_kind`] as string;\n const propsRaw: unknown = row[`${alias}_props`];\n const rawProps: Record<string, unknown> =\n typeof propsRaw === \"string\" ?\n (JSON.parse(propsRaw) as Record<string, unknown>)\n : ((propsRaw as Record<string, unknown> | undefined) ?? {});\n\n // Metadata columns - these are now always projected in CTEs\n // Normalize null → undefined for optional fields\n const version = row[`${alias}_version`] as number;\n const validFrom = nullToUndefined(\n row[`${alias}_valid_from`] as string | null,\n );\n const validTo = nullToUndefined(row[`${alias}_valid_to`] as string | null);\n const createdAt = row[`${alias}_created_at`] as string;\n const updatedAt = row[`${alias}_updated_at`] as string;\n const deletedAt = nullToUndefined(\n row[`${alias}_deleted_at`] as string | null,\n );\n\n const result: Record<string, unknown> = {\n id,\n kind,\n meta: {\n version,\n validFrom,\n validTo,\n createdAt,\n updatedAt,\n deletedAt,\n },\n };\n\n assignPropsExcludingReserved(result, rawProps, RESERVED_NODE_KEYS);\n return result as SelectableNode<NodeType>;\n}\n\n/**\n * Builds a SelectableNode from row data, returning undefined when the node\n * doesn't exist (for optional traversals with LEFT JOIN).\n */\nfunction buildSelectableNodeOrUndefined(\n row: Record<string, unknown>,\n alias: string,\n): SelectableNode<NodeType> | undefined {\n const id = row[`${alias}_id`] as string | null | undefined;\n if (id === null || id === undefined) {\n return undefined;\n }\n return buildSelectableNode(row, alias);\n}\n\n/**\n * Builds a SelectableEdge from row data for a given edge alias.\n *\n * Props are spread at top level, metadata goes under `meta`.\n * Reserved keys (id, kind, fromId, toId, meta) in props are filtered out to prevent collisions.\n * Null values from database are normalized to undefined.\n * Returns undefined if the edge doesn't exist (for optional traversals with LEFT JOIN).\n */\nfunction buildSelectableEdge(\n row: Record<string, unknown>,\n alias: string,\n): SelectableEdge | undefined {\n const id = row[`${alias}_id`] as string | null | undefined;\n\n // For optional traversals, edge may be null (LEFT JOIN)\n if (id === null || id === undefined) {\n return undefined;\n }\n\n const kind = row[`${alias}_kind`] as string;\n const fromId = row[`${alias}_from_id`] as string;\n const toId = row[`${alias}_to_id`] as string;\n\n const propsRaw: unknown = row[`${alias}_props`];\n const rawProps: Record<string, unknown> =\n typeof propsRaw === \"string\" ?\n (JSON.parse(propsRaw) as Record<string, unknown>)\n : ((propsRaw as Record<string, unknown> | undefined) ?? {});\n\n // Metadata columns - these are always projected in traversal CTEs\n // Normalize null → undefined for optional fields\n const validFrom = nullToUndefined(\n row[`${alias}_valid_from`] as string | null,\n );\n const validTo = nullToUndefined(row[`${alias}_valid_to`] as string | null);\n const createdAt = row[`${alias}_created_at`] as string;\n const updatedAt = row[`${alias}_updated_at`] as string;\n const deletedAt = nullToUndefined(\n row[`${alias}_deleted_at`] as string | null,\n );\n\n const result: Record<string, unknown> = {\n id,\n kind,\n fromId,\n toId,\n meta: {\n validFrom,\n validTo,\n createdAt,\n updatedAt,\n deletedAt,\n },\n };\n\n assignPropsExcludingReserved(result, rawProps, RESERVED_EDGE_KEYS);\n return result as SelectableEdge;\n}\n\n/**\n * Builds a SelectContext from a raw database row.\n * Includes node aliases, edge aliases, and recursive metadata (depth/path).\n */\nexport function buildSelectContext<\n Aliases extends AliasMap,\n EdgeAliases extends EdgeAliasMap,\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty when no recursive aliases\n RecursiveAliases extends RecursiveAliasMap = {},\n>(\n row: Record<string, unknown>,\n startAlias: string,\n traversals: readonly Traversal[],\n): SelectContext<Aliases, EdgeAliases, RecursiveAliases> {\n // Build the start node as initial context entry\n const context: Record<\n string,\n | SelectableNode<NodeType>\n | SelectableEdge\n | number\n | readonly string[]\n | undefined\n > = {\n [startAlias]: buildSelectableNode(row, startAlias),\n };\n\n // Build traversal nodes and edges\n for (const traversal of traversals) {\n const nodeAlias = traversal.nodeAlias;\n const edgeAlias = traversal.edgeAlias;\n\n // Add node\n context[nodeAlias] =\n traversal.optional ?\n buildSelectableNodeOrUndefined(row, nodeAlias)\n : buildSelectableNode(row, nodeAlias);\n\n // Add edge (may be undefined for optional traversals)\n context[edgeAlias] = buildSelectableEdge(row, edgeAlias);\n\n // Add recursive depth/path values\n const vl = traversal.variableLength;\n if (vl !== undefined) {\n if (vl.depthAlias !== undefined) {\n context[vl.depthAlias] = row[vl.depthAlias] as number;\n }\n if (vl.pathAlias !== undefined) {\n context[vl.pathAlias] = row[vl.pathAlias] as readonly string[];\n }\n }\n }\n\n return context as SelectContext<Aliases, EdgeAliases, RecursiveAliases>;\n}\n\n/**\n * Maps raw database rows to typed results using a select function.\n */\nexport function mapResults<\n Aliases extends AliasMap,\n EdgeAliases extends EdgeAliasMap,\n R,\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty when no recursive aliases\n RA extends RecursiveAliasMap = {},\n>(\n rows: readonly Record<string, unknown>[],\n startAlias: string,\n traversals: readonly Traversal[],\n selectFunction: (context: SelectContext<Aliases, EdgeAliases, RA>) => R,\n): readonly R[] {\n return rows.map((row) => {\n const context = buildSelectContext<Aliases, EdgeAliases, RA>(\n row,\n startAlias,\n traversals,\n );\n return selectFunction(context);\n });\n}\n","/**\n * Cursor encoding/decoding for keyset pagination.\n *\n * Cursors are opaque URL-safe base64-encoded JSON containing:\n * - Column values at cursor position\n * - Direction indicator\n * - Version for forward compatibility\n */\n\nimport { ValidationError } from \"../errors\";\nimport { type OrderSpec } from \"./ast\";\nimport { resolveJsonPointer } from \"./json-pointer\";\n\n// ============================================================\n// Types\n// ============================================================\n\nconst CURSOR_VERSION = 1;\n\n/**\n * Internal cursor data structure.\n */\nexport type CursorData = Readonly<{\n /** Version for forward compatibility */\n v: number;\n /** Direction: 'f' = forward, 'b' = backward */\n d: \"f\" | \"b\";\n /** ORDER BY column values at cursor position */\n vals: readonly unknown[];\n /** Column identifiers for validation */\n cols: readonly string[];\n}>;\n\n// ============================================================\n// Encoding / Decoding\n// ============================================================\n\n/**\n * Encodes cursor data to a URL-safe base64 string.\n */\nexport function encodeCursor(data: CursorData): string {\n const json = JSON.stringify(data);\n // Use URL-safe base64: replace + with -, / with _, remove padding\n return btoa(json)\n .replaceAll(\"+\", \"-\")\n .replaceAll(\"/\", \"_\")\n .replace(/=+$/, \"\");\n}\n\n/**\n * Decodes a cursor string to cursor data.\n *\n * @throws ValidationError if cursor is invalid or incompatible\n */\nexport function decodeCursor(cursor: string): CursorData {\n try {\n // Restore standard base64\n let base64 = cursor.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n // Add padding if needed\n while (base64.length % 4) {\n base64 += \"=\";\n }\n const json = atob(base64);\n const raw = JSON.parse(json) as Record<string, unknown>;\n\n if (typeof raw[\"v\"] !== \"number\" || raw[\"v\"] > CURSOR_VERSION) {\n throw new ValidationError(\n `Unsupported cursor version: ${String(raw[\"v\"])}. Maximum supported: ${CURSOR_VERSION}`,\n {\n issues: [\n {\n path: \"cursor\",\n message: `Cursor version ${String(raw[\"v\"])} is not supported`,\n },\n ],\n },\n {\n suggestion: `This cursor was created with a newer version. Re-fetch the data to get a compatible cursor.`,\n },\n );\n }\n\n if (raw[\"d\"] !== \"f\" && raw[\"d\"] !== \"b\") {\n throw new ValidationError(\n `Invalid cursor direction: ${String(raw[\"d\"])}`,\n {\n issues: [\n {\n path: \"cursor\",\n message: `Direction must be \"f\" (forward) or \"b\" (backward)`,\n },\n ],\n },\n );\n }\n\n if (!Array.isArray(raw[\"vals\"]) || !Array.isArray(raw[\"cols\"])) {\n throw new ValidationError(\"Invalid cursor structure\", {\n issues: [\n {\n path: \"cursor\",\n message: \"Cursor must contain vals and cols arrays\",\n },\n ],\n });\n }\n\n if (raw[\"vals\"].length !== raw[\"cols\"].length) {\n throw new ValidationError(\"Cursor column count mismatch\", {\n issues: [\n {\n path: \"cursor\",\n message: `vals (${raw[\"vals\"].length}) and cols (${raw[\"cols\"].length}) must have same length`,\n },\n ],\n });\n }\n\n return {\n v: raw[\"v\"],\n d: raw[\"d\"],\n vals: raw[\"vals\"] as readonly unknown[],\n cols: raw[\"cols\"] as readonly string[],\n };\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ValidationError(\n \"Invalid cursor format\",\n {\n issues: [{ path: \"cursor\", message: \"Failed to decode cursor\" }],\n },\n { cause: error },\n );\n }\n}\n\n// ============================================================\n// Cursor Building\n// ============================================================\n\n/**\n * Builds a column identifier from an order spec.\n *\n * Format: \"alias.fieldName\" for property fields, \"alias.path[0]...\" for system fields.\n * Handles two field ref formats:\n * 1. New format: path=[\"props\"], jsonPointer=\"/name\"\n * 2. Legacy format: path=[\"props\", \"name\"]\n *\n * In both cases, outputs flattened format \"p.name\" to match the flattened API.\n */\nexport function buildColumnId(spec: OrderSpec): string {\n const { alias, path, jsonPointer } = spec.field;\n\n // New format: path=[\"props\"] with jsonPointer=\"/fieldName\"\n // jsonPointer is a branded string like \"/name\" or \"/nested/field\"\n if (path.length === 1 && path[0] === \"props\" && jsonPointer) {\n const parts = (jsonPointer as string).split(\"/\").filter(Boolean);\n return `${alias}.${parts.join(\".\")}`;\n }\n\n // Legacy format: path=[\"props\", \"fieldName\", ...] without jsonPointer\n if (path.length >= 2 && path[0] === \"props\") {\n return `${alias}.${path.slice(1).join(\".\")}`;\n }\n\n // System fields (id, kind) or other paths\n return `${alias}.${path.join(\".\")}`;\n}\n\n/**\n * Extracts the value for a cursor column from a result row.\n *\n * The row can be in two formats:\n * 1. Raw database row with flat column names\n * 2. Mapped result with alias-keyed nested data\n *\n * For mapped results, we navigate through the path and then jsonPointer.\n */\nexport function extractCursorValue(\n row: Record<string, unknown>,\n spec: OrderSpec,\n): unknown {\n const { alias, path, jsonPointer } = spec.field;\n\n // Try alias-keyed format first (mapped results)\n let current: unknown = row[alias];\n if (current !== undefined) {\n // Follow path first (e.g., [\"props\"])\n for (const segment of path) {\n if (current === null || current === undefined) return undefined;\n if (typeof current !== \"object\") return undefined;\n\n const record = current as Record<string, unknown>;\n if (segment === \"props\" && !Object.hasOwn(record, segment)) {\n continue;\n }\n\n current = record[segment];\n }\n\n // Then follow jsonPointer if present (e.g., \"/name\")\n if (jsonPointer) {\n return resolveJsonPointer(current, jsonPointer);\n }\n\n return current;\n }\n\n // Fallback: try direct path lookup for raw rows\n current = row;\n for (const segment of path) {\n if (current === null || current === undefined) return undefined;\n if (typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * Builds a cursor from a result row and order specifications.\n *\n * @param row - The result row (mapped with alias-keyed data)\n * @param orderSpecs - The ORDER BY specifications\n * @param direction - Pagination direction\n * @returns Encoded cursor string\n */\nexport function buildCursorFromRow(\n row: Record<string, unknown>,\n orderSpecs: readonly OrderSpec[],\n direction: \"f\" | \"b\",\n): string {\n const vals = orderSpecs.map((spec) => extractCursorValue(row, spec));\n const cols = orderSpecs.map((spec) => buildColumnId(spec));\n\n return encodeCursor({\n v: CURSOR_VERSION,\n d: direction,\n vals,\n cols,\n });\n}\n\n/**\n * Validates that cursor columns match the query's ORDER BY columns.\n *\n * @throws ValidationError if columns don't match\n */\nexport function validateCursorColumns(\n cursorData: CursorData,\n orderSpecs: readonly OrderSpec[],\n): void {\n const expectedCols = orderSpecs.map((spec) => buildColumnId(spec));\n\n if (cursorData.cols.length !== expectedCols.length) {\n throw new ValidationError(\n `Cursor has ${cursorData.cols.length} columns but query has ${expectedCols.length} ORDER BY columns`,\n {\n issues: [\n {\n path: \"cursor\",\n message: `Column count mismatch: cursor has ${cursorData.cols.length}, query has ${expectedCols.length}`,\n },\n ],\n },\n {\n suggestion: `The cursor was created with a different ORDER BY. Re-fetch with consistent ordering.`,\n },\n );\n }\n\n for (const [index, expectedCol] of expectedCols.entries()) {\n if (cursorData.cols[index] !== expectedCol) {\n throw new ValidationError(\n `Cursor column mismatch at position ${index}: expected \"${expectedCol}\", got \"${cursorData.cols[index]}\"`,\n {\n issues: [\n {\n path: \"cursor\",\n message: `Column ${index}: expected \"${expectedCol}\", got \"${cursorData.cols[index]}\"`,\n },\n ],\n },\n {\n suggestion: `The cursor was created with a different ORDER BY. Re-fetch with consistent ordering.`,\n },\n );\n }\n }\n}\n","/**\n * Cursor-based pagination utilities.\n *\n * Provides pagination logic for ExecutableQuery including cursor predicate\n * building and result page construction.\n */\nimport {\n DEFAULT_PAGINATION_LIMIT,\n DEFAULT_STREAM_BATCH_SIZE,\n} from \"../../constants\";\nimport { requireDefined } from \"../../utils/presence\";\nimport {\n type FieldRef,\n type NodePredicate,\n type OrderSpec,\n type PredicateExpression,\n} from \"../ast\";\nimport type {\n AliasMap,\n EdgeAliasMap,\n PaginatedResult,\n PaginateOptions,\n SelectContext,\n StreamOptions,\n} from \"../builder/types\";\nimport {\n buildCursorFromRow,\n type CursorData,\n decodeCursor,\n validateCursorColumns,\n} from \"../cursor\";\n\n/**\n * Parses pagination options into internal format.\n */\nexport function parsePaginateOptions(options: PaginateOptions): {\n isBackward: boolean;\n limit: number;\n cursor: string | undefined;\n cursorData: CursorData | undefined;\n orderBy: readonly OrderSpec[];\n} {\n const isBackward = options.last !== undefined || options.before !== undefined;\n const limit = options.first ?? options.last ?? DEFAULT_PAGINATION_LIMIT;\n const cursor = options.after ?? options.before;\n\n let cursorData: CursorData | undefined;\n if (cursor) {\n cursorData = decodeCursor(cursor);\n }\n\n return { isBackward, limit, cursor, cursorData, orderBy: [] };\n}\n\n/**\n * Validates cursor data against ORDER BY columns.\n */\nexport function validateCursor(\n cursorData: CursorData | undefined,\n orderBy: readonly OrderSpec[],\n): void {\n if (cursorData) {\n validateCursorColumns(cursorData, orderBy);\n }\n}\n\n/**\n * Adjusts ORDER BY for backward pagination (reverses directions).\n */\nexport function adjustOrderByForDirection(\n orderBy: readonly OrderSpec[],\n direction: \"forward\" | \"backward\",\n): readonly OrderSpec[] {\n if (direction === \"forward\") {\n return orderBy;\n }\n return orderBy.map((spec) => ({\n ...spec,\n direction: spec.direction === \"asc\" ? (\"desc\" as const) : (\"asc\" as const),\n }));\n}\n\n/**\n * Builds a cursor predicate for keyset pagination.\n * Generates (col1 > val1) OR (col1 = val1 AND col2 > val2) OR ... pattern.\n */\nexport function buildCursorPredicate(\n cursorData: CursorData,\n orderBy: readonly OrderSpec[],\n direction: \"forward\" | \"backward\",\n targetAlias: string,\n): NodePredicate {\n const values = cursorData.vals;\n\n // Build OR of progressively longer AND conditions\n const orConditions: PredicateExpression[] = [];\n\n for (let index = 0; index < orderBy.length; index++) {\n const andConditions: PredicateExpression[] = [];\n\n // All preceding columns must be equal\n for (let index_ = 0; index_ < index; index_++) {\n const spec = requireDefined(orderBy[index_]);\n const value = values[index_];\n andConditions.push(buildEqualityPredicate(spec.field, value));\n }\n\n // Current column uses comparison\n const currentSpec = requireDefined(orderBy[index]);\n const currentValue = values[index];\n const isAsc = currentSpec.direction === \"asc\";\n const isForward = direction === \"forward\";\n // ASC + forward = gt | ASC + backward = lt\n // DESC + forward = lt | DESC + backward = gt\n const op = isAsc === isForward ? \"gt\" : \"lt\";\n\n andConditions.push(\n buildComparisonPredicate(currentSpec.field, op, currentValue),\n );\n\n // Combine with AND\n if (andConditions.length === 1) {\n orConditions.push(requireDefined(andConditions[0]));\n } else {\n orConditions.push({ __type: \"and\", predicates: andConditions });\n }\n }\n\n // Combine with OR\n const expression: PredicateExpression =\n orConditions.length === 1 ?\n requireDefined(orConditions[0])\n : { __type: \"or\", predicates: orConditions };\n\n return {\n targetAlias,\n expression,\n };\n}\n\n/**\n * Builds an equality predicate for cursor pagination.\n */\nfunction buildEqualityPredicate(\n field: FieldRef,\n value: unknown,\n): PredicateExpression {\n if (value === null || value === undefined) {\n return { __type: \"null_check\", op: \"isNull\", field };\n }\n return {\n __type: \"comparison\",\n op: \"eq\",\n left: field,\n right: { __type: \"literal\", value: value as string | number | boolean },\n };\n}\n\n/**\n * Builds a comparison predicate for cursor pagination.\n */\nfunction buildComparisonPredicate(\n field: FieldRef,\n op: \"gt\" | \"lt\",\n value: unknown,\n): PredicateExpression {\n if (value === null || value === undefined) {\n // For null, the comparison depends on NULLS FIRST/LAST behavior\n // For simplicity, treat as IS NOT NULL for forward, fail for backward\n return { __type: \"null_check\", op: \"isNotNull\", field };\n }\n return {\n __type: \"comparison\",\n op,\n left: field,\n right: { __type: \"literal\", value: value as string | number | boolean },\n };\n}\n\n/**\n * Builds cursor string from a context row.\n */\nexport function buildCursorFromContext<\n Aliases extends AliasMap,\n EdgeAliases extends EdgeAliasMap,\n>(\n context: SelectContext<Aliases, EdgeAliases>,\n orderBy: readonly OrderSpec[],\n direction: \"f\" | \"b\",\n): string {\n return buildCursorFromRow(context, orderBy, direction);\n}\n\n/**\n * Constructs a PaginatedResult from query results.\n */\nexport function buildPaginatedResult<\n Aliases extends AliasMap,\n EdgeAliases extends EdgeAliasMap,\n R,\n>(\n data: readonly R[],\n orderedRows: readonly Record<string, unknown>[],\n orderBy: readonly OrderSpec[],\n limit: number,\n hasMore: boolean,\n isBackward: boolean,\n cursor: string | undefined,\n buildContext: (\n row: Record<string, unknown>,\n ) => SelectContext<Aliases, EdgeAliases>,\n): PaginatedResult<R> {\n let nextCursor: string | undefined;\n let previousCursor: string | undefined;\n\n if (orderedRows.length > 0) {\n const firstRow = requireDefined(orderedRows[0]);\n const lastRow = requireDefined(orderedRows.at(-1));\n\n // Build cursors using mapped result context\n const firstContext = buildContext(firstRow);\n const lastContext = buildContext(lastRow);\n\n // Extract values for ORDER BY columns from the context\n previousCursor = buildCursorFromContext(firstContext, orderBy, \"b\");\n nextCursor = buildCursorFromContext(lastContext, orderBy, \"f\");\n }\n\n return {\n data,\n nextCursor: hasMore || isBackward ? nextCursor : undefined,\n prevCursor:\n cursor !== undefined || (isBackward && hasMore) ?\n previousCursor\n : undefined,\n hasNextPage: isBackward ? cursor !== undefined : hasMore,\n hasPrevPage: isBackward ? hasMore : cursor !== undefined,\n };\n}\n\n/**\n * Creates an async iterable that streams results using cursor pagination.\n */\nexport async function* createStreamIterable<R>(\n batchSize: number,\n paginate: (options: PaginateOptions) => Promise<PaginatedResult<R>>,\n): AsyncGenerator<R> {\n let cursor: string | undefined;\n let hasMore = true;\n\n while (hasMore) {\n const options: PaginateOptions =\n cursor ? { first: batchSize, after: cursor } : { first: batchSize };\n const page = await paginate(options);\n\n for (const item of page.data) {\n yield item;\n }\n\n cursor = page.nextCursor;\n hasMore = page.hasNextPage;\n }\n}\n\n/**\n * Gets default stream options.\n */\nexport function getStreamBatchSize(options?: StreamOptions): number {\n return options?.batchSize ?? DEFAULT_STREAM_BATCH_SIZE;\n}\n","/**\n * Field Tracking for Smart Select Optimization.\n *\n * Provides infrastructure for tracking which fields are accessed during\n * a select callback, enabling the query compiler to selectively project\n * only those fields instead of fetching the full props blob.\n */\n\nimport type { KindEntity } from \"../../core/types\";\nimport { EDGE_META_KEYS, NODE_META_KEYS } from \"../../system-fields\";\nimport { compareStrings } from \"../../utils/compare\";\nimport { mergeEdgeKinds, type SelectiveField, type ValueType } from \"../ast\";\nimport { type QueryBuilderState } from \"../builder/types\";\nimport {\n type FieldTypeInfo,\n type SchemaIntrospector,\n} from \"../schema-introspector\";\n\n// ============================================================\n// Types\n// ============================================================\n\ntype TrackingValueMode = \"falsy\" | \"truthy\" | \"max\";\n\ntype AccessedField = Readonly<{\n alias: string;\n field: string;\n isSystemField: boolean;\n}>;\n\nexport type TrackingContextOptions = Readonly<{\n schemaIntrospector: SchemaIntrospector;\n mode: TrackingValueMode;\n /**\n * When \"absent\", optional traversal aliases are set to undefined to\n * encourage exploring fallback branches (e.g., `ctx.friend ? ... : ...`).\n */\n optionalTraversalAliases: \"present\" | \"absent\";\n}>;\n\n// ============================================================\n// Constants\n// ============================================================\n\nconst OBJECT_PROTOTYPE_PROPERTIES = new Set<string>([\n \"__proto__\",\n \"constructor\",\n \"hasOwnProperty\",\n \"isPrototypeOf\",\n \"propertyIsEnumerable\",\n \"toLocaleString\",\n \"toString\",\n \"valueOf\",\n]);\n\n// ============================================================\n// FieldAccessTracker\n// ============================================================\n\nexport class FieldAccessTracker {\n readonly #fields = new Map<string, AccessedField>();\n\n record(alias: string, field: string, isSystemField: boolean): void {\n const key = `${alias}\\u0000${field}`;\n const existing = this.#fields.get(key);\n // System fields (id, kind) are dedicated columns — not in the props JSON.\n // Never downgrade a system field to a props field, as that would cause the\n // compiler to emit props->>'id' (nonexistent) instead of the id column.\n if (existing !== undefined && existing.isSystemField && !isSystemField) {\n return;\n }\n this.#fields.set(key, { alias, field, isSystemField });\n }\n\n getAccessedFields(): readonly AccessedField[] {\n return [...this.#fields.values()];\n }\n}\n\n// ============================================================\n// Tracking Context Creation\n// ============================================================\n\nexport function createTrackingContext(\n state: QueryBuilderState,\n tracker: FieldAccessTracker,\n options: TrackingContextOptions,\n): Record<string, unknown> {\n const context: Record<string, unknown> = {\n [state.startAlias]: createNodeTrackingProxy(\n state.startAlias,\n state.startKinds,\n tracker,\n options,\n ),\n };\n\n for (const traversal of state.traversals) {\n const edgeKindNames = mergeEdgeKinds(traversal);\n\n const optionalAbsent =\n options.optionalTraversalAliases === \"absent\" && traversal.optional;\n\n context[traversal.nodeAlias] =\n optionalAbsent ? undefined : (\n createNodeTrackingProxy(\n traversal.nodeAlias,\n traversal.nodeKinds,\n tracker,\n options,\n )\n );\n\n context[traversal.edgeAlias] =\n optionalAbsent ? undefined : (\n createEdgeTrackingProxy(\n traversal.edgeAlias,\n edgeKindNames,\n tracker,\n options,\n )\n );\n\n // Provide placeholder values for recursive depth/path so the\n // select callback can access them without crashing during tracking.\n const vl = traversal.variableLength;\n if (vl !== undefined) {\n if (vl.depthAlias !== undefined) {\n context[vl.depthAlias] = options.mode === \"falsy\" ? 0 : 1;\n }\n if (vl.pathAlias !== undefined) {\n context[vl.pathAlias] = options.mode === \"falsy\" ? [] : [\"placeholder\"];\n }\n }\n }\n\n return context;\n}\n\nfunction createNodeTrackingProxy(\n alias: string,\n kindNames: readonly string[],\n tracker: FieldAccessTracker,\n options: TrackingContextOptions,\n): unknown {\n return new Proxy(\n {},\n {\n get: (_, property: string | symbol) => {\n if (typeof property === \"symbol\") return;\n if (property === \"then\") return;\n if (property === \"toJSON\") return;\n\n if (OBJECT_PROTOTYPE_PROPERTIES.has(property)) {\n if (property === \"constructor\") return Object;\n if (property === \"__proto__\") return Object.prototype;\n return Reflect.get(Object.prototype, property) as unknown;\n }\n\n if (property === \"id\" || property === \"kind\") {\n tracker.record(alias, property, true);\n return getPlaceholderForSystemField(property, options.mode);\n }\n\n if (property === \"meta\") {\n for (const key of NODE_META_KEYS) {\n tracker.record(alias, `meta.${key}`, true);\n }\n return buildNodeMetaPlaceholder(options.mode);\n }\n\n tracker.record(alias, property, false);\n const typeInfo = options.schemaIntrospector.getSharedFieldTypeInfo(\n kindNames,\n property,\n );\n return getPlaceholderForTypeInfo(typeInfo, options.mode);\n },\n },\n );\n}\n\nfunction createEdgeTrackingProxy(\n alias: string,\n edgeKindNames: readonly string[],\n tracker: FieldAccessTracker,\n options: TrackingContextOptions,\n): unknown {\n return new Proxy(\n {},\n {\n get: (_, property: string | symbol) => {\n if (typeof property === \"symbol\") return;\n if (property === \"then\") return;\n if (property === \"toJSON\") return;\n\n if (OBJECT_PROTOTYPE_PROPERTIES.has(property)) {\n if (property === \"constructor\") return Object;\n if (property === \"__proto__\") return Object.prototype;\n return Reflect.get(Object.prototype, property) as unknown;\n }\n\n if (\n property === \"id\" ||\n property === \"kind\" ||\n property === \"fromId\" ||\n property === \"toId\"\n ) {\n tracker.record(alias, property, true);\n return getPlaceholderForSystemField(property, options.mode);\n }\n\n if (property === \"meta\") {\n for (const key of EDGE_META_KEYS) {\n tracker.record(alias, `meta.${key}`, true);\n }\n return buildEdgeMetaPlaceholder(options.mode);\n }\n\n tracker.record(alias, property, false);\n const typeInfo = options.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n edgeKindNames,\n property,\n );\n return getPlaceholderForTypeInfo(typeInfo, options.mode);\n },\n },\n );\n}\n\n// ============================================================\n// Selective Field Construction\n// ============================================================\n\ntype BuildSelectiveFieldsOptions = Readonly<{\n state: QueryBuilderState;\n schemaIntrospector: SchemaIntrospector;\n}>;\n\nexport function buildSelectiveFields(\n accessedFields: readonly AccessedField[],\n options?: BuildSelectiveFieldsOptions,\n): readonly SelectiveField[] {\n const aliasInfo = options ? buildAliasKindMap(options.state) : undefined;\n\n return accessedFields\n .map((access) => {\n const base: SelectiveField = {\n alias: access.alias,\n field: access.field,\n outputName: `${access.alias}_${access.field}`,\n isSystemField: access.isSystemField,\n };\n\n if (!options || access.isSystemField) {\n return base;\n }\n\n const info = aliasInfo?.get(access.alias);\n if (!info) {\n return base;\n }\n\n const typeInfo =\n info.kind === \"node\" ?\n options.schemaIntrospector.getSharedFieldTypeInfo(\n info.kindNames,\n access.field,\n )\n : options.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n info.kindNames,\n access.field,\n );\n\n return {\n ...base,\n valueType: typeInfo?.valueType,\n };\n })\n .toSorted((a, b) => {\n const aliasCompare = compareStrings(a.alias, b.alias);\n if (aliasCompare !== 0) return aliasCompare;\n return compareStrings(a.field, b.field);\n });\n}\n\ntype AliasKind = KindEntity;\n\ntype AliasKindInfo = Readonly<{\n kind: AliasKind;\n kindNames: readonly string[];\n}>;\n\nfunction buildAliasKindMap(\n state: QueryBuilderState,\n): ReadonlyMap<string, AliasKindInfo> {\n const map = new Map<string, AliasKindInfo>([\n [\n state.startAlias,\n {\n kind: \"node\",\n kindNames: state.startKinds,\n },\n ],\n ]);\n\n for (const traversal of state.traversals) {\n const edgeKindNames = mergeEdgeKinds(traversal);\n\n map.set(traversal.nodeAlias, {\n kind: \"node\",\n kindNames: traversal.nodeKinds,\n });\n map.set(traversal.edgeAlias, {\n kind: \"edge\",\n kindNames: edgeKindNames,\n });\n }\n\n return map;\n}\n\n// ============================================================\n// Placeholder Values\n// ============================================================\n\nfunction getPlaceholderForSystemField(\n field: string,\n mode: TrackingValueMode,\n): unknown {\n if (\n field === \"id\" ||\n field === \"kind\" ||\n field === \"fromId\" ||\n field === \"toId\"\n ) {\n return mode === \"falsy\" ? \"\" : \"x\";\n }\n return undefined;\n}\n\nfunction buildNodeMetaPlaceholder(mode: TrackingValueMode): Readonly<{\n version: number;\n validFrom: string | undefined;\n validTo: string | undefined;\n createdAt: string;\n updatedAt: string;\n deletedAt: string | undefined;\n}> {\n const empty = mode === \"falsy\";\n return {\n version: empty ? 0 : 1,\n validFrom: empty ? undefined : \"2020-01-01T00:00:00.000Z\",\n validTo: undefined,\n createdAt: \"2020-01-01T00:00:00.000Z\",\n updatedAt: \"2020-01-01T00:00:00.000Z\",\n deletedAt: undefined,\n };\n}\n\nfunction buildEdgeMetaPlaceholder(mode: TrackingValueMode): Readonly<{\n validFrom: string | undefined;\n validTo: string | undefined;\n createdAt: string;\n updatedAt: string;\n deletedAt: string | undefined;\n}> {\n const empty = mode === \"falsy\";\n return {\n validFrom: empty ? undefined : \"2020-01-01T00:00:00.000Z\",\n validTo: undefined,\n createdAt: \"2020-01-01T00:00:00.000Z\",\n updatedAt: \"2020-01-01T00:00:00.000Z\",\n deletedAt: undefined,\n };\n}\n\nfunction getPlaceholderForTypeInfo(\n typeInfo: FieldTypeInfo | undefined,\n mode: TrackingValueMode,\n): unknown {\n if (!typeInfo) {\n return undefined;\n }\n\n return getPlaceholderForValueType(typeInfo.valueType, mode);\n}\n\nfunction getPlaceholderForValueType(\n valueType: ValueType,\n mode: TrackingValueMode,\n): unknown {\n switch (valueType) {\n case \"string\":\n case \"date\": {\n if (mode === \"falsy\") return \"\";\n if (mode === \"max\") return \"active\";\n return \"x\";\n }\n case \"number\": {\n if (mode === \"falsy\") return 0;\n if (mode === \"max\") return 100;\n return 1;\n }\n case \"boolean\": {\n return mode !== \"falsy\";\n }\n case \"array\":\n case \"embedding\": {\n return [];\n }\n case \"object\": {\n return {};\n }\n case \"unknown\": {\n return undefined;\n }\n }\n}\n","/**\n * Selective Result Mapping for Smart Select Optimization.\n *\n * Converts rows returned from a selective projection query into the\n * SelectContext expected by the select callback, while guarding against\n * missing fields and unsupported \"return whole node/edge\" selections.\n */\n\nimport type { KindEntity } from \"../../core/types\";\nimport { compareStrings, normalizePath } from \"../../utils\";\nimport { mergeEdgeKinds, type SelectiveField, type Traversal } from \"../ast\";\nimport type {\n AliasMap,\n EdgeAliasMap,\n QueryBuilderState,\n SelectContext,\n} from \"../builder/types\";\nimport {\n type FieldTypeInfo,\n type SchemaIntrospector,\n} from \"../schema-introspector\";\nimport { decodeSelectedValue, nullToUndefined } from \"./value-decoder\";\n\n// ============================================================\n// Errors\n// ============================================================\n\nexport class MissingSelectiveFieldError extends Error {\n readonly alias: string;\n readonly field: string;\n\n constructor(alias: string, field: string) {\n super(`Smart select missing field: ${alias}.${field}`);\n this.alias = alias;\n this.field = field;\n }\n}\n\n// ============================================================\n// Internal Types\n// ============================================================\n\ntype AliasKind = KindEntity;\n\ntype SystemFieldPlan = Readonly<{\n field: string;\n outputName: string;\n}>;\n\ntype MetaFieldPlan = Readonly<{\n metaKey: string;\n outputName: string;\n}>;\n\ntype PropsFieldPlan = Readonly<{\n field: string;\n outputName: string;\n typeInfo: FieldTypeInfo | undefined;\n}>;\n\ntype AliasPlan = Readonly<{\n alias: string;\n kind: AliasKind;\n optional: boolean;\n systemFields: readonly SystemFieldPlan[];\n metaFields: readonly MetaFieldPlan[];\n propsFields: readonly PropsFieldPlan[];\n idOutputName: string | undefined;\n metaOutputNames: ReadonlySet<string>;\n propsOutputNames: ReadonlySet<string>;\n systemOutputNames: ReadonlySet<string>;\n}>;\n\n// ============================================================\n// Marker for \"whole alias object\" detection\n// ============================================================\n\nconst SELECTABLE_ALIAS_MARKER = Symbol(\"selectable_alias_marker\");\n\ntype SelectableAliasMarker = Readonly<{\n alias: string;\n kind: AliasKind;\n}>;\n\nfunction isSelectableAliasObject(\n value: unknown,\n): value is SelectableAliasMarker {\n return (\n typeof value === \"object\" &&\n value !== null &&\n SELECTABLE_ALIAS_MARKER in value\n );\n}\n\nfunction containsSelectableAliasObject(value: unknown): boolean {\n const visited = new WeakSet<object>();\n\n function walk(current: unknown): boolean {\n if (isSelectableAliasObject(current)) return true;\n\n if (Array.isArray(current)) {\n for (const item of current) {\n if (walk(item)) return true;\n }\n return false;\n }\n\n if (typeof current !== \"object\" || current === null) {\n return false;\n }\n\n if (visited.has(current)) return false;\n visited.add(current);\n\n for (const value of Object.values(current)) {\n if (walk(value)) return true;\n }\n return false;\n }\n\n return walk(value);\n}\n\n// ============================================================\n// Public API\n// ============================================================\n\nexport function mapSelectiveResults<\n Aliases extends AliasMap,\n EdgeAliases extends EdgeAliasMap,\n R,\n>(\n rows: readonly Record<string, unknown>[],\n state: QueryBuilderState,\n selectiveFields: readonly SelectiveField[],\n schemaIntrospector: SchemaIntrospector,\n selectFunction: (context: SelectContext<Aliases, EdgeAliases>) => R,\n): readonly R[] {\n const plans = buildAliasPlans(state, selectiveFields, schemaIntrospector);\n\n return rows.map((row) => {\n const context = buildSelectiveContext<Aliases, EdgeAliases>(\n row,\n plans,\n state.traversals,\n );\n const result = selectFunction(context);\n\n // Returning whole alias objects is not supported by selective projection.\n // If it happens, fall back to the full fetch path.\n if (containsSelectableAliasObject(result)) {\n throw new MissingSelectiveFieldError(\n state.startAlias,\n \"whole node/edge selection\",\n );\n }\n\n return result;\n });\n}\n\n// ============================================================\n// Plan Construction\n// ============================================================\n\nfunction buildAliasPlans(\n state: QueryBuilderState,\n selectiveFields: readonly SelectiveField[],\n schemaIntrospector: SchemaIntrospector,\n): readonly AliasPlan[] {\n const aliasInfo = new Map<\n string,\n Readonly<{\n kind: AliasKind;\n optional: boolean;\n kindNames: readonly string[];\n }>\n >([\n [\n state.startAlias,\n {\n kind: \"node\",\n optional: false,\n kindNames: state.startKinds,\n },\n ],\n ]);\n\n for (const traversal of state.traversals) {\n const edgeKindNames = mergeEdgeKinds(traversal);\n\n aliasInfo.set(traversal.nodeAlias, {\n kind: \"node\",\n optional: traversal.optional,\n kindNames: traversal.nodeKinds,\n });\n aliasInfo.set(traversal.edgeAlias, {\n kind: \"edge\",\n optional: traversal.optional,\n kindNames: edgeKindNames,\n });\n }\n\n const fieldsByAlias = new Map<string, SelectiveField[]>();\n for (const field of selectiveFields) {\n const existing = fieldsByAlias.get(field.alias) ?? [];\n existing.push(field);\n fieldsByAlias.set(field.alias, existing);\n }\n\n const plans: AliasPlan[] = [];\n\n for (const [alias, info] of aliasInfo.entries()) {\n const fields = fieldsByAlias.get(alias) ?? [];\n\n const systemFields: SystemFieldPlan[] = [];\n const metaFields: MetaFieldPlan[] = [];\n const propsFields: PropsFieldPlan[] = [];\n\n for (const field of fields) {\n if (field.isSystemField) {\n if (field.field.startsWith(\"meta.\")) {\n metaFields.push({\n metaKey: field.field.slice(5),\n outputName: field.outputName,\n });\n } else {\n systemFields.push({\n field: field.field,\n outputName: field.outputName,\n });\n }\n } else {\n const typeInfo =\n info.kind === \"node\" ?\n schemaIntrospector.getSharedFieldTypeInfo(\n info.kindNames,\n field.field,\n )\n : schemaIntrospector.getSharedEdgeFieldTypeInfo(\n info.kindNames,\n field.field,\n );\n\n propsFields.push({\n field: field.field,\n outputName: field.outputName,\n typeInfo,\n });\n }\n }\n\n const idOutputName =\n systemFields.find((f) => f.field === \"id\")?.outputName ?? undefined;\n\n plans.push({\n alias,\n kind: info.kind,\n optional: info.optional,\n systemFields,\n metaFields,\n propsFields,\n idOutputName,\n metaOutputNames: new Set(metaFields.map((f) => f.outputName)),\n propsOutputNames: new Set(propsFields.map((f) => f.outputName)),\n systemOutputNames: new Set(systemFields.map((f) => f.outputName)),\n });\n }\n\n // Keep plan iteration stable.\n return plans.toSorted((a, b) => compareStrings(a.alias, b.alias));\n}\n\n// ============================================================\n// Context Building\n// ============================================================\n\nfunction buildSelectiveContext<\n Aliases extends AliasMap,\n EdgeAliases extends EdgeAliasMap,\n>(\n row: Record<string, unknown>,\n plans: readonly AliasPlan[],\n traversals: readonly Traversal[],\n): SelectContext<Aliases, EdgeAliases> {\n const context: Record<string, unknown> = {};\n\n for (const plan of plans) {\n const value =\n plan.optional && plan.idOutputName !== undefined ?\n buildOptionalAliasValue(row, plan)\n : buildRequiredAliasValue(row, plan);\n context[plan.alias] = value;\n }\n\n // Extract recursive depth/path values from the row\n for (const traversal of traversals) {\n const vl = traversal.variableLength;\n if (vl !== undefined) {\n if (vl.depthAlias !== undefined) {\n context[vl.depthAlias] = row[vl.depthAlias];\n }\n if (vl.pathAlias !== undefined) {\n context[vl.pathAlias] = normalizePath(row[vl.pathAlias]);\n }\n }\n }\n\n return context as SelectContext<Aliases, EdgeAliases>;\n}\n\nfunction buildOptionalAliasValue(\n row: Record<string, unknown>,\n plan: AliasPlan,\n): unknown {\n if (plan.idOutputName === undefined) {\n return undefined;\n }\n const idValue = row[plan.idOutputName];\n\n if (idValue === null || idValue === undefined) {\n return undefined;\n }\n return buildRequiredAliasValue(row, plan);\n}\n\nfunction buildRequiredAliasValue(\n row: Record<string, unknown>,\n plan: AliasPlan,\n): unknown {\n const base: Record<string, unknown> = {\n [SELECTABLE_ALIAS_MARKER]: {\n alias: plan.alias,\n kind: plan.kind,\n } satisfies SelectableAliasMarker,\n };\n\n for (const field of plan.systemFields) {\n base[field.field] = nullToUndefined(row[field.outputName]);\n }\n\n if (plan.metaFields.length > 0) {\n const meta: Record<string, unknown> = {};\n for (const field of plan.metaFields) {\n meta[field.metaKey] = nullToUndefined(row[field.outputName]);\n }\n base[\"meta\"] = createGuardedProxy(meta, `${plan.alias}.meta`);\n }\n\n for (const field of plan.propsFields) {\n const decoded = decodeSelectedValue(row[field.outputName], field.typeInfo);\n base[field.field] = decoded;\n }\n\n return createGuardedProxy(base, plan.alias);\n}\n\nfunction createGuardedProxy(\n target: Record<string, unknown>,\n debugPath: string,\n): unknown {\n return new Proxy(target, {\n get: (object, property: string | symbol, receiver) => {\n if (typeof property === \"symbol\") {\n return Reflect.get(object, property, receiver) as unknown;\n }\n\n if (property === \"then\" || property === \"toJSON\") {\n return;\n }\n\n if (property in object) {\n return Reflect.get(object, property, receiver);\n }\n\n if (property in Object.prototype) {\n return Reflect.get(Object.prototype, property, receiver) as unknown;\n }\n\n throw new MissingSelectiveFieldError(debugPath, property);\n },\n });\n}\n","/**\n * Compiled-SQL template cache keyed on the reserved read-instant placeholder.\n *\n * A \"current\" (live) query bakes its valid-time read instant into the compiled\n * SQL as a bound parameter. Recompiling the whole AST on every execution just\n * to refresh that one value — the behavior PR #246 introduced to fix a frozen\n * \"now\" — is pure waste: the SQL text is byte-identical across calls, only the\n * instant differs. This module compiles the statement ONCE in `\"placeholder\"`\n * mode (the read instant becomes {@link CURRENT_READ_INSTANT_PLACEHOLDER}\n * instead of a frozen value), caches the resulting `{ sql, params }`, and fills\n * a fresh instant into the placeholder on every execution via\n * {@link fillTemplateParams}.\n *\n * The fast path requires a backend that can both compile a TypeGraph `SqlFragment`\n * to text (`compileSql`) and execute pre-compiled text (`executeRaw`). Custom\n * or async backends without those members fall back to per-call recompilation,\n * exactly as before.\n */\nimport { ConfigurationError } from \"../../errors\";\nimport { nowIso } from \"../../utils/date\";\nimport { type ComposableQuery, type QueryAst } from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport { CURRENT_READ_INSTANT_PLACEHOLDER } from \"../compiler/temporal\";\nimport { bindSqlValue } from \"../dialect/profile\";\nimport { type SqlDialect } from \"../dialect/types\";\nimport { isSqlPlaceholder, type SqlFragment } from \"../sql-fragment\";\nimport { type CompiledSelectSql, isRawExecutable } from \"../sql-intent\";\n\n/**\n * A compiled statement ready for `executeRaw`: SQL text plus a positional\n * parameter list that may still contain unfilled named placeholder objects\n * (the read instant, and any user `param()` refs on a prepared query).\n */\nexport type CompiledTemplate = Readonly<{\n sql: string;\n params: readonly unknown[];\n}>;\n\n/** Compiles a TypeGraph `SqlFragment` to `{ sql, params }` without executing. */\ntype CompileSqlFunction = (query: SqlFragment) => CompiledTemplate;\n\n/**\n * The receiver-free slice of a backend used to build a template.\n */\nexport type SqlCompilerBackend = Readonly<{ compileSql?: CompileSqlFunction }>;\n\n/** Whether a compiled template carries the reserved read-instant placeholder. */\nfunction templateHasReadInstant(template: CompiledTemplate): boolean {\n return template.params.some(\n (parameter) =>\n isSqlPlaceholder(parameter) &&\n parameter.name === CURRENT_READ_INSTANT_PLACEHOLDER,\n );\n}\n\n/**\n * True when a query's compiled SQL must bind a fresh \"current\" instant per\n * execution — i.e. it reads valid-time \"current\" and is not pinned to a\n * recorded instant (a recorded pin replaces the wall clock with a fixed\n * instant). `asOf`, `includeEnded`, and `includeTombstones` reads bind no\n * read instant at all, so their compiled statement is stable and cacheable\n * verbatim.\n */\nfunction queryAstNeedsCurrentReadInstant(ast: QueryAst): boolean {\n return ast.temporalMode.mode === \"current\" && ast.recordedAsOf === undefined;\n}\n\n/** {@link queryAstNeedsCurrentReadInstant} lifted over a set operation's operands. */\nexport function composableNeedsCurrentReadInstant(\n query: ComposableQuery,\n): boolean {\n if (\"__type\" in query) {\n return (\n composableNeedsCurrentReadInstant(query.left) ||\n composableNeedsCurrentReadInstant(query.right)\n );\n }\n return queryAstNeedsCurrentReadInstant(query);\n}\n\ntype BuildReadInstantTemplateArguments = Readonly<{\n /** Compiles the statement in `\"placeholder\"` read-instant mode. */\n compile: () => CompiledSelectSql;\n /**\n * The backend, whose `compileSql` produces the cacheable text. When it (or\n * its `compileSql`) is absent the backend has no raw-execution fast path, so\n * there is no template to build.\n */\n backend: SqlCompilerBackend | undefined;\n /**\n * Whether the source query requires a fresh instant per execution (see\n * {@link queryAstNeedsCurrentReadInstant}). Used as a correctness guard: a\n * query that needs a read instant but whose compiled template carries no\n * read-instant placeholder has frozen \"now\" into a literal, so it is NOT\n * safe to cache — the caller must recompile per call instead.\n */\n needsReadInstant: boolean;\n}>;\n\n/**\n * Compiles the reusable placeholder template, or returns `undefined` when the\n * statement cannot be safely cached (or the backend has no raw-execution fast\n * path).\n *\n * The `needsReadInstant` guard enforces the lesson of the #246 freshness\n * regression: if the query needs a \"current\" instant yet the placeholder-mode\n * compilation did not templatize one, some read-instant emission escaped the\n * placeholder seam and would freeze into the cache. Every \"current\" query in\n * the builder's compile pipeline binds its instant through the one placeholder\n * seam, so this branch is unreachable by construction today; it exists to fail\n * safe — degrading to correct-but-uncached — if a future emission path forgets\n * the mode, rather than resting the invariant on a whole-compiler proof.\n */\nexport function buildReadInstantTemplate(\n args: BuildReadInstantTemplateArguments,\n): CompiledTemplate | undefined {\n const { backend } = args;\n if (backend?.compileSql === undefined) return undefined;\n\n const compiled = args.compile();\n // A statement whose execution semantics ride on the compiled SQL OBJECT\n // (pgvector ANN GUCs, force-custom-plan) loses them when flattened to raw\n // text, so it can't take the executeRaw fast path — the caller falls back to\n // backend.execute, which honors the brand. See isRawExecutable.\n if (!isRawExecutable(compiled)) return undefined;\n\n const template = backend.compileSql(compiled);\n if (args.needsReadInstant && !templateHasReadInstant(template)) {\n return undefined;\n }\n return template;\n}\n\n/**\n * Convenience over {@link buildReadInstantTemplate} for a standard (non\n * set-operation) query: compiles `ast` in placeholder mode via\n * {@link compileQuery} and derives {@link queryAstNeedsCurrentReadInstant}.\n * Set operations call {@link buildReadInstantTemplate} directly with their own\n * compile function and composable need-check.\n */\nexport function buildQueryTemplate(\n ast: QueryAst,\n graphId: string,\n compileOptions: CompileQueryOptions,\n backend: SqlCompilerBackend | undefined,\n): CompiledTemplate | undefined {\n return buildReadInstantTemplate({\n compile: () =>\n compileQuery(ast, graphId, {\n ...compileOptions,\n readInstant: \"placeholder\",\n }),\n backend,\n needsReadInstant: queryAstNeedsCurrentReadInstant(ast),\n });\n}\n\n/**\n * Resolves a template's positional parameters for `executeRaw`, replacing\n * every {@link Placeholder} with a concrete value:\n *\n * - the reserved read-instant placeholder → a single fresh {@link nowIso}\n * sampled once and shared by every occurrence, preserving the \"one instant\n * per statement\" invariant the literal path guaranteed;\n * - a user `param()` placeholder → its binding, mapped the same way the\n * compile path binds a literal (Date → ISO string; everything else through\n * the dialect's `bindValue`).\n */\nexport function fillTemplateParams(\n params: readonly unknown[],\n bindings: Readonly<Record<string, unknown>>,\n dialect: SqlDialect,\n): unknown[] {\n let readInstant: string | undefined;\n return params.map((parameter) => {\n if (!isSqlPlaceholder(parameter)) return parameter;\n\n const name = parameter.name;\n if (name === CURRENT_READ_INSTANT_PLACEHOLDER) {\n readInstant ??= nowIso();\n return readInstant;\n }\n\n const value = bindings[name];\n if (value === undefined) {\n throw new ConfigurationError(`Missing binding for parameter \"${name}\"`, {\n parameterName: name,\n });\n }\n return bindSqlValue(value, dialect);\n });\n}\n","/**\n * PreparedQuery — a pre-validated, parameterized query.\n *\n * Created via `ExecutableQuery.prepare()`. Builds and structurally validates\n * the query AST once at prepare time (so a malformed query fails fast, before\n * the first `execute()`).\n *\n * Fast path: when the backend can compile and run raw SQL (`compileSql` +\n * `executeRaw`), the statement is compiled ONCE into a cached template whose\n * \"current\" read instant and user `param()` refs are reserved placeholders\n * (see {@link buildReadInstantTemplate}). Every `execute()` fills those\n * placeholders — a fresh instant plus the call's bindings — and runs the\n * cached SQL text directly, so a reused prepared query never recompiles and\n * never freezes \"now\" the way a cached literal instant would (the #246\n * regression).\n *\n * Fallback: on a backend without raw execution (custom/async), substitutes\n * parameter refs into the AST, compiles fresh per call, and executes via the\n * standard `backend.execute` path.\n */\nimport { type GraphBackend } from \"../../backend/types\";\nimport { ConfigurationError, UnsupportedPredicateError } from \"../../errors\";\nimport {\n type BetweenPredicate,\n type ComparisonPredicate,\n type ComposableQuery,\n type LiteralValue,\n type PredicateExpression,\n type QueryAst,\n type SelectiveField,\n type StringPredicate,\n} from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport { type SqlDialect } from \"../dialect/types\";\nimport {\n mapResults,\n mapSelectiveResults,\n MissingSelectiveFieldError,\n transformPathColumns,\n} from \"../execution\";\nimport { isParameterRef } from \"../predicates\";\nimport { type SchemaIntrospector } from \"../schema-introspector\";\nimport {\n buildQueryTemplate,\n type CompiledTemplate,\n fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n type AliasMap,\n type EdgeAliasMap,\n type QueryBuilderState,\n type SelectContext,\n} from \"./types\";\n\n// ============================================================\n// Parameter Substitution\n// ============================================================\n\nfunction toLiteral(value: unknown): LiteralValue {\n if (value === null) {\n throw new ConfigurationError(\n \"Parameter value must not be null (use undefined-based patterns instead)\",\n { parameterName: \"value\", valueType: \"null\" },\n );\n }\n if (value instanceof Date) {\n return { __type: \"literal\", value: value.toISOString(), valueType: \"date\" };\n }\n if (typeof value === \"string\") {\n return { __type: \"literal\", value, valueType: \"string\" };\n }\n if (typeof value === \"number\") {\n return { __type: \"literal\", value, valueType: \"number\" };\n }\n if (typeof value === \"boolean\") {\n return { __type: \"literal\", value, valueType: \"boolean\" };\n }\n throw new ConfigurationError(\n `Unsupported parameter value type: ${typeof value}`,\n { parameterName: \"value\", actualType: typeof value },\n );\n}\n\n/**\n * Walks a predicate expression tree and replaces ParameterRef nodes\n * with LiteralValue nodes using the provided bindings.\n */\nfunction substitutePredicateExpression(\n expr: PredicateExpression,\n bindings: Readonly<Record<string, unknown>>,\n): PredicateExpression {\n switch (expr.__type) {\n case \"comparison\": {\n if (isParameterRef(expr.right)) {\n const value = bindings[expr.right.name];\n if (value === undefined) {\n throw new ConfigurationError(\n `Missing binding for parameter \"${expr.right.name}\"`,\n { parameterName: expr.right.name },\n );\n }\n return {\n ...expr,\n right: toLiteral(value),\n } satisfies ComparisonPredicate;\n }\n return expr;\n }\n\n case \"string_op\": {\n if (isParameterRef(expr.pattern)) {\n const value = bindings[expr.pattern.name];\n if (value === undefined) {\n throw new ConfigurationError(\n `Missing binding for parameter \"${expr.pattern.name}\"`,\n { parameterName: expr.pattern.name },\n );\n }\n if (typeof value !== \"string\") {\n throw new ConfigurationError(\n `Parameter \"${expr.pattern.name}\" must be a string for string operations`,\n { parameterName: expr.pattern.name, actualType: typeof value },\n );\n }\n return {\n ...expr,\n pattern: value,\n } satisfies StringPredicate;\n }\n return expr;\n }\n\n case \"between\": {\n const lowerIsParam = isParameterRef(expr.lower);\n const upperIsParam = isParameterRef(expr.upper);\n if (!lowerIsParam && !upperIsParam) return expr;\n\n const lower =\n lowerIsParam ?\n toLiteral(resolveBinding(bindings, expr.lower.name))\n : expr.lower;\n const upper =\n upperIsParam ?\n toLiteral(resolveBinding(bindings, expr.upper.name))\n : expr.upper;\n return { ...expr, lower, upper } satisfies BetweenPredicate;\n }\n\n case \"and\": {\n return {\n ...expr,\n predicates: expr.predicates.map((p) =>\n substitutePredicateExpression(p, bindings),\n ),\n };\n }\n\n case \"or\": {\n return {\n ...expr,\n predicates: expr.predicates.map((p) =>\n substitutePredicateExpression(p, bindings),\n ),\n };\n }\n\n case \"not\": {\n return {\n ...expr,\n predicate: substitutePredicateExpression(expr.predicate, bindings),\n };\n }\n\n // These predicate types don't contain ParameterRef nodes\n case \"null_check\":\n case \"array_op\":\n case \"object_op\":\n case \"aggregate_comparison\":\n case \"vector_similarity\":\n case \"fulltext_match\": {\n return expr;\n }\n\n case \"exists\": {\n return {\n ...expr,\n subquery: substituteParameters(expr.subquery, bindings),\n };\n }\n\n case \"in_subquery\": {\n return {\n ...expr,\n subquery: substituteParameters(expr.subquery, bindings),\n };\n }\n }\n}\n\nfunction resolveBinding(\n bindings: Readonly<Record<string, unknown>>,\n name: string,\n): unknown {\n const value = bindings[name];\n if (value === undefined) {\n throw new ConfigurationError(`Missing binding for parameter \"${name}\"`, {\n parameterName: name,\n });\n }\n return value;\n}\n\n/**\n * Substitutes all ParameterRef nodes in a QueryAst with concrete values.\n */\nfunction substituteParameters(\n ast: QueryAst,\n bindings: Readonly<Record<string, unknown>>,\n): QueryAst {\n return {\n ...ast,\n predicates: ast.predicates.map((pred) => ({\n ...pred,\n expression: substitutePredicateExpression(pred.expression, bindings),\n })),\n ...(ast.having !== undefined && {\n having: substitutePredicateExpression(ast.having, bindings),\n }),\n };\n}\n\n// ============================================================\n// PreparedQuery\n// ============================================================\n\ntype PreparedQueryConfig<R> = Readonly<{\n ast: QueryAst;\n unoptimizedAst: QueryAst;\n backend: GraphBackend;\n dialect: SqlDialect;\n graphId: string;\n compileOptions: CompileQueryOptions;\n state: QueryBuilderState;\n selectiveFields: readonly SelectiveField[] | undefined;\n selectFn: (context: SelectContext<AliasMap, EdgeAliasMap>) => R;\n schemaIntrospector: SchemaIntrospector;\n}>;\n\n/**\n * A pre-validated, parameterized query — see the module doc comment above for\n * how a reused prepared query runs a cached SQL template with a fresh read\n * instant filled per call.\n *\n * @example\n * ```typescript\n * const prepared = store.query()\n * .from(\"Person\", \"p\")\n * .whereNode(\"p\", (p) => p.name.eq(param(\"name\")))\n * .select((ctx) => ctx.p)\n * .prepare();\n *\n * // Execute with different bindings\n * const alice = await prepared.execute({ name: \"Alice\" });\n * const bob = await prepared.execute({ name: \"Bob\" });\n * ```\n */\nexport class PreparedQuery<R> {\n readonly #ast: QueryAst;\n readonly #unoptimizedAst: QueryAst;\n readonly #backend: GraphBackend;\n readonly #dialect: SqlDialect;\n readonly #graphId: string;\n readonly #compileOptions: CompileQueryOptions;\n readonly #state: QueryBuilderState;\n readonly #selectiveFields: readonly SelectiveField[] | undefined;\n readonly #selectFn: (context: SelectContext<AliasMap, EdgeAliasMap>) => R;\n readonly #schemaIntrospector: SchemaIntrospector;\n readonly #parameterMetadata: ParameterMetadata;\n /**\n * Per-AST cached placeholder template, keyed by AST reference so the\n * optimized (`#ast`) and unoptimized (`#unoptimizedAst`) variants cache\n * independently. A cached `undefined` records \"no fast-path template\" (the\n * backend lacks `compileSql`, or the statement was not safely cacheable) so\n * we don't rebuild it on every call.\n */\n readonly #templateCache = new Map<QueryAst, CompiledTemplate | undefined>();\n\n constructor(config: PreparedQueryConfig<R>) {\n this.#ast = config.ast;\n this.#unoptimizedAst = config.unoptimizedAst;\n this.#backend = config.backend;\n this.#dialect = config.dialect;\n this.#graphId = config.graphId;\n this.#compileOptions = config.compileOptions;\n this.#state = config.state;\n this.#selectiveFields = config.selectiveFields;\n this.#selectFn = config.selectFn;\n this.#schemaIntrospector = config.schemaIntrospector;\n this.#parameterMetadata = collectParameterMetadata(this.#ast);\n }\n\n /**\n * The cached placeholder template for `ast`, or `undefined` when no fast\n * path applies. Compiled once (in placeholder mode) and reused across every\n * `execute()`; the read instant is refreshed per call by\n * {@link fillTemplateParams}, never frozen into the cache.\n */\n #template(ast: QueryAst): CompiledTemplate | undefined {\n if (this.#templateCache.has(ast)) return this.#templateCache.get(ast);\n const template = this.#buildTemplate(ast);\n this.#templateCache.set(ast, template);\n return template;\n }\n\n #buildTemplate(ast: QueryAst): CompiledTemplate | undefined {\n return buildQueryTemplate(\n ast,\n this.#graphId,\n this.#compileOptions,\n this.#backend,\n );\n }\n\n /** The set of parameter names required by this prepared query. */\n get parameterNames(): ReadonlySet<string> {\n return this.#parameterMetadata.names;\n }\n\n /**\n * Executes the prepared query with the given parameter bindings.\n *\n * @param bindings - A record mapping parameter names to their values\n * @returns The query results\n */\n async execute(\n bindings: Readonly<Record<string, unknown>> = {},\n ): Promise<readonly R[]> {\n validateBindings(bindings, this.#parameterMetadata);\n\n if (this.#selectiveFields !== undefined) {\n try {\n const rows = await this.#executeSelectiveRows(bindings);\n return mapSelectiveResults<AliasMap, EdgeAliasMap, R>(\n rows,\n this.#state,\n this.#selectiveFields,\n this.#schemaIntrospector,\n this.#selectFn,\n );\n } catch (error) {\n if (\n error instanceof MissingSelectiveFieldError ||\n error instanceof UnsupportedPredicateError\n ) {\n // Fall back per-call without permanently disabling the optimized path,\n // since different bindings may succeed on the optimized path.\n // Note: this fallback is observable via query profiler hooks (onQueryStart\n // fires twice — once for the optimized attempt, once for the fallback).\n return this.#executeUnoptimized(bindings);\n }\n throw error;\n }\n }\n\n return this.#executeUnoptimized(bindings);\n }\n\n async #executeSelectiveRows(\n bindings: Readonly<Record<string, unknown>>,\n ): Promise<readonly Record<string, unknown>[]> {\n return this.#executeRows(this.#ast, bindings);\n }\n\n async #executeUnoptimized(\n bindings: Readonly<Record<string, unknown>>,\n ): Promise<readonly R[]> {\n const rows = await this.#executeUnoptimizedRows(bindings);\n return mapResults<AliasMap, EdgeAliasMap, R>(\n rows,\n this.#state.startAlias,\n this.#state.traversals,\n this.#selectFn,\n );\n }\n\n async #executeUnoptimizedRows(\n bindings: Readonly<Record<string, unknown>>,\n ): Promise<readonly Record<string, unknown>[]> {\n return this.#executeRows(this.#unoptimizedAst, bindings);\n }\n\n /**\n * Runs one AST variant with the given bindings. Prefers the cached template\n * + `executeRaw` fast path; falls back to substituting bindings into the AST\n * and compiling fresh when the backend cannot execute raw SQL text.\n */\n async #executeRows(\n ast: QueryAst,\n bindings: Readonly<Record<string, unknown>>,\n ): Promise<readonly Record<string, unknown>[]> {\n const executeRaw = this.#backend.executeRaw;\n const template = executeRaw === undefined ? undefined : this.#template(ast);\n if (template !== undefined && executeRaw !== undefined) {\n const params = fillTemplateParams(\n template.params,\n bindings,\n this.#dialect,\n );\n const rawRows = await executeRaw<Record<string, unknown>>(\n template.sql,\n params,\n );\n return transformPathColumns(rawRows, this.#state, this.#dialect);\n }\n\n const concreteAst = substituteParameters(ast, bindings);\n const compiled = compileQuery(\n concreteAst,\n this.#graphId,\n this.#compileOptions,\n );\n const rawRows =\n await this.#backend.execute<Record<string, unknown>>(compiled);\n return transformPathColumns(rawRows, this.#state, this.#dialect);\n }\n}\n\ntype ParameterMetadata = Readonly<{\n names: ReadonlySet<string>;\n /** Parameters used in string_op predicates (must receive string values). */\n stringOpParameters: ReadonlySet<string>;\n}>;\n\nfunction collectParameterMetadata(ast: QueryAst): ParameterMetadata {\n const names = new Set<string>();\n const stringOpParameters = new Set<string>();\n\n collectParameterMetadataFromAst(ast, names, stringOpParameters);\n\n return { names, stringOpParameters };\n}\n\nexport function hasParameterReferences(ast: QueryAst): boolean {\n return collectParameterMetadata(ast).names.size > 0;\n}\n\nexport function composableQueryHasParameterReferences(\n query: ComposableQuery,\n): boolean {\n if (\"__type\" in query) {\n return (\n composableQueryHasParameterReferences(query.left) ||\n composableQueryHasParameterReferences(query.right)\n );\n }\n return hasParameterReferences(query);\n}\n\nfunction collectParameterMetadataFromAst(\n ast: QueryAst,\n names: Set<string>,\n stringOpParameters: Set<string>,\n): void {\n for (const predicate of ast.predicates) {\n collectParameterMetadataFromExpression(\n predicate.expression,\n names,\n stringOpParameters,\n );\n }\n if (ast.having !== undefined) {\n collectParameterMetadataFromExpression(\n ast.having,\n names,\n stringOpParameters,\n );\n }\n}\n\nfunction collectParameterMetadataFromExpression(\n expression: PredicateExpression,\n names: Set<string>,\n stringOpParameters: Set<string>,\n): void {\n switch (expression.__type) {\n case \"comparison\": {\n if (isParameterRef(expression.right)) {\n names.add(expression.right.name);\n }\n return;\n }\n case \"string_op\": {\n if (isParameterRef(expression.pattern)) {\n names.add(expression.pattern.name);\n stringOpParameters.add(expression.pattern.name);\n }\n return;\n }\n case \"between\": {\n if (isParameterRef(expression.lower)) {\n names.add(expression.lower.name);\n }\n if (isParameterRef(expression.upper)) {\n names.add(expression.upper.name);\n }\n return;\n }\n case \"and\":\n case \"or\": {\n for (const predicate of expression.predicates) {\n collectParameterMetadataFromExpression(\n predicate,\n names,\n stringOpParameters,\n );\n }\n return;\n }\n case \"not\": {\n collectParameterMetadataFromExpression(\n expression.predicate,\n names,\n stringOpParameters,\n );\n return;\n }\n case \"null_check\":\n case \"array_op\":\n case \"object_op\":\n case \"aggregate_comparison\":\n case \"vector_similarity\":\n case \"fulltext_match\": {\n return;\n }\n case \"exists\": {\n collectParameterMetadataFromAst(\n expression.subquery,\n names,\n stringOpParameters,\n );\n return;\n }\n case \"in_subquery\": {\n collectParameterMetadataFromAst(\n expression.subquery,\n names,\n stringOpParameters,\n );\n return;\n }\n }\n}\n\nfunction validateBindings(\n bindings: Readonly<Record<string, unknown>>,\n metadata: ParameterMetadata,\n): void {\n const { names: expectedNames, stringOpParameters } = metadata;\n\n const missing: string[] = [];\n for (const name of expectedNames) {\n if (bindings[name] === undefined) {\n missing.push(name);\n }\n }\n\n if (missing.length > 0) {\n throw new ConfigurationError(\n `Missing bindings for parameter${missing.length === 1 ? \"\" : \"s\"}: ${missing.map((name) => `\"${name}\"`).join(\", \")}`,\n { missingParameters: missing },\n );\n }\n\n const unexpected = Object.keys(bindings).filter(\n (name) => !expectedNames.has(name),\n );\n if (unexpected.length > 0) {\n throw new ConfigurationError(\n `Unexpected bindings provided: ${unexpected.map((name) => `\"${name}\"`).join(\", \")}`,\n { unexpectedParameters: unexpected },\n );\n }\n\n // Validate value types upfront so both the fast path (executeRaw) and the\n // fallback path (AST substitution) reject the same invalid inputs.\n for (const name of expectedNames) {\n const value = bindings[name];\n validateBindingValue(name, value, stringOpParameters.has(name));\n }\n}\n\nfunction validateBindingValue(\n name: string,\n value: unknown,\n isStringOp: boolean,\n): void {\n if (value === null) {\n throw new ConfigurationError(\n \"Parameter value must not be null (use undefined-based patterns instead)\",\n { parameterName: name, valueType: \"null\" },\n );\n }\n if (isStringOp) {\n if (typeof value !== \"string\") {\n throw new ConfigurationError(\n `Parameter \"${name}\" must be a string for string operations`,\n { parameterName: name, actualType: typeof value },\n );\n }\n return;\n }\n if (\n value instanceof Date ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return;\n }\n throw new ConfigurationError(\n `Unsupported parameter value type: ${typeof value}`,\n { parameterName: name, actualType: typeof value },\n );\n}\n","/**\n * SQL Identifier Validation\n *\n * Validates aliases and identifiers to prevent SQL injection.\n */\nimport { ValidationError } from \"../../errors\";\nimport { type HybridFusionOptions, type PredicateExpression } from \"../ast\";\n\n/**\n * Pattern for valid SQL identifiers (aliases).\n * Must start with a letter or underscore, followed by letters, digits, or underscores.\n * Maximum length of 63 characters (PostgreSQL limit).\n */\nconst SQL_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/;\n\n/**\n * Reserved SQL keywords that cannot be used as aliases.\n */\nconst SQL_RESERVED_KEYWORDS = new Set([\n \"select\",\n \"from\",\n \"where\",\n \"and\",\n \"or\",\n \"not\",\n \"in\",\n \"is\",\n \"null\",\n \"true\",\n \"false\",\n \"as\",\n \"on\",\n \"join\",\n \"left\",\n \"right\",\n \"inner\",\n \"outer\",\n \"cross\",\n \"full\",\n \"group\",\n \"by\",\n \"having\",\n \"order\",\n \"asc\",\n \"desc\",\n \"limit\",\n \"offset\",\n \"union\",\n \"intersect\",\n \"except\",\n \"all\",\n \"distinct\",\n \"case\",\n \"when\",\n \"then\",\n \"else\",\n \"end\",\n \"exists\",\n \"between\",\n \"like\",\n \"ilike\",\n \"insert\",\n \"update\",\n \"delete\",\n \"create\",\n \"drop\",\n \"alter\",\n \"table\",\n \"index\",\n \"view\",\n \"with\",\n \"recursive\",\n]);\n\n/**\n * Validates that an alias is a safe SQL identifier.\n *\n * @param alias - The alias to validate\n * @throws ValidationError if the alias is not a valid SQL identifier\n */\nexport function validateSqlIdentifier(alias: string): void {\n if (!SQL_IDENTIFIER_PATTERN.test(alias)) {\n throw new ValidationError(\n `Invalid alias \"${alias}\": must start with a letter or underscore, ` +\n `contain only letters, digits, and underscores, and be at most 63 characters`,\n {\n issues: [\n {\n path: \"alias\",\n message: `\"${alias}\" is not a valid SQL identifier`,\n },\n ],\n },\n {\n suggestion: `Use a simple identifier like \"p\", \"e\", \"node1\", or \"my_alias\".`,\n },\n );\n }\n\n if (alias.toLowerCase().startsWith(\"cte_\")) {\n throw new ValidationError(\n `Invalid alias \"${alias}\": aliases starting with \"cte_\" are reserved for internal use`,\n {\n issues: [\n {\n path: \"alias\",\n message: `\"${alias}\" conflicts with internal CTE naming`,\n },\n ],\n },\n {\n suggestion: `Choose an alias that does not start with \"cte_\".`,\n },\n );\n }\n\n if (SQL_RESERVED_KEYWORDS.has(alias.toLowerCase())) {\n throw new ValidationError(\n `Invalid alias \"${alias}\": \"${alias}\" is a reserved SQL keyword`,\n {\n issues: [\n { path: \"alias\", message: `\"${alias}\" is a reserved SQL keyword` },\n ],\n },\n {\n suggestion: `Choose a different alias. Reserved words like SELECT, FROM, WHERE cannot be used.`,\n },\n );\n }\n}\n\n/**\n * Walks a predicate expression and rejects placement under OR/NOT for\n * structural predicates (vector / fulltext) — those rewrite the query\n * shape and are incompatible with disjunction or negation. Both\n * predicate kinds use this same machinery; the `match` callback selects\n * which one is being validated.\n */\nfunction validateStructuralPredicatePlacement(\n expression: PredicateExpression,\n matchType: \"vector_similarity\" | \"fulltext_match\",\n buildError: (path: string) => never,\n inDisallowedBranch: boolean,\n path: string,\n): void {\n if (expression.__type === matchType) {\n if (inDisallowedBranch) buildError(path);\n return;\n }\n switch (expression.__type) {\n case \"and\": {\n for (const [index, child] of expression.predicates.entries()) {\n validateStructuralPredicatePlacement(\n child,\n matchType,\n buildError,\n inDisallowedBranch,\n `${path}.predicates[${index}]`,\n );\n }\n return;\n }\n case \"or\": {\n for (const [index, child] of expression.predicates.entries()) {\n validateStructuralPredicatePlacement(\n child,\n matchType,\n buildError,\n true,\n `${path}.predicates[${index}]`,\n );\n }\n return;\n }\n case \"not\": {\n validateStructuralPredicatePlacement(\n expression.predicate,\n matchType,\n buildError,\n true,\n `${path}.predicate`,\n );\n return;\n }\n case \"comparison\":\n case \"string_op\":\n case \"null_check\":\n case \"between\":\n case \"array_op\":\n case \"object_op\":\n case \"aggregate_comparison\":\n case \"exists\":\n case \"in_subquery\":\n case \"vector_similarity\":\n case \"fulltext_match\": {\n return;\n }\n }\n}\n\nfunction throwInvalidVectorPredicatePlacement(path: string): never {\n throw new ValidationError(\n \"Vector similarity predicates cannot be nested under OR or NOT. \" +\n \"Use top-level AND combinations instead.\",\n {\n issues: [\n {\n path,\n message:\n \"Vector similarity predicates are only supported at top-level \" +\n \"or inside AND groups.\",\n },\n ],\n },\n {\n suggestion:\n \"Rewrite the predicate to keep vector similarity at top-level \" +\n \"or combine with additional filters using AND.\",\n },\n );\n}\n\nfunction throwInvalidFulltextPredicatePlacement(path: string): never {\n throw new ValidationError(\n \"Fulltext match predicates (.matches()) cannot be nested under OR or NOT. \" +\n \"Use top-level AND combinations instead.\",\n {\n issues: [\n {\n path,\n message:\n \"Fulltext match predicates are only supported at top-level \" +\n \"or inside AND groups.\",\n },\n ],\n },\n {\n suggestion:\n \"Restructure your query so the fulltext match appears at the top level \" +\n \"of a whereNode() or inside an .and() combination.\",\n },\n );\n}\n\nexport function validateVectorPredicatePlacement(\n predicates: readonly { expression: PredicateExpression }[],\n): void {\n for (const [index, predicate] of predicates.entries()) {\n validateStructuralPredicatePlacement(\n predicate.expression,\n \"vector_similarity\",\n throwInvalidVectorPredicatePlacement,\n false,\n `predicates[${index}].expression`,\n );\n }\n}\n\nexport function validateFulltextPredicatePlacement(\n predicates: readonly { expression: PredicateExpression }[],\n): void {\n for (const [index, predicate] of predicates.entries()) {\n validateStructuralPredicatePlacement(\n predicate.expression,\n \"fulltext_match\",\n throwInvalidFulltextPredicatePlacement,\n false,\n `predicates[${index}].expression`,\n );\n }\n}\n\n/**\n * Validates fusion options shared by `QueryBuilder.fuseWith()` and\n * `store.search.hybrid({ fusion })`. Rejects unsupported methods, and\n * non-finite / non-positive k, and negative / non-finite weights.\n */\nexport function validateHybridFusionOptions(\n options: HybridFusionOptions,\n): void {\n // Cast through string to survive callers that bypass the TS type\n // (e.g. user-supplied JSON on the store.search.hybrid path).\n const method = options.method as string | undefined;\n if (method !== undefined && method !== \"rrf\") {\n throw new ValidationError(`Unsupported fusion method: ${method}`, {\n issues: [{ path: \"fusion.method\", message: `Only \"rrf\" is supported.` }],\n });\n }\n const { k } = options;\n if (k !== undefined && (!Number.isFinite(k) || k <= 0)) {\n throw new ValidationError(\n `Fusion k must be a positive finite number, got: ${String(k)}`,\n {\n issues: [{ path: \"fusion.k\", message: \"Must be a positive number.\" }],\n },\n );\n }\n const weights = options.weights;\n if (weights !== undefined) {\n for (const key of [\"vector\", \"fulltext\"] as const) {\n const weight = weights[key];\n if (weight !== undefined && (!Number.isFinite(weight) || weight < 0)) {\n throw new ValidationError(\n `Fusion weight for \"${key}\" must be a non-negative finite number, got: ${String(weight)}`,\n {\n issues: [\n {\n path: `fusion.weights.${key}`,\n message: \"Must be a non-negative number.\",\n },\n ],\n },\n );\n }\n }\n }\n}\n","/**\n * AST Builder utilities for query construction.\n *\n * Provides shared functions for building QueryAst objects from builder state.\n */\nimport { type QueryAst } from \"../ast\";\nimport type { QueryBuilderConfig, QueryBuilderState } from \"./types\";\nimport {\n validateFulltextPredicatePlacement,\n validateVectorPredicatePlacement,\n} from \"./validation\";\n\n/**\n * Builds a QueryAst from builder config and state.\n *\n * This is shared by ExecutableQuery and ExecutableAggregateQuery to avoid\n * duplicating the AST construction logic.\n */\nexport function buildQueryAst(\n config: QueryBuilderConfig,\n state: QueryBuilderState,\n): QueryAst {\n validateVectorPredicatePlacement(state.predicates);\n validateFulltextPredicatePlacement(state.predicates);\n\n const temporalMode: { mode: typeof state.temporalMode; asOf?: string } = {\n mode: state.temporalMode,\n };\n if (state.asOf !== undefined) {\n temporalMode.asOf = state.asOf;\n }\n\n return {\n graphId: config.graphId,\n start: {\n alias: state.startAlias,\n kinds: state.startKinds,\n includeSubClasses: state.includeSubClasses,\n },\n traversals: state.traversals,\n predicates: state.predicates,\n projection: {\n fields: state.projection,\n },\n temporalMode,\n ...(state.recordedAsOf !== undefined && {\n recordedAsOf: state.recordedAsOf,\n }),\n ...(state.orderBy.length > 0 && { orderBy: state.orderBy }),\n ...(state.limit !== undefined && { limit: state.limit }),\n ...(state.offset !== undefined && { offset: state.offset }),\n ...(state.groupBy !== undefined && { groupBy: state.groupBy }),\n ...(state.having !== undefined && { having: state.having }),\n ...(state.aggregateOrderBy.length > 0 && {\n aggregateOrderBy: state.aggregateOrderBy,\n }),\n ...(state.fusion !== undefined && { fusion: state.fusion }),\n };\n}\n","/**\n * Module-private builder context used by StoreView and recorded-time reads.\n *\n * These values are real query-builder mechanics, but not public builder API:\n * callers should pin coordinates through Store/StoreView and bind recorded\n * reads through Store options. A WeakMap keeps the public QueryBuilderConfig\n * free of internal-only fields while preserving clone-by-config behavior.\n */\nimport { type ReadCoordinate } from \"../../core/temporal\";\nimport { type RecordedReadBinding } from \"../compiler/schema\";\nimport { type QueryBuilderConfig } from \"./types\";\n\nexport type QueryBuilderInternalContext = Readonly<{\n recordedReadBinding?: RecordedReadBinding | undefined;\n sealedCoordinate?: ReadCoordinate | undefined;\n}>;\n\nconst contexts = new WeakMap<QueryBuilderConfig, QueryBuilderInternalContext>();\n\nexport function registerQueryBuilderInternalContext(\n config: QueryBuilderConfig,\n context: QueryBuilderInternalContext,\n): void {\n if (\n context.recordedReadBinding === undefined &&\n context.sealedCoordinate === undefined\n ) {\n return;\n }\n contexts.set(config, context);\n}\n\nexport function getQueryBuilderInternalContext(\n config: QueryBuilderConfig,\n): QueryBuilderInternalContext {\n return contexts.get(config) ?? {};\n}\n","/**\n * Shared `CompileQueryOptions` construction for the executable query,\n * aggregate query, and unionable query builders. Keeps one source of\n * truth for which config fields are propagated to the compiler.\n */\nimport { resolveEmbeddingFields } from \"../../core/embedding\";\nimport { resolveDeclaredFulltextLanguage } from \"../../core/searchable\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { type CompileQueryOptions } from \"../compiler/index\";\nimport {\n type VectorSlotDescriptor,\n vectorSlotKey,\n type VectorSlotMap,\n} from \"../compiler/schema\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport { type QueryBuilderConfig } from \"./types\";\n\nexport function buildCompileOptions(\n config: QueryBuilderConfig,\n): CompileQueryOptions {\n const fulltextStrategy = config.backend?.fulltextStrategy;\n const vectorStrategy = config.backend?.vectorStrategy;\n const { recordedReadBinding } = getQueryBuilderInternalContext(config);\n return {\n dialect: config.dialect ?? \"sqlite\",\n schema: config.schema,\n windowFunctions: config.backend?.capabilities.windowFunctions ?? true,\n ...(fulltextStrategy === undefined ?\n {}\n : {\n fulltextStrategy,\n fulltextLanguages: buildFulltextLanguages(config.registry),\n }),\n ...(vectorStrategy === undefined ?\n {}\n : { vectorStrategy, vectorSlots: buildVectorSlots(config.registry) }),\n ...(recordedReadBinding === undefined ? {} : { recordedReadBinding }),\n };\n}\n\n/**\n * Memoizes the {@link VectorSlotMap} per registry. A registry is immutable\n * for its lifetime, and `buildCompileOptions` runs on every query compile, so\n * caching avoids re-walking every node kind's schema (and re-allocating the\n * map) on each query — including the majority that contain no `similarTo()`.\n */\nconst vectorSlotsCache = new WeakMap<KindRegistry, VectorSlotMap>();\n\n/**\n * Memoizes each kind's DECLARED fulltext language per registry (the\n * winning-language rule the write path applies). The `$fulltext` CTE uses\n * it to parse queries with a CONSTANT regconfig when every kind in the\n * alias shares one declared language — the per-row\n * `websearch_to_tsquery(\"language\", ...)` form makes the tsquery\n * non-constant, so PostgreSQL's GIN index on `tsv` can never serve the\n * match.\n */\nconst fulltextLanguagesCache = new WeakMap<\n KindRegistry,\n ReadonlyMap<string, string>\n>();\n\nfunction buildFulltextLanguages(\n registry: KindRegistry,\n): ReadonlyMap<string, string> {\n const cached = fulltextLanguagesCache.get(registry);\n if (cached !== undefined) return cached;\n\n const languages = new Map<string, string>();\n for (const [nodeKind, nodeType] of registry.nodeKinds) {\n const language = resolveDeclaredFulltextLanguage(nodeType.schema);\n if (language !== undefined) languages.set(nodeKind, language);\n }\n fulltextLanguagesCache.set(registry, languages);\n return languages;\n}\n\n/**\n * Builds the compiler's {@link VectorSlotMap} from every registered node\n * kind's embedding fields. Used only when a vector strategy is present —\n * it tells the `field.similarTo(...)` CTE which `(kind, fieldPath)` pairs\n * back a per-field table, so the UNION ALL only scans kinds that declare\n * the field. Memoized per (immutable) registry.\n */\nfunction buildVectorSlots(registry: KindRegistry): VectorSlotMap {\n const cached = vectorSlotsCache.get(registry);\n if (cached !== undefined) return cached;\n\n const slots = new Map<string, VectorSlotDescriptor>();\n for (const [nodeKind, nodeType] of registry.nodeKinds) {\n for (const field of resolveEmbeddingFields(nodeType.schema)) {\n slots.set(vectorSlotKey(nodeKind, field.fieldPath), {\n dimensions: field.dimensions,\n metric: field.metric,\n indexType: field.indexType,\n });\n }\n }\n vectorSlotsCache.set(registry, slots);\n return slots;\n}\n","/**\n * ExecutableQuery - A query that can be executed, paginated, or streamed.\n */\nimport {\n type GraphBackend,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { DEFAULT_PAGINATION_LIMIT } from \"../../constants\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { UnsupportedPredicateError, ValidationError } from \"../../errors\";\nimport { compareStrings } from \"../../utils/compare\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\nimport {\n mergeEdgeKinds,\n type OrderSpec,\n type QueryAst,\n type SelectiveField,\n type SortDirection,\n} from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport {\n buildCursorFromRow,\n type CursorData,\n decodeCursor,\n validateCursorColumns,\n} from \"../cursor\";\nimport { type SqlDialect } from \"../dialect/types\";\nimport {\n buildCursorPredicate,\n buildPaginatedResult,\n buildSelectContext,\n buildSelectiveFields,\n createStreamIterable,\n createTrackingContext,\n decodeSelectedValue,\n FieldAccessTracker,\n getStreamBatchSize,\n mapResults,\n mapSelectiveResults,\n MissingSelectiveFieldError,\n nullToUndefined,\n transformPathColumns,\n} from \"../execution\";\nimport { jsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport { fieldRef } from \"../predicates\";\nimport { type FieldTypeInfo } from \"../schema-introspector\";\nimport { type CompiledSelectSql } from \"../sql-intent\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { hasParameterReferences, PreparedQuery } from \"./prepared-query\";\nimport {\n buildQueryTemplate,\n type CompiledTemplate,\n fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n type AliasMap,\n type EdgeAliasMap,\n type PaginatedResult,\n type PaginateOptions,\n type QueryBuilderConfig,\n type QueryBuilderState,\n type RecursiveAliasMap,\n type SelectContext,\n type StreamOptions,\n} from \"./types\";\nimport { type UnionableQuery } from \"./unionable-query\";\n\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\n// Forward declaration for UnionableQuery to avoid circular imports\ntype UnionableQueryConstructor = new (\n config: QueryBuilderConfig,\n state: {\n left: QueryAst;\n operator: \"union\" | \"unionAll\" | \"intersect\" | \"except\";\n right: QueryAst;\n // Additional state for result transformation\n startAlias: string;\n traversals: QueryBuilderState[\"traversals\"];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any select function type for set operations\n selectFn: (context: SelectContext<any, any>) => unknown;\n },\n) => unknown;\n\nlet UnionableQueryClass: UnionableQueryConstructor;\n\n/**\n * Sets the UnionableQuery class reference.\n * Called during module initialization to break circular dependency.\n */\nexport function setUnionableQueryClass(cls: UnionableQueryConstructor): void {\n UnionableQueryClass = cls;\n}\n\n/**\n * A query that can be executed.\n */\nexport class ExecutableQuery<\n G extends GraphDef,\n Aliases extends AliasMap,\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty object for initial empty edge alias map\n EdgeAliases extends EdgeAliasMap = {},\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Empty when no recursive aliases\n RecursiveAliases extends RecursiveAliasMap = {},\n R = unknown,\n> {\n readonly #config: QueryBuilderConfig;\n readonly #state: QueryBuilderState;\n readonly #selectFn: (\n context: SelectContext<Aliases, EdgeAliases, RecursiveAliases>,\n ) => R;\n #cachedSelectiveFieldsForExecute:\n readonly SelectiveField[] | typeof NOT_COMPUTED | undefined = NOT_COMPUTED;\n #cachedSelectiveFieldsForPagination:\n readonly SelectiveField[] | typeof NOT_COMPUTED | undefined = NOT_COMPUTED;\n // The instance is immutable (every builder method returns a new instance),\n // so the AST and its param-ref check are invariant — compute each once and\n // reuse across execute()/paginate()/stream() instead of rebuilding per call.\n #cachedAst: QueryAst | undefined;\n #cachedHasParameterReferences: boolean | undefined;\n // Per-instance compiled placeholder templates for the full and\n // selective-field ASTs (NOT_COMPUTED = not yet built; undefined = no fast\n // path). Reused across execute()/executeOn() calls so a repeated query\n // compiles once; the read instant is filled fresh per call, never cached.\n #fullTemplate: CompiledTemplate | typeof NOT_COMPUTED | undefined =\n NOT_COMPUTED;\n #selectiveTemplate: CompiledTemplate | typeof NOT_COMPUTED | undefined =\n NOT_COMPUTED;\n\n constructor(\n config: QueryBuilderConfig,\n state: QueryBuilderState,\n selectFunction: (\n context: SelectContext<Aliases, EdgeAliases, RecursiveAliases>,\n ) => R,\n ) {\n this.#config = config;\n this.#state = state;\n this.#selectFn = selectFunction;\n }\n\n /**\n * Builds the query AST (memoized — the instance is immutable).\n */\n toAst(): QueryAst {\n return (this.#cachedAst ??= buildQueryAst(this.#config, this.#state));\n }\n\n /** Whether this query uses `param()` refs (memoized). */\n #hasParameterReferences(): boolean {\n return (this.#cachedHasParameterReferences ??= hasParameterReferences(\n this.toAst(),\n ));\n }\n\n /**\n * Orders results.\n */\n orderBy<A extends (keyof Aliases | keyof EdgeAliases) & string>(\n alias: A,\n field: string,\n direction: SortDirection = \"asc\",\n ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R> {\n const edgeTraversal = this.#state.traversals.find(\n (traversal) => traversal.edgeAlias === alias,\n );\n const isEdge = edgeTraversal !== undefined;\n const isSystem =\n field === \"id\" ||\n field === \"kind\" ||\n (isEdge && (field === \"from_id\" || field === \"to_id\"));\n\n let typeInfo: FieldTypeInfo | undefined;\n if (!isSystem) {\n if (isEdge) {\n const edgeKindNames = mergeEdgeKinds(edgeTraversal);\n typeInfo = this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n edgeKindNames,\n field,\n );\n } else {\n const kindNames =\n alias === this.#state.startAlias ?\n this.#state.startKinds\n : this.#state.traversals.find(\n (traversal) => traversal.nodeAlias === alias,\n )?.nodeKinds;\n typeInfo =\n kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n kindNames,\n field,\n )\n : undefined;\n }\n }\n\n const orderSpec: OrderSpec =\n isSystem ?\n {\n field: fieldRef(alias, [field], { valueType: \"string\" }),\n direction,\n }\n : {\n field: fieldRef(alias, [\"props\"], {\n jsonPointer: jsonPointer([field]),\n valueType: typeInfo?.valueType,\n elementType: typeInfo?.elementType,\n }),\n direction,\n };\n\n const newState: QueryBuilderState = {\n ...this.#state,\n orderBy: [...this.#state.orderBy, orderSpec],\n };\n\n return new ExecutableQuery(this.#config, newState, this.#selectFn);\n }\n\n /**\n * Limits the number of results.\n */\n limit(\n n: number,\n ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R> {\n return new ExecutableQuery(\n this.#config,\n { ...this.#state, limit: n },\n this.#selectFn,\n );\n }\n\n /**\n * Offsets the results.\n */\n offset(\n n: number,\n ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R> {\n return new ExecutableQuery(\n this.#config,\n { ...this.#state, offset: n },\n this.#selectFn,\n );\n }\n\n /**\n * Applies a query fragment to transform this executable query.\n *\n * Useful for applying post-select transformations like ordering,\n * limits, and offsets from reusable fragments.\n *\n * @example\n * ```typescript\n * const paginated = (q) => q.orderBy(\"u\", \"createdAt\", \"desc\").limit(10);\n *\n * const results = await query()\n * .from(\"User\", \"u\")\n * .select((ctx) => ctx.u)\n * .pipe(paginated)\n * .execute();\n * ```\n *\n * @param fragment - A function that transforms the executable query\n * @returns The transformed executable query\n */\n pipe<NewR = R>(\n fragment: (\n query: ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R>,\n ) => ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, NewR>,\n ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, NewR> {\n return fragment(this);\n }\n\n /**\n * Combines this query with another using UNION (removes duplicates).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any alias map for set operations\n union(other: ExecutableQuery<G, any, any, any, R>): UnionableQuery<G, R> {\n return new UnionableQueryClass(this.#config, {\n left: this.toAst(),\n operator: \"union\",\n right: other.toAst(),\n // Pass state for result transformation\n startAlias: this.#state.startAlias,\n traversals: this.#state.traversals,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure for set operations\n selectFn: this.#selectFn as (context: SelectContext<any, any>) => unknown,\n }) as UnionableQuery<G, R>;\n }\n\n /**\n * Combines this query with another using UNION ALL (keeps duplicates).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any alias map for set operations\n unionAll(other: ExecutableQuery<G, any, any, any, R>): UnionableQuery<G, R> {\n return new UnionableQueryClass(this.#config, {\n left: this.toAst(),\n operator: \"unionAll\",\n right: other.toAst(),\n // Pass state for result transformation\n startAlias: this.#state.startAlias,\n traversals: this.#state.traversals,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure for set operations\n selectFn: this.#selectFn as (context: SelectContext<any, any>) => unknown,\n }) as UnionableQuery<G, R>;\n }\n\n /**\n * Combines this query with another using INTERSECT.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any alias map for set operations\n intersect(other: ExecutableQuery<G, any, any, any, R>): UnionableQuery<G, R> {\n return new UnionableQueryClass(this.#config, {\n left: this.toAst(),\n operator: \"intersect\",\n right: other.toAst(),\n // Pass state for result transformation\n startAlias: this.#state.startAlias,\n traversals: this.#state.traversals,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure for set operations\n selectFn: this.#selectFn as (context: SelectContext<any, any>) => unknown,\n }) as UnionableQuery<G, R>;\n }\n\n /**\n * Combines this query with another using EXCEPT.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Allow any alias map for set operations\n except(other: ExecutableQuery<G, any, any, any, R>): UnionableQuery<G, R> {\n return new UnionableQueryClass(this.#config, {\n left: this.toAst(),\n operator: \"except\",\n right: other.toAst(),\n // Pass state for result transformation\n startAlias: this.#state.startAlias,\n traversals: this.#state.traversals,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure for set operations\n selectFn: this.#selectFn as (context: SelectContext<any, any>) => unknown,\n }) as UnionableQuery<G, R>;\n }\n\n /**\n * Compiles the query and returns the SQL text and parameters.\n *\n * Requires a backend to be configured (the backend determines the SQL dialect).\n * Use this for debugging, logging, or running the query with a custom executor.\n */\n toSQL(): Readonly<{ sql: string; params: readonly unknown[] }> {\n if (!this.#config.backend?.compileSql) {\n throw new Error(\n \"Cannot convert to SQL: no backend configured or backend does not support compileSql. \" +\n \"Use store.query() to get a backend-aware query builder.\",\n );\n }\n return this.#config.backend.compileSql(this.compile());\n }\n\n /**\n * Compiles the query to TypeGraph's database-independent SQL fragment.\n *\n * Pass the result to a GraphBackend, or use toSQL() to render SQL text and\n * parameters for the configured dialect.\n */\n compile(): CompiledSelectSql {\n // Emits a directly-runnable statement with the read instant as a literal\n // (a backend may execute the result directly), so this is not the\n // reusable placeholder template execute() caches — see #templateFor.\n const ast = this.toAst();\n return compileQuery(ast, this.#config.graphId, this.#compileOptions());\n }\n\n /**\n * Creates a prepared (pre-validated) query that can be executed multiple\n * times with different parameter bindings. Builds and structurally\n * validates the AST once (a malformed query fails fast, here, instead of on\n * first use); the prepared query then compiles once into a reusable template\n * and fills a fresh read instant per execute() — see PreparedQuery's class\n * doc comment.\n *\n * Use `param(\"name\")` in predicates to create parameterized slots,\n * then pass values via `prepared.execute({ name: \"value\" })`.\n *\n * @example\n * ```typescript\n * import { param } from \"@nicia-ai/typegraph\";\n *\n * const prepared = store.query()\n * .from(\"Person\", \"p\")\n * .whereNode(\"p\", (p) => p.name.eq(param(\"name\")))\n * .select((ctx) => ctx.p)\n * .prepare();\n *\n * const alice = await prepared.execute({ name: \"Alice\" });\n * const bob = await prepared.execute({ name: \"Bob\" });\n * ```\n *\n * @throws Error if no backend is configured\n */\n prepare(): PreparedQuery<R> {\n if (!this.#config.backend) {\n throw new Error(\n \"Cannot prepare query: no backend configured. \" +\n \"Use store.query() or pass a backend to createQueryBuilder().\",\n );\n }\n\n // Build AST once\n const baseAst = this.toAst();\n\n // Attempt selective field optimization\n const selectiveFields = this.#getSelectiveFieldsForExecute();\n const ast =\n selectiveFields === undefined ? baseAst : { ...baseAst, selectiveFields };\n const unoptimizedAst = baseAst;\n\n // Compile once here purely to fail fast on a malformed query. PreparedQuery\n // caches its own reusable placeholder template (built lazily on first\n // execute), so this validation compile is safe to discard — it only exists\n // to surface a structural error at prepare() time rather than first use.\n const compileOptions = this.#compileOptions();\n compileQuery(ast, this.#config.graphId, compileOptions);\n compileQuery(unoptimizedAst, this.#config.graphId, compileOptions);\n\n return new PreparedQuery({\n ast,\n unoptimizedAst,\n backend: this.#config.backend,\n dialect: this.#config.dialect ?? \"sqlite\",\n graphId: this.#config.graphId,\n compileOptions: compileOptions,\n state: this.#state,\n selectiveFields,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type erasure needed for PreparedQuery which uses AliasMap\n selectFn: this.#selectFn as (context: SelectContext<any, any>) => R,\n schemaIntrospector: this.#config.schemaIntrospector,\n });\n }\n\n /**\n * Builds compile options from the config.\n */\n #compileOptions(): CompileQueryOptions {\n return buildCompileOptions(this.#config);\n }\n\n #requireBackend(): GraphBackend {\n const { backend } = this.#config;\n if (backend === undefined) {\n throw new Error(\n \"Cannot execute query: no backend configured. \" +\n \"Provide a backend when creating the QueryBuilder.\",\n );\n }\n return backend;\n }\n\n #executeOnBackend<T>(\n backend: GraphBackend | TransactionBackend,\n promise: Promise<T>,\n surface: string,\n ): Promise<T> {\n if (this.#state.recordedAsOf === undefined) return promise;\n return withRecordedRelationsPrecondition(promise, {\n dialect: backend.dialect,\n surface,\n });\n }\n\n #dialect(): SqlDialect {\n return this.#config.dialect ?? \"sqlite\";\n }\n\n /**\n * The cached placeholder template for one AST variant (`\"full\"` or\n * `\"selective\"`), or `undefined` when no fast path applies. Built once per\n * instance from the store backend's compiler; reusable across executions and\n * across store/transaction backends of the same dialect, since SQL text and\n * parameters depend only on the AST and dialect. The read instant is filled\n * fresh per call by {@link fillTemplateParams}, never frozen into the cache.\n */\n #templateFor(\n ast: QueryAst,\n slot: \"full\" | \"selective\",\n ): CompiledTemplate | undefined {\n const cached =\n slot === \"full\" ? this.#fullTemplate : this.#selectiveTemplate;\n if (cached !== NOT_COMPUTED) return cached;\n const built = this.#buildTemplate(ast);\n if (slot === \"full\") this.#fullTemplate = built;\n else this.#selectiveTemplate = built;\n return built;\n }\n\n #buildTemplate(ast: QueryAst): CompiledTemplate | undefined {\n return buildQueryTemplate(\n ast,\n this.#config.graphId,\n this.#compileOptions(),\n this.#config.backend,\n );\n }\n\n /**\n * Fetches raw rows for one AST variant, path-column-normalized. Prefers the\n * cached template + `executeRaw` fast path; falls back to a fresh literal\n * compile via `backend.execute` when the backend cannot run raw SQL text (in\n * which case no template is built). Callers map the returned rows to typed\n * results.\n */\n async #fetchRows(\n backend: GraphBackend | TransactionBackend,\n ast: QueryAst,\n slot: \"full\" | \"selective\",\n surface: string,\n ): Promise<readonly Record<string, unknown>[]> {\n const executeRaw = backend.executeRaw;\n const template =\n executeRaw === undefined ? undefined : this.#templateFor(ast, slot);\n const rawRows = await this.#executeOnBackend(\n backend,\n template !== undefined && executeRaw !== undefined ?\n executeRaw<Record<string, unknown>>(\n template.sql,\n fillTemplateParams(template.params, {}, this.#dialect()),\n )\n : backend.execute<Record<string, unknown>>(\n compileQuery(ast, this.#config.graphId, this.#compileOptions()),\n ),\n surface,\n );\n return transformPathColumns(rawRows, this.#state, this.#dialect());\n }\n\n /**\n * Executes the query and returns typed results.\n *\n * Uses smart optimization to detect when only specific fields are accessed\n * in the select callback. If the callback only accesses simple field\n * references (no method calls or computations), generates optimized SQL\n * that only extracts those fields instead of the full props blob.\n *\n * @throws Error if no backend is configured\n */\n async execute(): Promise<readonly R[]> {\n if (!this.#config.backend) {\n throw new Error(\n \"Cannot execute query: no backend configured. \" +\n \"Use store.query() or pass a backend to createQueryBuilder().\",\n );\n }\n const backend = this.#config.backend;\n\n // Guard: reject queries with param() refs — must use .prepare().execute({...})\n const ast = this.toAst();\n if (this.#hasParameterReferences()) {\n throw new Error(\n \"Query contains param() references. Use .prepare().execute({...}) instead of .execute().\",\n );\n }\n\n // Phase 1: Try optimized execution\n const optimizedResult = await this.#tryOptimizedExecution();\n if (optimizedResult !== undefined) {\n return optimizedResult;\n }\n\n // Phase 2: Fall back to full fetch (cached template + executeRaw, or a\n // fresh literal compile on backends without raw execution).\n const rows = await this.#fetchRows(backend, ast, \"full\", \"recorded-query\");\n\n // Cast: runtime context includes recursive aliases; type erasure in mapResults is safe\n return mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n rows,\n this.#state.startAlias,\n this.#state.traversals,\n this.#selectFn,\n );\n }\n\n /**\n * Executes the query against a provided backend.\n *\n * Used by `store.batch()` to run multiple queries over a single connection\n * (e.g., within a transaction). The full compile → execute → transform\n * pipeline runs identically to `execute()`, but against the given backend.\n */\n async executeOn(\n backend: GraphBackend | TransactionBackend,\n ): Promise<readonly R[]> {\n const ast = this.toAst();\n // Guard: reject queries with param() refs — must use .prepare().execute({...})\n if (this.#hasParameterReferences()) {\n throw new Error(\n \"Query contains param() references. Use .prepare().execute({...}) instead of .execute().\",\n );\n }\n\n // Try optimized execution with the provided backend\n const optimizedResult = await this.#tryOptimizedExecutionOn(backend);\n if (optimizedResult !== undefined) {\n return optimizedResult;\n }\n\n // Fall back to full fetch (cached template + executeRaw on the provided\n // backend, or a fresh literal compile when it can't run raw SQL).\n const rows = await this.#fetchRows(\n backend,\n ast,\n \"full\",\n \"recorded-batch-query\",\n );\n\n return mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n rows,\n this.#state.startAlias,\n this.#state.traversals,\n this.#selectFn,\n );\n }\n\n /**\n * Attempts optimized execution by tracking which fields the select callback accesses.\n *\n * Returns undefined if optimization is not possible (callback uses method calls,\n * computations, or returns whole nodes).\n */\n async #tryOptimizedExecution(): Promise<readonly R[] | undefined> {\n const selectiveFields = this.#getSelectiveFieldsForExecute();\n if (selectiveFields === undefined) {\n return undefined;\n }\n\n // Cached template + executeRaw when available; the read instant is filled\n // fresh per call, so a reused query never freezes \"now\" (the #246\n // regression) yet compiles only once.\n const baseAst = this.toAst();\n const selectiveAst = { ...baseAst, selectiveFields };\n\n const backend = this.#requireBackend();\n const rows = await this.#fetchRows(\n backend,\n selectiveAst,\n \"selective\",\n \"recorded-query\",\n );\n\n try {\n // RecursiveAliases are populated at runtime but erased in mapSelectiveResults' signature\n return mapSelectiveResults<Aliases, EdgeAliases, R>(\n rows,\n this.#state,\n selectiveFields,\n this.#config.schemaIntrospector,\n this.#selectFn as (context: SelectContext<Aliases, EdgeAliases>) => R,\n );\n } catch (error) {\n if (error instanceof MissingSelectiveFieldError) {\n this.#cachedSelectiveFieldsForExecute = undefined;\n return undefined;\n }\n if (error instanceof UnsupportedPredicateError) {\n this.#cachedSelectiveFieldsForExecute = undefined;\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * Attempts optimized execution against a provided backend.\n * Mirror of #tryOptimizedExecution but delegates to the given backend.\n */\n async #tryOptimizedExecutionOn(\n backend: GraphBackend | TransactionBackend,\n ): Promise<readonly R[] | undefined> {\n const selectiveFields = this.#getSelectiveFieldsForExecute();\n if (selectiveFields === undefined) {\n return undefined;\n }\n\n // Cached template + executeRaw on the provided backend; see\n // #tryOptimizedExecution.\n const baseAst = this.toAst();\n const selectiveAst = { ...baseAst, selectiveFields };\n\n const rows = await this.#fetchRows(\n backend,\n selectiveAst,\n \"selective\",\n \"recorded-batch-query\",\n );\n\n try {\n return mapSelectiveResults<Aliases, EdgeAliases, R>(\n rows,\n this.#state,\n selectiveFields,\n this.#config.schemaIntrospector,\n this.#selectFn as (context: SelectContext<Aliases, EdgeAliases>) => R,\n );\n } catch (error) {\n if (error instanceof MissingSelectiveFieldError) {\n this.#cachedSelectiveFieldsForExecute = undefined;\n return undefined;\n }\n if (error instanceof UnsupportedPredicateError) {\n this.#cachedSelectiveFieldsForExecute = undefined;\n return undefined;\n }\n throw error;\n }\n }\n\n #trackSelectFunctionAccesses(tracker: FieldAccessTracker): void {\n const hasOptionalTraversal = this.#state.traversals.some(\n (traversal) => traversal.optional,\n );\n\n const trackingRuns =\n hasOptionalTraversal ?\n ([\n {\n mode: \"truthy\" as const,\n optionalTraversalAliases: \"present\" as const,\n },\n {\n mode: \"falsy\" as const,\n optionalTraversalAliases: \"present\" as const,\n },\n {\n mode: \"falsy\" as const,\n optionalTraversalAliases: \"absent\" as const,\n },\n ] as const)\n : ([\n {\n mode: \"truthy\" as const,\n optionalTraversalAliases: \"present\" as const,\n },\n {\n mode: \"falsy\" as const,\n optionalTraversalAliases: \"present\" as const,\n },\n ] as const);\n\n for (const run of trackingRuns) {\n const trackingContext = createTrackingContext(this.#state, tracker, {\n schemaIntrospector: this.#config.schemaIntrospector,\n mode: run.mode,\n optionalTraversalAliases: run.optionalTraversalAliases,\n });\n\n try {\n // Execute the select callback against a lightweight tracking context.\n // We intentionally ignore the return value: we only need accessed fields.\n void this.#selectFn(\n trackingContext as SelectContext<\n Aliases,\n EdgeAliases,\n RecursiveAliases\n >,\n );\n } catch {\n // Best-effort tracking: any runtime errors in the callback (e.g. calling\n // a method on an undefined optional field) should simply disable or\n // reduce optimization, never change correctness.\n }\n }\n }\n\n #getSelectiveFieldsForExecute(): readonly SelectiveField[] | undefined {\n if (this.#cachedSelectiveFieldsForExecute === undefined) {\n return undefined;\n }\n\n if (this.#cachedSelectiveFieldsForExecute !== NOT_COMPUTED) {\n return this.#cachedSelectiveFieldsForExecute;\n }\n\n const tracker = new FieldAccessTracker();\n this.#trackSelectFunctionAccesses(tracker);\n\n const accessed = tracker.getAccessedFields();\n if (accessed.length === 0) {\n this.#cachedSelectiveFieldsForExecute = undefined;\n return undefined;\n }\n\n const selectiveFields = this.#ensureOptionalTraversalIdsSelected(\n buildSelectiveFields(accessed, {\n state: this.#state,\n schemaIntrospector: this.#config.schemaIntrospector,\n }),\n );\n this.#cachedSelectiveFieldsForExecute = selectiveFields;\n return selectiveFields;\n }\n\n #getSelectiveFieldsForPagination(): readonly SelectiveField[] | undefined {\n if (this.#cachedSelectiveFieldsForPagination === undefined) {\n return undefined;\n }\n\n if (this.#cachedSelectiveFieldsForPagination !== NOT_COMPUTED) {\n return this.#cachedSelectiveFieldsForPagination;\n }\n\n const tracker = new FieldAccessTracker();\n this.#trackSelectFunctionAccesses(tracker);\n if (!this.#recordOrderByFieldsForPagination(tracker)) {\n this.#cachedSelectiveFieldsForPagination = undefined;\n return undefined;\n }\n\n const selectiveFields = this.#ensureOptionalTraversalIdsSelected(\n buildSelectiveFields(tracker.getAccessedFields(), {\n state: this.#state,\n schemaIntrospector: this.#config.schemaIntrospector,\n }),\n );\n this.#cachedSelectiveFieldsForPagination = selectiveFields;\n return selectiveFields;\n }\n\n #ensureOptionalTraversalIdsSelected(\n selectiveFields: readonly SelectiveField[],\n ): readonly SelectiveField[] {\n const result = [...selectiveFields];\n const keys = new Set(\n result.map(\n (field) =>\n `${field.alias}\\u0000${field.field}\\u0000${String(field.isSystemField)}`,\n ),\n );\n\n function add(alias: string): void {\n const key = `${alias}\\u0000id\\u0000true`;\n if (keys.has(key)) return;\n keys.add(key);\n result.push({\n alias,\n field: \"id\",\n outputName: `${alias}_id`,\n isSystemField: true,\n });\n }\n\n for (const traversal of this.#state.traversals) {\n if (!traversal.optional) continue;\n add(traversal.nodeAlias);\n add(traversal.edgeAlias);\n }\n\n return result.toSorted((a, b) => {\n const aliasCompare = compareStrings(a.alias, b.alias);\n if (aliasCompare !== 0) return aliasCompare;\n return compareStrings(a.field, b.field);\n });\n }\n\n async #tryOptimizedPaginate(\n cursorData: CursorData | undefined,\n direction: \"forward\" | \"backward\",\n pageLimit: number,\n fetchLimit: number,\n cursor: string | undefined,\n isBackward: boolean,\n ): Promise<PaginatedResult<R> | undefined> {\n const selectiveFields = this.#getSelectiveFieldsForPagination();\n if (selectiveFields === undefined) {\n return undefined;\n }\n\n let rows: readonly Record<string, unknown>[];\n try {\n rows = await this.#executeWithCursor(cursorData, direction, fetchLimit, {\n selectiveFields,\n });\n } catch (error) {\n if (error instanceof UnsupportedPredicateError) {\n this.#cachedSelectiveFieldsForPagination = undefined;\n return undefined;\n }\n throw error;\n }\n\n const hasMore = rows.length > pageLimit;\n const resultRows = hasMore ? rows.slice(0, pageLimit) : rows;\n const paginationDialect = this.#config.dialect ?? \"sqlite\";\n const orderedRows = transformPathColumns(\n isBackward ? resultRows.toReversed() : resultRows,\n this.#state,\n paginationDialect,\n );\n\n let data: readonly R[];\n try {\n // RecursiveAliases are populated at runtime but erased in mapSelectiveResults' signature\n data = mapSelectiveResults<Aliases, EdgeAliases, R>(\n orderedRows,\n this.#state,\n selectiveFields,\n this.#config.schemaIntrospector,\n this.#selectFn as (context: SelectContext<Aliases, EdgeAliases>) => R,\n );\n } catch (error) {\n if (error instanceof MissingSelectiveFieldError) {\n this.#cachedSelectiveFieldsForPagination = undefined;\n return undefined;\n }\n if (error instanceof UnsupportedPredicateError) {\n this.#cachedSelectiveFieldsForPagination = undefined;\n return undefined;\n }\n throw error;\n }\n\n let nextCursor: string | undefined;\n let previousCursor: string | undefined;\n\n if (orderedRows.length > 0) {\n try {\n previousCursor = this.#buildCursorFromSelectiveRow(\n requireDefined(orderedRows[0]),\n selectiveFields,\n \"b\",\n );\n nextCursor = this.#buildCursorFromSelectiveRow(\n requireDefined(orderedRows.at(-1)),\n selectiveFields,\n \"f\",\n );\n } catch (error) {\n if (error instanceof MissingSelectiveFieldError) {\n this.#cachedSelectiveFieldsForPagination = undefined;\n return undefined;\n }\n if (error instanceof UnsupportedPredicateError) {\n this.#cachedSelectiveFieldsForPagination = undefined;\n return undefined;\n }\n throw error;\n }\n }\n\n return {\n data,\n nextCursor: hasMore || isBackward ? nextCursor : undefined,\n prevCursor:\n cursor !== undefined || (isBackward && hasMore) ?\n previousCursor\n : undefined,\n hasNextPage: isBackward ? cursor !== undefined : hasMore,\n hasPrevPage: isBackward ? hasMore : cursor !== undefined,\n };\n }\n\n #recordOrderByFieldsForPagination(tracker: FieldAccessTracker): boolean {\n for (const spec of this.#paginationOrderBy()) {\n const field = spec.field;\n\n // System field (e.g., id, kind) — path is [\"id\"] or [\"kind\"]\n if (\n field.path.length === 1 &&\n field.path[0] !== \"props\" &&\n field.jsonPointer === undefined\n ) {\n tracker.record(field.alias, requireDefined(field.path[0]), true);\n continue;\n }\n\n // Props field — path is [\"props\"] with a JSON pointer\n if (field.path.length !== 1 || field.path[0] !== \"props\") {\n return false;\n }\n\n if (field.jsonPointer === undefined) {\n return false;\n }\n\n const segments = parseJsonPointer(field.jsonPointer);\n if (segments.length !== 1) {\n return false;\n }\n\n tracker.record(field.alias, requireDefined(segments[0]), false);\n }\n\n return true;\n }\n\n #buildCursorFromSelectiveRow(\n row: Record<string, unknown>,\n selectiveFields: readonly SelectiveField[],\n direction: \"f\" | \"b\",\n ): string {\n const contextRow = this.#buildCursorContextFromSelectiveRow(\n row,\n selectiveFields,\n );\n return buildCursorFromRow(contextRow, this.#paginationOrderBy(), direction);\n }\n\n #buildCursorContextFromSelectiveRow(\n row: Record<string, unknown>,\n selectiveFields: readonly SelectiveField[],\n ): Record<string, unknown> {\n const outputNameByAliasField = new Map<string, string>();\n for (const field of selectiveFields) {\n outputNameByAliasField.set(\n `${field.alias}\\u0000${field.field}`,\n field.outputName,\n );\n }\n\n const optionalNodeAliases = new Set<string>();\n for (const traversal of this.#state.traversals) {\n if (traversal.optional) {\n optionalNodeAliases.add(traversal.nodeAlias);\n }\n }\n\n const cursorContext: Record<string, unknown> = {};\n\n for (const spec of this.#paginationOrderBy()) {\n const alias = spec.field.alias;\n const jsonPointer = spec.field.jsonPointer;\n\n // System field order spec (e.g., path=[\"id\"], no jsonPointer)\n if (jsonPointer === undefined) {\n if (spec.field.path.length !== 1) {\n throw new MissingSelectiveFieldError(alias, \"orderBy\");\n }\n const fieldName = requireDefined(spec.field.path[0]);\n const outputName = outputNameByAliasField.get(\n `${alias}\\u0000${fieldName}`,\n );\n if (outputName === undefined) {\n throw new MissingSelectiveFieldError(alias, fieldName);\n }\n\n const aliasObject = this.#getOrCreateAliasObject(cursorContext, alias);\n aliasObject[fieldName] = nullToUndefined(row[outputName]);\n continue;\n }\n\n const segments = parseJsonPointer(jsonPointer);\n if (segments.length === 0) {\n throw new MissingSelectiveFieldError(alias, \"orderBy\");\n }\n\n const topField = requireDefined(segments[0]);\n const outputName = outputNameByAliasField.get(\n `${alias}\\u0000${topField}`,\n );\n if (outputName === undefined) {\n throw new MissingSelectiveFieldError(alias, topField);\n }\n\n if (optionalNodeAliases.has(alias)) {\n const idOutputName = outputNameByAliasField.get(`${alias}\\u0000id`);\n if (idOutputName === undefined) {\n throw new MissingSelectiveFieldError(alias, \"id\");\n }\n const idValue = row[idOutputName];\n if (idValue === null || idValue === undefined) {\n continue;\n }\n }\n\n const aliasObject = this.#getOrCreateAliasObject(cursorContext, alias);\n\n const kindNames = this.#getNodeKindNamesForAlias(alias);\n const typeInfo =\n kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n kindNames,\n topField,\n )\n : undefined;\n\n const decoded = decodeSelectedValue(row[outputName], typeInfo);\n\n if (segments.length === 1) {\n aliasObject[topField] = decoded;\n continue;\n }\n\n let current = aliasObject;\n for (let index = 0; index < segments.length - 1; index++) {\n const segment = requireDefined(segments[index]);\n const existing_ = current[segment];\n if (typeof existing_ === \"object\" && existing_ !== null) {\n current = existing_ as Record<string, unknown>;\n } else {\n const created: Record<string, unknown> = {};\n current[segment] = created;\n current = created;\n }\n }\n current[requireDefined(segments.at(-1))] = decoded;\n }\n\n return cursorContext;\n }\n\n #getOrCreateAliasObject(\n cursorContext: Record<string, unknown>,\n alias: string,\n ): Record<string, unknown> {\n const existing = cursorContext[alias];\n if (typeof existing === \"object\" && existing !== null) {\n return existing as Record<string, unknown>;\n }\n const created: Record<string, unknown> = {};\n cursorContext[alias] = created;\n return created;\n }\n\n #getNodeKindNamesForAlias(alias: string): readonly string[] | undefined {\n if (alias === this.#state.startAlias) {\n return this.#state.startKinds;\n }\n return this.#state.traversals.find((t) => t.nodeAlias === alias)?.nodeKinds;\n }\n\n /**\n * The ORDER BY used for keyset pagination: the caller's ORDER BY plus a final\n * unique tiebreaker on the start alias's `id`. Without a unique final key, a\n * non-unique sort (e.g. `orderBy(\"p\", \"age\")` with many equal ages) makes the\n * keyset predicate `age > lastAge` skip every not-yet-returned equal-age row,\n * silently losing data across pages. The start node's `id` is unique and\n * always projected, so appending it gives a total order that page boundaries\n * can split cleanly. Skipped when the caller already orders by the start\n * alias's `id` (the sort is already total). Every pagination read of ORDER BY\n * — the emitted sort, the cursor predicate, cursor encoding, and cursor\n * validation — routes through here so the extra column stays consistent across\n * the standard and selective-field-optimized paths.\n */\n #paginationOrderBy(): readonly OrderSpec[] {\n const orderBy = this.#state.orderBy;\n const startAlias = this.#state.startAlias;\n const alreadyTotal = orderBy.some(\n (spec) =>\n spec.field.alias === startAlias &&\n spec.field.path.length === 1 &&\n spec.field.path[0] === \"id\" &&\n spec.field.jsonPointer === undefined,\n );\n if (alreadyTotal) return orderBy;\n const tiebreaker: OrderSpec = {\n field: { __type: \"field_ref\", alias: startAlias, path: [\"id\"] },\n direction: \"asc\",\n };\n return [...orderBy, tiebreaker];\n }\n\n /**\n * Executes a paginated query using cursor-based keyset pagination.\n *\n * Cursor pagination is efficient for large datasets as it avoids OFFSET.\n * Requires ORDER BY to be specified for deterministic results.\n *\n * @param options - Pagination options (first/after for forward, last/before for backward)\n * @throws ValidationError if ORDER BY is not specified\n * @throws ValidationError if cursor columns don't match query ORDER BY columns\n */\n async paginate(options: PaginateOptions): Promise<PaginatedResult<R>> {\n if (!this.#config.backend) {\n throw new Error(\n \"Cannot execute query: no backend configured. \" +\n \"Use store.query() or pass a backend to createQueryBuilder().\",\n );\n }\n\n // Validate ORDER BY is present\n if (this.#state.orderBy.length === 0) {\n throw new ValidationError(\n \"Cursor pagination requires ORDER BY. Add .orderBy() before .paginate()\",\n {\n issues: [\n {\n path: \"orderBy\",\n message: \"ORDER BY is required for cursor pagination\",\n },\n ],\n },\n {\n suggestion: `Add .orderBy(alias, field) before .paginate() to specify sort order.`,\n },\n );\n }\n\n // Determine pagination direction and parameters\n const isBackward =\n options.last !== undefined || options.before !== undefined;\n const limit = options.first ?? options.last ?? DEFAULT_PAGINATION_LIMIT;\n const cursor = options.after ?? options.before;\n\n // Decode and validate cursor if provided\n let cursorData: CursorData | undefined;\n if (cursor) {\n cursorData = decodeCursor(cursor);\n validateCursorColumns(cursorData, this.#paginationOrderBy());\n }\n\n // Fetch limit + 1 to detect if there are more pages\n const fetchLimit = limit + 1;\n\n const direction = isBackward ? \"backward\" : \"forward\";\n const optimized = await this.#tryOptimizedPaginate(\n cursorData,\n direction,\n limit,\n fetchLimit,\n cursor,\n isBackward,\n );\n if (optimized !== undefined) {\n return optimized;\n }\n\n // Build and execute query with cursor condition\n const rows = await this.#executeWithCursor(\n cursorData,\n direction,\n fetchLimit,\n );\n\n // Detect if there are more items\n const hasMore = rows.length > limit;\n const resultRows = hasMore ? rows.slice(0, limit) : rows;\n\n // For backward pagination, reverse the results to maintain natural order\n const orderedRows = isBackward ? resultRows.toReversed() : resultRows;\n\n // Map to typed results\n const data = mapResults<Aliases, EdgeAliases, R, RecursiveAliases>(\n orderedRows,\n this.#state.startAlias,\n this.#state.traversals,\n this.#selectFn,\n );\n\n // Build paginated result with cursors\n return buildPaginatedResult(\n data,\n orderedRows,\n this.#paginationOrderBy(),\n limit,\n hasMore,\n isBackward,\n cursor,\n (row) =>\n buildSelectContext<Aliases, EdgeAliases, RecursiveAliases>(\n row,\n this.#state.startAlias,\n this.#state.traversals,\n ),\n );\n }\n\n /**\n * Returns an async iterator that streams results in batches.\n *\n * Uses cursor pagination internally for efficient memory usage.\n * Requires ORDER BY to be specified for deterministic results.\n *\n * @param options - Stream options (batchSize defaults to 1000)\n * @throws ValidationError if ORDER BY is not specified\n */\n stream(options?: StreamOptions): AsyncIterable<R> {\n // Validate ORDER BY is present\n if (this.#state.orderBy.length === 0) {\n throw new ValidationError(\n \"Streaming requires ORDER BY. Add .orderBy() before .stream()\",\n {\n issues: [\n { path: \"orderBy\", message: \"ORDER BY is required for streaming\" },\n ],\n },\n {\n suggestion: `Add .orderBy(alias, field) before .stream() to specify sort order.`,\n },\n );\n }\n\n const batchSize = getStreamBatchSize(options);\n return createStreamIterable(batchSize, (paginateOptions) =>\n this.paginate(paginateOptions),\n );\n }\n\n /**\n * Executes a query with cursor conditions applied.\n */\n async #executeWithCursor(\n cursorData: CursorData | undefined,\n direction: \"forward\" | \"backward\",\n limit: number,\n options?: Readonly<{ selectiveFields?: readonly SelectiveField[] }>,\n ): Promise<readonly Record<string, unknown>[]> {\n const ast = this.toAst();\n\n // Adjust ORDER BY for backward pagination (reverse all directions)\n let orderBy = this.#paginationOrderBy();\n if (direction === \"backward\") {\n orderBy = orderBy.map((spec) => ({\n ...spec,\n direction:\n spec.direction === \"asc\" ? (\"desc\" as const) : (\"asc\" as const),\n }));\n }\n\n // Build cursor predicates if we have cursor data\n let predicates = [...this.#state.predicates];\n if (cursorData) {\n const cursorPredicate = buildCursorPredicate(\n cursorData,\n this.#paginationOrderBy(),\n direction,\n this.#state.startAlias,\n );\n predicates = [...predicates, cursorPredicate];\n }\n\n // Apply modified ORDER BY, predicates, and limit to AST (discard offset)\n const { offset: _discarded, ...astWithoutOffset } = ast;\n const modifiedAst = {\n ...astWithoutOffset,\n predicates,\n orderBy,\n limit,\n ...(options?.selectiveFields !== undefined && {\n selectiveFields: options.selectiveFields,\n }),\n };\n\n // Compile and execute\n const compiled = compileQuery(\n modifiedAst,\n this.#config.graphId,\n this.#compileOptions(),\n );\n const rawRows =\n await this.#requireBackend().execute<Record<string, unknown>>(compiled);\n const dialect = this.#config.dialect ?? \"sqlite\";\n return transformPathColumns(rawRows, this.#state, dialect);\n }\n}\n","/**\n * ExecutableAggregateQuery - A query with aggregate functions that can be executed.\n */\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n type AggregateExpr,\n type AggregateOrderSpec,\n type FieldRef,\n type QueryAst,\n type SortDirection,\n} from \"../ast\";\nimport { compileQuery, type CompileQueryOptions } from \"../compiler/index\";\nimport { type CompiledSelectSql } from \"../sql-intent\";\nimport { buildQueryAst } from \"./ast-builder\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { hasParameterReferences } from \"./prepared-query\";\nimport {\n buildQueryTemplate,\n type CompiledTemplate,\n fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n type AliasMap,\n type QueryBuilderConfig,\n type QueryBuilderState,\n} from \"./types\";\n\n/** Sentinel distinguishing \"template not yet built\" from a built `undefined`. */\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\n/**\n * Result type for aggregate queries.\n * Maps field refs to their value types and aggregates to numbers.\n */\nexport type AggregateResult<\n R extends Record<string, FieldRef | AggregateExpr>,\n> = {\n [K in keyof R]: R[K] extends AggregateExpr ? number\n : R[K] extends FieldRef ? unknown\n : never;\n};\n\n/**\n * An aggregate query that can be executed.\n */\nexport class ExecutableAggregateQuery<\n G extends GraphDef,\n Aliases extends AliasMap,\n R extends Record<string, FieldRef | AggregateExpr>,\n> {\n readonly #config: QueryBuilderConfig;\n readonly #state: QueryBuilderState;\n readonly #fields: R;\n // Per-instance compiled placeholder template, reused across execute() calls\n // (see #resolveTemplate). NOT_COMPUTED = not yet built; undefined = no fast\n // path.\n #template: CompiledTemplate | typeof NOT_COMPUTED | undefined = NOT_COMPUTED;\n\n constructor(config: QueryBuilderConfig, state: QueryBuilderState, fields: R) {\n this.#config = config;\n this.#state = state;\n this.#fields = fields;\n }\n\n /**\n * Builds the query AST.\n */\n toAst(): QueryAst {\n return buildQueryAst(this.#config, this.#state);\n }\n\n /**\n * Orders results by a grouped field or aggregate alias.\n *\n * `key` is one of the output names passed to `.aggregate({...})` — either\n * a grouped field (e.g. `genre`) or an aggregate alias (e.g. `bookCount`).\n * Both are ordered the same way: by referencing the SELECT-list output\n * column, since every `.aggregate()` field is projected with an alias.\n *\n * Chain multiple calls to sort by more than one key, in call order:\n * `.orderBy(\"genre\").orderBy(\"bookCount\", \"desc\")` sorts by genre first,\n * then by book count within each genre.\n *\n * @example\n * ```typescript\n * // Top 2 authors by book count\n * store.query()\n * .from(\"Author\", \"a\")\n * .traverse(\"wrote\", \"e\")\n * .to(\"Book\", \"b\")\n * .groupByNode(\"a\")\n * .aggregate({ author: field(\"a\", \"name\"), bookCount: count(\"b\") })\n * .orderBy(\"bookCount\", \"desc\")\n * .limit(2)\n * .execute();\n * ```\n */\n orderBy<K extends keyof R & string>(\n key: K,\n direction: SortDirection = \"asc\",\n ): ExecutableAggregateQuery<G, Aliases, R> {\n const orderSpec: AggregateOrderSpec = { outputName: key, direction };\n return new ExecutableAggregateQuery(\n this.#config,\n {\n ...this.#state,\n aggregateOrderBy: [...this.#state.aggregateOrderBy, orderSpec],\n },\n this.#fields,\n );\n }\n\n /**\n * Limits the number of results.\n */\n limit(n: number): ExecutableAggregateQuery<G, Aliases, R> {\n return new ExecutableAggregateQuery(\n this.#config,\n { ...this.#state, limit: n },\n this.#fields,\n );\n }\n\n /**\n * Offsets the results.\n */\n offset(n: number): ExecutableAggregateQuery<G, Aliases, R> {\n return new ExecutableAggregateQuery(\n this.#config,\n { ...this.#state, offset: n },\n this.#fields,\n );\n }\n\n /**\n * Compiles the query and returns the SQL text and parameters.\n *\n * Requires a backend to be configured (the backend determines the SQL dialect).\n * Use this for debugging, logging, or running the query with a custom executor.\n */\n toSQL(): Readonly<{ sql: string; params: readonly unknown[] }> {\n if (!this.#config.backend?.compileSql) {\n throw new Error(\n \"Cannot convert to SQL: no backend configured or backend does not support compileSql. \" +\n \"Use store.query() to get a backend-aware query builder.\",\n );\n }\n return this.#config.backend.compileSql(this.compile());\n }\n\n /**\n * Compiles the query to TypeGraph's database-independent SQL fragment.\n */\n compile(): CompiledSelectSql {\n // Emits a directly-runnable statement with the read instant as a literal;\n // this is not the reusable placeholder template execute() caches (see\n // #resolveTemplate).\n const ast = this.toAst();\n return compileQuery(ast, this.#config.graphId, this.#compileOptions());\n }\n\n #compileOptions(): CompileQueryOptions {\n return buildCompileOptions(this.#config);\n }\n\n /**\n * The cached placeholder template for this aggregate query, or `undefined`\n * when no fast path applies. Built once per instance; the read instant is\n * filled fresh per execution by {@link fillTemplateParams}.\n */\n #resolveTemplate(ast: QueryAst): CompiledTemplate | undefined {\n if (this.#template !== NOT_COMPUTED) return this.#template;\n this.#template = buildQueryTemplate(\n ast,\n this.#config.graphId,\n this.#compileOptions(),\n this.#config.backend,\n );\n return this.#template;\n }\n\n /**\n * Executes the query and returns typed results.\n *\n * @throws Error if no backend is configured\n */\n async execute(): Promise<readonly AggregateResult<R>[]> {\n const backend = this.#config.backend;\n if (!backend) {\n throw new Error(\n \"Cannot execute query: no backend configured. \" +\n \"Use store.query() or pass a backend to createQueryBuilder().\",\n );\n }\n\n const ast = this.toAst();\n // Aggregate queries expose no `.prepare()`, so a param() ref can never be\n // bound — reject it with clear guidance instead of a downstream \"missing\n // binding\" error once it reaches the template's placeholder fill.\n if (hasParameterReferences(ast)) {\n throw new Error(\n \"Aggregate queries do not support param() references; bind a concrete value instead.\",\n );\n }\n\n const executeRaw = backend.executeRaw;\n const template =\n executeRaw === undefined ? undefined : this.#resolveTemplate(ast);\n const rows =\n template !== undefined && executeRaw !== undefined ?\n await executeRaw<Record<string, unknown>>(\n template.sql,\n fillTemplateParams(\n template.params,\n {},\n this.#config.dialect ?? \"sqlite\",\n ),\n )\n : await backend.execute<Record<string, unknown>>(\n compileQuery(ast, this.#config.graphId, this.#compileOptions()),\n );\n\n return this.#mapResults(rows);\n }\n\n /**\n * Maps raw database rows to typed results.\n * Handles database-specific value conversions:\n * - PostgreSQL returns bigint/numeric as strings → convert to numbers\n * - SQLite returns JSON booleans as 0/1 numbers → convert to booleans\n * - PostgreSQL returns JSON booleans as \"true\"/\"false\" strings → convert to booleans\n */\n #mapResults(\n rows: readonly Record<string, unknown>[],\n ): readonly AggregateResult<R>[] {\n return rows.map((row) => {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(this.#fields)) {\n const field = this.#fields[key];\n if (!field) continue;\n const value = row[key];\n\n if (field.__type === \"aggregate\") {\n // PostgreSQL returns aggregate bigint/numeric as strings.\n result[key] = typeof value === \"string\" ? Number(value) : value;\n continue;\n }\n\n result[key] = normalizeFieldValue(field, value);\n }\n return result as AggregateResult<R>;\n });\n }\n}\n\n/**\n * Converts database-specific boolean encodings to JS booleans.\n *\n * - SQLite json_extract() returns 0/1 for JSON booleans\n * - PostgreSQL #>> returns \"true\"/\"false\" for JSON booleans\n */\nfunction normalizeBooleanValue(value: unknown): unknown {\n if (value === null) return undefined;\n if (value === true || value === false) return value;\n if (value === 1) return true;\n if (value === 0) return false;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n if (value === \"1\") return true;\n if (value === \"0\") return false;\n return value;\n}\n\nfunction normalizeFieldValue(field: FieldRef, value: unknown): unknown {\n if (field.valueType === \"boolean\") {\n return normalizeBooleanValue(value);\n }\n\n return value === null ? undefined : value;\n}\n","/**\n * Dynamic query builder types.\n *\n * Backs `fromDynamic` / `traverseDynamic` / `optionalTraverseDynamic`\n * / `toDynamic` — the string-keyed sibling methods on `QueryBuilder`\n * and `TraversalBuilder` that admit runtime-declared kinds. Same SQL\n * compiler under the hood; only the alias-level surface types differ.\n *\n * Aliases declared via the dynamic methods carry `DynamicNodeType` /\n * `DynamicEdgeType` brands. `NodeAccessor<N>` / `EdgeAccessor<E>` /\n * `SelectableNode<N>` / `SelectableEdge<E>` branch on those brands so a\n * single query can mix typed and dynamic aliases — a typed alias keeps\n * `StringFieldAccessor`, etc., while a dynamic alias gets\n * `DynamicNodeAccessor` with a `.field(name)` discriminator.\n */\nimport {\n type AnyEdgeType,\n type KindEntity,\n type NodeType,\n} from \"../../core/types\";\nimport { jsonPointer } from \"../json-pointer\";\nimport {\n buildFieldBuilderForTypeInfo,\n fieldRef,\n type FulltextAccessor,\n} from \"../predicates\";\nimport {\n type FieldTypeInfo,\n type SchemaIntrospector,\n} from \"../schema-introspector\";\nimport {\n type ArrayFieldAccessor,\n type BaseFieldAccessor,\n type DateFieldAccessor,\n type EmbeddingFieldAccessor,\n type NumberFieldAccessor,\n type ObjectFieldAccessor,\n type SelectableEdgeMeta,\n type SelectableNodeMeta,\n type StringFieldAccessor,\n} from \"./types\";\n\ndeclare const DYNAMIC_NODE_BRAND: unique symbol;\ndeclare const DYNAMIC_EDGE_BRAND: unique symbol;\n\nexport type DynamicNodeType = NodeType &\n Readonly<{ [DYNAMIC_NODE_BRAND]: true }>;\n\nexport type DynamicEdgeType = AnyEdgeType &\n Readonly<{ [DYNAMIC_EDGE_BRAND]: true }>;\n\nexport type IsDynamicNodeType<N> =\n N extends Readonly<{ [DYNAMIC_NODE_BRAND]: true }> ? true : false;\n\nexport type IsDynamicEdgeType<E> =\n E extends Readonly<{ [DYNAMIC_EDGE_BRAND]: true }> ? true : false;\n\n/**\n * Type-discriminated field builder for runtime-typed properties.\n *\n * `BaseFieldAccessor` methods (`eq`, `isNull`, etc.) are available\n * directly. Type-specific methods (`gte`, `contains`, `similarTo`, …)\n * sit behind a discriminator method that asserts the field's type:\n *\n * ```ts\n * (n) => n.field(\"year\").number().gte(2020)\n * ```\n *\n * The discriminator validates against the registered Zod schema at\n * query-build time and throws `TypeError` on mismatch — the user can't\n * accidentally call `.between(...)` on a string field. The discriminator\n * is a type assertion *and* a runtime check.\n */\nexport type DynamicFieldBuilder = BaseFieldAccessor &\n Readonly<{\n string: () => StringFieldAccessor;\n number: () => NumberFieldAccessor;\n date: () => DateFieldAccessor;\n array: () => ArrayFieldAccessor<unknown>;\n object: () => ObjectFieldAccessor<Readonly<Record<string, unknown>>>;\n embedding: () => EmbeddingFieldAccessor;\n }>;\n\n/**\n * Predicate accessor for a runtime-kind alias.\n *\n * System fields keep their narrow types. Schema properties are reached\n * through `.field(name)` — `.field()` validates the property exists on\n * the registered Zod schema and throws if it doesn't.\n */\nexport type DynamicNodeAccessor = Readonly<{\n id: StringFieldAccessor;\n kind: StringFieldAccessor;\n $fulltext: FulltextAccessor;\n field: (name: string) => DynamicFieldBuilder;\n}>;\n\nexport type DynamicEdgeAccessor = Readonly<{\n id: StringFieldAccessor;\n kind: StringFieldAccessor;\n fromId: StringFieldAccessor;\n toId: StringFieldAccessor;\n field: (name: string) => DynamicFieldBuilder;\n}>;\n\nexport type DynamicSelectableNode = Readonly<{\n id: string;\n kind: string;\n meta: SelectableNodeMeta;\n}> &\n Readonly<Record<string, unknown>>;\n\nexport type DynamicSelectableEdge = Readonly<{\n id: string;\n kind: string;\n fromId: string;\n toId: string;\n meta: SelectableEdgeMeta;\n}> &\n Readonly<Record<string, unknown>>;\n\n/**\n * Renders a kind-context string for error messages — `node kind \"Paper\"`\n * or `edge kinds \"knows\" | \"follows\"`.\n */\nfunction describeKindContext(\n entity: KindEntity,\n kindNames: readonly string[] | undefined,\n): string {\n if (kindNames === undefined || kindNames.length === 0) {\n return `${entity} (kind unresolved)`;\n }\n const list = kindNames.map((k) => `\"${k}\"`).join(\" | \");\n return `${entity} kind${kindNames.length > 1 ? \"s\" : \"\"} ${list}`;\n}\n\n/**\n * Shared dynamic-field-builder factory. Returns a `DynamicFieldBuilder`\n * (typed as `BaseFieldAccessor` at the runtime boundary): the property\n * is validated against the registered Zod schema, and each\n * `.string()` / `.number()` / … discriminator throws `TypeError` on\n * type mismatch.\n *\n * Used by `QueryBuilder.#createNodeAccessor` for node aliases and by\n * `TraversalBuilder.#createEdgeAccessor` for edge aliases — they only\n * differ in which introspector method to call.\n */\nexport function createDynamicFieldBuilder(\n introspector: SchemaIntrospector,\n alias: string,\n name: string,\n kindNames: readonly string[] | undefined,\n entity: KindEntity,\n): BaseFieldAccessor {\n const typeInfo =\n kindNames === undefined ? undefined\n : entity === \"node\" ? introspector.getSharedFieldTypeInfo(kindNames, name)\n : introspector.getSharedEdgeFieldTypeInfo(kindNames, name);\n\n const where = describeKindContext(entity, kindNames);\n if (typeInfo === undefined) {\n throw new Error(`Property \"${name}\" is not declared on ${where}.`);\n }\n\n const ref = fieldRef(alias, [\"props\"], {\n jsonPointer: jsonPointer([name]),\n valueType: typeInfo.valueType,\n elementType: typeInfo.elementType,\n });\n const base = buildFieldBuilderForTypeInfo(ref, typeInfo);\n\n const expect = (asserted: FieldTypeInfo[\"valueType\"]): BaseFieldAccessor => {\n if (typeInfo.valueType !== asserted) {\n throw new TypeError(\n `Property \"${name}\" on ${where} is ${typeInfo.valueType}, not ${asserted}.`,\n );\n }\n return base;\n };\n\n return {\n ...base,\n string: () => expect(\"string\"),\n number: () => expect(\"number\"),\n date: () => expect(\"date\"),\n array: () => expect(\"array\"),\n object: () => expect(\"object\"),\n embedding: () => expect(\"embedding\"),\n } as BaseFieldAccessor;\n}\n","/**\n * TraversalBuilder - Intermediate builder for edge traversals.\n */\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type AnyEdgeType, type NodeType } from \"../../core/types\";\nimport { EndpointError, KindNotFoundError } from \"../../errors\";\nimport {\n type NodePredicate,\n type RecursiveCyclePolicy,\n type Traversal,\n type TraversalDirection,\n} from \"../ast\";\nimport { MAX_EXPLICIT_RECURSIVE_DEPTH } from \"../compiler\";\nimport { jsonPointer } from \"../json-pointer\";\nimport {\n arrayField,\n baseField,\n dateField,\n fieldRef,\n numberField,\n objectField,\n type Predicate,\n stringField,\n} from \"../predicates\";\n// Type-only import to get the QueryBuilder type without runtime circular dependency\nimport {\n createDynamicFieldBuilder,\n type DynamicEdgeType,\n type DynamicNodeType,\n} from \"./dynamic\";\nimport { type QueryBuilder } from \"./query-builder\";\nimport {\n type AliasMap,\n type BaseFieldAccessor,\n type BuildRecursiveAliases,\n type EdgeAccessor,\n type EdgeAlias,\n type EdgeAliasMap,\n type EmptyEdgeAliasMap,\n type EmptyRecursiveAliasMap,\n type NodeAlias,\n type QueryBuilderConfig,\n type QueryBuilderState,\n type QueryCoordinateState,\n type RecursiveAliasMap,\n type RecursiveTraversalOptions,\n type UniqueAlias,\n type ValidEdgeTargets,\n} from \"./types\";\nimport { validateSqlIdentifier } from \"./validation\";\n\n/**\n * Resolves the edge type for an edge alias based on its kind type parameter.\n *\n * For `traverse(...)`, `EK` is a literal like `\"authoredBy\"` and the\n * type comes from the typed graph. For `traverseDynamic(...)`, `EK` is\n * widened to `string` — `string extends EK` distinguishes that case and\n * resolves to `DynamicEdgeType`, so the conditional accessor types fire.\n */\ntype EdgeTypeForKey<G extends GraphDef, EK> =\n string extends EK ? DynamicEdgeType\n : EK extends keyof G[\"edges\"] & string ? G[\"edges\"][EK][\"type\"]\n : DynamicEdgeType;\n\n// Forward declaration - actual import would cause circular dependency\ntype QueryBuilderConstructor = new (\n config: QueryBuilderConfig,\n state: QueryBuilderState,\n) => unknown;\n\n// This will be set by the main builder module to avoid circular imports\nlet QueryBuilderClass: QueryBuilderConstructor;\n\n/**\n * Sets the QueryBuilder class reference for use by TraversalBuilder.\n * Called during module initialization to break circular dependency.\n */\nexport function setQueryBuilderClass(cls: QueryBuilderConstructor): void {\n QueryBuilderClass = cls;\n}\n\n/**\n * State for variable-length traversal configuration.\n */\ninterface VariableLengthState {\n enabled: boolean;\n minDepth: number;\n maxDepth: number;\n cyclePolicy: RecursiveCyclePolicy;\n pathEnabled: boolean;\n pathAlias?: string;\n depthEnabled: boolean;\n depthAlias?: string;\n}\n\n/**\n * Default variable-length state (disabled).\n */\nconst DEFAULT_VARIABLE_LENGTH_STATE: VariableLengthState = {\n enabled: false,\n minDepth: 1,\n maxDepth: -1,\n cyclePolicy: \"prevent\",\n pathEnabled: false,\n depthEnabled: false,\n};\n\nfunction validateMaxHops(max: number): void {\n if (!Number.isFinite(max) || !Number.isInteger(max)) {\n throw new TypeError(\"maxHops must be a finite integer\");\n }\n if (max < 1) {\n throw new Error(\"maxHops must be >= 1\");\n }\n if (max > MAX_EXPLICIT_RECURSIVE_DEPTH) {\n throw new Error(\n `maxHops must be <= ${MAX_EXPLICIT_RECURSIVE_DEPTH}. ` +\n `Use a smaller bound to prevent runaway recursive queries.`,\n );\n }\n}\n\nfunction validateMinHops(min: number): void {\n if (!Number.isFinite(min) || !Number.isInteger(min)) {\n throw new TypeError(\"minHops must be a finite integer\");\n }\n if (min < 0) {\n throw new Error(\"minHops must be >= 0\");\n }\n}\n\nfunction resolveAliasOption(\n option: boolean | string | undefined,\n): string | undefined {\n if (option === undefined || option === false) {\n return;\n }\n\n if (option === true) {\n return;\n }\n\n return option;\n}\n\n/**\n * Intermediate builder for traversal operations.\n *\n * Type parameters track the edge kind and direction to constrain\n * which node kinds are valid targets in the `to()` method.\n */\nexport class TraversalBuilder<\n G extends GraphDef,\n Aliases extends AliasMap,\n EdgeAliases extends EdgeAliasMap = EmptyEdgeAliasMap,\n EK extends keyof G[\"edges\"] & string = keyof G[\"edges\"] & string,\n EA extends string = string,\n Dir extends TraversalDirection = \"out\",\n Optional extends boolean = false,\n DC extends boolean | string = false,\n PC extends boolean | string = false,\n RecAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n CoordinateState extends QueryCoordinateState = \"open\",\n> {\n readonly #config: QueryBuilderConfig;\n readonly #state: QueryBuilderState;\n readonly #edgeKinds: readonly string[];\n readonly #inverseEdgeKinds: readonly string[];\n readonly #edgeAlias: EA;\n readonly #direction: Dir;\n readonly #fromAlias: string;\n readonly #optional: Optional;\n readonly #variableLength: VariableLengthState;\n readonly #pendingEdgePredicates: readonly NodePredicate[];\n\n constructor(\n config: QueryBuilderConfig,\n state: QueryBuilderState,\n edgeKinds: readonly string[],\n edgeAlias: EA,\n direction: Dir,\n fromAlias: string,\n inverseEdgeKinds: readonly string[] = [],\n optional: Optional = false as Optional,\n variableLength: VariableLengthState = DEFAULT_VARIABLE_LENGTH_STATE,\n pendingEdgePredicates: readonly NodePredicate[] = [],\n ) {\n this.#config = config;\n this.#state = state;\n this.#edgeKinds = edgeKinds;\n this.#inverseEdgeKinds = inverseEdgeKinds;\n this.#edgeAlias = edgeAlias;\n this.#direction = direction;\n this.#fromAlias = fromAlias;\n this.#optional = optional;\n this.#variableLength = variableLength;\n this.#pendingEdgePredicates = pendingEdgePredicates;\n }\n\n /**\n * Enables variable-length (recursive) traversal.\n * Defaults to MAX_RECURSIVE_DEPTH (10) hops with cycle prevention.\n * Use `maxHops` to override (up to MAX_EXPLICIT_RECURSIVE_DEPTH).\n */\n recursive<const O extends RecursiveTraversalOptions = Record<string, never>>(\n options?: O,\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n Dir,\n Optional,\n O extends { depth: infer D extends boolean | string } ? D : DC,\n O extends { path: infer P extends boolean | string } ? P : PC,\n RecAliases,\n CoordinateState\n > {\n const minDepth = options?.minHops ?? this.#variableLength.minDepth;\n const maxDepth = options?.maxHops ?? this.#variableLength.maxDepth;\n validateMinHops(minDepth);\n if (options?.maxHops !== undefined) {\n validateMaxHops(maxDepth);\n }\n if (maxDepth > 0 && minDepth > maxDepth) {\n throw new Error(\"minHops must be <= maxHops\");\n }\n\n const pathAlias = resolveAliasOption(options?.path);\n const depthAlias = resolveAliasOption(options?.depth);\n if (pathAlias !== undefined) validateSqlIdentifier(pathAlias);\n if (depthAlias !== undefined) validateSqlIdentifier(depthAlias);\n const cyclePolicy =\n options?.cyclePolicy ?? this.#variableLength.cyclePolicy;\n\n return new TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n Dir,\n Optional,\n O extends { depth: infer D extends boolean | string } ? D : DC,\n O extends { path: infer P extends boolean | string } ? P : PC,\n RecAliases,\n CoordinateState\n >(\n this.#config,\n this.#state,\n this.#edgeKinds,\n this.#edgeAlias,\n this.#direction,\n this.#fromAlias,\n this.#inverseEdgeKinds,\n this.#optional,\n {\n ...this.#variableLength,\n enabled: true,\n minDepth,\n maxDepth,\n cyclePolicy,\n ...(options?.path !== undefined && {\n pathEnabled: options.path !== false,\n ...(pathAlias !== undefined && { pathAlias }),\n }),\n ...(options?.depth !== undefined && {\n depthEnabled: options.depth !== false,\n ...(depthAlias !== undefined && { depthAlias }),\n }),\n },\n this.#pendingEdgePredicates,\n );\n }\n\n /**\n * Adds a WHERE clause for the edge being traversed.\n *\n * @param alias - The edge alias to filter on (must be the current edge alias)\n * @param predicateFunction - A function that builds predicates using the edge accessor\n */\n whereEdge(\n alias: EA,\n predicateFunction: (edge: EdgeAccessor<EdgeTypeForKey<G, EK>>) => Predicate,\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n Dir,\n Optional,\n DC,\n PC,\n RecAliases,\n CoordinateState\n > {\n const accessor = this.#createEdgeAccessor(alias);\n const predicate = predicateFunction(\n accessor as EdgeAccessor<EdgeTypeForKey<G, EK>>,\n );\n\n const newPredicate: NodePredicate = {\n targetAlias: alias,\n targetType: \"edge\",\n expression: predicate.__expr,\n };\n\n return new TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n Dir,\n Optional,\n DC,\n PC,\n RecAliases,\n CoordinateState\n >(\n this.#config,\n this.#state,\n this.#edgeKinds,\n this.#edgeAlias,\n this.#direction,\n this.#fromAlias,\n this.#inverseEdgeKinds,\n this.#optional,\n this.#variableLength,\n [...this.#pendingEdgePredicates, newPredicate],\n );\n }\n\n /**\n * Creates a type-safe accessor for edge properties.\n */\n #createEdgeAccessor(alias: string): EdgeAccessor<AnyEdgeType> {\n const allEdgeKinds = [\n ...this.#edgeKinds,\n ...this.#inverseEdgeKinds.filter(\n (kind) => !this.#edgeKinds.includes(kind),\n ),\n ];\n\n // Pre-compute system field accessors\n const idAccessor = stringField(\n fieldRef(alias, [\"id\"], { valueType: \"string\" }),\n );\n const kindAccessor = stringField(\n fieldRef(alias, [\"kind\"], { valueType: \"string\" }),\n );\n const fromIdAccessor = stringField(\n fieldRef(alias, [\"from_id\"], { valueType: \"string\" }),\n );\n const toIdAccessor = stringField(\n fieldRef(alias, [\"to_id\"], { valueType: \"string\" }),\n );\n\n // Build field accessor for a schema property\n const buildFieldAccessor = (propertyName: string): BaseFieldAccessor => {\n const typeInfo =\n this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n allEdgeKinds,\n propertyName,\n );\n\n const valueType = typeInfo?.valueType;\n const elementType = typeInfo?.elementType;\n\n const ref = fieldRef(alias, [\"props\"], {\n jsonPointer: jsonPointer([propertyName]),\n valueType,\n elementType,\n });\n\n switch (valueType) {\n case \"string\": {\n return stringField(ref);\n }\n case \"number\": {\n return numberField(ref);\n }\n case \"boolean\": {\n return baseField(ref);\n }\n case \"date\": {\n return dateField(ref);\n }\n case \"array\": {\n return arrayField(ref);\n }\n case \"object\": {\n return objectField(ref);\n }\n case \"embedding\":\n case \"unknown\":\n case undefined: {\n // Embedding, unknown, or unresolved type - return base field\n return baseField(ref);\n }\n }\n };\n\n if (this.#state.dynamicEdgeAliases.has(alias)) {\n return {\n id: idAccessor,\n kind: kindAccessor,\n fromId: fromIdAccessor,\n toId: toIdAccessor,\n field: (name: string) =>\n createDynamicFieldBuilder(\n this.#config.schemaIntrospector,\n alias,\n name,\n allEdgeKinds,\n \"edge\",\n ),\n } as unknown as EdgeAccessor<AnyEdgeType>;\n }\n\n // Use a Proxy to provide flattened property access\n return new Proxy({} as EdgeAccessor<AnyEdgeType>, {\n get: (_, property: string | symbol) => {\n // Handle symbols and special properties to avoid infinite loops\n if (typeof property === \"symbol\") return;\n if (property === \"then\") return;\n if (property === \"toJSON\") return;\n\n // System fields\n if (property === \"id\") return idAccessor;\n if (property === \"kind\") return kindAccessor;\n if (property === \"fromId\") return fromIdAccessor;\n if (property === \"toId\") return toIdAccessor;\n\n // Schema properties\n return buildFieldAccessor(property);\n },\n });\n }\n\n /**\n * Specifies the target node kind.\n *\n * The kind must be a valid target for this edge based on the traversal direction:\n * - \"out\" direction: kind must be in the edge's \"to\" array\n * - \"in\" direction: kind must be in the edge's \"from\" array\n *\n * @param kind - The target node kind\n * @param alias - A unique alias for this node (compile-time error if duplicate)\n */\n to<K extends ValidEdgeTargets<G, EK, Dir>, A extends string>(\n kind: K,\n alias: UniqueAlias<A, Aliases>,\n options?: { includeSubClasses?: false },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<G[\"nodes\"][K][\"type\"], Optional>>,\n EdgeAliases & Record<EA, EdgeAlias<G[\"edges\"][EK][\"type\"], Optional>>,\n RecAliases & BuildRecursiveAliases<DC, PC, A>,\n CoordinateState\n >;\n\n to<K extends ValidEdgeTargets<G, EK, Dir>, A extends string>(\n kind: K,\n alias: UniqueAlias<A, Aliases>,\n options: { includeSubClasses: true },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<NodeType, Optional>>,\n EdgeAliases & Record<EA, EdgeAlias<G[\"edges\"][EK][\"type\"], Optional>>,\n RecAliases & BuildRecursiveAliases<DC, PC, A>,\n CoordinateState\n >;\n\n to<K extends ValidEdgeTargets<G, EK, Dir>, A extends string>(\n kind: K,\n alias: UniqueAlias<A, Aliases>,\n options?: { includeSubClasses?: boolean },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<NodeType, Optional>>,\n EdgeAliases & Record<EA, EdgeAlias<G[\"edges\"][EK][\"type\"], Optional>>,\n RecAliases & BuildRecursiveAliases<DC, PC, A>,\n CoordinateState\n > {\n validateSqlIdentifier(alias);\n\n const includeSubClasses = options?.includeSubClasses ?? false;\n const kinds =\n includeSubClasses ? this.#config.registry.expandSubClasses(kind) : [kind];\n\n const newState = this.#stateWithTraversal(alias, kinds);\n\n // Cast is safe because the overloads provide compile-time type safety\n // The runtime QueryBuilderClass is the correct implementation\n return new QueryBuilderClass(this.#config, newState) as QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<NodeType, Optional>>,\n EdgeAliases & Record<EA, EdgeAlias<G[\"edges\"][EK][\"type\"], Optional>>,\n RecAliases & BuildRecursiveAliases<DC, PC, A>,\n CoordinateState\n >;\n }\n\n /**\n * String-keyed sibling of `to` for runtime-declared target kinds.\n * Throws `KindNotFoundError` if the kind is not registered.\n */\n toDynamic<A extends string>(\n kind: string,\n alias: UniqueAlias<A, Aliases>,\n options?: { includeSubClasses?: boolean },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<DynamicNodeType, Optional>>,\n EdgeAliases & Record<EA, EdgeAlias<EdgeTypeForKey<G, EK>, Optional>>,\n RecAliases & BuildRecursiveAliases<DC, PC, A>,\n CoordinateState\n > {\n validateSqlIdentifier(alias);\n if (!this.#config.registry.hasNodeType(kind)) {\n throw new KindNotFoundError(kind, \"node\", {\n graphId: this.#config.graphId,\n });\n }\n this.#assertValidEndpoint(kind);\n\n const includeSubClasses = options?.includeSubClasses ?? false;\n const kinds =\n includeSubClasses ? this.#config.registry.expandSubClasses(kind) : [kind];\n\n const baseState = this.#stateWithTraversal(alias, kinds);\n const newState: QueryBuilderState = {\n ...baseState,\n dynamicNodeAliases: new Set([...baseState.dynamicNodeAliases, alias]),\n };\n\n return new QueryBuilderClass(this.#config, newState) as QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<DynamicNodeType, Optional>>,\n EdgeAliases & Record<EA, EdgeAlias<EdgeTypeForKey<G, EK>, Optional>>,\n RecAliases & BuildRecursiveAliases<DC, PC, A>,\n CoordinateState\n >;\n }\n\n /**\n * Builds the next `QueryBuilderState` after appending a traversal\n * targeting `alias` with `kinds`. Shared by `to` and `toDynamic`.\n */\n #stateWithTraversal(\n alias: string,\n kinds: readonly string[],\n ): QueryBuilderState {\n const traversalBase: Traversal = {\n edgeAlias: this.#edgeAlias,\n edgeKinds: this.#edgeKinds,\n direction: this.#direction,\n nodeAlias: alias,\n nodeKinds: kinds,\n joinFromAlias: this.#fromAlias,\n joinEdgeField: this.#direction === \"out\" ? \"from_id\" : \"to_id\",\n optional: this.#optional,\n };\n\n const baseTraversal: Traversal =\n this.#inverseEdgeKinds.length > 0 ?\n { ...traversalBase, inverseEdgeKinds: this.#inverseEdgeKinds }\n : traversalBase;\n\n const traversal: Traversal =\n this.#variableLength.enabled ?\n {\n ...baseTraversal,\n variableLength: {\n minDepth: this.#variableLength.minDepth,\n maxDepth: this.#variableLength.maxDepth,\n cyclePolicy: this.#variableLength.cyclePolicy,\n ...(this.#variableLength.pathEnabled && {\n pathAlias: this.#variableLength.pathAlias ?? `${alias}_path`,\n }),\n ...(this.#variableLength.depthEnabled && {\n depthAlias: this.#variableLength.depthAlias ?? `${alias}_depth`,\n }),\n },\n }\n : baseTraversal;\n\n return {\n ...this.#state,\n traversals: [...this.#state.traversals, traversal],\n predicates: [...this.#state.predicates, ...this.#pendingEdgePredicates],\n currentAlias: alias,\n };\n }\n\n /**\n * Asserts a runtime-declared target kind is a valid endpoint for the\n * current traversal. Mirrors the compile-time `ValidEdgeTargets`\n * constraint enforced by `to(...)` — without this check `toDynamic`\n * would silently accept e.g. `traverseDynamic(\"authoredBy\") +\n * toDynamic(\"Document\")` where authoredBy.to=[Author] and produce an\n * empty result set.\n *\n * Permissive on unions: if the target is assignable to any valid\n * endpoint across the edges being traversed, accept. Subclass\n * relationships are honored via `registry.isAssignableTo`.\n */\n #assertValidEndpoint(targetKind: string): void {\n const expectedKinds = new Set<string>();\n const collectFromEdge = (edgeName: string, side: \"to\" | \"from\"): void => {\n const edgeType = this.#config.registry.getEdgeType(edgeName);\n const endpoints = edgeType?.[side];\n if (!endpoints) return;\n for (const endpoint of endpoints) {\n expectedKinds.add(endpoint.kind);\n }\n };\n const forwardSide = this.#direction === \"out\" ? \"to\" : \"from\";\n const inverseSide = this.#direction === \"out\" ? \"from\" : \"to\";\n for (const edgeName of this.#edgeKinds) {\n collectFromEdge(edgeName, forwardSide);\n }\n for (const edgeName of this.#inverseEdgeKinds) {\n collectFromEdge(edgeName, inverseSide);\n }\n\n // No declared endpoints anywhere — edge kinds in the registry can\n // legally have undefined `to` / `from`; nothing to validate against.\n if (expectedKinds.size === 0) return;\n\n for (const expected of expectedKinds) {\n if (this.#config.registry.isAssignableTo(targetKind, expected)) return;\n }\n\n throw new EndpointError({\n edgeKind: this.#edgeKinds[0] ?? \"(unknown)\",\n endpoint: forwardSide,\n actualKind: targetKind,\n expectedKinds: [...expectedKinds],\n });\n }\n}\n","/**\n * QueryBuilder - The fluent query builder.\n */\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n coordinateContext,\n describeCoordinate,\n resolveReadCoordinate,\n} from \"../../core/temporal\";\nimport {\n type EdgeType,\n type NodeType,\n type TemporalMode,\n} from \"../../core/types\";\nimport { ConfigurationError, KindNotFoundError } from \"../../errors\";\nimport {\n type AggregateExpr,\n type FieldRef,\n type GroupBySpec,\n type HybridFusionOptions,\n mergeEdgeKinds,\n type OrderSpec,\n type PredicateExpression,\n type ProjectedField,\n type SortDirection,\n type TraversalDirection,\n type TraversalExpansion,\n} from \"../ast\";\nimport { jsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport {\n buildFieldBuilderForTypeInfo,\n createFulltextAccessor,\n fieldRef,\n type Predicate,\n stringField,\n} from \"../predicates\";\nimport { type FieldTypeInfo } from \"../schema-introspector\";\nimport {\n createDynamicFieldBuilder,\n type DynamicEdgeType,\n type DynamicNodeType,\n} from \"./dynamic\";\nimport { ExecutableAggregateQuery } from \"./executable-aggregate-query\";\nimport { ExecutableQuery } from \"./executable-query\";\nimport { getQueryBuilderInternalContext } from \"./internal-context\";\nimport { TraversalBuilder } from \"./traversal-builder\";\nimport {\n type AliasMap,\n type BaseFieldAccessor,\n type EdgeAccessor,\n type EdgeAlias,\n type EdgeAliasMap,\n type EmptyAliasMap,\n type EmptyEdgeAliasMap,\n type EmptyRecursiveAliasMap,\n type NodeAccessor,\n type NodeAlias,\n type QueryBuilderConfig,\n type QueryBuilderState,\n type QueryCoordinateState,\n type RecursiveAliasMap,\n type SelectContext,\n type UniqueAlias,\n} from \"./types\";\nimport {\n validateHybridFusionOptions,\n validateSqlIdentifier,\n} from \"./validation\";\n\n/**\n * Builds projected fields for a node alias (including all metadata columns).\n */\nfunction buildNodeFields(alias: string): ProjectedField[] {\n return [\n {\n outputName: `${alias}_id`,\n source: fieldRef(alias, [\"id\"]),\n },\n {\n outputName: `${alias}_kind`,\n source: fieldRef(alias, [\"kind\"]),\n },\n {\n outputName: `${alias}_props`,\n source: fieldRef(alias, [\"props\"]),\n },\n {\n outputName: `${alias}_version`,\n source: fieldRef(alias, [\"version\"]),\n },\n {\n outputName: `${alias}_valid_from`,\n source: fieldRef(alias, [\"valid_from\"]),\n },\n {\n outputName: `${alias}_valid_to`,\n source: fieldRef(alias, [\"valid_to\"]),\n },\n {\n outputName: `${alias}_created_at`,\n source: fieldRef(alias, [\"created_at\"]),\n },\n {\n outputName: `${alias}_updated_at`,\n source: fieldRef(alias, [\"updated_at\"]),\n },\n {\n outputName: `${alias}_deleted_at`,\n source: fieldRef(alias, [\"deleted_at\"]),\n },\n ];\n}\n\n/**\n * Builds projected fields for an edge alias (including all metadata columns).\n *\n * Edge columns are stored in the traversal's node CTE (e.g., cte_c contains e_id, e_kind, etc.).\n * The nodeCteAlias parameter specifies which CTE contains these columns.\n */\nfunction buildEdgeFields(\n edgeAlias: string,\n nodeCteAlias: string,\n): ProjectedField[] {\n const cteAlias = `cte_${nodeCteAlias}`;\n return [\n {\n outputName: `${edgeAlias}_id`,\n source: fieldRef(edgeAlias, [\"id\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_kind`,\n source: fieldRef(edgeAlias, [\"kind\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_from_id`,\n source: fieldRef(edgeAlias, [\"from_id\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_to_id`,\n source: fieldRef(edgeAlias, [\"to_id\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_props`,\n source: fieldRef(edgeAlias, [\"props\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_valid_from`,\n source: fieldRef(edgeAlias, [\"valid_from\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_valid_to`,\n source: fieldRef(edgeAlias, [\"valid_to\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_created_at`,\n source: fieldRef(edgeAlias, [\"created_at\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_updated_at`,\n source: fieldRef(edgeAlias, [\"updated_at\"]),\n cteAlias,\n },\n {\n outputName: `${edgeAlias}_deleted_at`,\n source: fieldRef(edgeAlias, [\"deleted_at\"]),\n cteAlias,\n },\n ];\n}\n\ntype TemporalMethod<\n G extends GraphDef,\n Aliases extends AliasMap,\n EdgeAliases extends EdgeAliasMap,\n RecursiveAliases extends RecursiveAliasMap,\n CoordinateState extends QueryCoordinateState,\n> =\n CoordinateState extends \"open\" ?\n (\n mode: TemporalMode,\n asOf?: string,\n ) => QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, \"open\">\n : never;\n\n/**\n * The fluent query builder.\n *\n * Type parameters accumulate as methods are chained:\n * - G: The graph definition\n * - Aliases: Map of alias names to their node kinds\n * - EdgeAliases: Map of alias names to their edge kinds (accumulated during traversals)\n */\nexport class QueryBuilder<\n G extends GraphDef,\n Aliases extends AliasMap = EmptyAliasMap,\n EdgeAliases extends EdgeAliasMap = EmptyEdgeAliasMap,\n RecursiveAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n CoordinateState extends QueryCoordinateState = \"open\",\n> {\n readonly #config: QueryBuilderConfig;\n readonly #state: QueryBuilderState;\n readonly temporal: TemporalMethod<\n G,\n Aliases,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n >;\n\n constructor(config: QueryBuilderConfig, state: QueryBuilderState) {\n this.#config = config;\n this.#state = state;\n this.temporal = ((mode, asOf) =>\n this.#setTemporal(mode, asOf)) as TemporalMethod<\n G,\n Aliases,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n >;\n }\n\n /**\n * Sets temporal mode.\n *\n * @param mode - The temporal mode to use\n * @param asOf - Required timestamp for \"asOf\" mode (ISO 8601 string).\n * Rejected for every other mode — pinning an instant is only meaningful\n * in \"asOf\" mode, so `temporal(\"current\", t)` is a caller error, not a\n * silently-dropped argument.\n * @throws ValidationError if mode is \"asOf\" but no timestamp is provided, or\n * if an asOf is supplied with a non-\"asOf\" mode.\n */\n #setTemporal(\n mode: TemporalMode,\n asOf?: string,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, \"open\"> {\n const { sealedCoordinate } = getQueryBuilderInternalContext(this.#config);\n if (sealedCoordinate !== undefined) {\n const coordinate = sealedCoordinate;\n throw new ConfigurationError(\n `.temporal() is not available on a StoreView query — the view's ` +\n `temporal coordinate (${describeCoordinate(coordinate)}) is sealed. ` +\n `Re-coordinate on the live Store via store.query() or store.view(...).`,\n {\n code: \"STORE_VIEW_SEALED_QUERY\",\n ...coordinateContext(coordinate),\n requestedMode: mode,\n },\n );\n }\n const coordinate = resolveReadCoordinate(\n mode,\n asOf,\n `Use .temporal(\"asOf\", \"2024-01-15T10:00:00.000Z\") or .temporal(\"current\") for current time.`,\n );\n return new QueryBuilder(this.#config, {\n ...this.#state,\n temporalMode: coordinate.valid.mode,\n asOf: coordinate.valid.asOf,\n });\n }\n\n /**\n * Starts a query from a node kind.\n *\n * @param kind - The node kind to start from\n * @param alias - A unique alias for this node (compile-time error if duplicate)\n */\n from<K extends keyof G[\"nodes\"] & string, A extends string>(\n kind: K,\n alias: UniqueAlias<A, Aliases>,\n options?: { includeSubClasses?: false },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<G[\"nodes\"][K][\"type\"]>>,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n >;\n\n from<K extends keyof G[\"nodes\"] & string, A extends string>(\n kind: K,\n alias: UniqueAlias<A, Aliases>,\n options: { includeSubClasses: true },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias>,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n >;\n\n from<K extends keyof G[\"nodes\"] & string, A extends string>(\n kind: K,\n alias: UniqueAlias<A, Aliases>,\n options?: { includeSubClasses?: boolean },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias>,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n > {\n // Validate alias to prevent SQL injection\n validateSqlIdentifier(alias);\n\n const includeSubClasses = options?.includeSubClasses ?? false;\n\n // Expand kinds if including subclasses\n const kinds =\n includeSubClasses ? this.#config.registry.expandSubClasses(kind) : [kind];\n\n const newState: QueryBuilderState = {\n ...this.#state,\n startAlias: alias,\n currentAlias: alias,\n startKinds: kinds,\n includeSubClasses,\n };\n\n return new QueryBuilder(this.#config, newState);\n }\n\n /**\n * String-keyed sibling of `from` for runtime-declared kinds. Throws\n * `KindNotFoundError` if the kind is not registered. Predicates use\n * the `n.field(\"name\").number().gte(...)` discriminator.\n */\n fromDynamic<A extends string>(\n kind: string,\n alias: UniqueAlias<A, Aliases>,\n options?: { includeSubClasses?: boolean },\n ): QueryBuilder<\n G,\n Aliases & Record<A, NodeAlias<DynamicNodeType>>,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n > {\n validateSqlIdentifier(alias);\n if (!this.#config.registry.hasNodeType(kind)) {\n throw new KindNotFoundError(kind, \"node\", {\n graphId: this.#config.graphId,\n });\n }\n\n const includeSubClasses = options?.includeSubClasses ?? false;\n const kinds =\n includeSubClasses ? this.#config.registry.expandSubClasses(kind) : [kind];\n\n const newState: QueryBuilderState = {\n ...this.#state,\n startAlias: alias,\n currentAlias: alias,\n startKinds: kinds,\n includeSubClasses,\n dynamicNodeAliases: new Set([...this.#state.dynamicNodeAliases, alias]),\n };\n\n return new QueryBuilder(this.#config, newState);\n }\n\n /**\n * Adds a WHERE clause for a node.\n */\n whereNode<A extends keyof Aliases & string>(\n alias: A,\n predicateFunction: (n: NodeAccessor<Aliases[A][\"type\"]>) => Predicate,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n const accessor = this.#createNodeAccessor(alias);\n const predicate = predicateFunction(\n accessor as NodeAccessor<Aliases[A][\"type\"]>,\n );\n\n const newState: QueryBuilderState = {\n ...this.#state,\n predicates: [\n ...this.#state.predicates,\n {\n targetAlias: alias,\n expression: predicate.__expr,\n },\n ],\n };\n\n return new QueryBuilder(this.#config, newState);\n }\n\n /**\n * Adds a WHERE clause for an edge.\n *\n * @param alias - The edge alias to filter on\n * @param predicateFunction - A function that builds predicates using the edge accessor\n */\n whereEdge<EA extends keyof EdgeAliases & string>(\n alias: EA,\n predicateFunction: (\n edge: EdgeAccessor<EdgeAliases[EA][\"type\"]>,\n ) => Predicate,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n const accessor = this.#createEdgeAccessor(alias);\n const predicate = predicateFunction(\n accessor as EdgeAccessor<EdgeAliases[EA][\"type\"]>,\n );\n\n const newState: QueryBuilderState = {\n ...this.#state,\n predicates: [\n ...this.#state.predicates,\n {\n targetAlias: alias,\n targetType: \"edge\",\n expression: predicate.__expr,\n },\n ],\n };\n\n return new QueryBuilder(this.#config, newState);\n }\n\n /**\n * Traverses an edge to another node (outgoing direction).\n *\n * By default, traverses from the current node (last traversal target, or start node).\n * Use the `from` option to traverse from a different alias (fan-out pattern).\n *\n * @param options.expand - Ontology expansion mode for implying/inverse edges\n * @param options.from - Alias to traverse from (defaults to current/last traversal target)\n */\n traverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n edgeKind: EK,\n edgeAlias: EA,\n options?: {\n direction?: \"out\";\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n \"out\",\n false,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n >;\n\n /**\n * Traverses an edge to another node (incoming direction).\n *\n * By default, traverses from the current node (last traversal target, or start node).\n * Use the `from` option to traverse from a different alias (fan-out pattern).\n *\n * @param options.direction - Set to \"in\" for incoming edge traversal\n * @param options.expand - Ontology expansion mode for implying/inverse edges\n * @param options.from - Alias to traverse from (defaults to current/last traversal target)\n */\n traverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n edgeKind: EK,\n edgeAlias: EA,\n options: {\n direction: \"in\";\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n \"in\",\n false,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n >;\n\n traverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n edgeKind: EK,\n edgeAlias: EA,\n options?: {\n direction?: TraversalDirection;\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n TraversalDirection,\n false,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n > {\n // Validate edge alias to prevent SQL injection\n validateSqlIdentifier(edgeAlias);\n\n const direction = options?.direction ?? \"out\";\n const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\n const includeImplyingEdges =\n expansion === \"implying\" || expansion === \"all\";\n const includeInverseEdges = expansion === \"inverse\" || expansion === \"all\";\n // Use explicit `from` if provided, otherwise chain from currentAlias\n const fromAlias = options?.from ?? this.#state.currentAlias;\n\n // Expand edge kinds if including implying edges\n const edgeKinds = this.#expandTraversalEdgeKinds(\n edgeKind,\n includeImplyingEdges,\n );\n const inverseEdgeKinds =\n includeInverseEdges ?\n this.#expandInverseTraversalEdgeKinds(edgeKinds, includeImplyingEdges)\n : [];\n\n return new TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n TraversalDirection,\n false,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n >(\n this.#config,\n this.#state,\n edgeKinds,\n edgeAlias,\n direction,\n fromAlias,\n inverseEdgeKinds,\n false,\n );\n }\n\n /**\n * String-keyed sibling of `traverse` for runtime-declared edge kinds.\n * Throws `KindNotFoundError` if the edge kind is not registered.\n */\n traverseDynamic<EA extends string>(\n edgeKind: string,\n edgeAlias: EA,\n options?: {\n direction?: TraversalDirection;\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeType>>,\n string,\n EA,\n TraversalDirection,\n false,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n > {\n return this.#beginDynamicTraversal(edgeKind, edgeAlias, false, options);\n }\n\n /**\n * Optionally traverses an edge to another node (LEFT JOIN semantics).\n * If no matching edge/node exists, the result will include null values.\n *\n * By default, traverses from the current node (last traversal target, or start node).\n * Use the `from` option to traverse from a different alias (fan-out pattern).\n *\n * @param options.direction - Direction of traversal: \"out\" (default) or \"in\"\n * @param options.expand - Ontology expansion mode for implying/inverse edges\n * @param options.from - Alias to traverse from (defaults to current/last traversal target)\n */\n optionalTraverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n edgeKind: EK,\n edgeAlias: EA,\n options?: {\n direction?: \"out\";\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n \"out\",\n true,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n >;\n\n optionalTraverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n edgeKind: EK,\n edgeAlias: EA,\n options: {\n direction: \"in\";\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n \"in\",\n true,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n >;\n\n optionalTraverse<EK extends keyof G[\"edges\"] & string, EA extends string>(\n edgeKind: EK,\n edgeAlias: EA,\n options?: {\n direction?: TraversalDirection;\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n TraversalDirection,\n true,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n > {\n // Validate edge alias to prevent SQL injection\n validateSqlIdentifier(edgeAlias);\n\n const direction = options?.direction ?? \"out\";\n const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\n const includeImplyingEdges =\n expansion === \"implying\" || expansion === \"all\";\n const includeInverseEdges = expansion === \"inverse\" || expansion === \"all\";\n // Use explicit `from` if provided, otherwise chain from currentAlias\n const fromAlias = options?.from ?? this.#state.currentAlias;\n\n // Expand edge kinds if including implying edges\n const edgeKinds = this.#expandTraversalEdgeKinds(\n edgeKind,\n includeImplyingEdges,\n );\n const inverseEdgeKinds =\n includeInverseEdges ?\n this.#expandInverseTraversalEdgeKinds(edgeKinds, includeImplyingEdges)\n : [];\n\n return new TraversalBuilder<\n G,\n Aliases,\n EdgeAliases,\n EK,\n EA,\n TraversalDirection,\n true,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n >(\n this.#config,\n this.#state,\n edgeKinds,\n edgeAlias,\n direction,\n fromAlias,\n inverseEdgeKinds,\n true,\n );\n }\n\n /**\n * String-keyed sibling of `optionalTraverse` for runtime-declared edge\n * kinds. LEFT JOIN semantics — non-matching rows produce a null edge\n * alias instead of dropping. Throws `KindNotFoundError` if the edge\n * kind is not registered.\n */\n optionalTraverseDynamic<EA extends string>(\n edgeKind: string,\n edgeAlias: EA,\n options?: {\n direction?: TraversalDirection;\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n },\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeType, true>>,\n string,\n EA,\n TraversalDirection,\n true,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n > {\n return this.#beginDynamicTraversal(edgeKind, edgeAlias, true, options);\n }\n\n /**\n * Shared body for `traverseDynamic` and `optionalTraverseDynamic`.\n * The only difference is the `optional` flag passed to the\n * `TraversalBuilder` constructor.\n */\n #beginDynamicTraversal<EA extends string, Optional extends boolean>(\n edgeKind: string,\n edgeAlias: EA,\n optional: Optional,\n options:\n | {\n direction?: TraversalDirection;\n expand?: TraversalExpansion;\n from?: keyof Aliases & string;\n }\n | undefined,\n ): TraversalBuilder<\n G,\n Aliases,\n EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeType, Optional>>,\n string,\n EA,\n TraversalDirection,\n Optional,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n > {\n validateSqlIdentifier(edgeAlias);\n if (!this.#config.registry.hasEdgeType(edgeKind)) {\n throw new KindNotFoundError(edgeKind, \"edge\", {\n graphId: this.#config.graphId,\n });\n }\n\n const direction = options?.direction ?? \"out\";\n const expansion = options?.expand ?? this.#config.defaultTraversalExpansion;\n const includeImplyingEdges =\n expansion === \"implying\" || expansion === \"all\";\n const includeInverseEdges = expansion === \"inverse\" || expansion === \"all\";\n const fromAlias = options?.from ?? this.#state.currentAlias;\n\n const edgeKinds = this.#expandTraversalEdgeKinds(\n edgeKind,\n includeImplyingEdges,\n );\n const inverseEdgeKinds =\n includeInverseEdges ?\n this.#expandInverseTraversalEdgeKinds(edgeKinds, includeImplyingEdges)\n : [];\n\n const newState: QueryBuilderState = {\n ...this.#state,\n dynamicEdgeAliases: new Set([\n ...this.#state.dynamicEdgeAliases,\n edgeAlias,\n ]),\n };\n\n return new TraversalBuilder<\n G,\n Aliases,\n EdgeAliases & Record<EA, EdgeAlias<DynamicEdgeType, Optional>>,\n string,\n EA,\n TraversalDirection,\n Optional,\n false,\n false,\n RecursiveAliases,\n CoordinateState\n >(\n this.#config,\n newState,\n edgeKinds,\n edgeAlias,\n direction,\n fromAlias,\n inverseEdgeKinds,\n optional,\n );\n }\n\n /**\n * Selects fields to return.\n */\n select<R>(\n selectFunction: (\n context: SelectContext<Aliases, EdgeAliases, RecursiveAliases>,\n ) => R,\n ): ExecutableQuery<G, Aliases, EdgeAliases, RecursiveAliases, R> {\n // For now, project all fields from all aliases\n // A more sophisticated implementation would parse the selectFn\n\n // Start node fields (including metadata)\n const startFields = buildNodeFields(this.#state.startAlias);\n\n // Traversal node and edge fields (including metadata)\n // Edge fields are in the node's CTE, so we pass the node alias for CTE reference\n const traversalFields = this.#state.traversals.flatMap((traversal) => [\n ...buildEdgeFields(traversal.edgeAlias, traversal.nodeAlias),\n ...buildNodeFields(traversal.nodeAlias),\n ]);\n\n const projection = [...startFields, ...traversalFields];\n\n const newState: QueryBuilderState = {\n ...this.#state,\n projection,\n };\n\n return new ExecutableQuery(this.#config, newState, selectFunction);\n }\n\n /**\n * Selects fields including aggregates.\n * Use with groupBy() for aggregate queries.\n *\n * @param fields - Object mapping output names to field refs or aggregate expressions\n */\n aggregate<R extends Record<string, FieldRef | AggregateExpr>>(\n fields: R,\n ): ExecutableAggregateQuery<G, Aliases, R> {\n const resolvedFields = Object.fromEntries(\n Object.entries(fields).map(([outputName, source]) => {\n if (source.__type !== \"field_ref\") {\n return [outputName, source];\n }\n\n if (\n source.valueType !== undefined ||\n source.path.length !== 1 ||\n source.path[0] !== \"props\" ||\n source.jsonPointer === undefined\n ) {\n return [outputName, source];\n }\n\n const segments = parseJsonPointer(source.jsonPointer);\n if (segments.length !== 1) {\n return [outputName, source];\n }\n\n const propertyName = segments[0];\n if (propertyName === undefined) {\n return [outputName, source];\n }\n\n const kindNames = this.#getKindNamesForAlias(source.alias);\n const typeInfo =\n kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n kindNames,\n propertyName,\n )\n : undefined;\n\n if (!typeInfo) {\n return [outputName, source];\n }\n\n return [\n outputName,\n {\n ...source,\n valueType: typeInfo.valueType,\n elementType: typeInfo.elementType,\n } satisfies FieldRef,\n ];\n }),\n ) as R;\n\n const projection: ProjectedField[] = Object.entries(resolvedFields).map(\n ([outputName, source]) => ({\n outputName,\n source,\n }),\n );\n\n const newState: QueryBuilderState = {\n ...this.#state,\n projection,\n };\n\n return new ExecutableAggregateQuery(this.#config, newState, resolvedFields);\n }\n\n /**\n * Orders results.\n */\n orderBy<A extends (keyof Aliases | keyof EdgeAliases) & string>(\n alias: A,\n field: string,\n direction: SortDirection = \"asc\",\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n const edgeKindNames = this.#getEdgeKindNamesForAlias(alias);\n const isEdge = edgeKindNames !== undefined;\n const isSystem =\n field === \"id\" ||\n field === \"kind\" ||\n (isEdge && (field === \"from_id\" || field === \"to_id\"));\n const typeInfo =\n isSystem ? undefined\n : isEdge ?\n this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n edgeKindNames,\n field,\n )\n : this.#getOrderByTypeInfo(alias, field);\n const orderSpec: OrderSpec =\n isSystem ?\n {\n field: fieldRef(alias, [field], { valueType: \"string\" }),\n direction,\n }\n : {\n field: fieldRef(alias, [\"props\"], {\n jsonPointer: jsonPointer([field]),\n valueType: typeInfo?.valueType,\n elementType: typeInfo?.elementType,\n }),\n direction,\n };\n\n const newState: QueryBuilderState = {\n ...this.#state,\n orderBy: [...this.#state.orderBy, orderSpec],\n };\n\n return new QueryBuilder(this.#config, newState);\n }\n\n #getOrderByTypeInfo(alias: string, field: string): FieldTypeInfo | undefined {\n const kindNames = this.#getKindNamesForAlias(alias);\n return kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(kindNames, field)\n : undefined;\n }\n\n /**\n * Limits the number of results.\n */\n limit(\n n: number,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n return new QueryBuilder(this.#config, {\n ...this.#state,\n limit: n,\n });\n }\n\n /**\n * Offsets the results.\n */\n offset(\n n: number,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n return new QueryBuilder(this.#config, {\n ...this.#state,\n offset: n,\n });\n }\n\n /**\n * Groups results by the specified field.\n * Use with aggregate functions like COUNT, SUM, AVG in select().\n *\n * @param alias - The node alias to group by\n * @param field - The field name to group by\n */\n groupBy<A extends keyof Aliases & string>(\n alias: A,\n field: string,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n const kindNames = this.#getKindNamesForAlias(alias);\n const typeInfo =\n kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(kindNames, field)\n : undefined;\n\n const fieldRefValue: FieldRef = {\n __type: \"field_ref\",\n alias,\n path: [\"props\"],\n jsonPointer: jsonPointer([field]),\n valueType: typeInfo?.valueType,\n elementType: typeInfo?.elementType,\n };\n\n const existingFields = this.#state.groupBy?.fields ?? [];\n const newGroupBy: GroupBySpec = {\n fields: [...existingFields, fieldRefValue],\n };\n\n return new QueryBuilder(this.#config, {\n ...this.#state,\n groupBy: newGroupBy,\n });\n }\n\n /**\n * Groups results by the node ID.\n * Use when you want to group by a complete node rather than a specific field.\n *\n * @param alias - The node alias to group by (uses the node's ID)\n */\n groupByNode<A extends keyof Aliases & string>(\n alias: A,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n const fieldRefValue: FieldRef = {\n __type: \"field_ref\",\n alias,\n path: [\"id\"],\n valueType: \"string\",\n };\n\n const existingFields = this.#state.groupBy?.fields ?? [];\n const newGroupBy: GroupBySpec = {\n fields: [...existingFields, fieldRefValue],\n };\n\n return new QueryBuilder(this.#config, {\n ...this.#state,\n groupBy: newGroupBy,\n });\n }\n\n /**\n * Filters grouped results using aggregate conditions (HAVING clause).\n * Use after groupBy() to filter based on aggregate values.\n *\n * @param predicate - A predicate expression to filter groups\n */\n having(\n predicate: PredicateExpression,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n return new QueryBuilder(this.#config, {\n ...this.#state,\n having: predicate,\n });\n }\n\n /**\n * Sets fusion parameters for hybrid (vector + fulltext) queries.\n *\n * Applies only when the query contains both a `.similarTo()` and a\n * `.$fulltext.matches()` predicate. Without this call, the default is\n * RRF with k=60 and equal weights. A mismatch between `.fuseWith()`\n * configuration and the predicates on the query is caught during\n * compilation, not here.\n *\n * @example\n * ```typescript\n * store.query()\n * .from(\"Document\", \"d\")\n * .whereNode(\"d\", d =>\n * d.$fulltext.matches(\"renewable energy\", 50)\n * .and(d.embedding.similarTo(vec, 50))\n * .and(d.tenantId.eq(tenant))\n * )\n * .fuseWith({ k: 60, weights: { fulltext: 1.5 } })\n * .limit(10)\n * .execute();\n * ```\n */\n fuseWith(\n options: HybridFusionOptions,\n ): QueryBuilder<G, Aliases, EdgeAliases, RecursiveAliases, CoordinateState> {\n validateHybridFusionOptions(options);\n return new QueryBuilder(this.#config, {\n ...this.#state,\n fusion: options,\n });\n }\n\n /**\n * Applies a query fragment to transform this builder.\n *\n * Fragments are reusable query transformations that can add predicates,\n * traversals, ordering, and other query operations. Use this for\n * composing complex queries from simpler, reusable parts.\n *\n * @example\n * ```typescript\n * // Define a reusable fragment\n * const activeUsers = createFragment<MyGraph>()((q) =>\n * q.whereNode(\"u\", ({ status }) => status.eq(\"active\"))\n * );\n *\n * // Apply the fragment\n * const results = await query()\n * .from(\"User\", \"u\")\n * .pipe(activeUsers)\n * .select((ctx) => ctx.u)\n * .execute();\n * ```\n *\n * @param fragment - A function that transforms the builder\n * @returns The transformed builder\n */\n pipe<\n OutAliases extends AliasMap,\n OutEdgeAliases extends EdgeAliasMap = EdgeAliases,\n OutRecAliases extends RecursiveAliasMap = RecursiveAliases,\n >(\n fragment: (\n builder: QueryBuilder<\n G,\n Aliases,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n >,\n ) => QueryBuilder<\n G,\n OutAliases,\n OutEdgeAliases,\n OutRecAliases,\n CoordinateState\n >,\n ): QueryBuilder<\n G,\n OutAliases,\n OutEdgeAliases,\n OutRecAliases,\n CoordinateState\n > {\n return fragment(this);\n }\n\n /**\n * Gets all kind names for an alias.\n */\n #getKindNamesForAlias(alias: string): readonly string[] | undefined {\n if (alias === this.#state.startAlias) {\n return this.#state.startKinds;\n }\n for (const traversal of this.#state.traversals) {\n if (traversal.nodeAlias === alias) {\n return traversal.nodeKinds;\n }\n }\n return undefined;\n }\n\n /**\n * Determines the appropriate field builder based on Zod schema type.\n */\n #getFieldBuilderForProperty(\n kindNames: readonly string[] | undefined,\n property: string,\n alias: string,\n ): BaseFieldAccessor {\n const typeInfo =\n kindNames ?\n this.#config.schemaIntrospector.getSharedFieldTypeInfo(\n kindNames,\n property,\n )\n : undefined;\n\n const ref = fieldRef(alias, [\"props\"], {\n jsonPointer: jsonPointer([property]),\n valueType: typeInfo?.valueType,\n elementType: typeInfo?.elementType,\n });\n\n return this.#buildFieldBuilderForTypeInfo(ref, typeInfo);\n }\n\n #buildFieldBuilderForTypeInfo(\n ref: ReturnType<typeof fieldRef>,\n typeInfo: FieldTypeInfo | undefined,\n ): BaseFieldAccessor {\n return buildFieldBuilderForTypeInfo(ref, typeInfo);\n }\n\n #createNodeAccessor(alias: string): NodeAccessor<NodeType> {\n const kindNames = this.#getKindNamesForAlias(alias);\n const idAccessor = stringField(\n fieldRef(alias, [\"id\"], { valueType: \"string\" }),\n );\n const kindAccessor = stringField(\n fieldRef(alias, [\"kind\"], { valueType: \"string\" }),\n );\n const fulltextAccessor = createFulltextAccessor(alias, () =>\n this.#hasSearchableField(kindNames),\n );\n\n if (this.#state.dynamicNodeAliases.has(alias)) {\n return {\n id: idAccessor,\n kind: kindAccessor,\n $fulltext: fulltextAccessor,\n field: (name: string) =>\n createDynamicFieldBuilder(\n this.#config.schemaIntrospector,\n alias,\n name,\n kindNames,\n \"node\",\n ),\n } as unknown as NodeAccessor<NodeType>;\n }\n\n // Use a Proxy to provide flattened property access\n return new Proxy({} as NodeAccessor<NodeType>, {\n get: (_, property: string | symbol) => {\n // Handle symbols and special properties to avoid infinite loops\n if (typeof property === \"symbol\") return;\n if (property === \"then\") return;\n if (property === \"toJSON\") return;\n\n // System fields\n if (property === \"id\") return idAccessor;\n if (property === \"kind\") return kindAccessor;\n if (property === \"$fulltext\") return fulltextAccessor;\n\n // Schema properties\n return this.#getFieldBuilderForProperty(kindNames, property, alias);\n },\n });\n }\n\n #hasSearchableField(kindNames: readonly string[] | undefined): boolean {\n if (!kindNames) return false;\n return this.#config.schemaIntrospector.hasSearchableField(kindNames);\n }\n\n #expandTraversalEdgeKinds(\n edgeKind: string,\n includeImplyingEdges: boolean,\n ): readonly string[] {\n return includeImplyingEdges ?\n this.#config.registry.expandImplyingEdges(edgeKind)\n : [edgeKind];\n }\n\n #expandInverseTraversalEdgeKinds(\n edgeKinds: readonly string[],\n includeImplyingEdges: boolean,\n ): readonly string[] {\n const inverseKinds = new Set<string>();\n\n for (const kind of edgeKinds) {\n const inverseKind = this.#config.registry.getInverseEdge(kind);\n if (inverseKind === undefined) {\n continue;\n }\n\n inverseKinds.add(inverseKind);\n\n if (!includeImplyingEdges) {\n continue;\n }\n\n for (const implyingKind of this.#config.registry.expandImplyingEdges(\n inverseKind,\n )) {\n inverseKinds.add(implyingKind);\n }\n }\n\n return [...inverseKinds];\n }\n\n /**\n * Gets edge kind names for an edge alias.\n */\n #getEdgeKindNamesForAlias(alias: string): readonly string[] | undefined {\n for (const traversal of this.#state.traversals) {\n if (traversal.edgeAlias === alias) {\n return mergeEdgeKinds(traversal);\n }\n }\n return undefined;\n }\n\n /**\n * Determines the appropriate field builder for an edge property based on Zod schema type.\n */\n #getFieldBuilderForEdgeProperty(\n edgeKindNames: readonly string[] | undefined,\n property: string,\n alias: string,\n ): BaseFieldAccessor {\n const typeInfo =\n edgeKindNames ?\n this.#config.schemaIntrospector.getSharedEdgeFieldTypeInfo(\n edgeKindNames,\n property,\n )\n : undefined;\n\n const ref = fieldRef(alias, [\"props\"], {\n jsonPointer: jsonPointer([property]),\n valueType: typeInfo?.valueType,\n elementType: typeInfo?.elementType,\n });\n\n return this.#buildFieldBuilderForTypeInfo(ref, typeInfo);\n }\n\n #createEdgeAccessor(alias: string): EdgeAccessor<EdgeType> {\n const edgeKindNames = this.#getEdgeKindNamesForAlias(alias);\n const idAccessor = stringField(\n fieldRef(alias, [\"id\"], { valueType: \"string\" }),\n );\n const kindAccessor = stringField(\n fieldRef(alias, [\"kind\"], { valueType: \"string\" }),\n );\n const fromIdAccessor = stringField(\n fieldRef(alias, [\"from_id\"], { valueType: \"string\" }),\n );\n const toIdAccessor = stringField(\n fieldRef(alias, [\"to_id\"], { valueType: \"string\" }),\n );\n\n if (this.#state.dynamicEdgeAliases.has(alias)) {\n return {\n id: idAccessor,\n kind: kindAccessor,\n fromId: fromIdAccessor,\n toId: toIdAccessor,\n field: (name: string) =>\n createDynamicFieldBuilder(\n this.#config.schemaIntrospector,\n alias,\n name,\n edgeKindNames,\n \"edge\",\n ),\n } as unknown as EdgeAccessor<EdgeType>;\n }\n\n // Use a Proxy to provide flattened property access\n return new Proxy({} as EdgeAccessor<EdgeType>, {\n get: (_, property: string | symbol) => {\n // Handle symbols and special properties to avoid infinite loops\n if (typeof property === \"symbol\") return;\n if (property === \"then\") return;\n if (property === \"toJSON\") return;\n\n // System fields\n if (property === \"id\") return idAccessor;\n if (property === \"kind\") return kindAccessor;\n if (property === \"fromId\") return fromIdAccessor;\n if (property === \"toId\") return toIdAccessor;\n\n // Schema properties\n return this.#getFieldBuilderForEdgeProperty(\n edgeKindNames,\n property,\n alias,\n );\n },\n });\n }\n}\n","/**\n * UnionableQuery - A query formed by combining multiple queries with set operations.\n */\nimport {\n type GraphBackend,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { withRecordedRelationsPrecondition } from \"../../utils/sql-errors\";\nimport {\n type ComposableQuery,\n type QueryAst,\n type SetOperation,\n type SetOperationType,\n type Traversal,\n} from \"../ast\";\nimport {\n type CompileQueryOptions,\n compileSetOperation,\n} from \"../compiler/index\";\nimport { mapResults } from \"../execution\";\nimport { type CompiledSelectSql } from \"../sql-intent\";\nimport { buildCompileOptions } from \"./compile-options\";\nimport { composableQueryHasParameterReferences } from \"./prepared-query\";\nimport {\n buildReadInstantTemplate,\n type CompiledTemplate,\n composableNeedsCurrentReadInstant,\n fillTemplateParams,\n} from \"./read-instant-template\";\nimport {\n type AliasMap,\n type EdgeAliasMap,\n type QueryBuilderConfig,\n type SelectContext,\n} from \"./types\";\n\nfunction executeOnBackend<T>(\n backend: GraphBackend | TransactionBackend,\n recordedAsOf: string | undefined,\n promise: Promise<T>,\n surface: string,\n): Promise<T> {\n if (recordedAsOf === undefined) return promise;\n return withRecordedRelationsPrecondition(promise, {\n dialect: backend.dialect,\n surface,\n });\n}\n\nfunction recordedAsOfForComposableQuery(\n query: ComposableQuery,\n): string | undefined {\n if (\"__type\" in query) {\n return (\n recordedAsOfForComposableQuery(query.left) ??\n recordedAsOfForComposableQuery(query.right)\n );\n }\n return query.recordedAsOf;\n}\n\n// Forward declaration for ExecutableQuery to avoid circular imports\n// G and R are used for type compatibility with ExecutableQuery but not accessed in the interface body\ninterface ExecutableQueryLike<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Used for type compatibility\n G extends GraphDef,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Used for type compatibility\n R,\n> {\n toAst(): QueryAst;\n}\n\n/**\n * Internal state for unionable query.\n */\ntype UnionableQueryState = Readonly<{\n left: ComposableQuery;\n operator: SetOperationType;\n right: ComposableQuery;\n limit?: number;\n offset?: number;\n // For result transformation\n startAlias?: string;\n traversals?: readonly Traversal[];\n selectFn?: (context: SelectContext<AliasMap, EdgeAliasMap>) => unknown;\n}>;\n\n/**\n * A query formed by combining multiple queries with set operations.\n * Supports chaining: q1.union(q2).intersect(q3)\n */\n/** Sentinel distinguishing \"template not yet built\" from a built `undefined`. */\nconst NOT_COMPUTED = Symbol(\"NOT_COMPUTED\");\n\nexport class UnionableQuery<G extends GraphDef, R> {\n readonly #config: QueryBuilderConfig;\n readonly #state: UnionableQueryState;\n // Per-instance compiled placeholder template, reused across\n // execute()/executeOn() calls; the read instant is filled fresh per call.\n // NOT_COMPUTED = not yet built; undefined = no fast path.\n #template: CompiledTemplate | typeof NOT_COMPUTED | undefined = NOT_COMPUTED;\n\n constructor(config: QueryBuilderConfig, state: UnionableQueryState) {\n this.#config = config;\n this.#state = state;\n }\n\n /**\n * Combines with another query using UNION.\n */\n union(other: ExecutableQueryLike<G, R>): UnionableQuery<G, R> {\n return new UnionableQuery(this.#config, {\n left: this.toAst(),\n operator: \"union\",\n right: other.toAst(),\n // Preserve result transformation info (only include defined properties)\n ...(this.#state.startAlias !== undefined && {\n startAlias: this.#state.startAlias,\n }),\n ...(this.#state.traversals !== undefined && {\n traversals: this.#state.traversals,\n }),\n ...(this.#state.selectFn !== undefined && {\n selectFn: this.#state.selectFn,\n }),\n });\n }\n\n /**\n * Combines with another query using UNION ALL.\n */\n unionAll(other: ExecutableQueryLike<G, R>): UnionableQuery<G, R> {\n return new UnionableQuery(this.#config, {\n left: this.toAst(),\n operator: \"unionAll\",\n right: other.toAst(),\n // Preserve result transformation info (only include defined properties)\n ...(this.#state.startAlias !== undefined && {\n startAlias: this.#state.startAlias,\n }),\n ...(this.#state.traversals !== undefined && {\n traversals: this.#state.traversals,\n }),\n ...(this.#state.selectFn !== undefined && {\n selectFn: this.#state.selectFn,\n }),\n });\n }\n\n /**\n * Combines with another query using INTERSECT.\n */\n intersect(other: ExecutableQueryLike<G, R>): UnionableQuery<G, R> {\n return new UnionableQuery(this.#config, {\n left: this.toAst(),\n operator: \"intersect\",\n right: other.toAst(),\n // Preserve result transformation info (only include defined properties)\n ...(this.#state.startAlias !== undefined && {\n startAlias: this.#state.startAlias,\n }),\n ...(this.#state.traversals !== undefined && {\n traversals: this.#state.traversals,\n }),\n ...(this.#state.selectFn !== undefined && {\n selectFn: this.#state.selectFn,\n }),\n });\n }\n\n /**\n * Combines with another query using EXCEPT.\n */\n except(other: ExecutableQueryLike<G, R>): UnionableQuery<G, R> {\n return new UnionableQuery(this.#config, {\n left: this.toAst(),\n operator: \"except\",\n right: other.toAst(),\n // Preserve result transformation info (only include defined properties)\n ...(this.#state.startAlias !== undefined && {\n startAlias: this.#state.startAlias,\n }),\n ...(this.#state.traversals !== undefined && {\n traversals: this.#state.traversals,\n }),\n ...(this.#state.selectFn !== undefined && {\n selectFn: this.#state.selectFn,\n }),\n });\n }\n\n /**\n * Limits the number of results from the combined query.\n */\n limit(n: number): UnionableQuery<G, R> {\n return new UnionableQuery(this.#config, { ...this.#state, limit: n });\n }\n\n /**\n * Offsets the results from the combined query.\n */\n offset(n: number): UnionableQuery<G, R> {\n return new UnionableQuery(this.#config, { ...this.#state, offset: n });\n }\n\n /**\n * Builds the set operation AST.\n */\n toAst(): SetOperation {\n return {\n __type: \"set_operation\",\n operator: this.#state.operator,\n left: this.#state.left,\n right: this.#state.right,\n ...(this.#state.limit !== undefined && { limit: this.#state.limit }),\n ...(this.#state.offset !== undefined && { offset: this.#state.offset }),\n };\n }\n\n /**\n * Compiles the query and returns the SQL text and parameters.\n *\n * Requires a backend to be configured (the backend determines the SQL dialect).\n * Use this for debugging, logging, or running the query with a custom executor.\n */\n toSQL(): Readonly<{ sql: string; params: readonly unknown[] }> {\n if (!this.#config.backend?.compileSql) {\n throw new Error(\n \"Cannot convert to SQL: no backend configured or backend does not support compileSql. \" +\n \"Use store.query() to get a backend-aware query builder.\",\n );\n }\n return this.#config.backend.compileSql(this.compile());\n }\n\n /**\n * Compiles the set operation to SQL.\n */\n compile(): CompiledSelectSql {\n // Emits a directly-runnable statement with the read instant as a literal;\n // this is not the reusable placeholder template execute() caches (see\n // #resolveTemplate).\n return compileSetOperation(\n this.toAst(),\n this.#config.graphId,\n this.#compileOptions(),\n );\n }\n\n #compileOptions(): CompileQueryOptions {\n return buildCompileOptions(this.#config);\n }\n\n /**\n * The cached placeholder template for this set operation, or `undefined`\n * when no fast path applies. Built once per instance; every operand's read\n * instant is the shared placeholder, filled fresh per execution by\n * {@link fillTemplateParams}.\n */\n #resolveTemplate(ast: SetOperation): CompiledTemplate | undefined {\n if (this.#template !== NOT_COMPUTED) return this.#template;\n this.#template = buildReadInstantTemplate({\n compile: () =>\n compileSetOperation(ast, this.#config.graphId, {\n ...this.#compileOptions(),\n readInstant: \"placeholder\",\n }),\n backend: this.#config.backend,\n needsReadInstant: composableNeedsCurrentReadInstant(ast),\n });\n return this.#template;\n }\n\n /**\n * Fetches raw rows for the set operation: cached template + `executeRaw`\n * when available, else a fresh literal compile via `backend.execute`.\n */\n async #fetchRows(\n backend: GraphBackend | TransactionBackend,\n ast: SetOperation,\n surface: string,\n ): Promise<readonly Record<string, unknown>[]> {\n const executeRaw = backend.executeRaw;\n const template =\n executeRaw === undefined ? undefined : this.#resolveTemplate(ast);\n return executeOnBackend(\n backend,\n recordedAsOfForComposableQuery(ast),\n template !== undefined && executeRaw !== undefined ?\n executeRaw<Record<string, unknown>>(\n template.sql,\n fillTemplateParams(\n template.params,\n {},\n this.#config.dialect ?? \"sqlite\",\n ),\n )\n : backend.execute<Record<string, unknown>>(\n compileSetOperation(\n ast,\n this.#config.graphId,\n this.#compileOptions(),\n ),\n ),\n surface,\n );\n }\n\n /** Applies the select-function transformation, if one is attached. */\n #mapRows(rows: readonly Record<string, unknown>[]): readonly R[] {\n if (this.#state.selectFn && this.#state.startAlias) {\n return mapResults(\n rows,\n this.#state.startAlias,\n this.#state.traversals ?? [],\n this.#state.selectFn,\n ) as readonly R[];\n }\n return rows as readonly R[];\n }\n\n /**\n * Executes the combined query.\n */\n async execute(): Promise<readonly R[]> {\n if (!this.#config.backend) {\n throw new Error(\n \"Cannot execute query: no backend configured. \" +\n \"Use store.query() or pass a backend to createQueryBuilder().\",\n );\n }\n const backend = this.#config.backend;\n\n const ast = this.toAst();\n if (composableQueryHasParameterReferences(ast)) {\n throw new Error(\n \"Query contains param() references. Use .prepare().execute({...}) instead of .execute().\",\n );\n }\n\n return this.#mapRows(await this.#fetchRows(backend, ast, \"recorded-query\"));\n }\n\n /**\n * Executes the combined query against a provided backend.\n *\n * Used by `store.batch()` to run multiple queries over a single connection.\n */\n async executeOn(\n backend: GraphBackend | TransactionBackend,\n ): Promise<readonly R[]> {\n const ast = this.toAst();\n if (composableQueryHasParameterReferences(ast)) {\n throw new Error(\n \"Query contains param() references. Use .prepare().execute({...}) instead of .execute().\",\n );\n }\n\n return this.#mapRows(\n await this.#fetchRows(backend, ast, \"recorded-batch-query\"),\n );\n }\n}\n","/**\n * Aggregate and HAVING Helper Functions\n *\n * Provides factory functions for creating aggregate expressions (COUNT, SUM, etc.)\n * and HAVING clause predicates for use in GROUP BY queries.\n */\nimport {\n type AggregateComparisonPredicate,\n type AggregateExpr,\n type ComparisonOp,\n type FieldRef,\n} from \"../ast\";\nimport { jsonPointer } from \"../json-pointer\";\n\n// ============================================================\n// Aggregate Helpers\n// ============================================================\n\n/**\n * Creates a COUNT aggregate expression.\n *\n * @param alias - The node alias to count\n * @param field - Optional field to count (defaults to counting nodes by ID)\n *\n * @example\n * ```typescript\n * // COUNT all persons\n * count(\"p\")\n *\n * // COUNT persons with email field\n * count(\"p\", \"email\")\n * ```\n */\nexport function count(alias: string, field?: string): AggregateExpr {\n return {\n __type: \"aggregate\",\n function: \"count\",\n field: {\n __type: \"field_ref\",\n alias,\n path: field ? [\"props\"] : [\"id\"],\n jsonPointer: field ? jsonPointer([field]) : undefined,\n valueType: field ? undefined : \"string\",\n },\n };\n}\n\n/**\n * Creates a COUNT DISTINCT aggregate expression.\n *\n * @param alias - The node alias to count\n * @param field - Optional field to count distinct values of\n */\nexport function countDistinct(alias: string, field?: string): AggregateExpr {\n return {\n __type: \"aggregate\",\n function: \"countDistinct\",\n field: {\n __type: \"field_ref\",\n alias,\n path: field ? [\"props\"] : [\"id\"],\n jsonPointer: field ? jsonPointer([field]) : undefined,\n valueType: field ? undefined : \"string\",\n },\n };\n}\n\n/**\n * Creates a COUNT aggregate expression over an edge alias.\n *\n * Counts edges directly, without joining back to the target node table.\n * This has different semantics from `count(targetAlias)`:\n *\n * - `countEdges(edgeAlias)` — counts live edges, regardless of target-node\n * temporal state. If a target node's `validTo` is in the past while its\n * incident edges are still live, those edges are still counted.\n * - `count(targetAlias)` — counts edges whose target node is currently\n * valid under the query's temporal mode.\n *\n * For the common case (\"how many follow relationships does this user\n * have?\") the edge-count semantics is what you want, and the compiler\n * can skip the target-node join entirely — measurably faster on\n * full-graph aggregates where the join dominates cost.\n *\n * @example\n * ```typescript\n * store\n * .query()\n * .from(\"User\", \"u\")\n * .optionalTraverse(\"follows\", \"e\", { expand: \"none\" })\n * .to(\"User\", \"target\")\n * .groupByNode(\"u\")\n * .aggregate({\n * name: field(\"u\", \"name\"),\n * // counts edges — skips the target-node join\n * followCount: countEdges(\"e\"),\n * })\n * .execute();\n * ```\n */\nexport function countEdges(edgeAlias: string): AggregateExpr {\n return count(edgeAlias);\n}\n\n/**\n * Creates a COUNT DISTINCT aggregate expression over an edge alias.\n * See {@link countEdges} for semantics.\n *\n * Distinct-on-edge-id is equivalent to `countEdges` when the query\n * surface produces each edge exactly once, but stays meaningful under\n * polymorphic expansions and ontology-driven edge fan-outs where the\n * same edge can appear multiple times in the join output.\n */\nexport function countDistinctEdges(edgeAlias: string): AggregateExpr {\n return countDistinct(edgeAlias);\n}\n\n/**\n * Creates a SUM aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The numeric field to sum\n */\nexport function sum(alias: string, field: string): AggregateExpr {\n return {\n __type: \"aggregate\",\n function: \"sum\",\n field: {\n __type: \"field_ref\",\n alias,\n path: [\"props\"],\n jsonPointer: jsonPointer([field]),\n valueType: \"number\",\n },\n };\n}\n\n/**\n * Creates an AVG aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The numeric field to average\n */\nexport function avg(alias: string, field: string): AggregateExpr {\n return {\n __type: \"aggregate\",\n function: \"avg\",\n field: {\n __type: \"field_ref\",\n alias,\n path: [\"props\"],\n jsonPointer: jsonPointer([field]),\n valueType: \"number\",\n },\n };\n}\n\n/**\n * Creates a MIN aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The field to find minimum of\n */\nexport function min(alias: string, field: string): AggregateExpr {\n return {\n __type: \"aggregate\",\n function: \"min\",\n field: {\n __type: \"field_ref\",\n alias,\n path: [\"props\"],\n jsonPointer: jsonPointer([field]),\n valueType: \"number\",\n },\n };\n}\n\n/**\n * Creates a MAX aggregate expression.\n *\n * @param alias - The node alias\n * @param field - The field to find maximum of\n */\nexport function max(alias: string, field: string): AggregateExpr {\n return {\n __type: \"aggregate\",\n function: \"max\",\n field: {\n __type: \"field_ref\",\n alias,\n path: [\"props\"],\n jsonPointer: jsonPointer([field]),\n valueType: \"number\",\n },\n };\n}\n\n/**\n * Creates a field reference for use in aggregate.\n *\n * @param alias - The node alias\n * @param path - Path to the field. Use \"id\" for node ID, \"kind\" for node kind,\n * or the property name directly (e.g., \"title\", \"year\").\n *\n * @example\n * ```typescript\n * field(\"p\", \"id\") // Node ID\n * field(\"p\", \"kind\") // Node kind\n * field(\"p\", \"title\") // Property field\n * field(\"p\", \"nested\", \"field\") // Nested property\n * ```\n */\nexport function field(alias: string, ...path: string[]): FieldRef {\n if (path.length === 0 || path[0] === \"id\") {\n return {\n __type: \"field_ref\",\n alias,\n path: [\"id\"],\n valueType: \"string\",\n };\n }\n if (path[0] === \"kind\") {\n return {\n __type: \"field_ref\",\n alias,\n path: [\"kind\"],\n valueType: \"string\",\n };\n }\n if (path[0] === \"props\") {\n throw new Error(\n `field(): Do not include \"props\" in the path. Use field(\"${alias}\", ${path\n .slice(1)\n .map((p) => `\"${p}\"`)\n .join(\", \")}) instead.`,\n );\n }\n return {\n __type: \"field_ref\",\n alias,\n path: [\"props\"],\n jsonPointer: jsonPointer(path),\n };\n}\n\n// ============================================================\n// HAVING Helpers\n// ============================================================\n\n/**\n * Creates a HAVING predicate that compares an aggregate to a value.\n *\n * @param aggregate - The aggregate expression (count, sum, avg, etc.)\n * @param op - The comparison operator\n * @param value - The value to compare against\n *\n * @example\n * ```typescript\n * // HAVING COUNT(*) > 10\n * having(count(\"p\"), \"gt\", 10)\n *\n * // HAVING AVG(salary) >= 50000\n * having(avg(\"p\", \"salary\"), \"gte\", 50000)\n * ```\n */\nexport function having(\n aggregate: AggregateExpr,\n op: ComparisonOp,\n value: number | string | boolean,\n): AggregateComparisonPredicate {\n return {\n __type: \"aggregate_comparison\",\n op,\n aggregate,\n value: {\n __type: \"literal\",\n value,\n valueType: typeof value === \"number\" ? \"number\" : \"string\",\n },\n };\n}\n\n/**\n * Creates a HAVING predicate: aggregate > value\n */\nexport function havingGt(\n aggregate: AggregateExpr,\n value: number,\n): AggregateComparisonPredicate {\n return having(aggregate, \"gt\", value);\n}\n\n/**\n * Creates a HAVING predicate: aggregate >= value\n */\nexport function havingGte(\n aggregate: AggregateExpr,\n value: number,\n): AggregateComparisonPredicate {\n return having(aggregate, \"gte\", value);\n}\n\n/**\n * Creates a HAVING predicate: aggregate < value\n */\nexport function havingLt(\n aggregate: AggregateExpr,\n value: number,\n): AggregateComparisonPredicate {\n return having(aggregate, \"lt\", value);\n}\n\n/**\n * Creates a HAVING predicate: aggregate <= value\n */\nexport function havingLte(\n aggregate: AggregateExpr,\n value: number,\n): AggregateComparisonPredicate {\n return having(aggregate, \"lte\", value);\n}\n\n/**\n * Creates a HAVING predicate: aggregate = value\n */\nexport function havingEq(\n aggregate: AggregateExpr,\n value: number,\n): AggregateComparisonPredicate {\n return having(aggregate, \"eq\", value);\n}\n","/**\n * Query Fragment Composition\n *\n * Provides types and utilities for creating reusable query fragments\n * that can be composed together using the pipe() method.\n *\n * @example\n * ```typescript\n * // Define a reusable fragment\n * const activeUsers = createFragment<MyGraph>()((q) =>\n * q.whereNode(\"u\", ({ status }) => status.eq(\"active\"))\n * );\n *\n * // Use in queries\n * const results = await query()\n * .from(\"User\", \"u\")\n * .pipe(activeUsers)\n * .select((ctx) => ctx.u)\n * .execute();\n * ```\n */\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type TraversalDirection } from \"../ast\";\nimport { type QueryBuilder } from \"./query-builder\";\nimport { type TraversalBuilder } from \"./traversal-builder\";\nimport {\n type AliasMap,\n type EdgeAliasMap,\n type EmptyRecursiveAliasMap,\n type QueryCoordinateState,\n type RecursiveAliasMap,\n} from \"./types\";\n\n// ============================================================\n// Fragment Types\n// ============================================================\n\n/**\n * A query fragment that transforms a QueryBuilder.\n *\n * Fragments are functions that take a builder and return a modified builder.\n * They can add predicates, traversals, ordering, and other query operations.\n *\n * @typeParam G - The graph definition\n * @typeParam InAliases - Input alias map (what the fragment requires)\n * @typeParam OutAliases - Output alias map (what the fragment produces)\n * @typeParam InEdgeAliases - Input edge alias map\n * @typeParam OutEdgeAliases - Output edge alias map\n * @typeParam InRecursiveAliases - Input recursive alias map\n * @typeParam OutRecursiveAliases - Output recursive alias map\n */\nexport type QueryFragment<\n G extends GraphDef,\n InAliases extends AliasMap = AliasMap,\n OutAliases extends AliasMap = InAliases,\n InEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\n OutEdgeAliases extends EdgeAliasMap = InEdgeAliases,\n InRecursiveAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n OutRecursiveAliases extends RecursiveAliasMap = InRecursiveAliases,\n> = <CoordinateState extends QueryCoordinateState>(\n builder: QueryBuilder<\n G,\n InAliases,\n InEdgeAliases,\n InRecursiveAliases,\n CoordinateState\n >,\n) => QueryBuilder<\n G,\n OutAliases,\n OutEdgeAliases,\n OutRecursiveAliases,\n CoordinateState\n>;\n\n/**\n * A flexible query fragment that works with any compatible builder.\n *\n * Use this when you want a fragment that only requires certain aliases\n * to exist, but doesn't care about other aliases that may be present.\n */\nexport type FlexibleQueryFragment<\n G extends GraphDef,\n RequiredAliases extends AliasMap = AliasMap,\n AddedAliases extends AliasMap = AliasMap,\n RequiredEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\n AddedEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\n> = <\n Aliases extends RequiredAliases,\n EdgeAliases extends RequiredEdgeAliases,\n RecursiveAliases extends RecursiveAliasMap,\n CoordinateState extends QueryCoordinateState,\n>(\n builder: QueryBuilder<\n G,\n Aliases,\n EdgeAliases,\n RecursiveAliases,\n CoordinateState\n >,\n) => QueryBuilder<\n G,\n Aliases & AddedAliases,\n EdgeAliases & AddedEdgeAliases,\n RecursiveAliases,\n CoordinateState\n>;\n\n/**\n * A traversal fragment that transforms a TraversalBuilder.\n *\n * Use this for reusable traversal patterns including edge filtering,\n * recursive traversals, and path collection.\n */\nexport type TraversalFragment<\n G extends GraphDef,\n EK extends keyof G[\"edges\"] & string,\n EA extends string,\n InAliases extends AliasMap = AliasMap,\n InEdgeAliases extends EdgeAliasMap = EdgeAliasMap,\n> = <\n Dir extends TraversalDirection,\n Optional extends boolean,\n DC extends boolean | string,\n PC extends boolean | string,\n RecursiveAliases extends RecursiveAliasMap,\n CoordinateState extends QueryCoordinateState,\n>(\n builder: TraversalBuilder<\n G,\n InAliases,\n InEdgeAliases,\n EK,\n EA,\n Dir,\n Optional,\n DC,\n PC,\n RecursiveAliases,\n CoordinateState\n >,\n) => unknown;\n\n// ============================================================\n// Fragment Factory\n// ============================================================\n\n/**\n * Creates a typed query fragment factory for a specific graph.\n *\n * This is the recommended way to create reusable fragments with full type safety.\n * The factory returns a function that creates fragments bound to your graph type.\n *\n * @example\n * ```typescript\n * // Create a factory for your graph\n * const fragment = createFragment<MyGraph>();\n *\n * // Define a simple filter fragment\n * const activeOnly = fragment((q) =>\n * q.whereNode(\"u\", ({ isActive }) => isActive.eq(true))\n * );\n *\n * // Define a traversal fragment\n * const withManager = fragment((q) =>\n * q.traverse(\"reportsTo\", \"r\").to(\"User\", \"manager\")\n * );\n *\n * // Compose fragments\n * query()\n * .from(\"User\", \"u\")\n * .pipe(activeOnly)\n * .pipe(withManager)\n * .select((ctx) => ({ user: ctx.u, manager: ctx.manager }))\n * ```\n */\n/**\n * Identity function used by createFragment to return the fragment unchanged.\n * Defined at module scope to satisfy consistent-function-scoping lint rule.\n */\nfunction fragmentIdentity<\n G extends GraphDef,\n InAliases extends AliasMap,\n OutAliases extends AliasMap,\n InEdgeAliases extends EdgeAliasMap,\n OutEdgeAliases extends EdgeAliasMap,\n InRecursiveAliases extends RecursiveAliasMap,\n OutRecursiveAliases extends RecursiveAliasMap,\n>(\n fn: QueryFragment<\n G,\n InAliases,\n OutAliases,\n InEdgeAliases,\n OutEdgeAliases,\n InRecursiveAliases,\n OutRecursiveAliases\n >,\n): QueryFragment<\n G,\n InAliases,\n OutAliases,\n InEdgeAliases,\n OutEdgeAliases,\n InRecursiveAliases,\n OutRecursiveAliases\n> {\n return fn;\n}\n\nexport function createFragment<G extends GraphDef>(): <\n InAliases extends AliasMap,\n OutAliases extends AliasMap,\n InEdgeAliases extends EdgeAliasMap,\n OutEdgeAliases extends EdgeAliasMap,\n InRecursiveAliases extends RecursiveAliasMap = EmptyRecursiveAliasMap,\n OutRecursiveAliases extends RecursiveAliasMap = InRecursiveAliases,\n>(\n fn: QueryFragment<\n G,\n InAliases,\n OutAliases,\n InEdgeAliases,\n OutEdgeAliases,\n InRecursiveAliases,\n OutRecursiveAliases\n >,\n) => QueryFragment<\n G,\n InAliases,\n OutAliases,\n InEdgeAliases,\n OutEdgeAliases,\n InRecursiveAliases,\n OutRecursiveAliases\n> {\n return fragmentIdentity;\n}\n\ntype ErasedFragment = (builder: unknown) => unknown;\n\n/**\n * Combines multiple fragments into a single fragment.\n *\n * Fragments are applied in order from left to right.\n *\n * @example\n * ```typescript\n * const combinedFragment = composeFragments(\n * activeOnly,\n * withManager,\n * recentlyUpdated\n * );\n *\n * query()\n * .from(\"User\", \"u\")\n * .pipe(combinedFragment)\n * .select(...)\n * ```\n */\nexport function composeFragments<\n G extends GraphDef,\n A1 extends AliasMap,\n A2 extends AliasMap,\n E1 extends EdgeAliasMap,\n E2 extends EdgeAliasMap,\n R1 extends RecursiveAliasMap,\n R2 extends RecursiveAliasMap,\n>(\n f1: QueryFragment<G, A1, A2, E1, E2, R1, R2>,\n): QueryFragment<G, A1, A2, E1, E2, R1, R2>;\n\nexport function composeFragments<\n G extends GraphDef,\n A1 extends AliasMap,\n A2 extends AliasMap,\n A3 extends AliasMap,\n E1 extends EdgeAliasMap,\n E2 extends EdgeAliasMap,\n E3 extends EdgeAliasMap,\n R1 extends RecursiveAliasMap,\n R2 extends RecursiveAliasMap,\n R3 extends RecursiveAliasMap,\n>(\n f1: QueryFragment<G, A1, A2, E1, E2, R1, R2>,\n f2: QueryFragment<G, A2, A3, E2, E3, R2, R3>,\n): QueryFragment<G, A1, A3, E1, E3, R1, R3>;\n\nexport function composeFragments<\n G extends GraphDef,\n A1 extends AliasMap,\n A2 extends AliasMap,\n A3 extends AliasMap,\n A4 extends AliasMap,\n E1 extends EdgeAliasMap,\n E2 extends EdgeAliasMap,\n E3 extends EdgeAliasMap,\n E4 extends EdgeAliasMap,\n R1 extends RecursiveAliasMap,\n R2 extends RecursiveAliasMap,\n R3 extends RecursiveAliasMap,\n R4 extends RecursiveAliasMap,\n>(\n f1: QueryFragment<G, A1, A2, E1, E2, R1, R2>,\n f2: QueryFragment<G, A2, A3, E2, E3, R2, R3>,\n f3: QueryFragment<G, A3, A4, E3, E4, R3, R4>,\n): QueryFragment<G, A1, A4, E1, E4, R1, R4>;\n\nexport function composeFragments<\n G extends GraphDef,\n A1 extends AliasMap,\n A2 extends AliasMap,\n A3 extends AliasMap,\n A4 extends AliasMap,\n A5 extends AliasMap,\n E1 extends EdgeAliasMap,\n E2 extends EdgeAliasMap,\n E3 extends EdgeAliasMap,\n E4 extends EdgeAliasMap,\n E5 extends EdgeAliasMap,\n R1 extends RecursiveAliasMap,\n R2 extends RecursiveAliasMap,\n R3 extends RecursiveAliasMap,\n R4 extends RecursiveAliasMap,\n R5 extends RecursiveAliasMap,\n>(\n f1: QueryFragment<G, A1, A2, E1, E2, R1, R2>,\n f2: QueryFragment<G, A2, A3, E2, E3, R2, R3>,\n f3: QueryFragment<G, A3, A4, E3, E4, R3, R4>,\n f4: QueryFragment<G, A4, A5, E4, E5, R4, R5>,\n): QueryFragment<G, A1, A5, E1, E5, R1, R5>;\n\nexport function composeFragments(...fragments: readonly unknown[]): unknown {\n return (builder: unknown) => {\n let result = builder;\n for (const fragment of fragments) {\n result = (fragment as ErasedFragment)(result);\n }\n return result;\n };\n}\n\n// ============================================================\n// Common Fragment Patterns\n// ============================================================\n\n/**\n * Creates a fragment that adds ordering.\n *\n * @example\n * ```typescript\n * const byCreatedAt = orderByFragment<MyGraph, \"u\">(\"u\", \"createdAt\", \"desc\");\n * ```\n */\nexport function orderByFragment<G extends GraphDef, A extends string>(\n alias: A,\n field: string,\n direction: \"asc\" | \"desc\" = \"asc\",\n): FlexibleQueryFragment<G> {\n return (builder) => builder.orderBy(alias, field, direction);\n}\n\n/**\n * Creates a fragment that adds a limit.\n *\n * @example\n * ```typescript\n * const first10 = limitFragment<MyGraph>(10);\n * ```\n */\nexport function limitFragment<G extends GraphDef>(\n n: number,\n): FlexibleQueryFragment<G> {\n return (builder) => builder.limit(n);\n}\n\n/**\n * Creates a fragment that adds an offset.\n *\n * @example\n * ```typescript\n * const skip10 = offsetFragment<MyGraph>(10);\n * ```\n */\nexport function offsetFragment<G extends GraphDef>(\n n: number,\n): FlexibleQueryFragment<G> {\n return (builder) => builder.offset(n);\n}\n","/**\n * Query Builder Module\n *\n * Re-exports from the builder submodules for clean imports.\n * Also wires up circular dependencies between classes.\n */\n\n// Import classes for circular dependency wiring\nimport { setUnionableQueryClass } from \"./executable-query\";\nimport { QueryBuilder } from \"./query-builder\";\nimport { setQueryBuilderClass } from \"./traversal-builder\";\nimport { UnionableQuery } from \"./unionable-query\";\n\n// Wire up circular dependencies.\n// Type assertions are needed because the circular dependency resolution\n// requires passing classes that TypeScript can't verify at module init time.\nsetQueryBuilderClass(QueryBuilder);\nsetUnionableQueryClass(UnionableQuery);\n\n// Classes\nexport {\n type AggregateResult,\n ExecutableAggregateQuery,\n} from \"./executable-aggregate-query\";\nexport { ExecutableQuery } from \"./executable-query\";\nexport { PreparedQuery } from \"./prepared-query\";\nexport { QueryBuilder } from \"./query-builder\";\nexport { TraversalBuilder } from \"./traversal-builder\";\nexport { UnionableQuery } from \"./unionable-query\";\n\n// Aggregate helpers\nexport {\n avg,\n count,\n countDistinct,\n countDistinctEdges,\n countEdges,\n field,\n having,\n havingEq,\n havingGt,\n havingGte,\n havingLt,\n havingLte,\n max,\n min,\n sum,\n} from \"./aggregates\";\n\n// Fragment composition\nexport {\n composeFragments,\n createFragment,\n type FlexibleQueryFragment,\n limitFragment,\n offsetFragment,\n orderByFragment,\n type QueryFragment,\n type TraversalFragment,\n} from \"./fragment\";\n\n// AST building utilities\nexport { buildQueryAst } from \"./ast-builder\";\n\n// Types\nexport {\n type AliasMap,\n type ArrayFieldAccessor,\n type BaseFieldAccessor,\n type BatchableQuery,\n type BatchResults,\n type BooleanFieldAccessor,\n type CreateQueryBuilderOptions,\n type DateFieldAccessor,\n type EdgeAccessor,\n type EmbeddingFieldAccessor,\n type EmptyAliasMap,\n type EmptyEdgeAliasMap,\n type EmptyRecursiveAliasMap,\n type FieldAccessor,\n type NodeAccessor,\n type NodeAlias,\n type NumberFieldAccessor,\n type ObjectFieldAccessor,\n type PaginatedResult,\n type PaginateOptions,\n type PropsAccessor,\n type QueryBuilderConfig,\n type QueryBuilderState,\n type QueryCoordinateState,\n type RecursiveAlias,\n type RecursiveAliasMap,\n type RecursiveAliasValue,\n type RecursiveTraversalOptions,\n type SelectableEdge,\n type SelectableEdgeMeta,\n type SelectableNode,\n type SelectableNodeMeta,\n type SelectContext,\n type StreamOptions,\n type StringFieldAccessor,\n type TraversalExpansion,\n type UniqueAlias,\n type ValidEdgeTargets,\n} from \"./types\";\n\n// Dynamic (string-keyed) builder types\nexport {\n type DynamicEdgeAccessor,\n type DynamicEdgeType,\n type DynamicFieldBuilder,\n type DynamicNodeAccessor,\n type DynamicNodeType,\n type DynamicSelectableEdge,\n type DynamicSelectableNode,\n} from \"./dynamic\";\n\n// Validation utilities\nexport { validateSqlIdentifier } from \"./validation\";\n","/**\n * Fluent query builder for TypeGraph.\n *\n * Provides a type-safe, chainable API for building queries.\n * Each method returns a new builder instance with expanded type information.\n *\n * This module re-exports from the builder submodules and provides the\n * createQueryBuilder factory function.\n */\nimport { type GraphDef } from \"../core/define-graph\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport {\n type CreateQueryBuilderOptions,\n type EmptyAliasMap,\n type EmptyEdgeAliasMap,\n type EmptyRecursiveAliasMap,\n QueryBuilder,\n type QueryBuilderConfig,\n type QueryBuilderState,\n type QueryCoordinateState,\n} from \"./builder/index\";\nimport {\n type QueryBuilderInternalContext,\n registerQueryBuilderInternalContext,\n} from \"./builder/internal-context\";\nimport { createSchemaIntrospector } from \"./schema-introspector\";\n\n// Re-export all classes\nexport {\n ExecutableAggregateQuery,\n ExecutableQuery,\n QueryBuilder,\n} from \"./builder/index\";\n\n// Re-export aggregate helpers\nexport {\n avg,\n count,\n countDistinct,\n countDistinctEdges,\n countEdges,\n field,\n having,\n havingEq,\n havingGt,\n havingGte,\n havingLt,\n havingLte,\n max,\n min,\n sum,\n} from \"./builder/index\";\n\n// Re-export types\nexport type {\n AggregateResult,\n AliasMap,\n BatchableQuery,\n BatchResults,\n DynamicEdgeAccessor,\n DynamicEdgeType,\n DynamicFieldBuilder,\n DynamicNodeAccessor,\n DynamicNodeType,\n DynamicSelectableEdge,\n DynamicSelectableNode,\n EdgeAccessor,\n EmptyAliasMap,\n EmptyEdgeAliasMap,\n EmptyRecursiveAliasMap,\n FieldAccessor,\n NodeAccessor,\n NodeAlias,\n PaginatedResult,\n PaginateOptions,\n PropsAccessor,\n QueryCoordinateState,\n RecursiveTraversalOptions,\n SelectableEdge,\n SelectableNode,\n SelectContext,\n StreamOptions,\n TraversalExpansion,\n} from \"./builder/index\";\n\n// ============================================================\n// Factory Function\n// ============================================================\n\n/**\n * Creates a new query builder for a graph.\n *\n * @param graphId - The graph identifier\n * @param registry - The kind registry for ontology lookups\n * @param options - Optional backend and dialect configuration\n * @returns A new QueryBuilder instance\n *\n * @example\n * ```typescript\n * // Without execution capability (compile only)\n * const builder = createQueryBuilder<MyGraph>(\"my_graph\", registry);\n *\n * // With execution capability\n * const builder = createQueryBuilder<MyGraph>(\"my_graph\", registry, {\n * backend: myBackend,\n * dialect: \"sqlite\",\n * });\n * ```\n */\ntype InternalCreateQueryBuilderOptions = CreateQueryBuilderOptions &\n QueryBuilderInternalContext;\n\nexport type InitialQueryBuilder<\n G extends GraphDef,\n CoordinateState extends QueryCoordinateState = \"open\",\n> = QueryBuilder<\n G,\n EmptyAliasMap,\n EmptyEdgeAliasMap,\n EmptyRecursiveAliasMap,\n CoordinateState\n>;\n\nexport function createQueryBuilder<G extends GraphDef>(\n graphId: string,\n registry: KindRegistry,\n options?: CreateQueryBuilderOptions,\n): InitialQueryBuilder<G>;\nexport function createQueryBuilder<G extends GraphDef>(\n graphId: string,\n registry: KindRegistry,\n options?: CreateQueryBuilderOptions,\n): InitialQueryBuilder<G> {\n return createQueryBuilderWithContext<G>(graphId, registry, options);\n}\n\nexport function createInternalQueryBuilder<\n G extends GraphDef,\n CoordinateState extends QueryCoordinateState = \"open\",\n>(\n graphId: string,\n registry: KindRegistry,\n options?: InternalCreateQueryBuilderOptions,\n): InitialQueryBuilder<G, CoordinateState> {\n return createQueryBuilderWithContext<G, CoordinateState>(\n graphId,\n registry,\n options,\n );\n}\n\nfunction createQueryBuilderWithContext<\n G extends GraphDef,\n CoordinateState extends QueryCoordinateState = \"open\",\n>(\n graphId: string,\n registry: KindRegistry,\n options?: InternalCreateQueryBuilderOptions,\n): InitialQueryBuilder<G, CoordinateState> {\n const schemaIntrospector = createSchemaIntrospector(\n registry.nodeKinds,\n registry.edgeKinds,\n );\n\n // Build config, only including optional properties if defined\n const config: QueryBuilderConfig = {\n graphId,\n registry,\n schemaIntrospector,\n defaultTraversalExpansion: options?.defaultTraversalExpansion ?? \"inverse\",\n ...(options?.backend !== undefined && { backend: options.backend }),\n ...(options?.dialect !== undefined && { dialect: options.dialect }),\n ...(options?.schema !== undefined && { schema: options.schema }),\n };\n registerQueryBuilderInternalContext(config, {\n ...(options?.recordedReadBinding !== undefined && {\n recordedReadBinding: options.recordedReadBinding,\n }),\n ...(options?.sealedCoordinate !== undefined && {\n sealedCoordinate: options.sealedCoordinate,\n }),\n });\n\n // A sealed coordinate (StoreView pin) seeds the temporal axis; `.temporal()`\n // then refuses to override it.\n const sealed = options?.sealedCoordinate?.valid;\n const recorded = options?.sealedCoordinate?.recorded;\n\n const initialState: QueryBuilderState = {\n startAlias: \"\",\n currentAlias: \"\",\n startKinds: [],\n includeSubClasses: false,\n traversals: [],\n predicates: [],\n projection: [],\n orderBy: [],\n aggregateOrderBy: [],\n limit: undefined,\n offset: undefined,\n temporalMode: sealed?.mode ?? \"current\",\n asOf: sealed?.asOf,\n recordedAsOf: recorded?.asOf,\n groupBy: undefined,\n having: undefined,\n fusion: undefined,\n dynamicNodeAliases: new Set(),\n dynamicEdgeAliases: new Set(),\n };\n\n return new QueryBuilder(config, initialState) as InitialQueryBuilder<\n G,\n CoordinateState\n >;\n}\n","/**\n * Rebuilds the fulltext index from existing node data.\n *\n * Iterates nodes via keyset pagination (ORDER BY id ASC, WHERE id > cursor)\n * so rebuild is stable even under shared created_at timestamps and light\n * concurrent writes. Each page runs in its own transaction; batch primitives\n * are used when the backend provides them, with per-row fallback otherwise.\n *\n * Rebuild is a maintenance operation. Concurrent deletes that happen\n * between page fetches can be missed by this pass — document as such.\n */\nimport { type z } from \"zod\";\n\nimport {\n type GraphBackend,\n type NodeRow,\n rowPropsToObject,\n runOptionallyInTransaction,\n type TransactionBackend,\n} from \"../backend/types\";\nimport { ConfigurationError, ValidationError } from \"../errors\";\nimport { type KindRegistry } from \"../registry\";\nimport { computeFulltextContent, getSearchableFields } from \"./fulltext-sync\";\n\n/**\n * Default page size. Fits under SQLite's ~32766 placeholder limit with\n * headroom: 6 params/row × 500 rows + 500-entry DELETE IN list ≈ 3500\n * placeholders. Bumping past ~5000 risks the ceiling on SQLite.\n */\nconst DEFAULT_PAGE_SIZE = 500;\n\n/**\n * Default cap on the length of `skippedIds` returned from rebuild. A\n * corrupted database could produce millions of skipped rows; surfacing\n * them all as a single in-memory array would turn a recovery tool into\n * an OOM. The total skipped *count* remains accurate; only the ID\n * listing is truncated. Operators who need the full list for recovery\n * can raise the cap via `maxSkippedIds`.\n */\nconst DEFAULT_MAX_SKIPPED_IDS = 10_000;\n\nexport type RebuildFulltextOptions = Readonly<{\n /** Page size. Must be a positive integer. Default: 500. */\n pageSize?: number;\n /**\n * Maximum number of skipped node IDs to include in the `skippedIds`\n * array. Default: 10,000. Set higher to collect the full list when\n * investigating systemic corruption; set lower when `processed` is\n * all you care about. The `skipped` total is always accurate.\n */\n maxSkippedIds?: number;\n}>;\n\nexport type RebuildFulltextResult = Readonly<{\n /** Node kinds that were rebuilt (those with at least one searchable field). */\n kinds: readonly string[];\n /** Total nodes scanned. */\n processed: number;\n /** Fulltext upsert operations executed. */\n upserted: number;\n /** Fulltext delete operations executed (soft-deleted or all-empty nodes). */\n cleared: number;\n /**\n * Nodes skipped due to corrupt or non-object `props` (not counted in\n * upserted/cleared).\n */\n skipped: number;\n /**\n * IDs of skipped nodes, capped at 10,000 entries so pathological\n * corruption doesn't turn rebuild into an OOM. See `skippedTruncated`\n * to tell whether the cap was hit. Empty when `skipped === 0`.\n */\n skippedIds: readonly string[];\n /** True when `skipped > skippedIds.length` (the cap was reached). */\n skippedTruncated: boolean;\n}>;\n\ntype RebuildContext = Readonly<{\n graphId: string;\n backend: GraphBackend;\n registry: KindRegistry;\n}>;\n\nfunction validatePageSize(value: number | undefined): number {\n if (value === undefined) return DEFAULT_PAGE_SIZE;\n if (!Number.isInteger(value) || value <= 0) {\n throw new ValidationError(\n `pageSize must be a positive integer, got: ${String(value)}`,\n {\n issues: [{ path: \"pageSize\", message: \"Must be a positive integer.\" }],\n },\n );\n }\n return value;\n}\n\nfunction validateMaxSkippedIds(value: number | undefined): number {\n if (value === undefined) return DEFAULT_MAX_SKIPPED_IDS;\n if (!Number.isInteger(value) || value < 0) {\n throw new ValidationError(\n `maxSkippedIds must be a non-negative integer, got: ${String(value)}`,\n {\n issues: [\n {\n path: \"maxSkippedIds\",\n message: \"Must be a non-negative integer.\",\n },\n ],\n },\n );\n }\n return value;\n}\n\nfunction isPropsObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport async function rebuildFulltextIndex(\n ctx: RebuildContext,\n nodeKind: string | undefined,\n options: RebuildFulltextOptions,\n): Promise<RebuildFulltextResult> {\n const { backend, registry } = ctx;\n\n if (!backend.upsertFulltext || !backend.deleteFulltext) {\n throw new ConfigurationError(\n \"Backend does not support fulltext; cannot rebuild index\",\n { backend: backend.dialect, capability: \"fulltext\" },\n );\n }\n\n const pageSize = validatePageSize(options.pageSize);\n const maxSkippedIds = validateMaxSkippedIds(options.maxSkippedIds);\n\n const targetKinds =\n nodeKind === undefined ? [...registry.nodeKinds.keys()] : [nodeKind];\n\n const rebuiltKinds: string[] = [];\n let processed = 0;\n let upserted = 0;\n let cleared = 0;\n let skipped = 0;\n const skippedIds: string[] = [];\n\n for (const kind of targetKinds) {\n const nodeType = registry.getNodeType(kind);\n if (!nodeType) {\n throw new ConfigurationError(`Unknown node kind: ${kind}`, { kind });\n }\n if (getSearchableFields(nodeType.schema).length === 0) {\n continue;\n }\n\n rebuiltKinds.push(kind);\n let cursor: string | undefined;\n for (;;) {\n // Keyset pagination on id. Include soft-deleted nodes so their\n // stale fulltext rows get cleaned up by this rebuild.\n const rows = await backend.findNodesByKind({\n graphId: ctx.graphId,\n kind,\n limit: pageSize,\n excludeDeleted: false,\n orderBy: \"id\",\n ...(cursor === undefined ? {} : { after: cursor }),\n });\n if (rows.length === 0) break;\n\n const pageResult = processPage(nodeType.schema, rows);\n skipped += pageResult.skipped;\n const remaining = maxSkippedIds - skippedIds.length;\n if (remaining > 0 && pageResult.skippedIds.length > 0) {\n skippedIds.push(...pageResult.skippedIds.slice(0, remaining));\n }\n\n const writePage = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n if (pageResult.toUpsert.length > 0) {\n if (target.upsertFulltextBatch) {\n await target.upsertFulltextBatch({\n graphId: ctx.graphId,\n nodeKind: kind,\n rows: pageResult.toUpsert,\n });\n } else if (target.upsertFulltext) {\n for (const item of pageResult.toUpsert) {\n await target.upsertFulltext({\n graphId: ctx.graphId,\n nodeKind: kind,\n nodeId: item.nodeId,\n content: item.content,\n language: item.language,\n });\n }\n }\n }\n if (pageResult.toDelete.length > 0) {\n if (target.deleteFulltextBatch) {\n await target.deleteFulltextBatch({\n graphId: ctx.graphId,\n nodeKind: kind,\n nodeIds: pageResult.toDelete,\n });\n } else if (target.deleteFulltext) {\n for (const nodeId of pageResult.toDelete) {\n await target.deleteFulltext({\n graphId: ctx.graphId,\n nodeKind: kind,\n nodeId,\n });\n }\n }\n }\n };\n\n // Wrapped in a transaction when supported so a partial failure\n // mid-page doesn't leave the index half-rebuilt. On backends without\n // transactions, refusing to rebuild would be worse than the lost\n // atomicity (the index would stay permanently stale).\n await runOptionallyInTransaction(backend, writePage);\n\n processed += rows.length;\n upserted += pageResult.toUpsert.length;\n cleared += pageResult.toDelete.length;\n\n const lastRow = rows.at(-1);\n if (!lastRow) break;\n cursor = lastRow.id;\n if (rows.length < pageSize) break;\n }\n }\n\n return {\n kinds: rebuiltKinds,\n processed,\n upserted,\n cleared,\n skipped,\n skippedIds,\n skippedTruncated: skipped > skippedIds.length,\n };\n}\n\ninterface PageResult {\n toUpsert: { nodeId: string; content: string; language: string }[];\n toDelete: string[];\n skipped: number;\n skippedIds: string[];\n}\n\nfunction processPage(schema: z.ZodType, rows: readonly NodeRow[]): PageResult {\n const toUpsert: PageResult[\"toUpsert\"] = [];\n const toDelete: string[] = [];\n const skippedIds: string[] = [];\n let skipped = 0;\n\n for (const row of rows) {\n if (row.deleted_at !== undefined) {\n toDelete.push(row.id);\n continue;\n }\n let parsed: unknown;\n try {\n parsed = rowPropsToObject(row.props);\n } catch {\n skipped += 1;\n skippedIds.push(row.id);\n continue;\n }\n if (!isPropsObject(parsed)) {\n skipped += 1;\n skippedIds.push(row.id);\n continue;\n }\n const computed = computeFulltextContent(schema, parsed);\n if (computed === undefined) {\n toDelete.push(row.id);\n } else {\n toUpsert.push({\n nodeId: row.id,\n content: computed.content,\n language: computed.language,\n });\n }\n }\n\n return { toUpsert, toDelete, skipped, skippedIds };\n}\n","/**\n * Store-level search helpers.\n *\n * `fulltextSearch` is a thin typed wrapper over `backend.fulltextSearch`.\n * `hybridSearch` runs a vector and a fulltext query in parallel and\n * fuses the two ranked lists with Reciprocal Rank Fusion. RRF is\n * rank-based, so it papers over score-scale differences between\n * pgvector/sqlite-vec (distance-derived) and tsvector/FTS5 (BM25-style).\n */\nimport {\n type FulltextCapabilities,\n type FulltextQueryMode,\n type GraphBackend,\n type VectorIndexType,\n type VectorMetric,\n} from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { resolveDeclaredFulltextLanguage } from \"../core/searchable\";\nimport { type NodeType } from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport {\n DEFAULT_RRF_K,\n DEFAULT_RRF_WEIGHT,\n type HybridFusionOptions,\n} from \"../query/ast\";\nimport { type QueryBuilder } from \"../query/builder/query-builder\";\nimport { type NodeAccessor } from \"../query/builder/types\";\nimport { validateHybridFusionOptions } from \"../query/builder/validation\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport { assertVectorMinScore } from \"../query/dialect/vector-strategy\";\nimport { type Predicate } from \"../query/predicates\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { compareCodePoints } from \"../utils/compare\";\nimport { requireDefined } from \"../utils/presence\";\nimport { getEmbeddingFields } from \"./embedding-sync\";\nimport { rowToNode } from \"./row-mappers\";\nimport { type Node } from \"./types\";\n\n/**\n * A fulltext search hit. `N` defaults to the generic `Node`; the\n * `store.search.fulltext<K>(kind)` facade narrows it to the concrete\n * typed node for that kind so callers get `hit.node.title` without a cast.\n */\nexport type FulltextSearchHit<N = Node> = Readonly<{\n node: N;\n /** Backend-native relevance score; higher is better. */\n score: number;\n /** 1-based rank within the result set. */\n rank: number;\n /** Highlighted snippet (only present when `includeSnippets: true`). */\n snippet?: string;\n}>;\n\nexport type VectorSearchHit<N = Node> = Readonly<{\n node: N;\n score: number;\n rank: number;\n}>;\n\n/**\n * A hybrid search hit. Both sub-results (`vector`, `fulltext`) carry the\n * same narrowed node type as the top-level `node` for ergonomic access.\n */\nexport type HybridSearchHit<N = Node> = Readonly<{\n node: N;\n /** Fused RRF score (higher is better). */\n score: number;\n /** 1-based rank in the fused list. */\n rank: number;\n /** Sub-result from the vector half, if it ranked this node. */\n vector?: VectorSearchHit<N>;\n /** Sub-result from the fulltext half, if it ranked this node. */\n fulltext?: FulltextSearchHit<N>;\n}>;\n\n/**\n * Scope options shared by every facade search leg.\n *\n * `where` and `includeSubClasses` compile into the search statement's\n * candidate set (a subquery produced by the store's own query compiler), so\n * filtering happens INSIDE the engine's top-k — never by post-filtering a\n * ranked list. `offset` is rank-relative pagination: the engine fetches\n * `limit + offset` ranked candidates and discards the leading page.\n */\nexport type SearchScopeOptions<N extends NodeType = NodeType> = Readonly<{\n /**\n * Predicate over the node's properties, compiled by the shared query\n * compiler into the candidate subquery. Requires a query-capable store.\n * The facade instantiates `N` to the searched kind's node type, so the\n * accessor is fully typed at the call site; the base instantiation\n * exposes the system accessors (`id`, `kind`) for standalone option\n * values.\n */\n where?: (accessor: NodeAccessor<N>) => Predicate;\n /** Rows to skip after ranking (rank-relative pagination). */\n offset?: number;\n /**\n * Expand the searched kind to include its `subClassOf` descendants.\n * Vector legs search each declaring kind's storage and merge by score;\n * kinds that don't declare the embedding field are skipped (mirroring\n * the query builder). Requires a query-capable store.\n */\n includeSubClasses?: boolean;\n}>;\n\nexport type FulltextSearchOptions<N extends NodeType = NodeType> =\n SearchScopeOptions<N> &\n Readonly<{\n /** The user-supplied query string. */\n query: string;\n /** Max results. Required. */\n limit: number;\n /** Query parser mode. Default: \"websearch\". */\n mode?: FulltextQueryMode;\n /**\n * Language override for query parsing. Default: the kind's\n * declared language (the same config rows were indexed with),\n * which keeps the parsed tsquery a plan-time constant on\n * PostgreSQL so the GIN index can serve the match.\n */\n language?: string;\n /** Minimum relevance score to include in results. */\n minScore?: number;\n /** Return a highlighted snippet alongside each hit. */\n includeSnippets?: boolean;\n }>;\n\nexport type HybridVectorOptions = Readonly<{\n /** Field path of the embedding column on the node kind. */\n fieldPath: string;\n /** Query embedding to compare against. */\n queryEmbedding: readonly number[];\n /** Distance metric. Default: \"cosine\". */\n metric?: VectorMetric;\n /** How many candidates to retrieve from the vector side. Default: 4 * limit. */\n k?: number;\n /** Minimum similarity to include (units depend on metric). */\n minScore?: number;\n /**\n * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n * The vector side over-fetches `k` (default `4 * limit`) candidates;\n * `efSearch` must be `>= k` for the index to surface that many\n * neighbors, and ~2–4× `k` is the high-recall target. Postgres HNSW\n * only — no-op elsewhere. See `VectorSearchOptions.efSearch`.\n */\n efSearch?: number;\n}>;\n\n/**\n * Options for the standalone `store.search.vector` path. Mirrors the\n * vector half of `HybridSearchOptions` but flattens it because the\n * standalone path doesn't fuse against fulltext.\n */\nexport type VectorSearchOptions<N extends NodeType = NodeType> =\n SearchScopeOptions<N> &\n Readonly<{\n /** Field path of the embedding column on the node kind. */\n fieldPath: string;\n /** Query embedding to compare against. */\n queryEmbedding: readonly number[];\n /** Max results. Required. */\n limit: number;\n /** Distance metric. Default: \"cosine\". */\n metric?: VectorMetric;\n /** Minimum similarity to include (units depend on metric). */\n minScore?: number;\n /**\n * HNSW search frontier for this query (pgvector `hnsw.ef_search`).\n * Sizes the dynamic candidate list the index scan maintains — higher\n * trades latency for recall. The floor for the index to surface\n * `limit` neighbors is `efSearch >= limit`; ~2–4× is the high-recall\n * target on million-scale corpora. Lets a latency-sensitive\n * interactive path and a recall-sensitive batch path share one\n * connection pool, tuning per query rather than per session.\n *\n * Postgres HNSW only: applied transaction-locally via `SET LOCAL`.\n * sqlite-vec has no equivalent frontier knob and ignores it; Postgres\n * backends without transactions (`drizzle-orm/neon-http`) ignore it\n * with a one-time warning. Must be a positive integer; pgvector caps\n * it at 1000.\n */\n efSearch?: number;\n }>;\n\nexport type HybridFulltextOptions = Readonly<{\n query: string;\n /** How many candidates to retrieve from the fulltext side. Default: 4 * limit. */\n k?: number;\n mode?: FulltextQueryMode;\n language?: string;\n minScore?: number;\n includeSnippets?: boolean;\n}>;\n\nexport type HybridSearchOptions<N extends NodeType = NodeType> =\n SearchScopeOptions<N> &\n Readonly<{\n vector: HybridVectorOptions;\n fulltext: HybridFulltextOptions;\n fusion?: HybridFusionOptions;\n /** Final number of fused results to return. Required. */\n limit: number;\n }>;\n\ntype StoreSearchContext = Readonly<{\n graphId: string;\n backend: GraphBackend;\n registry: KindRegistry;\n /**\n * Builds a fresh query for candidate compilation (`store.query()`, the\n * same seam collection `find({ where })` uses). Optional so a bare\n * context still supports unscoped searches; `where` /\n * `includeSubClasses` throw without it.\n */\n createQuery?: () => QueryBuilder<GraphDef>;\n}>;\n\n/**\n * Internal alias for the candidate query. The compiled query prefixes its\n * output columns with the alias, so the id column is `\"_sc_id\"`.\n */\nconst SEARCH_CANDIDATE_ALIAS = \"_sc\";\n\n/**\n * Compiles the candidate subquery for one kind: the ids of nodes a search\n * statement may rank. Runs the store's own query compiler, so the\n * predicate, valid-time currency, tombstone exclusion, and graph scoping\n * are exactly the semantics of a `current` read — search can never return\n * (or lose top-k slots to) rows a `find()` would not see.\n *\n * Compiled ONLY when a `where` predicate exists: the unfiltered case\n * returns `undefined` so the backend supplies its flat, parameter-bound\n * current-read candidates (same semantics, far cheaper — the compiled\n * query's per-row SQL now() currency checks measurably dominated\n * unfiltered facade searches on SQLite and planned poorly on Postgres).\n */\nfunction buildKindCandidates(\n ctx: StoreSearchContext,\n nodeKind: string,\n where: ((accessor: NodeAccessor<NodeType>) => Predicate) | undefined,\n): SqlFragment | undefined {\n if (where === undefined) return undefined;\n if (ctx.createQuery === undefined) {\n throw new ConfigurationError(\n \"search with a where predicate requires a query-capable store\",\n { capability: \"search\", graphId: ctx.graphId },\n );\n }\n const chain = ctx\n .createQuery()\n .from(nodeKind, SEARCH_CANDIDATE_ALIAS)\n .whereNode(SEARCH_CANDIDATE_ALIAS, where);\n const compiled = chain\n .select(\n (aliases: Record<string, unknown>) => aliases[SEARCH_CANDIDATE_ALIAS],\n )\n .compile();\n return sql`SELECT ${sql.raw(`\"${SEARCH_CANDIDATE_ALIAS}_id\"`)} AS node_id FROM (${compiled}) AS tg_search_candidates`;\n}\n\n/**\n * The kinds one search call spans: the kind itself, plus its `subClassOf`\n * descendants when requested.\n */\nfunction resolveSearchKinds(\n ctx: StoreSearchContext,\n nodeKind: string,\n includeSubClasses: boolean | undefined,\n): readonly string[] {\n if (includeSubClasses !== true) return [nodeKind];\n if (ctx.createQuery === undefined) {\n throw new ConfigurationError(\n \"search with includeSubClasses requires a query-capable store\",\n { capability: \"search\", graphId: ctx.graphId },\n );\n }\n return ctx.registry.expandSubClasses(nodeKind);\n}\n\nfunction assertSearchOffset(offset: number | undefined, label: string): void {\n if (offset === undefined) return;\n if (!Number.isInteger(offset) || offset < 0) {\n throw new RangeError(\n `${label} must be a non-negative integer, got: ${offset}`,\n );\n }\n}\n\n/**\n * The language a fulltext query should be parsed with for one kind: the\n * caller's explicit override, else the kind's DECLARED language (the one\n * its rows were written with). Passing the declared language keeps the\n * tsquery CONSTANT, so PostgreSQL's GIN index on `tsv` can serve the\n * match — the per-row `websearch_to_tsquery(\"language\", ...)` fallback\n * (used only when the kind declares no searchable fields) forces a scan.\n */\nfunction effectiveFulltextLanguage(\n ctx: StoreSearchContext,\n nodeKind: string,\n override: string | undefined,\n): string | undefined {\n if (override !== undefined) return override;\n const nodeType = ctx.registry.getNodeType(nodeKind);\n if (nodeType === undefined) return undefined;\n return resolveDeclaredFulltextLanguage(nodeType.schema);\n}\n\n/** A ranked row tagged with the kind whose search leg produced it. */\ntype RankedSourceRow = Readonly<{\n kind: string;\n nodeId: string;\n score: number;\n snippet?: string;\n}>;\n\n/** Node ids are unique per kind, not globally — key hydration by both. */\nfunction searchNodeKey(kind: string, nodeId: string): string {\n return `${kind}\\u0000${nodeId}`;\n}\n\n/**\n * Whether higher scores rank first for a metric. Cosine scores are\n * similarities (`1 - distance`); l2 / inner_product scores are the raw\n * distance expression, where lower is better (matching each strategy's\n * `ORDER BY distance ASC`).\n */\nfunction scoreDescending(metric: VectorMetric): boolean {\n return metric === \"cosine\";\n}\n\n/**\n * Hydrates ranked rows spanning multiple kinds. One batched fetch per\n * kind, results keyed by {@link searchNodeKey}.\n */\nasync function fetchNodesForRows(\n backend: GraphBackend,\n graphId: string,\n rows: readonly RankedSourceRow[],\n): Promise<Map<string, Node>> {\n const idsByKind = new Map<string, Set<string>>();\n for (const row of rows) {\n const ids = idsByKind.get(row.kind) ?? new Set<string>();\n ids.add(row.nodeId);\n idsByKind.set(row.kind, ids);\n }\n const map = new Map<string, Node>();\n await Promise.all(\n [...idsByKind].map(async ([kind, ids]) => {\n const kindMap = await fetchNodesByIds(backend, graphId, kind, [...ids]);\n for (const [id, node] of kindMap) {\n map.set(searchNodeKey(kind, id), node);\n }\n }),\n );\n return map;\n}\n\n/**\n * Resolved storage identity of one embedding field on a concrete node\n * kind — the `(dimensions, metric, indexType)` the backend needs (in\n * addition to the runtime `metric` override) to address the field's\n * typed per-`(kind, field)` storage slot during search.\n */\ntype ResolvedSearchSlot = Readonly<{\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n}>;\n\n/**\n * Resolves the `(dimensions, metric, indexType)` for a node kind's\n * embedding field from the registered node schema's `embedding()`\n * declaration. Throws a `ConfigurationError` when the kind has no such\n * embedding field so the caller gets a clear boundary error instead of a\n * downstream missing-table failure.\n */\nfunction tryResolveSearchSlot(\n ctx: StoreSearchContext,\n nodeKind: string,\n fieldPath: string,\n): ResolvedSearchSlot | undefined {\n const nodeType = ctx.registry.getNodeType(nodeKind);\n if (nodeType === undefined) return undefined;\n const fields = getEmbeddingFields(nodeType.schema);\n const field = fields.find((entry) => entry.fieldPath === fieldPath);\n if (field === undefined) return undefined;\n return {\n dimensions: field.dimensions,\n metric: field.metric,\n indexType: field.indexType,\n };\n}\n\nfunction resolveSearchSlot(\n ctx: StoreSearchContext,\n nodeKind: string,\n fieldPath: string,\n): ResolvedSearchSlot {\n const slot = tryResolveSearchSlot(ctx, nodeKind, fieldPath);\n if (slot !== undefined) return slot;\n throw new ConfigurationError(\n `Node kind \"${nodeKind}\" has no embedding field \"${fieldPath}\". ` +\n `Declare it with embedding(dimensions) on the node schema.`,\n { capability: \"vector\", graphId: ctx.graphId },\n );\n}\n\nexport async function executeFulltextSearch<N = Node>(\n ctx: StoreSearchContext,\n nodeKind: string,\n options: FulltextSearchOptions,\n): Promise<readonly FulltextSearchHit<N>[]> {\n const { backend, graphId } = ctx;\n if (!backend.fulltextSearch) {\n throw new ConfigurationError(\"Backend does not support fulltext search\", {\n backend: backend.dialect,\n capability: \"fulltext\",\n });\n }\n if (!Number.isInteger(options.limit) || options.limit <= 0) {\n throw new RangeError(\n `fulltextSearch.limit must be a positive integer, got: ${options.limit}`,\n );\n }\n assertSearchOffset(options.offset, \"fulltextSearch.offset\");\n validateFulltextCallOptions(backend, {\n mode: options.mode,\n includeSnippets: options.includeSnippets,\n language: options.language,\n });\n\n const kinds = resolveSearchKinds(ctx, nodeKind, options.includeSubClasses);\n const offset = options.offset ?? 0;\n const singleKind = kinds.length === 1;\n\n const perKindRows = await Promise.all(\n kinds.map(async (kind): Promise<readonly RankedSourceRow[]> => {\n const candidates = buildKindCandidates(ctx, kind, options.where);\n const language = effectiveFulltextLanguage(ctx, kind, options.language);\n const rows = await requireDefined(backend.fulltextSearch)({\n graphId,\n nodeKind: kind,\n query: options.query,\n // A single kind pushes the page into SQL; multiple kinds fetch\n // each kind's full page-covering prefix and re-slice after merge.\n limit: singleKind ? options.limit : options.limit + offset,\n ...(singleKind && offset > 0 ? { offset } : {}),\n ...(candidates === undefined ? {} : { candidates }),\n ...(options.mode ? { mode: options.mode } : {}),\n ...(language === undefined ? {} : { language }),\n ...(options.minScore === undefined ?\n {}\n : { minScore: options.minScore }),\n ...(options.includeSnippets === undefined ?\n {}\n : { includeSnippets: options.includeSnippets }),\n });\n return rows.map((row) => ({\n kind,\n nodeId: row.nodeId,\n score: row.score,\n ...(row.snippet === undefined ? {} : { snippet: row.snippet }),\n }));\n }),\n );\n\n const merged =\n singleKind ?\n requireDefined(perKindRows[0])\n : perKindRows\n .flat()\n .toSorted(\n (a, b) =>\n b.score - a.score ||\n compareCodePoints(a.kind, b.kind) ||\n compareCodePoints(a.nodeId, b.nodeId),\n )\n .slice(offset, offset + options.limit);\n if (merged.length === 0) return [];\n\n const nodeMap = await fetchNodesForRows(backend, graphId, merged);\n\n const hits: FulltextSearchHit<N>[] = [];\n let rank = 1;\n for (const row of merged) {\n const node = nodeMap.get(searchNodeKey(row.kind, row.nodeId));\n if (!node) continue;\n hits.push({\n node: node as N,\n score: row.score,\n rank,\n ...(row.snippet === undefined ? {} : { snippet: row.snippet }),\n });\n rank += 1;\n }\n return hits;\n}\n\nexport async function executeVectorSearch<N = Node>(\n ctx: StoreSearchContext,\n nodeKind: string,\n options: VectorSearchOptions,\n): Promise<readonly VectorSearchHit<N>[]> {\n const { backend, graphId } = ctx;\n if (!backend.vectorSearch) {\n throw new ConfigurationError(\"Backend does not support vector search\", {\n backend: backend.dialect,\n capability: \"vector\",\n });\n }\n if (!Number.isInteger(options.limit) || options.limit <= 0) {\n throw new RangeError(\n `vectorSearch.limit must be a positive integer, got: ${options.limit}`,\n );\n }\n assertEfSearch(options.efSearch, \"vectorSearch.efSearch\");\n assertSearchOffset(options.offset, \"vectorSearch.offset\");\n\n const searchKinds = resolveVectorSearchKinds(\n ctx,\n nodeKind,\n options.fieldPath,\n options.includeSubClasses,\n \"vectorSearch\",\n );\n for (const { slot } of searchKinds) {\n assertVectorQueryCompatible(\n backend,\n slot,\n { metric: options.metric, queryEmbedding: options.queryEmbedding },\n \"vectorSearch\",\n );\n assertMinScore(\n options.minScore,\n options.metric ?? slot.metric,\n \"vectorSearch.minScore\",\n );\n }\n const offset = options.offset ?? 0;\n const singleKind = searchKinds.length === 1;\n const metric = options.metric ?? requireDefined(searchKinds[0]).slot.metric;\n\n const perKindRows = await Promise.all(\n searchKinds.map(\n async ({ kind, slot }): Promise<readonly RankedSourceRow[]> => {\n const candidates = buildKindCandidates(ctx, kind, options.where);\n const rows = await requireDefined(backend.vectorSearch)({\n graphId,\n nodeKind: kind,\n fieldPath: options.fieldPath,\n queryEmbedding: options.queryEmbedding,\n // Default to the field's DECLARED metric (the metric its index was\n // built for); only an explicit caller override changes it.\n // Defaulting to cosine here would mis-rank l2 / inner_product\n // fields and bypass their ANN index.\n metric,\n dimensions: slot.dimensions,\n indexType: slot.indexType,\n // A single kind pushes the page into SQL; multiple kinds fetch\n // each kind's full page-covering prefix and re-slice after merge.\n limit: singleKind ? options.limit : options.limit + offset,\n ...(singleKind && offset > 0 ? { offset } : {}),\n ...(candidates === undefined ? {} : { candidates }),\n ...(options.minScore === undefined ?\n {}\n : { minScore: options.minScore }),\n ...(options.efSearch === undefined ?\n {}\n : { efSearch: options.efSearch }),\n });\n return rows.map((row) => ({\n kind,\n nodeId: row.nodeId,\n score: row.score,\n }));\n },\n ),\n );\n\n const merged =\n singleKind ?\n requireDefined(perKindRows[0])\n : mergeVectorRows(perKindRows, metric).slice(\n offset,\n offset + options.limit,\n );\n if (merged.length === 0) return [];\n\n const nodeMap = await fetchNodesForRows(backend, graphId, merged);\n\n const hits: VectorSearchHit<N>[] = [];\n let rank = 1;\n for (const row of merged) {\n const node = nodeMap.get(searchNodeKey(row.kind, row.nodeId));\n if (!node) continue;\n hits.push({ node: node as N, score: row.score, rank });\n rank += 1;\n }\n return hits;\n}\n\n/** One vector-search target: a kind and its resolved embedding slot. */\ntype VectorSearchKind = Readonly<{ kind: string; slot: ResolvedSearchSlot }>;\n\n/**\n * Resolves the kinds a vector search spans, keeping only kinds that\n * declare the embedding field (mirroring the query builder, which skips\n * non-declaring kinds instead of referencing a table that was never\n * created). Enforces one shared declared metric across the expansion:\n * scores from different metrics cannot be merged into one ranking, and a\n * per-call metric override cannot bridge the gap either (each kind's\n * storage is built for — and validated against — its declared metric), so\n * mixed declared metrics are unsupported for cross-kind ranking.\n */\nfunction resolveVectorSearchKinds(\n ctx: StoreSearchContext,\n nodeKind: string,\n fieldPath: string,\n includeSubClasses: boolean | undefined,\n label: string,\n): readonly VectorSearchKind[] {\n const kinds = resolveSearchKinds(ctx, nodeKind, includeSubClasses);\n const resolved: VectorSearchKind[] = [];\n for (const kind of kinds) {\n const slot = tryResolveSearchSlot(ctx, kind, fieldPath);\n if (slot !== undefined) resolved.push({ kind, slot });\n }\n // No declaring kind: surface the standard configuration error for the\n // requested kind.\n if (resolved.length === 0) resolveSearchSlot(ctx, nodeKind, fieldPath);\n const metrics = new Set(resolved.map(({ slot }) => slot.metric));\n if (metrics.size > 1) {\n throw new ConfigurationError(\n `${label}: kinds expanded from \"${nodeKind}\" declare different ` +\n `metrics for \"${fieldPath}\" (${[...metrics].join(\", \")}). ` +\n `Cross-kind vector ranking requires one shared declared metric — ` +\n `search the kinds separately.`,\n { capability: \"vector\", graphId: ctx.graphId },\n );\n }\n return resolved;\n}\n\n/**\n * Merges per-kind ranked rows into one globally ordered list.\n *\n * Applied even to a single kind's rows, whose SQL already ordered them. The\n * vector source SQL breaks a score tie arbitrarily (no `node_id` tiebreak — a\n * second sort key would cost pgvector its ordered index scan), so trusting its\n * arrival order would make the rank a source of nondeterminism. The\n * single-statement hybrid path re-ranks the very same rows with\n * `ROW_NUMBER() OVER (ORDER BY score …, node_id)`; this is that window, in JS.\n * Ranks feed the fusion, so the two paths must assign them identically.\n */\nfunction mergeVectorRows(\n perKindRows: readonly (readonly RankedSourceRow[])[],\n metric: VectorMetric,\n): readonly RankedSourceRow[] {\n const descending = scoreDescending(metric);\n return perKindRows\n .flat()\n .toSorted(\n (a, b) =>\n (descending ? b.score - a.score : a.score - b.score) ||\n compareCodePoints(a.kind, b.kind) ||\n compareCodePoints(a.nodeId, b.nodeId),\n );\n}\n\n/** {@link mergeVectorRows} for the fulltext leg, whose score always descends. */\nfunction mergeFulltextRows(\n perKindRows: readonly (readonly RankedSourceRow[])[],\n): readonly RankedSourceRow[] {\n return perKindRows\n .flat()\n .toSorted(\n (a, b) =>\n b.score - a.score ||\n compareCodePoints(a.kind, b.kind) ||\n compareCodePoints(a.nodeId, b.nodeId),\n );\n}\n\nexport async function executeHybridSearch<N = Node>(\n ctx: StoreSearchContext,\n nodeKind: string,\n options: HybridSearchOptions,\n): Promise<readonly HybridSearchHit<N>[]> {\n const { backend, graphId } = ctx;\n if (!backend.vectorSearch) {\n throw new ConfigurationError(\"Backend does not support vector search\", {\n backend: backend.dialect,\n capability: \"vector\",\n });\n }\n if (!backend.fulltextSearch) {\n throw new ConfigurationError(\"Backend does not support fulltext search\", {\n backend: backend.dialect,\n capability: \"fulltext\",\n });\n }\n if (!Number.isInteger(options.limit) || options.limit <= 0) {\n throw new RangeError(\n `hybridSearch.limit must be a positive integer, got: ${options.limit}`,\n );\n }\n\n if (options.fusion !== undefined) {\n validateHybridFusionOptions(options.fusion);\n }\n assertEfSearch(options.vector.efSearch, \"hybridSearch.vector.efSearch\");\n\n validateFulltextCallOptions(backend, {\n mode: options.fulltext.mode,\n includeSnippets: options.fulltext.includeSnippets,\n language: options.fulltext.language,\n });\n\n assertSearchOffset(options.offset, \"hybridSearch.offset\");\n\n const fusionK = options.fusion?.k ?? DEFAULT_RRF_K;\n const vectorWeight = options.fusion?.weights?.vector ?? DEFAULT_RRF_WEIGHT;\n const fulltextWeight =\n options.fusion?.weights?.fulltext ?? DEFAULT_RRF_WEIGHT;\n const offset = options.offset ?? 0;\n // Over-fetch covers the requested page: fused top-(limit+offset) needs\n // deep-enough per-source prefixes.\n const overFetchMultiplier = 4;\n const pageLimit = options.limit + offset;\n const vectorK = options.vector.k ?? pageLimit * overFetchMultiplier;\n const fulltextK = options.fulltext.k ?? pageLimit * overFetchMultiplier;\n\n // The fulltext half spans every expanded kind; the vector half only the\n // kinds that declare the embedding field (mirroring the query builder's\n // treatment of non-declaring kinds).\n const fulltextKinds = resolveSearchKinds(\n ctx,\n nodeKind,\n options.includeSubClasses,\n );\n const vectorKinds = resolveVectorSearchKinds(\n ctx,\n nodeKind,\n options.vector.fieldPath,\n options.includeSubClasses,\n \"hybridSearch.vector\",\n );\n for (const { slot } of vectorKinds) {\n assertVectorQueryCompatible(\n backend,\n slot,\n {\n metric: options.vector.metric,\n queryEmbedding: options.vector.queryEmbedding,\n },\n \"hybridSearch.vector\",\n );\n assertMinScore(\n options.vector.minScore,\n options.vector.metric ?? slot.metric,\n \"hybridSearch.vector.minScore\",\n );\n }\n const vectorMetric =\n options.vector.metric ?? requireDefined(vectorKinds[0]).slot.metric;\n\n // One candidate subquery per kind, shared by both halves.\n const candidatesByKind = new Map<string, SqlFragment | undefined>();\n for (const kind of fulltextKinds) {\n candidatesByKind.set(kind, buildKindCandidates(ctx, kind, options.where));\n }\n for (const { kind } of vectorKinds) {\n if (!candidatesByKind.has(kind)) {\n candidatesByKind.set(kind, buildKindCandidates(ctx, kind, options.where));\n }\n }\n\n // Single-statement fast path: one kind, backend support. Both sources,\n // fusion, liveness, and hydration compose into ONE statement (see\n // `buildHybridSearchStatement`) — the multi-statement path below remains\n // for kind expansions and backends without the member.\n if (\n backend.hybridSearch !== undefined &&\n fulltextKinds.length === 1 &&\n vectorKinds.length === 1 &&\n fulltextKinds[0] === requireDefined(vectorKinds[0]).kind\n ) {\n const kind = fulltextKinds[0];\n const { slot } = requireDefined(vectorKinds[0]);\n const candidates = candidatesByKind.get(kind);\n const hybridFulltextLanguage = effectiveFulltextLanguage(\n ctx,\n kind,\n options.fulltext.language,\n );\n const rows = await backend.hybridSearch({\n graphId,\n nodeKind: kind,\n vector: {\n fieldPath: options.vector.fieldPath,\n queryEmbedding: options.vector.queryEmbedding,\n metric: vectorMetric,\n dimensions: slot.dimensions,\n indexType: slot.indexType,\n k: vectorK,\n ...(options.vector.minScore === undefined ?\n {}\n : { minScore: options.vector.minScore }),\n ...(options.vector.efSearch === undefined ?\n {}\n : { efSearch: options.vector.efSearch }),\n },\n fulltext: {\n query: options.fulltext.query,\n k: fulltextK,\n ...(options.fulltext.mode ? { mode: options.fulltext.mode } : {}),\n ...(hybridFulltextLanguage === undefined ?\n {}\n : { language: hybridFulltextLanguage }),\n ...(options.fulltext.minScore === undefined ?\n {}\n : { minScore: options.fulltext.minScore }),\n ...(options.fulltext.includeSnippets === undefined ?\n {}\n : { includeSnippets: options.fulltext.includeSnippets }),\n },\n fusion: { k: fusionK, vectorWeight, fulltextWeight },\n limit: options.limit,\n ...(offset === 0 ? {} : { offset }),\n ...(candidates === undefined ? {} : { candidates }),\n });\n return rows.map((row, index) => {\n const typedNode = rowToNode(row.node) as N;\n return {\n node: typedNode,\n score: row.fusedScore,\n rank: index + 1,\n ...(row.vectorRank !== undefined && row.vectorScore !== undefined ?\n {\n vector: {\n node: typedNode,\n score: row.vectorScore,\n rank: row.vectorRank,\n },\n }\n : {}),\n ...(row.fulltextRank !== undefined && row.fulltextScore !== undefined ?\n {\n fulltext: {\n node: typedNode,\n score: row.fulltextScore,\n rank: row.fulltextRank,\n ...(row.snippet === undefined ? {} : { snippet: row.snippet }),\n },\n }\n : {}),\n };\n });\n }\n\n const vectorPromise = Promise.all(\n vectorKinds.map(\n async ({ kind, slot }): Promise<readonly RankedSourceRow[]> => {\n const candidates = candidatesByKind.get(kind);\n const rows = await requireDefined(backend.vectorSearch)({\n graphId,\n nodeKind: kind,\n fieldPath: options.vector.fieldPath,\n queryEmbedding: options.vector.queryEmbedding,\n // Default to the field's declared metric (see executeVectorSearch).\n metric: vectorMetric,\n dimensions: slot.dimensions,\n indexType: slot.indexType,\n limit: vectorK,\n ...(candidates === undefined ? {} : { candidates }),\n ...(options.vector.minScore === undefined ?\n {}\n : { minScore: options.vector.minScore }),\n ...(options.vector.efSearch === undefined ?\n {}\n : { efSearch: options.vector.efSearch }),\n });\n return rows.map((row) => ({\n kind,\n nodeId: row.nodeId,\n score: row.score,\n }));\n },\n ),\n ).then((perKind) => mergeVectorRows(perKind, vectorMetric).slice(0, vectorK));\n\n const fulltextPromise = Promise.all(\n fulltextKinds.map(async (kind): Promise<readonly RankedSourceRow[]> => {\n const candidates = candidatesByKind.get(kind);\n const language = effectiveFulltextLanguage(\n ctx,\n kind,\n options.fulltext.language,\n );\n const rows = await requireDefined(backend.fulltextSearch)({\n graphId,\n nodeKind: kind,\n query: options.fulltext.query,\n limit: fulltextK,\n ...(candidates === undefined ? {} : { candidates }),\n ...(options.fulltext.mode ? { mode: options.fulltext.mode } : {}),\n ...(language === undefined ? {} : { language }),\n ...(options.fulltext.minScore === undefined ?\n {}\n : { minScore: options.fulltext.minScore }),\n ...(options.fulltext.includeSnippets === undefined ?\n {}\n : { includeSnippets: options.fulltext.includeSnippets }),\n });\n return rows.map((row) => ({\n kind,\n nodeId: row.nodeId,\n score: row.score,\n ...(row.snippet === undefined ? {} : { snippet: row.snippet }),\n }));\n }),\n ).then((perKind) => mergeFulltextRows(perKind).slice(0, fulltextK));\n\n const [vectorRows, fulltextRows] = await Promise.all([\n vectorPromise,\n fulltextPromise,\n ]);\n\n // RRF fusion. The classic formula is score = Σ_src 1 / (k + rank_src).\n // Per-source weights extend it to a weighted sum.\n interface FusedEntry {\n kind: string;\n nodeId: string;\n fusedScore: number;\n vectorRank?: number;\n vectorScore?: number;\n fulltextRank?: number;\n fulltextScore?: number;\n fulltextSnippet?: string;\n }\n const fused = new Map<string, FusedEntry>();\n\n for (const [index, row] of vectorRows.entries()) {\n const rank = index + 1;\n const contribution = vectorWeight / (fusionK + rank);\n const key = searchNodeKey(row.kind, row.nodeId);\n const entry = fused.get(key) ?? {\n kind: row.kind,\n nodeId: row.nodeId,\n fusedScore: 0,\n };\n entry.fusedScore += contribution;\n entry.vectorRank = rank;\n entry.vectorScore = row.score;\n fused.set(key, entry);\n }\n\n for (const [index, row] of fulltextRows.entries()) {\n const rank = index + 1;\n const contribution = fulltextWeight / (fusionK + rank);\n const key = searchNodeKey(row.kind, row.nodeId);\n const entry = fused.get(key) ?? {\n kind: row.kind,\n nodeId: row.nodeId,\n fusedScore: 0,\n };\n entry.fusedScore += contribution;\n entry.fulltextRank = rank;\n entry.fulltextScore = row.score;\n if (row.snippet !== undefined) {\n entry.fulltextSnippet = row.snippet;\n }\n fused.set(key, entry);\n }\n\n // Code points, not code units: the single-statement path breaks the same tie\n // with `ORDER BY fused_score DESC, node_id` under SQLite's BINARY collation\n // or Postgres's forced `C` collation (see `buildHybridSearchStatement`). A\n // fused-score tie at the page boundary must pick the same winner on both\n // paths, and only code-point order agrees with byte order.\n const ranked = [...fused.values()]\n .toSorted(\n (a, b) =>\n b.fusedScore - a.fusedScore ||\n compareCodePoints(a.kind, b.kind) ||\n compareCodePoints(a.nodeId, b.nodeId),\n )\n .slice(offset, offset + options.limit);\n\n const nodeMap = await fetchNodesForRows(\n backend,\n graphId,\n ranked.map((entry) => ({\n kind: entry.kind,\n nodeId: entry.nodeId,\n score: entry.fusedScore,\n })),\n );\n\n const hits: HybridSearchHit<N>[] = [];\n let rank = 1;\n for (const entry of ranked) {\n const node = nodeMap.get(searchNodeKey(entry.kind, entry.nodeId));\n if (!node) continue;\n const typedNode = node as N;\n const hit: HybridSearchHit<N> = {\n node: typedNode,\n score: entry.fusedScore,\n rank,\n ...(entry.vectorRank !== undefined && entry.vectorScore !== undefined ?\n {\n vector: {\n node: typedNode,\n score: entry.vectorScore,\n rank: entry.vectorRank,\n },\n }\n : {}),\n ...((\n entry.fulltextRank !== undefined && entry.fulltextScore !== undefined\n ) ?\n {\n fulltext: {\n node: typedNode,\n score: entry.fulltextScore,\n rank: entry.fulltextRank,\n ...(entry.fulltextSnippet === undefined ?\n {}\n : { snippet: entry.fulltextSnippet }),\n },\n }\n : {}),\n };\n hits.push(hit);\n rank += 1;\n }\n return hits;\n}\n\n/**\n * Validates the optional `efSearch` knob at the API boundary. Rejects\n * non-positive-integer values uniformly across backends — the\n * backend-specific ceiling (pgvector caps `hnsw.ef_search` at 1000) is\n * enforced on the Postgres path, and backends without an HNSW frontier\n * knob treat a valid value as a no-op.\n */\nfunction assertEfSearch(efSearch: number | undefined, label: string): void {\n if (efSearch === undefined) return;\n if (!Number.isInteger(efSearch) || efSearch <= 0) {\n throw new RangeError(\n `${label} must be a positive integer, got: ${efSearch}`,\n );\n }\n}\n\n/**\n * Validates the optional `minScore` filter at the API boundary, mirroring the\n * query-compiler vector pass. Rejects non-finite values for any metric and,\n * for cosine (where the score is `1 - distance` similarity), values outside\n * [-1, 1]. Without this a `NaN` minScore compiles to `distance <= (1 - NaN)`,\n * which matches nothing — a silent empty result instead of a clear error.\n */\nfunction assertMinScore(\n minScore: number | undefined,\n metric: VectorMetric,\n label: string,\n): void {\n if (minScore === undefined) return;\n assertVectorMinScore(minScore, metric, label);\n}\n\n/**\n * Validates a vector search/hybrid call against the field's resolved slot:\n * an explicit `metric` override must match the field's declared metric (its\n * storage / ANN index is built for that metric), the declared metric must be\n * one the backend supports, and the query vector's length must match the\n * field's dimension. Rejects at the API boundary instead of surfacing an\n * opaque engine error from deep in `buildSearch`.\n */\nfunction assertVectorQueryCompatible(\n backend: GraphBackend,\n slot: ResolvedSearchSlot,\n options: {\n metric: VectorMetric | undefined;\n queryEmbedding: readonly number[];\n },\n label: string,\n): void {\n if (options.metric !== undefined && options.metric !== slot.metric) {\n throw new ConfigurationError(\n `${label}: metric \"${options.metric}\" does not match the field's declared metric \"${slot.metric}\". Vector storage is built for the declared metric — omit metric or pass \"${slot.metric}\".`,\n { backend: backend.dialect, capability: \"vector\" },\n );\n }\n const supported = backend.capabilities.vector?.metrics;\n if (supported !== undefined && !supported.includes(slot.metric)) {\n throw new ConfigurationError(\n `${label}: backend \"${backend.dialect}\" does not support the \"${slot.metric}\" metric (supported: ${supported.join(\", \")}).`,\n { backend: backend.dialect, capability: \"vector\" },\n );\n }\n if (options.queryEmbedding.length !== slot.dimensions) {\n throw new RangeError(\n `${label}: queryEmbedding has ${options.queryEmbedding.length} dimensions, but \"${slot.dimensions}\" are declared for this field.`,\n );\n }\n}\n\ntype FulltextCallOptions = Readonly<{\n mode: FulltextQueryMode | undefined;\n includeSnippets: boolean | undefined;\n language: string | undefined;\n}>;\n\n/**\n * Validates caller-supplied fulltext options against the active\n * `FulltextStrategy` (when present) or the declared `FulltextCapabilities`\n * projection (as a fallback). Strategy validation is authoritative:\n * `supportedModes` and `supportsLanguageOverride` reject options that the\n * capabilities projection would silently ignore (e.g. a `language`\n * override on the SQLite FTS5 strategy, whose tokenizer is fixed at\n * table-create time). Mode, snippets, and language are the fields\n * callers commonly get wrong; catching them here turns a downstream SQL\n * error — or worse, silent misbehavior — into a clear\n * `ConfigurationError` at the API boundary.\n */\nfunction validateFulltextCallOptions(\n backend: GraphBackend,\n options: FulltextCallOptions,\n): void {\n const strategy = backend.fulltextStrategy;\n const capabilities = backend.capabilities.fulltext;\n\n if (options.mode !== undefined) {\n validateFulltextMode(backend, strategy, capabilities, options.mode);\n }\n if (options.includeSnippets === true) {\n validateFulltextSnippets(backend, strategy, capabilities);\n }\n if (options.language !== undefined) {\n validateFulltextLanguageOption(\n backend,\n strategy,\n capabilities,\n options.language,\n );\n }\n}\n\nfunction validateFulltextMode(\n backend: GraphBackend,\n strategy: FulltextStrategy | undefined,\n capabilities: FulltextCapabilities | undefined,\n mode: FulltextQueryMode,\n): void {\n if (strategy !== undefined) {\n if (strategy.supportedModes.includes(mode)) return;\n throw new ConfigurationError(\n `Backend \"${backend.dialect}\" fulltext strategy \"${strategy.name}\" ` +\n `does not support mode \"${mode}\". Supported modes: ${strategy.supportedModes.join(\", \")}`,\n {\n backend: backend.dialect,\n strategy: strategy.name,\n capability: `fulltext.modes.${mode}`,\n },\n );\n }\n if (mode === \"phrase\" && capabilities && !capabilities.phraseQueries) {\n throw new ConfigurationError(\n `Backend \"${backend.dialect}\" does not support phrase queries`,\n { backend: backend.dialect, capability: \"fulltext.phraseQueries\" },\n );\n }\n}\n\nfunction validateFulltextSnippets(\n backend: GraphBackend,\n strategy: FulltextStrategy | undefined,\n capabilities: FulltextCapabilities | undefined,\n): void {\n const supportsSnippets =\n strategy === undefined ?\n capabilities?.highlighting !== false\n : strategy.supportsSnippets;\n if (supportsSnippets) return;\n throw new ConfigurationError(\n `Backend \"${backend.dialect}\" does not support snippet highlighting; ` +\n `drop includeSnippets or switch to a backend where highlighting is supported`,\n { backend: backend.dialect, capability: \"fulltext.highlighting\" },\n );\n}\n\nfunction validateFulltextLanguageOption(\n backend: GraphBackend,\n strategy: FulltextStrategy | undefined,\n capabilities: FulltextCapabilities | undefined,\n language: string,\n): void {\n if (strategy !== undefined && !strategy.supportsLanguageOverride) {\n throw new ConfigurationError(\n `Backend \"${backend.dialect}\" fulltext strategy \"${strategy.name}\" ` +\n `does not honor a per-query \\`language\\` override ` +\n `(its tokenizer is fixed at table-create time). ` +\n `Drop the option, or pick a strategy that advertises \\`supportsLanguageOverride: true\\`.`,\n {\n backend: backend.dialect,\n strategy: strategy.name,\n capability: \"fulltext.languageOverride\",\n },\n );\n }\n if (capabilities !== undefined) {\n warnIfLanguageNotAdvertised(backend.dialect, capabilities, language);\n }\n}\n\n/**\n * Advisory language check — warn, don't throw. Postgres accepts any\n * installed regconfig at runtime, so a strict list would produce false\n * positives for extension-provided dictionaries.\n */\nfunction warnIfLanguageNotAdvertised(\n dialect: string,\n capabilities: FulltextCapabilities,\n language: string,\n): void {\n if (capabilities.languages.length === 0) return;\n if (capabilities.languages.includes(language)) return;\n if (typeof console === \"undefined\" || typeof console.warn !== \"function\") {\n return;\n }\n console.warn(\n `[typegraph] fulltext language \"${language}\" is not in the advertised list ` +\n `for dialect \"${dialect}\" (${capabilities.languages.join(\", \")}). ` +\n `If your backend has this language installed this warning is safe to ignore.`,\n );\n}\n\nasync function fetchNodesByIds(\n backend: GraphBackend,\n graphId: string,\n nodeKind: string,\n ids: readonly string[],\n): Promise<Map<string, Node>> {\n if (ids.length === 0) return new Map();\n const map = new Map<string, Node>();\n if (backend.getNodes) {\n const rows = await backend.getNodes(graphId, nodeKind, ids);\n for (const row of rows) {\n // `getNodes` returns rows regardless of deleted_at. The search SQL\n // already constrains top-k to live nodes; this skip is\n // defense-in-depth for the window between the search statement and\n // this hydration read (they are separate transactions, so a\n // concurrent delete can land in between).\n if (row.deleted_at !== undefined) continue;\n map.set(row.id, rowToNode(row));\n }\n return map;\n }\n // Fallback: fetch one at a time. Slow, but only triggers on backends\n // that haven't implemented the batched accessor.\n for (const id of ids) {\n const row = await backend.getNode(graphId, nodeKind, id);\n if (row && row.deleted_at === undefined) map.set(row.id, rowToNode(row));\n }\n return map;\n}\n\nexport { type HybridFusionOptions } from \"../query/ast\";\n","/**\n * StoreSearch — store.search facade.\n *\n * Groups fulltext, vector, hybrid, and maintenance operations under one\n * namespace so the top-level Store API stays focused on CRUD + graph\n * traversal. The methods delegate to their respective execution\n * modules; this class exists to shape the surface and to gate kind\n * names through the registry — the kind argument is `string` so\n * graph-extension kinds (added via `store.evolve()`) work without a\n * type cast, with a runtime guard rejecting misspellings at the call\n * site.\n */\nimport { type GraphBackend } from \"../backend/types\";\nimport { type GraphDef, type NodeKinds } from \"../core/define-graph\";\nimport { type NodeRegistration, type NodeType } from \"../core/types\";\nimport { KindNotFoundError } from \"../errors\";\nimport { type QueryBuilder } from \"../query/builder/query-builder\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport {\n rebuildFulltextIndex,\n type RebuildFulltextOptions,\n type RebuildFulltextResult,\n} from \"./fulltext-rebuild\";\nimport {\n executeFulltextSearch,\n executeHybridSearch,\n executeVectorSearch,\n type FulltextSearchHit,\n type FulltextSearchOptions,\n type HybridSearchHit,\n type HybridSearchOptions,\n type VectorSearchHit,\n type VectorSearchOptions,\n} from \"./search\";\nimport { type Node } from \"./types\";\n\n/**\n * Resolves the hit's `node` type. Compile-time kinds keep their\n * narrowed `Node<N>`; kinds outside `G` (added via graph extension through\n * `store.evolve()`, or string variables the type system can't see)\n * widen to the base `Node` so callers don't need a cast.\n *\n * This is the same shape as `getNodeCollection` — the dynamic form\n * works for any registered kind, and the type narrows when (and only\n * when) the literal is statically known.\n */\ntype ResolveNode<G extends GraphDef, K extends string> =\n K extends NodeKinds<G> ?\n G[\"nodes\"][K] extends NodeRegistration<infer N extends NodeType> ?\n Node<N>\n : Node\n : Node;\n\n/**\n * The registered `NodeType` behind a kind literal — the accessor-level\n * companion of {@link ResolveNode}, used to type `where` predicates.\n * Falls back to the base `NodeType` for dynamic (string) kinds.\n */\ntype ResolveNodeType<G extends GraphDef, K extends string> =\n K extends NodeKinds<G> ?\n G[\"nodes\"][K] extends NodeRegistration<infer N extends NodeType> ?\n N\n : NodeType\n : NodeType;\n\ntype StoreSearchContext = Readonly<{\n graphId: string;\n backend: GraphBackend;\n registry: KindRegistry;\n createQuery?: () => QueryBuilder<GraphDef>;\n}>;\n\n/**\n * Search-related operations exposed via `store.search`.\n *\n * @example\n * ```typescript\n * // Fulltext only\n * const hits = await store.search.fulltext(\"Document\", {\n * query: \"climate change\",\n * limit: 10,\n * includeSnippets: true,\n * });\n *\n * // Vector only — for extension kinds with embedding() modifiers,\n * // the auto-derived index serves this query.\n * const nearest = await store.search.vector(\"Document\", {\n * fieldPath: \"embedding\",\n * queryEmbedding: vec,\n * limit: 10,\n * });\n *\n * // Hybrid: vector + fulltext, fused with RRF\n * const ranked = await store.search.hybrid(\"Document\", {\n * limit: 10,\n * vector: { fieldPath: \"embedding\", queryEmbedding: vec },\n * fulltext: { query: \"climate change\" },\n * });\n *\n * // Rebuild after backfill / schema change\n * const stats = await store.search.rebuildFulltext();\n * ```\n *\n * Extension kinds added via `store.evolve(...)` work with all four\n * methods without a type cast — the kind argument is `string` and a\n * registry check rejects misspellings at the call site.\n */\nexport class StoreSearch<G extends GraphDef> {\n readonly #context: StoreSearchContext;\n\n constructor(context: StoreSearchContext) {\n this.#context = context;\n }\n\n /**\n * Runs a fulltext search against nodes of the given kind.\n *\n * Requires fields on the node schema declared with `searchable()`.\n * The search hits the backend's fulltext index (tsvector + GIN on\n * Postgres, FTS5 on SQLite — or whatever strategy the backend is\n * configured with) and resolves the matching node IDs back to typed\n * `Node` objects.\n */\n async fulltext<K extends string>(\n nodeKind: K,\n options: FulltextSearchOptions<ResolveNodeType<G, K>>,\n ): Promise<readonly FulltextSearchHit<ResolveNode<G, K>>[]> {\n this.#assertKindRegistered(nodeKind);\n return executeFulltextSearch<ResolveNode<G, K>>(\n this.#context,\n nodeKind,\n // Contravariance: the narrowed accessor callback is intentionally\n // wider than the base instantiation the core helpers take.\n options as unknown as FulltextSearchOptions,\n );\n }\n\n /**\n * Runs a vector similarity search against nodes of the given kind.\n *\n * Requires a field on the node schema declared with `embedding()`,\n * either at compile time or via a graph extension (the auto-derived\n * `VectorIndexDeclaration` flows through `materializeIndexes()` on\n * the same path either way).\n *\n * Pure vector — no fulltext leg, no fusion. For combined\n * vector+fulltext ranking, use `hybrid`.\n */\n async vector<K extends string>(\n nodeKind: K,\n options: VectorSearchOptions<ResolveNodeType<G, K>>,\n ): Promise<readonly VectorSearchHit<ResolveNode<G, K>>[]> {\n this.#assertKindRegistered(nodeKind);\n return executeVectorSearch<ResolveNode<G, K>>(\n this.#context,\n nodeKind,\n // Contravariance: the narrowed accessor callback is intentionally\n // wider than the base instantiation the core helpers take.\n options as unknown as VectorSearchOptions,\n );\n }\n\n /**\n * Runs a vector + fulltext hybrid search and fuses the results with\n * Reciprocal Rank Fusion.\n *\n * RRF is rank-based, so it composes well across heterogeneous score\n * scales (cosine similarity vs ts_rank_cd vs FTS5 BM25). Default\n * over-fetch is 4× `limit` from each source — tune via `vector.k` /\n * `fulltext.k` for higher-recall corpora.\n */\n async hybrid<K extends string>(\n nodeKind: K,\n options: HybridSearchOptions<ResolveNodeType<G, K>>,\n ): Promise<readonly HybridSearchHit<ResolveNode<G, K>>[]> {\n this.#assertKindRegistered(nodeKind);\n return executeHybridSearch<ResolveNode<G, K>>(\n this.#context,\n nodeKind,\n // Contravariance: the narrowed accessor callback is intentionally\n // wider than the base instantiation the core helpers take.\n options as unknown as HybridSearchOptions,\n );\n }\n\n /**\n * Rebuilds the fulltext index from existing node data.\n *\n * Use when:\n * - A node kind gained a `searchable()` field after data was already\n * written and existing rows were never indexed.\n * - The fulltext table was dropped / truncated.\n * - `language` was changed on a `searchable()` field.\n *\n * Iterates nodes with keyset pagination (stable under shared\n * timestamps and light concurrent writes), transacts per page, skips\n * kinds with no searchable fields, and cleans up stale rows for\n * soft-deleted nodes. Corrupt or non-object `props` are counted in\n * `skipped` with their node IDs surfaced via `skippedIds` so operators\n * can investigate. Concurrent hard-deletes between page fetches can\n * be missed by a single pass — run during a maintenance window for\n * full consistency.\n */\n async rebuildFulltext<K extends string>(\n nodeKind?: K,\n options: RebuildFulltextOptions = {},\n ): Promise<RebuildFulltextResult> {\n if (nodeKind !== undefined) this.#assertKindRegistered(nodeKind);\n return rebuildFulltextIndex(\n {\n graphId: this.#context.graphId,\n backend: this.#context.backend,\n registry: this.#context.registry,\n },\n nodeKind,\n options,\n );\n }\n\n #assertKindRegistered(kind: string): void {\n if (this.#context.registry.hasNodeType(kind)) return;\n throw new KindNotFoundError(kind, \"node\", {\n graphId: this.#context.graphId,\n suggestion:\n \"Compile-time kinds come from defineGraph; extension kinds appear after store.evolve() returns. Check store.introspect() for the registered set.\",\n });\n }\n}\n","/**\n * Nominal brands that make the store's \"which backend does this work go\n * through?\" decision a compile-time choice instead of a convention.\n *\n * A history-enabled `Store` holds the same `GraphBackend` shape in two roles:\n *\n * - the **recorded-capture wrapper**, through which every public graph-entity\n * write must flow so the write is captured, and\n * - the **bare backend**, used for raw SQL / DDL / bulk-materialization work\n * that intentionally bypasses capture (the wrapper rejects raw DDL and writes\n * no graph entities of its own).\n *\n * Routing a graph write through the bare backend silently loses history with no\n * error. The brands below turn that footgun into a type error: a function that\n * does bulk/DDL work declares `RawBackend`, a function that performs graph\n * writes declares `GraphWriteBackend`, and the two are not mutually assignable.\n *\n * The brand is erased at runtime — both values are ordinary `GraphBackend`s.\n * Only the `as*` tagging functions, called at the few seams where a role is\n * asserted, bridge a plain backend into a role; they are the greppable audit\n * surface for \"this path was deliberately routed to a capture role.\"\n *\n * This does not brand `TransactionBackend`: the collection-write entrypoint is\n * polymorphic over `GraphBackend | TransactionBackend`, and a raw backend is\n * structurally a `TransactionBackend`, so a brand there would be swallowed by\n * the union. The protection therefore covers the full-`GraphBackend` bulk/DDL\n * seams (where new capture-bypassing paths are actually added). Branding the\n * transaction surface is a deliberate follow-up, gated on a real bypass pattern.\n */\nimport { type GraphBackend } from \"./types\";\n\ndeclare const BackendRoleBrand: unique symbol;\n\n/**\n * The backend through which **graph-entity writes** (node/edge\n * create/update/delete) flow. When `history: true` this is the recorded-capture\n * wrapper; when history is off it is the bare backend. Either way, routing graph\n * writes here is what guarantees capture runs when it should.\n */\nexport type GraphWriteBackend = GraphBackend &\n Readonly<{ [BackendRoleBrand]: \"graph-write\" }>;\n\n/**\n * A backend for raw SQL / DDL / bulk-materialization work that **intentionally\n * bypasses** recorded-time capture. Never route public graph-entity writes\n * here — that is the silent-history-loss footgun this brand exists to catch.\n */\nexport type RawBackend = GraphBackend & Readonly<{ [BackendRoleBrand]: \"raw\" }>;\n\n/** Tags a backend as the graph-write seam. Call only where capture is wired. */\nexport function asGraphWriteBackend(backend: GraphBackend): GraphWriteBackend {\n return backend as GraphWriteBackend;\n}\n\n/** Tags a backend as the raw/DDL/bulk seam (capture-bypassing). */\nexport function asRawBackend(backend: GraphBackend): RawBackend {\n return backend as RawBackend;\n}\n","/**\n * Per-delta classification for `evolve()` modify-existing-kind support.\n *\n * Distinguishes additive / loosening changes (allowed without data\n * inspection) from tightening changes that require an empty-kind\n * probe, from genuinely incompatible changes that always reject.\n *\n * Pure function — no I/O. The caller (`store.evolve`) takes the\n * `requireEmpty` candidate list and runs the existence probes before\n * committing.\n */\nimport type { KindEntity } from \"../core/types\";\nimport { canonicalEqual } from \"../schema/canonical\";\nimport { requireDefined } from \"../utils/presence\";\nimport { type IncompatibleChange, IncompatibleChangeError } from \"./errors\";\nimport {\n type ExtensionArrayProperty,\n type ExtensionEdgeDef,\n type ExtensionEnumProperty,\n type ExtensionNodeDef,\n type ExtensionNumberProperty,\n type ExtensionObjectProperty,\n type ExtensionPropertyType,\n type ExtensionStringProperty,\n type ExtensionUniqueConstraint,\n type GraphExtension,\n} from \"./extension-types\";\n\n/**\n * Result of classifying every delta between two graph-extension documents.\n *\n * `incompatible` collects rejections that the caller throws as a\n * single `IncompatibleChangeError`. `requireEmpty`\n * collects the names of kinds where at least one delta is\n * allowed-only-on-empty — the caller probes each kind's row count\n * and promotes the `requireEmpty` entries to `incompatible` when\n * the kind has rows.\n *\n * `entity` is tracked per-key so the probe dispatches to the right\n * backend primitive: `countNodesByKind` for `node`, `countEdgesByKind`\n * for `edge`. Without this, an edge-keyed `TIGHTEN_EDGE_ENDPOINTS`\n * delta would silently slip past the empty-kind gate (the node-\n * keyed count would always be 0 for an edge name).\n */\ntype ModificationClassification = Readonly<{\n /** Deltas that always reject. */\n incompatible: readonly IncompatibleChange[];\n /**\n * Deltas allowed only when the kind has zero rows. One entry per\n * `(entity, kindName)`; each carries the per-delta detail to promote\n * to `incompatible` if the empty-probe shows rows. Caller looks up\n * by entry identity (frozen reference) — no string-key encoding.\n */\n requireEmpty: readonly RequireEmptyEntry[];\n}>;\n\nexport type RequireEmptyEntry = Readonly<{\n entity: KindEntity;\n kindName: string;\n changes: readonly IncompatibleChange[];\n}>;\n\n/**\n * Classifies every delta between an existing and proposed graph-extension\n * document. Same-shape kinds produce no entries; new-kind additions\n * produce no entries (handled by the union spread upstream).\n *\n * The classification covers nodes and edges in scope; ontology and\n * indexes pass through unchanged because v1 evolve doesn't modify\n * them in-place (consumers add new ontology relations, runtime\n * indexes follow auto-derive on the underlying nodes).\n */\nexport function classifyModifications(\n existing: GraphExtension,\n next: GraphExtension,\n): ModificationClassification {\n const incompatible: IncompatibleChange[] = [];\n // Aggregate by (entity, kindName) using a temporary string-keyed Map\n // — the encoding is private to this function. The Map's values are\n // returned as a plain array; the caller never sees the key.\n const requireEmptyMutable = new Map<\n string,\n { entity: KindEntity; kindName: string; changes: IncompatibleChange[] }\n >();\n\n const recordIncompatible = (entry: IncompatibleChange): void => {\n incompatible.push(entry);\n };\n const recordRequireEmpty = (\n entity: KindEntity,\n entry: IncompatibleChange,\n ): void => {\n const key = `${entity}:${entry.kind}`;\n const existingEntry = requireEmptyMutable.get(key);\n if (existingEntry === undefined) {\n requireEmptyMutable.set(key, {\n entity,\n kindName: entry.kind,\n changes: [entry],\n });\n } else {\n existingEntry.changes.push(entry);\n }\n };\n\n for (const [name, nextNode] of Object.entries(next.nodes ?? {})) {\n const existingNode = existing.nodes?.[name];\n if (existingNode === undefined) continue;\n classifyNode(name, existingNode, nextNode, {\n recordIncompatible,\n recordRequireEmpty: (entry) => {\n recordRequireEmpty(\"node\", entry);\n },\n });\n }\n for (const [name, nextEdge] of Object.entries(next.edges ?? {})) {\n const existingEdge = existing.edges?.[name];\n if (existingEdge === undefined) continue;\n classifyEdge(name, existingEdge, nextEdge, {\n recordIncompatible,\n recordRequireEmpty: (entry) => {\n recordRequireEmpty(\"edge\", entry);\n },\n });\n }\n\n const requireEmpty: RequireEmptyEntry[] = [];\n for (const value of requireEmptyMutable.values()) {\n requireEmpty.push(\n Object.freeze({\n entity: value.entity,\n kindName: value.kindName,\n changes: Object.freeze([...value.changes]),\n }),\n );\n }\n\n return { incompatible, requireEmpty };\n}\n\n/**\n * Promotes the `requireEmpty` entries whose probe came back non-empty\n * to incompatible, returning a single `IncompatibleChangeError`\n * covering both the always-incompatible deltas and the promoted ones.\n * Returns `undefined` when nothing rejects (probe came back empty for\n * every entry and `incompatible` is empty).\n */\nexport function buildIncompatibleChangeError(\n classification: ModificationClassification,\n nonEmpty: ReadonlySet<RequireEmptyEntry>,\n graphId: string,\n): IncompatibleChangeError | undefined {\n const promoted: IncompatibleChange[] = [];\n for (const entry of nonEmpty) {\n promoted.push(...entry.changes);\n }\n const all = [...classification.incompatible, ...promoted];\n if (all.length === 0) return undefined;\n return new IncompatibleChangeError(all, graphId);\n}\n\n// ============================================================\n// Node classification\n// ============================================================\n\ntype Recorders = Readonly<{\n recordIncompatible: (entry: IncompatibleChange) => void;\n recordRequireEmpty: (entry: IncompatibleChange) => void;\n}>;\n\nfunction classifyNode(\n kind: string,\n existing: ExtensionNodeDef,\n next: ExtensionNodeDef,\n recorders: Recorders,\n): void {\n classifyProperties(kind, existing.properties, next.properties, recorders);\n classifyUnique(kind, existing.unique ?? [], next.unique ?? [], recorders);\n // description / annotations — always allowed (no semantic effect).\n}\n\nfunction classifyEdge(\n kind: string,\n existing: ExtensionEdgeDef,\n next: ExtensionEdgeDef,\n recorders: Recorders,\n): void {\n classifyProperties(\n kind,\n existing.properties ?? {},\n next.properties ?? {},\n recorders,\n );\n classifyEdgeEndpoints(kind, existing, next, recorders);\n}\n\nfunction classifyEdgeEndpoints(\n kind: string,\n existing: ExtensionEdgeDef,\n next: ExtensionEdgeDef,\n recorders: Recorders,\n): void {\n // Adding kinds to from/to is broadening — always allowed.\n // Removing kinds with no existing edges of that endpoint would be\n // allowed in the spec, but TypeGraph doesn't have a per-(edge,\n // endpoint-kind) row probe today; v1 stays conservative by treating\n // endpoint-kind removal as allowed-on-empty for the whole edge kind.\n const fromExisting = new Set(existing.from);\n const toExisting = new Set(existing.to);\n const fromNext = new Set(next.from);\n const toNext = new Set(next.to);\n\n for (const removed of [...fromExisting].filter(\n (entry) => !fromNext.has(entry),\n )) {\n recorders.recordRequireEmpty({\n kind,\n type: \"TIGHTEN_EDGE_ENDPOINTS\",\n detail: `removed \"${removed}\" from \\`from\\``,\n });\n }\n for (const removed of [...toExisting].filter((entry) => !toNext.has(entry))) {\n recorders.recordRequireEmpty({\n kind,\n type: \"TIGHTEN_EDGE_ENDPOINTS\",\n detail: `removed \"${removed}\" from \\`to\\``,\n });\n }\n}\n\n// ============================================================\n// Properties\n// ============================================================\n\nfunction classifyProperties(\n kind: string,\n existing: Readonly<Record<string, ExtensionPropertyType>>,\n next: Readonly<Record<string, ExtensionPropertyType>>,\n recorders: Recorders,\n): void {\n const existingNames = new Set(Object.keys(existing));\n const nextNames = new Set(Object.keys(next));\n\n // Removed properties — REMOVE_PROPERTY (always reject).\n for (const name of existingNames) {\n if (!nextNames.has(name)) {\n recorders.recordIncompatible({\n kind,\n field: name,\n type: \"REMOVE_PROPERTY\",\n });\n }\n }\n\n // Added properties — ADD_OPTIONAL (allowed) or ADD_REQUIRED\n // (allowed-on-empty).\n for (const name of nextNames) {\n if (!existingNames.has(name)) {\n const property = requireDefined(next[name]);\n if (property.optional === true) continue;\n recorders.recordRequireEmpty({\n kind,\n field: name,\n type: \"ADD_REQUIRED_PROPERTY\",\n });\n }\n }\n\n // Modified properties — per-property classification.\n for (const name of existingNames) {\n if (!nextNames.has(name)) continue;\n classifyProperty(\n kind,\n name,\n requireDefined(existing[name]),\n requireDefined(next[name]),\n recorders,\n );\n }\n}\n\nfunction classifyProperty(\n kind: string,\n field: string,\n existing: ExtensionPropertyType,\n next: ExtensionPropertyType,\n recorders: Recorders,\n): void {\n // Type change — always reject.\n if (existing.type !== next.type) {\n recorders.recordIncompatible({\n kind,\n field,\n type: \"TYPE_CHANGE\",\n detail: `${existing.type} → ${next.type}`,\n });\n return;\n }\n\n // Optionality.\n const wasOptional = existing.optional === true;\n const isOptional = next.optional === true;\n if (!wasOptional && isOptional) {\n // LOOSEN_OPTIONALITY — allowed.\n } else if (wasOptional && !isOptional) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"TIGHTEN_OPTIONALITY\",\n detail: \"optional: true → false\",\n });\n }\n\n // Searchable / embedding modifiers — always allowed (the materializer\n // backfills indexes via materializeIndexes; vector regen is on the\n // consumer per the design doc).\n\n // Per-type constraint deltas.\n switch (existing.type) {\n case \"string\": {\n classifyString(\n kind,\n field,\n existing,\n next as ExtensionStringProperty,\n recorders,\n );\n break;\n }\n case \"number\": {\n classifyNumber(\n kind,\n field,\n existing,\n next as ExtensionNumberProperty,\n recorders,\n );\n break;\n }\n case \"enum\": {\n classifyEnum(\n kind,\n field,\n existing,\n next as ExtensionEnumProperty,\n recorders,\n );\n break;\n }\n case \"array\": {\n classifyArray(\n kind,\n field,\n existing,\n next as ExtensionArrayProperty,\n recorders,\n );\n break;\n }\n case \"object\": {\n classifyObject(\n kind,\n field,\n existing,\n next as ExtensionObjectProperty,\n recorders,\n );\n break;\n }\n case \"boolean\": {\n // No classifiable deltas beyond optionality, already handled.\n break;\n }\n }\n}\n\nfunction classifyString(\n kind: string,\n field: string,\n existing: ExtensionStringProperty,\n next: ExtensionStringProperty,\n recorders: Recorders,\n): void {\n // Length bounds: tighten requires empty, loosen allowed.\n if (\n existing.minLength !== next.minLength &&\n next.minLength !== undefined &&\n (existing.minLength === undefined || next.minLength > existing.minLength)\n ) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"TIGHTEN_CONSTRAINT\",\n detail: `minLength: ${existing.minLength ?? \"(none)\"} → ${next.minLength}`,\n });\n }\n if (\n existing.maxLength !== next.maxLength &&\n next.maxLength !== undefined &&\n (existing.maxLength === undefined || next.maxLength < existing.maxLength)\n ) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"TIGHTEN_CONSTRAINT\",\n detail: `maxLength: ${existing.maxLength ?? \"(none)\"} → ${next.maxLength}`,\n });\n }\n // Pattern.\n if (existing.pattern !== next.pattern) {\n if (existing.pattern === undefined && next.pattern !== undefined) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"ADD_PATTERN\",\n detail: next.pattern,\n });\n } else if (existing.pattern !== undefined && next.pattern === undefined) {\n // DROP_PATTERN — allowed.\n } else if (\n existing.pattern !== undefined &&\n next.pattern !== undefined &&\n existing.pattern !== next.pattern\n ) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"CHANGE_PATTERN\",\n detail: `${existing.pattern} → ${next.pattern}`,\n });\n }\n }\n // Format.\n if (existing.format !== next.format) {\n if (existing.format === undefined && next.format !== undefined) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"ADD_FORMAT\",\n detail: next.format,\n });\n } else if (existing.format !== undefined && next.format === undefined) {\n // DROP_FORMAT — allowed.\n } else {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"CHANGE_FORMAT\",\n detail: `${existing.format} → ${next.format}`,\n });\n }\n }\n}\n\nfunction classifyNumber(\n kind: string,\n field: string,\n existing: ExtensionNumberProperty,\n next: ExtensionNumberProperty,\n recorders: Recorders,\n): void {\n if (\n next.min !== undefined &&\n (existing.min === undefined || next.min > existing.min)\n ) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"TIGHTEN_CONSTRAINT\",\n detail: `min: ${existing.min ?? \"(none)\"} → ${next.min}`,\n });\n }\n if (\n next.max !== undefined &&\n (existing.max === undefined || next.max < existing.max)\n ) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"TIGHTEN_CONSTRAINT\",\n detail: `max: ${existing.max ?? \"(none)\"} → ${next.max}`,\n });\n }\n if (existing.int !== next.int && next.int === true && existing.int !== true) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"TIGHTEN_INT\",\n detail: \"int: false → true\",\n });\n }\n // LOOSEN_INT — allowed.\n}\n\nfunction classifyEnum(\n kind: string,\n field: string,\n existing: ExtensionEnumProperty,\n next: ExtensionEnumProperty,\n recorders: Recorders,\n): void {\n const nextValues = new Set(next.values);\n const removed = existing.values.filter((value) => !nextValues.has(value));\n if (removed.length > 0) {\n recorders.recordRequireEmpty({\n kind,\n field,\n type: \"TIGHTEN_ENUM\",\n detail: `removed values: ${removed.join(\", \")}`,\n });\n }\n // Adding values — LOOSEN_ENUM, allowed.\n}\n\nfunction classifyArray(\n kind: string,\n field: string,\n existing: ExtensionArrayProperty,\n next: ExtensionArrayProperty,\n recorders: Recorders,\n): void {\n // v1: array.items deltas are nested-property deltas. Same-type\n // recurse; different-type → TYPE_CHANGE.\n if (existing.items.type !== next.items.type) {\n recorders.recordIncompatible({\n kind,\n field: `${field}.items`,\n type: \"TYPE_CHANGE\",\n detail: `${existing.items.type} → ${next.items.type}`,\n });\n return;\n }\n classifyProperty(\n kind,\n `${field}.items`,\n existing.items,\n next.items,\n recorders,\n );\n}\n\nfunction classifyObject(\n kind: string,\n field: string,\n existing: ExtensionObjectProperty,\n next: ExtensionObjectProperty,\n recorders: Recorders,\n): void {\n // Recurse into the object's properties with field-prefixed names so\n // the issue carries a useful path for the reviewer.\n classifyProperties(kind, existing.properties, next.properties, {\n recordIncompatible: (entry) => {\n recorders.recordIncompatible({\n ...entry,\n field: `${field}.${entry.field ?? \"\"}`,\n });\n },\n recordRequireEmpty: (entry) => {\n recorders.recordRequireEmpty({\n ...entry,\n field: `${field}.${entry.field ?? \"\"}`,\n });\n },\n });\n}\n\n// ============================================================\n// Unique constraints\n// ============================================================\n\nfunction classifyUnique(\n kind: string,\n existing: readonly ExtensionUniqueConstraint[],\n next: readonly ExtensionUniqueConstraint[],\n recorders: Recorders,\n): void {\n const existingByName = new Map(\n existing.map((constraint) => [constraint.name, constraint]),\n );\n const nextByName = new Map(\n next.map((constraint) => [constraint.name, constraint]),\n );\n for (const [name, constraint] of nextByName) {\n if (!existingByName.has(name)) {\n // ADD_UNIQUE — allowed-on-empty (existing rule, kept).\n recorders.recordRequireEmpty({\n kind,\n type: \"ADD_UNIQUE_ON_POPULATED\",\n detail: `unique constraint \"${name}\" on [${constraint.fields.join(\", \")}]`,\n });\n }\n }\n // Dropped unique constraints — DROP_UNIQUE, allowed.\n // Modified — DROP + ADD; the ADD is recorded above for any\n // structurally-different constraint with a same name.\n for (const [name, constraint] of existingByName) {\n const newOne = nextByName.get(name);\n if (newOne === undefined) continue;\n // Different shape with same name → treat as modify; ADD half is\n // allowed-on-empty. Use `canonicalEqual` so the comparison is\n // key-order-stable; plain `JSON.stringify` would flag two\n // structurally identical constraints with differently-ordered\n // keys as reshaped.\n const { name: _existingName, ...existingShape } = constraint;\n const { name: _nextName, ...nextShape } = newOne;\n if (!canonicalEqual(existingShape, nextShape)) {\n recorders.recordRequireEmpty({\n kind,\n type: \"ADD_UNIQUE_ON_POPULATED\",\n detail: `unique constraint \"${name}\" reshaped`,\n });\n }\n }\n}\n","/**\n * Graph-extension removal: mutate a `GraphExtension` to drop a\n * set of graph-extension kinds with cascading edge / ontology cleanup.\n *\n * Pure function — no I/O, no compilation. The caller (`store.removeKinds`)\n * handles persistence (CAS commit of the resulting document) and the\n * deferred data-cleanup phase via `materializeRemovals`. This module\n * answers two questions:\n *\n * 1. Is it valid to remove these names? Compile-time kinds are\n * rejected (compile-time kinds are removed by recompiling and\n * redeploying — persisting \"removed-compile-time-kind\" state in\n * `schema_doc` is incoherent). Graph-extension kinds referenced by a\n * compile-time edge or ontology relation are also rejected\n * (removing them would orphan compile-time references at the\n * next deploy).\n *\n * 2. What does the new document look like? Edges whose endpoint\n * list becomes empty after removal are cascading-removed; edges\n * with surviving endpoints are retained with the removed name\n * dropped from `from`/`to`. Ontology relations referencing any\n * removed kind are also cascading-removed.\n */\nimport { type GraphDef } from \"../core/define-graph\";\nimport { getTypeName } from \"../ontology/types\";\nimport {\n KindHasReferentsError,\n type KindReferent,\n RemoveCompileTimeKindError,\n} from \"./errors\";\nimport {\n type ExtensionEdgeDef,\n type ExtensionIndex,\n type ExtensionNodeDef,\n type ExtensionOntologyRelation,\n type GraphExtension,\n} from \"./extension-types\";\nimport {\n buildGraphExtensionOntologyKeySet,\n compileTimeOntologyKey,\n extensionKindNames,\n} from \"./ontology-keys\";\n\ntype RemovalPlan = Readonly<{\n /**\n * The new extension after applying the removals. When the input\n * list contained only absent names, the document is structurally\n * equal to the existing extension and the caller short-circuits\n * the schema commit.\n */\n document: GraphExtension | undefined;\n /** Kinds actually removed (extension kinds present in the document). */\n removedNodeKinds: readonly string[];\n /** Edge kinds dropped because every endpoint they connected was removed. */\n removedEdgeKinds: readonly string[];\n}>;\n\n/**\n * Plans the removal of a set of names from a host graph's\n * extension, validating against the host graph's compile-time\n * kinds and graph-extension kinds. Throws on the rejection cases:\n *\n * - `RemoveCompileTimeKindError` if any name is a compile-time kind.\n * - `KindHasReferentsError` if a graph-extension kind is referenced\n * by a compile-time edge endpoint or ontology relation.\n *\n * Returns a plan describing the new document and which kinds will be\n * cascading-removed alongside the explicitly named ones.\n */\nexport function planRemovals<G extends GraphDef>(\n graph: G,\n names: readonly string[],\n): RemovalPlan {\n const document = graph.extension;\n const namesSet = new Set(names);\n if (namesSet.size === 0) {\n return { document, removedNodeKinds: [], removedEdgeKinds: [] };\n }\n\n const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n extensionKindNames(document);\n const compileTimeNodeNames = new Set(\n Object.keys(graph.nodes).filter((name) => !runtimeNodeNames.has(name)),\n );\n const compileTimeEdgeNames = new Set(\n Object.keys(graph.edges).filter((name) => !runtimeEdgeNames.has(name)),\n );\n\n // Reject compile-time names first — same shape across the API\n // surface even when the call also references absent runtime names.\n for (const name of namesSet) {\n if (compileTimeNodeNames.has(name)) {\n throw new RemoveCompileTimeKindError(name, \"node\", graph.id);\n }\n if (compileTimeEdgeNames.has(name)) {\n throw new RemoveCompileTimeKindError(name, \"edge\", graph.id);\n }\n }\n\n const removedNodeKinds = [...namesSet].filter((name) =>\n runtimeNodeNames.has(name),\n );\n const explicitlyRemovedEdgeKinds = [...namesSet].filter((name) =>\n runtimeEdgeNames.has(name),\n );\n\n // Compile-time-edge referent check: a graph-extension kind being\n // removed cannot remain a target of any compile-time edge or ontology\n // relation, because the compile-time declaration would resurrect the\n // reference on the next deploy. Pre-build an inverted index of\n // `kindName → referents` once so the per-kind check is O(1) instead\n // of walking all edges + ontology per removed kind.\n const referentsByKind = buildCompileTimeReferentIndex(\n graph,\n runtimeEdgeNames,\n );\n for (const kindName of removedNodeKinds) {\n const referents = referentsByKind.get(kindName);\n if (referents !== undefined && referents.length > 0) {\n throw new KindHasReferentsError(kindName, referents, graph.id);\n }\n }\n\n if (document === undefined) {\n return {\n document: undefined,\n removedNodeKinds: [],\n removedEdgeKinds: [],\n };\n }\n\n // Build the cascading-edges set: any graph-extension edge whose `from` or\n // `to` becomes empty after removal is also removed; edges with\n // surviving endpoints are retained with the removed name pruned.\n const removedNodeKindsSet = new Set(removedNodeKinds);\n const explicitlyRemovedEdgeKindsSet = new Set(explicitlyRemovedEdgeKinds);\n const cascadeEdges = new Set<string>();\n const updatedEdges: Record<string, ExtensionEdgeDef> = {};\n\n for (const [edgeName, edgeDocument] of Object.entries(document.edges ?? {})) {\n if (explicitlyRemovedEdgeKindsSet.has(edgeName)) {\n cascadeEdges.add(edgeName);\n continue;\n }\n const newFrom = edgeDocument.from.filter(\n (kind) => !removedNodeKindsSet.has(kind),\n );\n const newTo = edgeDocument.to.filter(\n (kind) => !removedNodeKindsSet.has(kind),\n );\n if (newFrom.length === 0 || newTo.length === 0) {\n cascadeEdges.add(edgeName);\n continue;\n }\n updatedEdges[edgeName] = {\n ...edgeDocument,\n from: newFrom,\n to: newTo,\n };\n }\n\n // Filter nodes — explicit removals are dropped.\n const updatedNodes: Record<string, ExtensionNodeDef> = {};\n for (const [nodeName, nodeDocument] of Object.entries(document.nodes ?? {})) {\n if (removedNodeKindsSet.has(nodeName)) continue;\n updatedNodes[nodeName] = nodeDocument;\n }\n\n // Drop ontology relations referencing any removed kind. The compile-\n // time-referent check above already rejects compile-time-side\n // ontology referencing the removed kind, so any remaining ontology\n // is safe to filter.\n const survivingOntology: ExtensionOntologyRelation[] = (\n document.ontology ?? []\n ).filter(\n (relation) =>\n !removedNodeKindsSet.has(relation.from) &&\n !removedNodeKindsSet.has(relation.to),\n );\n\n // Drop graph-extension indexes referencing removed kinds (relational + edge\n // entries; the auto-derived vector indexes follow the graph-extension nodes\n // they were derived from, so dropping the graph-extension node implicitly\n // drops the index when `mergeGraphExtension` re-runs auto-derive\n // against the smaller node set).\n const allRemovedKinds = new Set([\n ...removedNodeKindsSet,\n ...cascadeEdges,\n ...explicitlyRemovedEdgeKindsSet,\n ]);\n const survivingIndexes: ExtensionIndex[] = (document.indexes ?? []).filter(\n (index) => !allRemovedKinds.has(index.kind),\n );\n\n const newDocument: GraphExtension = Object.freeze({\n ...(document.version === undefined ? {} : { version: document.version }),\n ...(Object.keys(updatedNodes).length === 0 ? {} : { nodes: updatedNodes }),\n ...(Object.keys(updatedEdges).length === 0 ? {} : { edges: updatedEdges }),\n ...(survivingOntology.length === 0 ? {} : { ontology: survivingOntology }),\n ...(survivingIndexes.length === 0 ? {} : { indexes: survivingIndexes }),\n });\n\n return {\n document: newDocument,\n removedNodeKinds,\n removedEdgeKinds: [\n ...explicitlyRemovedEdgeKinds,\n ...[...cascadeEdges].filter(\n (name) => !explicitlyRemovedEdgeKindsSet.has(name),\n ),\n ],\n };\n}\n\n/**\n * Returns a graph with the graph-extension slice stripped: nodes and edges\n * registered by `mergeGraphExtension` are dropped along with the\n * `extension` itself, leaving the compile-time-only graph.\n *\n * Used by `removeKinds` as the base for re-merging the post-removal\n * graph-extension document — the alternative (mutating `graph.nodes` /\n * `graph.edges` in-place) would skip the merge step's validation\n * (collision checks, endpoint resolution).\n */\nexport function stripGraphExtension<G extends GraphDef>(graph: G): G {\n const document = graph.extension;\n if (document === undefined) return graph;\n const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n extensionKindNames(document);\n const runtimeOntologyKeys = buildGraphExtensionOntologyKeySet(document);\n\n const compileNodes: Record<string, (typeof graph.nodes)[string]> = {};\n for (const [name, registration] of Object.entries(graph.nodes)) {\n if (runtimeNodeNames.has(name)) continue;\n compileNodes[name] = registration;\n }\n const compileEdges: Record<string, (typeof graph.edges)[string]> = {};\n for (const [name, registration] of Object.entries(graph.edges)) {\n if (runtimeEdgeNames.has(name)) continue;\n compileEdges[name] = registration;\n }\n const compileOntology = graph.ontology.filter(\n (relation) => !runtimeOntologyKeys.has(compileTimeOntologyKey(relation)),\n );\n // Drop runtime-origin indexes too — `mergeGraphExtension` re-runs\n // auto-derivation against the new (smaller) graph-extension kind set.\n const compileIndexes = (graph.indexes ?? []).filter(\n (index) => index.origin !== \"runtime\",\n );\n\n return Object.freeze({\n ...graph,\n nodes: compileNodes,\n edges: compileEdges,\n ontology: compileOntology,\n indexes: compileIndexes.length === 0 ? undefined : compileIndexes,\n extension: undefined,\n });\n}\n\n/**\n * Builds an inverted index `kindName → KindReferent[]` over the\n * compile-time edges and ontology relations of `graph`. One walk per\n * graph instead of one walk per removed kind, dropping the cost of the\n * referent check from O(K × (E + O)) to O(K + E + O).\n */\nfunction buildCompileTimeReferentIndex<G extends GraphDef>(\n graph: G,\n runtimeEdgeNames: ReadonlySet<string>,\n): ReadonlyMap<string, readonly KindReferent[]> {\n const index = new Map<string, KindReferent[]>();\n const append = (kindName: string, referent: KindReferent): void => {\n const existing = index.get(kindName);\n if (existing === undefined) index.set(kindName, [referent]);\n else existing.push(referent);\n };\n\n for (const [edgeName, registration] of Object.entries(graph.edges)) {\n if (runtimeEdgeNames.has(edgeName)) continue;\n const reg = registration as {\n from?: readonly { kind: string }[];\n to?: readonly { kind: string }[];\n };\n const referent: KindReferent = {\n type: \"compile-time-edge\",\n name: edgeName,\n };\n const seen = new Set<string>();\n for (const endpoint of reg.from ?? []) {\n if (seen.has(endpoint.kind)) continue;\n seen.add(endpoint.kind);\n append(endpoint.kind, referent);\n }\n for (const endpoint of reg.to ?? []) {\n if (seen.has(endpoint.kind)) continue;\n seen.add(endpoint.kind);\n append(endpoint.kind, referent);\n }\n }\n\n const runtimeOntologyKeys = buildGraphExtensionOntologyKeySet(\n graph.extension,\n );\n for (const relation of graph.ontology) {\n if (runtimeOntologyKeys.has(compileTimeOntologyKey(relation))) continue;\n const fromName = getTypeName(relation.from);\n const toName = getTypeName(relation.to);\n const referent: KindReferent = {\n type: \"compile-time-ontology\",\n name: `${relation.metaEdge.name}(${fromName}, ${toName})`,\n };\n append(fromName, referent);\n if (toName !== fromName) append(toName, referent);\n }\n\n return index;\n}\n","import { type GraphBackend } from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n assertValidRecordedInstant,\n type RecordedInstant,\n resolveReadCoordinate,\n} from \"../../core/temporal\";\nimport { type TemporalMode } from \"../../core/types\";\nimport {\n ConfigurationError,\n UnsupportedBackendCapabilityError,\n} from \"../../errors\";\nimport { compileKindFilter } from \"../../query/compiler/predicate-utils\";\nimport { MAX_EXPLICIT_RECURSIVE_DEPTH } from \"../../query/compiler/recursive\";\nimport {\n type RecordedReadBinding,\n recordedReadSchemaFor,\n type SqlSchema,\n} from \"../../query/compiler/schema\";\nimport {\n compileTemporalFilter,\n currentReadInstant,\n type TemporalFilterOptions,\n} from \"../../query/compiler/temporal\";\nimport { type DialectAdapter } from \"../../query/dialect/types\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { compareCodePoints } from \"../../utils/compare\";\nimport type { AlgorithmCyclePolicy, TraversalDirection } from \"./types\";\n\nexport const DEFAULT_ALGORITHM_MAX_HOPS = 10;\nexport const DEFAULT_NEIGHBOR_DEPTH = 1;\n\nexport type AlgorithmContext = Readonly<{\n graphId: string;\n /** Graph definition — degree() enumerates declared edge endpoint kinds. */\n graph: GraphDef;\n /** Kind registry — expands declared endpoint kinds through subClassOf. */\n registry: KindRegistry;\n backend: GraphBackend;\n dialect: DialectAdapter;\n schema: SqlSchema;\n recordedReadBinding: RecordedReadBinding | undefined;\n defaultTemporalMode: TemporalMode;\n}>;\n\nexport type InternalTemporalOptions = Readonly<{\n temporalMode?: TemporalMode;\n asOf?: string;\n recordedAsOf?: RecordedInstant;\n}>;\n\nexport type InternalTraversalOptions = InternalTemporalOptions &\n Readonly<{\n edges: readonly string[];\n maxHops?: number;\n direction?: TraversalDirection;\n cyclePolicy?: AlgorithmCyclePolicy;\n workingMemory?: string;\n /**\n * Numeric edge property supplying per-edge traversal weights. When set,\n * the iterative operation compiles a shared weight expression and every\n * edge expansion carries a `weight` column.\n */\n weightProperty?: string;\n /** Weight substituted for edges missing `weightProperty`. */\n defaultWeight?: number;\n }>;\n\n/** Copies only explicitly supplied temporal overrides for option forwarding. */\nexport function pickTemporalOptions(\n options: InternalTemporalOptions,\n): InternalTemporalOptions {\n return {\n ...(options.temporalMode === undefined ?\n {}\n : { temporalMode: options.temporalMode }),\n ...(options.asOf === undefined ? {} : { asOf: options.asOf }),\n ...(options.recordedAsOf === undefined ?\n {}\n : { recordedAsOf: options.recordedAsOf }),\n };\n}\n\n/**\n * Resolves per-call temporal overrides against the graph's default mode into\n * a plain `{ temporalMode, asOf? }` object. Shared by callers that forward\n * the pair to `buildReachableCte`. An `asOf` is rejected unless the mode is\n * `\"asOf\"` (via {@link resolveReadCoordinate}), matching every other read path.\n */\nexport function resolveTemporalOptions(\n ctx: AlgorithmContext,\n options: InternalTemporalOptions,\n): Readonly<{\n temporalMode: TemporalMode;\n asOf?: string;\n recordedAsOf?: RecordedInstant;\n}> {\n const { valid } = resolveReadCoordinate(\n options.temporalMode ?? ctx.defaultTemporalMode,\n options.asOf,\n );\n // `recordedAsOf` normally arrives pre-validated through StoreView's\n // withRecordedCoordinate, but it is absent from the public algorithm option\n // types, so validate here too: a type-unsafe caller that smuggles a\n // non-canonical timestamp would otherwise be string-compared raw against\n // recorded_from/recorded_to and return wrong rows on SQLite.\n if (options.recordedAsOf !== undefined) {\n assertValidRecordedInstant(options.recordedAsOf, \"recordedAsOf\");\n }\n return {\n temporalMode: valid.mode,\n ...(valid.asOf !== undefined && { asOf: valid.asOf }),\n ...(options.recordedAsOf === undefined ?\n {}\n : { recordedAsOf: options.recordedAsOf }),\n };\n}\n\nexport function resolveReadSchema(\n ctx: AlgorithmContext,\n options: InternalTemporalOptions,\n): SqlSchema {\n return recordedReadSchemaFor(\n ctx.schema,\n options.recordedAsOf,\n ctx.recordedReadBinding,\n \"recorded-graph-algorithm\",\n );\n}\n\n/**\n * Compiles the resolved temporal filter to SQL. `resolveTemporalOptions`\n * has already rejected an `asOf` paired with any non-`\"asOf\"` mode, so a\n * stray pin can never reach the filter; `current` resolves against the\n * dialect's current-timestamp expression.\n */\nexport function resolveTemporalFilter(\n ctx: AlgorithmContext,\n options: InternalTemporalOptions,\n tableAlias?: string,\n): ReturnType<typeof compileTemporalFilter> {\n const resolved = resolveTemporalOptions(ctx, options);\n const filterOptions: TemporalFilterOptions = {\n mode: resolved.temporalMode,\n asOf: resolved.asOf,\n recordedAsOf: resolved.recordedAsOf,\n tableAlias,\n currentTimestamp: currentReadInstant(),\n };\n return compileTemporalFilter(filterOptions);\n}\n\nexport function resolveMaxHops(\n rawMaxHops: number | undefined,\n fallback: number,\n optionName: \"maxHops\" | \"depth\",\n): number {\n const value = rawMaxHops ?? fallback;\n\n if (!Number.isFinite(value) || !Number.isInteger(value)) {\n throw new ConfigurationError(\n `Graph algorithm ${optionName} must be a finite integer, got ${String(value)}.`,\n { option: optionName, value },\n );\n }\n\n if (value < 1) {\n throw new ConfigurationError(\n `Graph algorithm ${optionName} must be at least 1, got ${value}.`,\n { option: optionName, value },\n );\n }\n\n if (value > MAX_EXPLICIT_RECURSIVE_DEPTH) {\n throw new ConfigurationError(\n `Graph algorithm ${optionName} (${value}) exceeds the maximum of ${MAX_EXPLICIT_RECURSIVE_DEPTH}.`,\n { option: optionName, value, limit: MAX_EXPLICIT_RECURSIVE_DEPTH },\n );\n }\n\n return value;\n}\n\n/**\n * Validates an iterative algorithm's round budget. Unlike {@link\n * resolveMaxHops}, the budget is not a traversal depth bound — convergence\n * normally ends the run first — so it is not capped at the recursive-CTE\n * depth limit.\n */\nexport function resolveMaxIterations(\n value: number | undefined,\n fallback: number,\n algorithm: string,\n): number {\n const maxIterations = value ?? fallback;\n if (!Number.isSafeInteger(maxIterations) || maxIterations < 1) {\n throw new ConfigurationError(\n `${algorithm} maxIterations must be a positive safe integer, got ${String(maxIterations)}.`,\n { maxIterations },\n );\n }\n return maxIterations;\n}\n\nexport function assertEdgeKinds(edges: readonly string[]): void {\n if (edges.length === 0) {\n throw new ConfigurationError(\n `Graph algorithms require at least one edge kind in 'edges'.`,\n { edges },\n );\n }\n}\n\n/**\n * Compiles the induced-subgraph node filter for a working-table seeding\n * statement over the nodes-table alias `n`; `undefined` selects every kind.\n */\nexport function compileNodeKindSeedFilter(\n nodeKinds: readonly string[] | undefined,\n): SqlFragment {\n if (nodeKinds === undefined) return sql`TRUE`;\n return compileKindFilter(sql.raw(\"n.kind\"), nodeKinds);\n}\n\n/**\n * Deduplicates and code-point-sorts an induced-subgraph kind selection so\n * compiled kind filters are deterministic across call sites and backends.\n */\nexport function normalizeNodeKinds(\n nodeKinds: readonly string[] | undefined,\n): readonly string[] | undefined {\n if (nodeKinds === undefined) return undefined;\n return [...new Set(nodeKinds)].toSorted((left, right) =>\n compareCodePoints(left, right),\n );\n}\n\nexport function assertGraphAnalyticsSupported(\n ctx: AlgorithmContext,\n algorithm: string,\n options: Readonly<{ requiresWindowFunctions?: boolean }> = {},\n): void {\n const graphAnalytics =\n ctx.backend.capabilities.graphAnalytics?.supported === true;\n const windowFunctions = ctx.backend.capabilities.windowFunctions;\n if (\n graphAnalytics &&\n (options.requiresWindowFunctions !== true || windowFunctions)\n ) {\n return;\n }\n\n throw new UnsupportedBackendCapabilityError(\n algorithm,\n \"graphAnalytics\",\n {\n dialect: ctx.backend.dialect,\n supported: graphAnalytics,\n ...(options.requiresWindowFunctions === true ? { windowFunctions } : {}),\n },\n \"Use a built-in transactional SQLite/PostgreSQL backend, or declare graphAnalytics support on a compatible custom backend.\",\n );\n}\n","import { compileKindFilter } from \"../../query/compiler/predicate-utils\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport {\n type AlgorithmContext,\n type InternalTemporalOptions,\n resolveReadSchema,\n resolveTemporalFilter,\n} from \"./context\";\nimport type { TraversalDirection } from \"./types\";\n\ntype InternalDegreeOptions = InternalTemporalOptions &\n Readonly<{\n edges?: readonly string[];\n direction?: TraversalDirection;\n }>;\n\nexport async function executeDegree(\n ctx: AlgorithmContext,\n nodeId: string,\n options: InternalDegreeOptions = {},\n): Promise<number> {\n const direction = options.direction ?? \"both\";\n const edgeKinds = options.edges ?? Object.keys(ctx.graph.edges);\n // A graph that declares no edge kinds has no edges to count — provably zero\n // without a round trip.\n if (edgeKinds.length === 0) return 0;\n\n const schema = resolveReadSchema(ctx, options);\n const whereClauses: SqlFragment[] = [\n sql`graph_id = ${ctx.graphId}`,\n resolveTemporalFilter(ctx, options),\n compileDirectionFilter(ctx, direction, nodeId, schema.nodesTable),\n ];\n if (options.edges !== undefined) {\n whereClauses.push(compileKindFilter(sql.raw(\"kind\"), options.edges));\n }\n\n // COUNT(DISTINCT id) collapses self-loops (from === to === nodeId) to a\n // single edge so they don't double-count under `\"both\"`.\n const countExpr =\n direction === \"both\" ? sql`COUNT(DISTINCT id)` : sql`COUNT(*)`;\n\n const query = sql`SELECT ${countExpr} AS count FROM ${schema.edgesTable} WHERE ${sql.join(whereClauses, sql` AND `)}`;\n\n const rows = await ctx.backend.execute<Readonly<{ count: number | string }>>(\n asCompiledRowsSql(query),\n );\n return Number(rows[0]?.count ?? 0);\n}\n\n/**\n * The counted node's own kind, as a scalar subquery.\n *\n * Every edge row stores the *actual* kind of each endpoint node — the write\n * path takes `from_kind` straight off the `from` node reference, and a node's\n * kind is immutable for the life of its id. So for any edge incident to\n * `nodeId`, the endpoint kind on `nodeId`'s side equals `nodeId`'s kind, and\n * nothing else. That makes this an equality the composite edge indexes seek on\n * directly, and it stays true no matter how the graph's endpoint declarations\n * evolve.\n *\n * (Enumerating the *declared* endpoint kinds instead — the shape this replaced\n * — held only for rows written under the current declaration. Narrow an edge's\n * `from: [Person]` to `from: [Employee]` and every `Person`-rooted edge already\n * on disk drops out of the filter, silently undercounting.)\n *\n * The subquery is uncorrelated, so both engines evaluate it once and treat the\n * result as a constant: Postgres hoists it to an InitPlan, SQLite runs it as a\n * one-shot scalar subquery. `LIMIT 1` is required in recorded-time mode, where\n * the resolved nodes relation holds one row per recorded version of the node.\n * An unknown `nodeId` yields NULL, and `from_kind = NULL` matches nothing —\n * degree 0, which is what a node that does not exist has.\n */\nfunction nodeKindSubquery(\n ctx: AlgorithmContext,\n nodeId: string,\n nodesTable: SqlFragment,\n): SqlFragment {\n return sql`(SELECT kind FROM ${nodesTable} WHERE graph_id = ${ctx.graphId} AND id = ${nodeId} LIMIT 1)`;\n}\n\n/**\n * Direction filter shaped for the default edge indexes: the endpoint-kind\n * equality comes first so `edges_from_idx (graph_id, from_kind, from_id, …)`\n * / `edges_to_idx (graph_id, to_kind, to_id, …)` can seek — a bare\n * `from_id = ?` scans the whole edge partition because both indexes lead\n * with the kind column.\n */\nfunction compileDirectionFilter(\n ctx: AlgorithmContext,\n direction: TraversalDirection,\n nodeId: string,\n nodesTable: SqlFragment,\n): SqlFragment {\n const nodeKind = nodeKindSubquery(ctx, nodeId, nodesTable);\n const fromSide = sql`(from_kind = ${nodeKind} AND from_id = ${nodeId})`;\n const toSide = sql`(to_kind = ${nodeKind} AND to_id = ${nodeId})`;\n\n switch (direction) {\n case \"out\": {\n return fromSide;\n }\n case \"in\": {\n return toSide;\n }\n case \"both\": {\n return sql`(${fromSide} OR ${toSide})`;\n }\n }\n}\n","import {\n type GraphBackend,\n INTERNAL_TEMPORARY_WRITES,\n type InternalTransactionOptions,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport {\n CompilerInvariantError,\n ConfigurationError,\n GraphAlgorithmConvergenceError,\n} from \"../../errors\";\nimport {\n compileKindFilter,\n sqlValueList,\n} from \"../../query/compiler/predicate-utils\";\nimport {\n compileTemporalFilter,\n currentReadInstant,\n} from \"../../query/compiler/temporal\";\nimport { type DialectAdapter } from \"../../query/dialect/types\";\nimport { jsonPointer } from \"../../query/json-pointer\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport {\n asCompiledRowsSql,\n asCompiledTemporaryStatementSql,\n} from \"../../query/sql-intent\";\nimport { compareCodePoints, compareStrings } from \"../../utils/compare\";\nimport { generateId } from \"../../utils/id\";\nimport { isPresent } from \"../../utils/presence\";\nimport type { AlgorithmContext, InternalTraversalOptions } from \"./context\";\nimport { resolveReadSchema, resolveTemporalOptions } from \"./context\";\nimport type { PathNode, TraversalDirection } from \"./types\";\n\ntype QueryBackend = Pick<GraphBackend, \"capabilities\" | \"execute\">;\ntype WorkingTableIdentifier = ReturnType<typeof sql.identifier>;\ntype CapturedFailure = Readonly<{ error: unknown }>;\n\nexport type IterativeGraphOperation = Readonly<{\n backend: QueryBackend;\n ctx: AlgorithmContext;\n edgeKindChunks: readonly (readonly string[])[];\n direction: TraversalDirection;\n maxWorkingSetSize: number;\n nodeTemporalFilter: ReturnType<typeof compileTemporalFilter>;\n edgeTemporalFilter: ReturnType<typeof compileTemporalFilter>;\n schema: ReturnType<typeof resolveReadSchema>;\n /**\n * Validated caller-requested transaction-scoped memory override for\n * working-table rounds; `undefined` inherits the engine's configuration.\n */\n workingMemory: string | undefined;\n /**\n * Per-edge traversal weight over the expansion's edge alias `e`, compiled\n * from the caller's `weightProperty`/`defaultWeight`. When set, every edge\n * expansion carries it as a `weight` column; `undefined` for unweighted\n * operations.\n */\n weightExpression: SqlFragment | undefined;\n}>;\n\nexport type NodeIdentityKey = string & {\n readonly __nodeIdentityKey: unique symbol;\n};\n\nexport type NodeExpansion = Readonly<{\n source: PathNode;\n target: PathNode;\n /** Edge weight; present exactly when the operation is weighted. */\n weight?: number;\n}>;\n\ntype TemporaryStatementBackend = QueryBackend &\n Pick<TransactionBackend, \"executeTemporaryStatement\"> &\n Readonly<{\n executeTemporaryStatement: NonNullable<\n TransactionBackend[\"executeTemporaryStatement\"]\n >;\n }>;\n\nexport type IterativeGraphRunContext = Readonly<{\n operation: IterativeGraphOperation;\n backend: TemporaryStatementBackend;\n workingTable: WorkingTableIdentifier;\n graphId: string;\n runId: string;\n executeTemporary: (query: SqlFragment) => Promise<void>;\n}>;\n\nexport type IterativeGraphState = Readonly<{\n workingTableSize: number;\n}>;\n\nexport function frontierIndexIdentifier(\n context: IterativeGraphRunContext,\n): SqlFragment {\n return sql.identifier(\n `typegraph_iterative_${context.runId.replaceAll(\"-\", \"_\")}_frontier`,\n );\n}\n\ntype WorkingTableCountRow = Readonly<{ count: number | string }>;\n\n/** Counts this run's working-table rows; drivers may deliver bigint text. */\nexport async function countWorkingTableRows(\n context: IterativeGraphRunContext,\n): Promise<number> {\n const rows = await context.backend.execute<WorkingTableCountRow>(\n asCompiledRowsSql(sql`\n SELECT COUNT(*) AS count\n FROM ${context.workingTable}\n WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n `),\n );\n return Number(rows[0]?.count ?? 0);\n}\n\nexport type IterativeGraphPlan<\n State extends IterativeGraphState,\n Result,\n> = Readonly<{\n algorithm: string;\n maxIterations: number;\n createWorkingTable: (context: IterativeGraphRunContext) => SqlFragment;\n initialize: (context: IterativeGraphRunContext) => Promise<State>;\n runRound: (\n context: IterativeGraphRunContext,\n state: State,\n iteration: number,\n ) => Promise<State>;\n hasConverged: (state: State) => boolean;\n extractResult: (\n context: IterativeGraphRunContext,\n state: State,\n ) => Promise<Result>;\n /** Drops any plan-owned temporary relations before the working table. */\n cleanup?: (context: IterativeGraphRunContext) => Promise<void>;\n}>;\n\ntype ExpansionRow = Readonly<{\n source_id: string;\n source_kind: string;\n target_id: string;\n target_kind: string;\n /** Present when the operation is weighted; drivers may deliver text. */\n weight?: number | string | null;\n}>;\n\ntype VisibleNodeRow = Readonly<{\n id: string;\n kind: string;\n}>;\n\nexport const DEFAULT_MAX_BIND_PARAMETERS = 999;\nconst RESERVED_TEMPORAL_BIND_PARAMETERS_PER_BRANCH = 12;\n/** Headroom for the weight expression's path and default-weight binds. */\nconst RESERVED_WEIGHT_BIND_PARAMETERS_PER_BRANCH = 4;\n/**\n * PostgreSQL initially estimates an un-analyzed temporary relation at one row.\n * Even a few dozen rows can distort join ordering on a dense edge expansion,\n * while ANALYZE remains a low-single-digit-millisecond operation at this size.\n * Keep the trigger below the 31-person smoke graph that exposed this cliff.\n */\nexport const WORKING_TABLE_ANALYZE_MINIMUM_ROWS = 16;\n/** Caps statistics drift for growing BFS-style working tables at under 4x. */\nexport const WORKING_TABLE_ANALYZE_GROWTH_FACTOR = 4;\n\n/**\n * Accepts only a plain integer with a binary unit suffix. The value reaches\n * the engine as a bound parameter, but a strict shape keeps the option from\n * ever smuggling arbitrary text into a settings statement and rejects\n * ambiguous inputs (fractions, spaces, unknown units) up front.\n */\nconst ITERATIVE_WORKING_MEMORY_PATTERN = /^(\\d+)(kB|MB|GB)$/;\n\nconst WORKING_MEMORY_KILOBYTES_PER_UNIT: Readonly<Record<string, number>> = {\n kB: 1,\n MB: 1024,\n GB: 1024 * 1024,\n};\n\n/**\n * PostgreSQL's accepted `work_mem` range (in kB, its base unit). Values\n * outside it fail `set_config` mid-transaction with a raw engine error on\n * PostgreSQL while SQLite would silently accept them — so both backends\n * reject them up front with the same typed error instead.\n */\nconst MIN_WORKING_MEMORY_KILOBYTES = 64;\nconst MAX_WORKING_MEMORY_KILOBYTES = 2_147_483_647;\n\n/**\n * Validates an explicitly requested working-memory override. `undefined`\n * means the caller did not opt in: the operation inherits the engine's\n * configured setting and emits no override — `work_mem` is a threshold each\n * sort/hash operator (and each parallel worker) may allocate up to, not a\n * per-operation budget, so silently raising it for every algorithm call\n * could multiply memory use far past what a DBA provisioned.\n */\nfunction resolveWorkingMemory(\n workingMemory: string | undefined,\n): string | undefined {\n if (workingMemory === undefined) return undefined;\n const match = ITERATIVE_WORKING_MEMORY_PATTERN.exec(workingMemory);\n if (match === null) {\n throw new ConfigurationError(\n `Iterative graph operation workingMemory must be digits followed by kB, MB, or GB (for example \"64MB\"), got ${JSON.stringify(workingMemory)}.`,\n { workingMemory },\n );\n }\n const kilobytes =\n Number(match[1]) * (WORKING_MEMORY_KILOBYTES_PER_UNIT[match[2] ?? \"\"] ?? 0);\n if (\n kilobytes < MIN_WORKING_MEMORY_KILOBYTES ||\n kilobytes > MAX_WORKING_MEMORY_KILOBYTES\n ) {\n throw new ConfigurationError(\n `Iterative graph operation workingMemory must be between ${MIN_WORKING_MEMORY_KILOBYTES}kB and ${MAX_WORKING_MEMORY_KILOBYTES}kB, got ${JSON.stringify(workingMemory)}.`,\n { workingMemory, kilobytes },\n );\n }\n return workingMemory;\n}\n\n/**\n * Opens the shared execution scope for iterative graph algorithms. The host\n * controls rounds and convergence; this scope supplies a snapshot-consistent,\n * bind-limit-aware SQL working relation for each round.\n *\n * The working relation is emitted as chunked `VALUES` rows rather than a\n * connection-local temporary table. That keeps the primitive portable to\n * backends such as D1 that cannot promise one pinned connection. Transactional\n * backends still run all rounds in one read-only snapshot.\n */\nexport async function withInlineIterativeGraphOperation<T>(\n ctx: AlgorithmContext,\n options: InternalTraversalOptions,\n run: (operation: IterativeGraphOperation) => Promise<T>,\n): Promise<T> {\n if (ctx.backend.capabilities.transactions) {\n return ctx.backend.transaction(\n async (backend) => run(createOperation(ctx, options, backend)),\n {\n isolationLevel: \"repeatable_read\",\n accessMode: \"read_only\",\n },\n );\n }\n return run(createOperation(ctx, options, ctx.backend));\n}\n\n/**\n * Runs a compiler-defined iterative algorithm against a real temporary working\n * table. The primitive owns the read-only snapshot, iteration cap, convergence\n * check, and `finally` cleanup; the plan owns only table shape, round SQL, and\n * result extraction.\n */\nexport async function runIterativeGraphOperation<\n State extends IterativeGraphState,\n Result,\n>(\n ctx: AlgorithmContext,\n options: InternalTraversalOptions,\n plan: IterativeGraphPlan<State, Result>,\n): Promise<Result> {\n if (!ctx.backend.capabilities.transactions) {\n throw new ConfigurationError(\n \"Temporary-table graph iteration requires a transactional backend.\",\n { dialect: ctx.backend.dialect },\n );\n }\n\n const transactionOptions = {\n isolationLevel: \"repeatable_read\",\n accessMode: \"read_only\",\n temporaryWrites: INTERNAL_TEMPORARY_WRITES,\n } satisfies InternalTransactionOptions;\n\n return ctx.backend.transaction(async (backend) => {\n const temporaryBackend = requireTemporaryStatements(backend);\n const runId = generateId();\n const workingTable = sql.identifier(\n `typegraph_iterative_${runId.replaceAll(\"-\", \"_\")}`,\n );\n const context: IterativeGraphRunContext = {\n operation: createOperation(ctx, options, temporaryBackend),\n backend: temporaryBackend,\n workingTable,\n graphId: ctx.graphId,\n runId,\n executeTemporary: async (query) => {\n await temporaryBackend.executeTemporaryStatement(\n asCompiledTemporaryStatementSql(query),\n );\n },\n };\n\n // Opt-in only: without an explicit workingMemory the rounds inherit\n // the engine's configured setting. When requested, the override is\n // transaction-scoped — `set_config(..., is_local => true)` reverts\n // when this transaction ends, so the session/server setting is never\n // touched. SQLite returns no statement here.\n if (context.operation.workingMemory !== undefined) {\n const workingMemoryStatement = ctx.dialect.setTransactionWorkingMemory(\n context.operation.workingMemory,\n );\n if (workingMemoryStatement !== undefined) {\n await context.executeTemporary(workingMemoryStatement);\n }\n }\n await context.executeTemporary(plan.createWorkingTable(context));\n let operationFailure: CapturedFailure | undefined;\n try {\n let state = await plan.initialize(context);\n let analyzedRowCount = await refreshWorkingTableStatistics(\n context,\n state.workingTableSize,\n );\n for (\n let iteration = 1;\n iteration <= plan.maxIterations && !plan.hasConverged(state);\n iteration++\n ) {\n state = await plan.runRound(context, state, iteration);\n // Statistics only pay off in a subsequent round: skip the refresh\n // when the operation just converged or the iteration budget is\n // spent — no further round will read the working table.\n if (iteration < plan.maxIterations && !plan.hasConverged(state)) {\n analyzedRowCount = await refreshWorkingTableStatistics(\n context,\n state.workingTableSize,\n analyzedRowCount,\n );\n }\n }\n if (!plan.hasConverged(state)) {\n throw new GraphAlgorithmConvergenceError(\n plan.algorithm,\n plan.maxIterations,\n );\n }\n return await plan.extractResult(context, state);\n } catch (error) {\n operationFailure = { error };\n throw error;\n } finally {\n await cleanupWorkingTables(context, plan.cleanup, operationFailure);\n }\n }, transactionOptions);\n}\n\nexport function shouldRefreshWorkingTableStatistics(\n workingTableSize: number,\n analyzedRowCount?: number,\n): boolean {\n if (workingTableSize < WORKING_TABLE_ANALYZE_MINIMUM_ROWS) return false;\n if (analyzedRowCount === undefined) return true;\n return (\n workingTableSize >= analyzedRowCount * WORKING_TABLE_ANALYZE_GROWTH_FACTOR\n );\n}\n\nasync function refreshWorkingTableStatistics(\n context: IterativeGraphRunContext,\n workingTableSize: number,\n analyzedRowCount?: number,\n): Promise<number | undefined> {\n if (\n !shouldRefreshWorkingTableStatistics(workingTableSize, analyzedRowCount)\n ) {\n return analyzedRowCount;\n }\n const statement = context.operation.ctx.dialect.analyzeTemporaryTable(\n context.workingTable,\n );\n if (statement === undefined) return analyzedRowCount;\n await context.executeTemporary(statement);\n return workingTableSize;\n}\n\nasync function dropWorkingTable(\n context: IterativeGraphRunContext,\n hasPrimaryFailure: boolean,\n): Promise<void> {\n try {\n await context.executeTemporary(\n sql`DROP TABLE IF EXISTS ${context.workingTable}`,\n );\n } catch (cleanupError) {\n // A failed PostgreSQL statement aborts the transaction, so DROP is\n // rejected too; rollback then owns cleanup. Preserve the algorithm's root\n // error instead of masking it with \"transaction is aborted\".\n if (!hasPrimaryFailure) throw cleanupError;\n }\n}\n\nasync function cleanupWorkingTables(\n context: IterativeGraphRunContext,\n cleanup: IterativeGraphPlan<IterativeGraphState, unknown>[\"cleanup\"],\n operationFailure: CapturedFailure | undefined,\n): Promise<void> {\n let cleanupFailure: CapturedFailure | undefined;\n try {\n await cleanup?.(context);\n } catch (error) {\n // Preserve a failed operation over a secondary cleanup failure. When\n // cleanup itself is the first failure, preserve it over a subsequent\n // PostgreSQL \"transaction is aborted\" error from dropping the main table.\n if (operationFailure === undefined) cleanupFailure = { error };\n }\n\n await dropWorkingTable(\n context,\n operationFailure !== undefined || cleanupFailure !== undefined,\n );\n if (cleanupFailure !== undefined) throw cleanupFailure.error;\n}\n\nexport async function fetchVisibleWorkingNodes(\n operation: IterativeGraphOperation,\n nodeIds: readonly string[],\n): Promise<readonly PathNode[]> {\n const nodes = new Map<NodeIdentityKey, PathNode>();\n for (const chunk of chunkValues(nodeIds, operation.maxWorkingSetSize)) {\n const query = sql`SELECT n.id, n.kind FROM ${operation.schema.nodesTable} n WHERE n.graph_id = ${operation.ctx.graphId} AND n.id IN (${sqlValueList(chunk)}) AND ${operation.nodeTemporalFilter}`;\n const rows = await operation.backend.execute<VisibleNodeRow>(\n asCompiledRowsSql(query),\n );\n for (const row of rows) nodes.set(nodeIdentityKey(row), row);\n }\n return [...nodes.values()].toSorted((left, right) =>\n compareNodeIdentity(left, right),\n );\n}\n\n/**\n * Expands one working-set round and reduces all matching edges by target-node\n * identity before returning to the host loop. Callers choose the reduction:\n * BFS keeps one predecessor, label-min keeps the smallest propagated label,\n * and other fixpoint algorithms can define their own associative merge.\n */\nexport async function reduceExpandedWorkingSet<T>(\n operation: IterativeGraphOperation,\n workingSet: readonly PathNode[],\n direction: TraversalDirection,\n reduce: (current: T | undefined, expansion: NodeExpansion) => T | undefined,\n): Promise<ReadonlyMap<NodeIdentityKey, T>> {\n const reduced = new Map<NodeIdentityKey, T>();\n for (const edgeKinds of operation.edgeKindChunks) {\n for (const chunk of chunkValues(workingSet, operation.maxWorkingSetSize)) {\n const rows = await operation.backend.execute<ExpansionRow>(\n asCompiledRowsSql(\n compileExpansionQuery(operation, chunk, direction, edgeKinds),\n ),\n );\n for (const row of rows) {\n // A weighted operation compiles a weight column into every\n // expansion, and weighted algorithms audit their weight domain\n // before expanding — so a NULL weight here means either a plan\n // skipped that audit, or (on a backend without snapshot isolation)\n // a concurrent write invalidated a weight mid-run. Silently\n // dropping the edge would return plausible-but-wrong results.\n if (\n operation.weightExpression !== undefined &&\n !isPresent(row.weight)\n ) {\n throw new CompilerInvariantError(\n \"Weighted graph expansion produced a NULL weight. Either the plan skipped its weight audit, or edge data changed concurrently during a run on a backend without snapshot isolation.\",\n { source: row.source_id, target: row.target_id },\n );\n }\n const expansion = {\n source: { id: row.source_id, kind: row.source_kind },\n target: { id: row.target_id, kind: row.target_kind },\n ...(isPresent(row.weight) ? { weight: Number(row.weight) } : {}),\n } satisfies NodeExpansion;\n const targetKey = nodeIdentityKey(expansion.target);\n const selected = reduce(reduced.get(targetKey), expansion);\n if (selected !== undefined) reduced.set(targetKey, selected);\n }\n }\n }\n return reduced;\n}\n\nexport function nodeIdentityKey(node: PathNode): NodeIdentityKey {\n return `${node.kind}\\u0000${node.id}` as NodeIdentityKey;\n}\n\n/**\n * Builds a node-identity key from a working-table row's nullable\n * predecessor columns. Drivers deliver SQL NULL in varying shapes, so only\n * a string pair counts as a real predecessor.\n */\nexport function nodeIdentityKeyFromRow(\n id: unknown,\n kind: unknown,\n): NodeIdentityKey | undefined {\n if (typeof id !== \"string\" || typeof kind !== \"string\") return undefined;\n return nodeIdentityKey({ id, kind });\n}\n\nexport function compareNodeIdentity(left: PathNode, right: PathNode): number {\n return (\n compareCodePoints(left.id, right.id) ||\n compareCodePoints(left.kind, right.kind)\n );\n}\n\ntype DirectionFields = Readonly<{\n joinField: \"from_id\" | \"to_id\";\n joinKindField: \"from_kind\" | \"to_kind\";\n targetField: \"from_id\" | \"to_id\";\n targetKindField: \"from_kind\" | \"to_kind\";\n}>;\n\nconst OUTGOING_DIRECTION_FIELDS = {\n joinField: \"from_id\",\n joinKindField: \"from_kind\",\n targetField: \"to_id\",\n targetKindField: \"to_kind\",\n} as const satisfies DirectionFields;\n\nconst INCOMING_DIRECTION_FIELDS = {\n joinField: \"to_id\",\n joinKindField: \"to_kind\",\n targetField: \"from_id\",\n targetKindField: \"from_kind\",\n} as const satisfies DirectionFields;\n\nfunction fieldsForDirection(\n direction: TraversalDirection,\n): readonly DirectionFields[] {\n switch (direction) {\n case \"out\": {\n return [OUTGOING_DIRECTION_FIELDS];\n }\n case \"in\": {\n return [INCOMING_DIRECTION_FIELDS];\n }\n case \"both\": {\n return [OUTGOING_DIRECTION_FIELDS, INCOMING_DIRECTION_FIELDS];\n }\n }\n}\n\nfunction compileDirectionUnion(\n direction: TraversalDirection,\n compileDirection: (fields: DirectionFields) => SqlFragment,\n): SqlFragment {\n return sql.join(\n fieldsForDirection(direction).map((fields) => compileDirection(fields)),\n sql` UNION ALL `,\n );\n}\n\nfunction compileExpansionQuery(\n operation: IterativeGraphOperation,\n workingSet: readonly PathNode[],\n direction: TraversalDirection,\n edgeKinds: readonly string[],\n): ReturnType<typeof sql> {\n const workingValues = sql.join(\n workingSet.map((node) => sql`(${node.id}, ${node.kind})`),\n sql`, `,\n );\n const workingCte = sql`WITH working_set(node_id, node_kind) AS (VALUES ${workingValues})`;\n\n const expansion = compileDirectionUnion(direction, (fields) =>\n compileDirectionalExpansion(\n operation,\n sql`working_set`,\n sql`TRUE`,\n edgeKinds,\n fields.joinField,\n fields.joinKindField,\n fields.targetField,\n fields.targetKindField,\n ),\n );\n return sql`${workingCte} ${expansion}`;\n}\n\nexport function compileWorkingTableExpansion(\n operation: IterativeGraphOperation,\n workingTable: WorkingTableIdentifier,\n sourceFilter: SqlFragment,\n direction: TraversalDirection,\n edgeKinds: readonly string[],\n): SqlFragment {\n return compileDirectionUnion(direction, (fields) =>\n compileDirectionalExpansion(\n operation,\n workingTable,\n sourceFilter,\n edgeKinds,\n fields.joinField,\n fields.joinKindField,\n fields.targetField,\n fields.targetKindField,\n ),\n );\n}\n\n/**\n * Expands a working-table frontier through visible edges without joining target\n * nodes. Callers that reduce duplicate targets first can defer the target-node\n * visibility join until after that reduction, avoiding repeated point lookups\n * for the same target on dense frontiers. `sourceProjection` lets callers\n * carry trusted working-row state through the expansion without re-joining it.\n */\nexport function compileWorkingTableEdgeExpansion(\n operation: IterativeGraphOperation,\n workingTable: WorkingTableIdentifier,\n sourceFilter: SqlFragment,\n direction: TraversalDirection,\n edgeKinds: readonly string[],\n sourceProjection?: SqlFragment,\n): SqlFragment {\n return compileDirectionUnion(direction, (fields) =>\n compileDirectionalEdgeExpansion(\n operation,\n workingTable,\n sourceFilter,\n edgeKinds,\n fields.joinField,\n fields.joinKindField,\n fields.targetField,\n fields.targetKindField,\n sourceProjection,\n ),\n );\n}\n\nfunction compileDirectionalExpansion(\n operation: IterativeGraphOperation,\n workingRelation: SqlFragment | WorkingTableIdentifier,\n sourceFilter: SqlFragment,\n edgeKinds: readonly string[],\n joinField: \"from_id\" | \"to_id\",\n joinKindField: \"from_kind\" | \"to_kind\",\n targetField: \"from_id\" | \"to_id\",\n targetKindField: \"from_kind\" | \"to_kind\",\n): ReturnType<typeof sql> {\n const edgeExpansion = compileDirectionalEdgeExpansion(\n operation,\n workingRelation,\n sourceFilter,\n edgeKinds,\n joinField,\n joinKindField,\n targetField,\n targetKindField,\n );\n const weightColumn =\n operation.weightExpression === undefined ? sql`` : sql`, expanded.weight`;\n return sql`SELECT expanded.source_id, expanded.source_kind, n.id AS target_id, n.kind AS target_kind${weightColumn} FROM (${edgeExpansion}) expanded JOIN ${operation.schema.nodesTable} n ON n.graph_id = ${operation.ctx.graphId} AND n.id = expanded.target_id AND n.kind = expanded.target_kind WHERE ${operation.nodeTemporalFilter}`;\n}\n\nfunction compileDirectionalEdgeExpansion(\n operation: IterativeGraphOperation,\n workingRelation: SqlFragment | WorkingTableIdentifier,\n sourceFilter: SqlFragment,\n edgeKinds: readonly string[],\n joinField: \"from_id\" | \"to_id\",\n joinKindField: \"from_kind\" | \"to_kind\",\n targetField: \"from_id\" | \"to_id\",\n targetKindField: \"from_kind\" | \"to_kind\",\n sourceProjection?: SqlFragment,\n): ReturnType<typeof sql> {\n const edgeKindFilter = compileKindFilter(sql.raw(\"e.kind\"), edgeKinds);\n const weightColumn =\n operation.weightExpression === undefined ?\n sql``\n : sql`, ${operation.weightExpression} AS weight`;\n const sourceColumns =\n sourceProjection === undefined ? sql`` : sql`, ${sourceProjection}`;\n return sql`SELECT w.node_id AS source_id, w.node_kind AS source_kind${sourceColumns}, e.${sql.raw(targetField)} AS target_id, e.${sql.raw(targetKindField)} AS target_kind${weightColumn} FROM ${workingRelation} w JOIN ${operation.schema.edgesTable} e ON e.${sql.raw(joinField)} = w.node_id AND e.${sql.raw(joinKindField)} = w.node_kind AND e.graph_id = ${operation.ctx.graphId} WHERE ${sourceFilter} AND ${edgeKindFilter} AND ${operation.edgeTemporalFilter}`;\n}\n\nfunction chunkValues<T>(\n values: readonly T[],\n chunkSize: number,\n): readonly (readonly T[])[] {\n const chunks: T[][] = [];\n for (let offset = 0; offset < values.length; offset += chunkSize) {\n chunks.push(values.slice(offset, offset + chunkSize));\n }\n return chunks;\n}\n\nfunction createOperation(\n ctx: AlgorithmContext,\n options: InternalTraversalOptions,\n backend: QueryBackend | TransactionBackend,\n): IterativeGraphOperation {\n const temporal = resolveTemporalOptions(ctx, options);\n const currentTimestamp = currentReadInstant();\n const nodeTemporalFilter = compileTemporalFilter({\n mode: temporal.temporalMode,\n ...(temporal.asOf === undefined ? {} : { asOf: temporal.asOf }),\n ...(temporal.recordedAsOf === undefined ?\n {}\n : { recordedAsOf: temporal.recordedAsOf }),\n tableAlias: \"n\",\n currentTimestamp,\n });\n const edgeTemporalFilter = compileTemporalFilter({\n mode: temporal.temporalMode,\n ...(temporal.asOf === undefined ? {} : { asOf: temporal.asOf }),\n ...(temporal.recordedAsOf === undefined ?\n {}\n : { recordedAsOf: temporal.recordedAsOf }),\n tableAlias: \"e\",\n currentTimestamp,\n });\n const weightExpression =\n options.weightProperty === undefined ?\n undefined\n : compileWeightExpression(\n ctx.dialect,\n options.weightProperty,\n options.defaultWeight,\n );\n const direction = options.direction ?? \"out\";\n const branchCount = direction === \"both\" ? 2 : 1;\n const parameterLimit =\n backend.capabilities.maxBindParameters ?? DEFAULT_MAX_BIND_PARAMETERS;\n const reservedPerBranch =\n RESERVED_TEMPORAL_BIND_PARAMETERS_PER_BRANCH +\n (weightExpression === undefined ? 0 : (\n RESERVED_WEIGHT_BIND_PARAMETERS_PER_BRANCH\n ));\n const fixedParameters = branchCount * reservedPerBranch;\n const sharedBudget = parameterLimit - fixedParameters;\n const maxEdgeKindsPerQuery = Math.floor(sharedBudget / (branchCount + 2));\n if (maxEdgeKindsPerQuery < 1) {\n throw new ConfigurationError(\n \"An iterative graph operation cannot fit its fixed filters within the backend bind-parameter limit.\",\n { parameterLimit, direction },\n );\n }\n const edgeKindChunks = chunkValues(\n [...new Set(options.edges)].toSorted((left, right) =>\n compareStrings(left, right),\n ),\n maxEdgeKindsPerQuery,\n );\n const largestEdgeKindChunk = Math.max(\n ...edgeKindChunks.map((chunk) => chunk.length),\n );\n const maxWorkingSetSize = Math.floor(\n (parameterLimit -\n branchCount * (largestEdgeKindChunk + reservedPerBranch)) /\n 2,\n );\n if (maxWorkingSetSize < 1) {\n throw new ConfigurationError(\n \"An iterative graph operation cannot fit one working-set node within the backend bind-parameter limit.\",\n { parameterLimit, direction },\n );\n }\n\n return {\n backend,\n ctx,\n edgeKindChunks,\n direction,\n maxWorkingSetSize,\n nodeTemporalFilter,\n edgeTemporalFilter,\n schema: resolveReadSchema(ctx, options),\n workingMemory: resolveWorkingMemory(options.workingMemory),\n weightExpression,\n };\n}\n\n/**\n * Compiles the per-edge weight expression over the expansion's edge alias\n * `e`. The extraction is cast to DOUBLE PRECISION — a spelling both engines\n * accept — so weight arithmetic is IEEE 754 double on both backends.\n * PostgreSQL's `::numeric` extraction would use exact decimal arithmetic and\n * could produce different accumulated distances (and therefore different\n * paths) than SQLite's binary doubles.\n *\n * The weight audit runs before any expansion, so by the time this expression\n * evaluates, every selected edge's property is a JSON number (never text the\n * cast could mangle or reject) or absent with a configured default.\n */\nfunction compileWeightExpression(\n dialect: DialectAdapter,\n weightProperty: string,\n defaultWeight: number | undefined,\n): SqlFragment {\n const extracted = dialect.jsonExtractDouble(\n sql.raw(\"e.props\"),\n jsonPointer([weightProperty]),\n );\n return defaultWeight === undefined ? extracted : (\n sql`COALESCE(${extracted}, ${defaultWeight})`\n );\n}\n\n/**\n * Whether the backend can host working-table rounds: a pinned transactional\n * connection, temporary-statement support, and `INSERT … RETURNING` for the\n * folded frontier bookkeeping. Callers without it take the inline\n * chunked-`VALUES` fallback.\n */\nexport function supportsTemporaryIteration(ctx: AlgorithmContext): boolean {\n return (\n ctx.backend.capabilities.transactions &&\n ctx.backend.capabilities.graphAnalytics?.supported !== false &&\n ctx.backend.capabilities.returning !== false &&\n ctx.backend.executeTemporaryStatement !== undefined\n );\n}\n\nfunction requireTemporaryStatements(\n backend: TransactionBackend,\n): TemporaryStatementBackend {\n if (backend.executeTemporaryStatement === undefined) {\n throw new ConfigurationError(\n \"Iterative graph operations require temporary-statement support on the transaction backend.\",\n { dialect: backend.dialect },\n {\n suggestion:\n \"Use a built-in SQLite/PostgreSQL backend or implement executeTemporaryStatement on the custom backend.\",\n },\n );\n }\n return backend as TemporaryStatementBackend;\n}\n","import type { GraphDef } from \"../../core/define-graph\";\nimport { GraphAlgorithmConvergenceError } from \"../../errors\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport {\n type AlgorithmContext,\n assertEdgeKinds,\n assertGraphAnalyticsSupported,\n compileNodeKindSeedFilter,\n type InternalTraversalOptions,\n normalizeNodeKinds,\n pickTemporalOptions,\n resolveMaxIterations,\n} from \"./context\";\nimport {\n compileWorkingTableEdgeExpansion,\n countWorkingTableRows,\n frontierIndexIdentifier,\n type IterativeGraphRunContext,\n type NodeIdentityKey,\n nodeIdentityKey,\n runIterativeGraphOperation,\n} from \"./iterative-graph-operation\";\nimport type {\n InternalLabelPropagationOptions,\n LabelPropagationMembership,\n} from \"./types\";\n\ntype IterationState = Readonly<{\n changedCount: number;\n workingTableSize: number;\n /** Fixed-round completion reached (`onMaxIterations: \"return\"` only). */\n completed: boolean;\n /** A detected oscillation needs one parity round before completing. */\n finishNextRound: boolean;\n}>;\ntype ChangedRow = Readonly<{\n node_id: string;\n node_kind: string;\n label_id: string;\n label_kind: string;\n}>;\ntype MembershipRow = Readonly<{\n node_id: string;\n node_kind: string;\n label_id: string;\n label_kind: string;\n}>;\n\ntype CompletionMode = \"return\" | \"throw\";\n\ntype RoundPolicy = Readonly<{\n detector: OscillationDetector;\n maxIterations: number;\n onMaxIterations: CompletionMode;\n}>;\n\ntype OscillationDetector = ReturnType<typeof createOscillationDetector>;\n\nconst DEFAULT_LABEL_PROPAGATION_MAX_ITERATIONS = 1000;\n\n/** Runs exact synchronous CDLP in the shared temporary-table loop. */\nexport async function executeLabelPropagation<G extends GraphDef>(\n ctx: AlgorithmContext,\n options: InternalLabelPropagationOptions<G>,\n): Promise<readonly LabelPropagationMembership[]> {\n assertEdgeKinds(options.edges);\n assertGraphAnalyticsSupported(ctx, \"labelPropagation\", {\n requiresWindowFunctions: true,\n });\n const maxIterations = resolveMaxIterations(\n options.maxIterations,\n DEFAULT_LABEL_PROPAGATION_MAX_ITERATIONS,\n \"labelPropagation\",\n );\n const nodeKinds = normalizeNodeKinds(options.nodeKinds);\n const policy: RoundPolicy = {\n detector: createOscillationDetector(),\n maxIterations,\n onMaxIterations: options.onMaxIterations ?? \"throw\",\n };\n const traversalOptions: InternalTraversalOptions = {\n edges: options.edges,\n direction: \"both\",\n ...pickTemporalOptions(options),\n ...(options.workingMemory === undefined ?\n {}\n : { workingMemory: options.workingMemory }),\n };\n\n return runIterativeGraphOperation(ctx, traversalOptions, {\n algorithm: \"labelPropagation\",\n maxIterations,\n createWorkingTable,\n initialize: (context) => initializeWorkingTables(context, nodeKinds),\n runRound: (context, state, iteration) =>\n runLabelPropagationRound(context, state, iteration, policy),\n hasConverged(state) {\n return state.changedCount === 0 || state.completed;\n },\n extractResult: extractMemberships,\n cleanup: dropNeighborTable,\n });\n}\n\n/**\n * Detects period-two oscillation from the per-round change feed. The round\n * map is a delta over a lazily built shadow labeling (every node starts as\n * its own label, and `applyNextLabels` reports every change), so a round\n * whose changes exactly invert the previous round's proves the labeling two\n * rounds back has recurred — and a deterministic synchronous rule then\n * alternates between the two labelings forever. Longer cycles are not\n * detected here and fall through to the `maxIterations` budget. Memory grows\n * with the number of distinct nodes that ever changed label.\n */\nfunction createOscillationDetector() {\n const shadowLabels = new Map<NodeIdentityKey, NodeIdentityKey>();\n let previousRound:\n | ReadonlyMap<NodeIdentityKey, Readonly<{ before: NodeIdentityKey }>>\n | undefined;\n return {\n /** Records one applied round; true when the round inverts the previous. */\n observeRound(changedRows: readonly ChangedRow[]): boolean {\n const round = new Map<\n NodeIdentityKey,\n Readonly<{ before: NodeIdentityKey; after: NodeIdentityKey }>\n >();\n for (const row of changedRows) {\n const node = nodeIdentityKey({ id: row.node_id, kind: row.node_kind });\n const after = nodeIdentityKey({\n id: row.label_id,\n kind: row.label_kind,\n });\n const before = shadowLabels.get(node) ?? node;\n round.set(node, { before, after });\n shadowLabels.set(node, after);\n }\n const priorRound = previousRound;\n previousRound = round;\n if (priorRound?.size !== round.size) return false;\n if (round.size === 0) return false;\n for (const [node, change] of round) {\n if (priorRound.get(node)?.before !== change.after) return false;\n }\n return true;\n },\n };\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext): SqlFragment {\n return sql`\n CREATE TEMP TABLE ${context.workingTable} (\n graph_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n node_id TEXT NOT NULL,\n node_kind TEXT NOT NULL,\n label_id TEXT NOT NULL,\n label_kind TEXT NOT NULL,\n next_label_id TEXT NOT NULL,\n next_label_kind TEXT NOT NULL,\n changed_round INTEGER NOT NULL,\n active_round INTEGER NOT NULL,\n PRIMARY KEY (graph_id, run_id, node_kind, node_id)\n )\n `;\n}\n\n// Single-letter discriminators before the run id keep the auxiliary relation\n// names aligned and clearly grouped per run; every name stays well inside\n// PostgreSQL's 63-byte identifier cap.\nfunction neighborTableIdentifier(context: IterativeGraphRunContext) {\n return sql.identifier(\n `typegraph_iterative_n_${context.runId.replaceAll(\"-\", \"_\")}`,\n );\n}\n\nfunction activeIndexIdentifier(context: IterativeGraphRunContext) {\n return sql.identifier(\n `typegraph_iterative_a_${context.runId.replaceAll(\"-\", \"_\")}`,\n );\n}\n\nasync function initializeWorkingTables(\n context: IterativeGraphRunContext,\n nodeKinds: readonly string[] | undefined,\n): Promise<IterationState> {\n const { operation, workingTable, graphId, runId } = context;\n const nodeKindFilter = compileNodeKindSeedFilter(nodeKinds);\n await context.executeTemporary(sql`\n INSERT INTO ${workingTable}\n (graph_id, run_id, node_id, node_kind, label_id, label_kind,\n next_label_id, next_label_kind, changed_round, active_round)\n SELECT\n ${graphId}, ${runId}, n.id, n.kind, n.id, n.kind, n.id, n.kind, 0, 1\n FROM ${operation.schema.nodesTable} n\n WHERE n.graph_id = ${graphId}\n AND ${nodeKindFilter}\n AND ${operation.nodeTemporalFilter}\n `);\n await context.executeTemporary(sql`\n CREATE INDEX ${frontierIndexIdentifier(context)}\n ON ${workingTable} (graph_id, run_id, changed_round)\n `);\n await context.executeTemporary(sql`\n CREATE INDEX ${activeIndexIdentifier(context)}\n ON ${workingTable} (graph_id, run_id, active_round)\n `);\n const neighborTable = neighborTableIdentifier(context);\n await context.executeTemporary(sql`\n CREATE TEMP TABLE ${neighborTable} (\n target_id TEXT NOT NULL,\n target_kind TEXT NOT NULL,\n neighbor_id TEXT NOT NULL,\n neighbor_kind TEXT NOT NULL,\n PRIMARY KEY (target_kind, target_id, neighbor_kind, neighbor_id)\n )\n `);\n for (const edgeKinds of operation.edgeKindChunks) {\n await materializeChunkNeighbors(context, edgeKinds);\n }\n const analyzeNeighbors =\n operation.ctx.dialect.analyzeTemporaryTable(neighborTable);\n if (analyzeNeighbors !== undefined) {\n await context.executeTemporary(analyzeNeighbors);\n }\n\n const workingTableSize = await countWorkingTableRows(context);\n return {\n changedCount: workingTableSize,\n workingTableSize,\n completed: false,\n finishNextRound: false,\n };\n}\n\nasync function runLabelPropagationRound(\n context: IterativeGraphRunContext,\n state: IterationState,\n iteration: number,\n policy: RoundPolicy,\n): Promise<IterationState> {\n // Every node owns a distinct initial label, so every non-isolated node votes\n // in round one. Later rounds activate only neighbors of the changed frontier.\n if (iteration > 1) {\n await markActiveNeighbors(context, iteration);\n }\n await selectWinningLabels(context, iteration);\n const changedRows = await applyNextLabels(context, iteration);\n const next: IterationState = {\n changedCount: changedRows.length,\n workingTableSize: state.workingTableSize,\n completed: false,\n finishNextRound: false,\n };\n if (next.changedCount === 0) return next;\n if (state.finishNextRound) return { ...next, completed: true };\n if (policy.detector.observeRound(changedRows)) {\n return resolveOscillation(next, iteration, policy);\n }\n if (\n policy.onMaxIterations === \"return\" &&\n iteration === policy.maxIterations\n ) {\n return { ...next, completed: true };\n }\n return next;\n}\n\n/**\n * The labeling two rounds back has recurred, so the synchronous rule now\n * alternates between two labelings forever. The fixed-round result is fully\n * determined by parity: an even remainder is this round's labeling, an odd\n * remainder is the next round's.\n */\nfunction resolveOscillation(\n state: IterationState,\n iteration: number,\n policy: RoundPolicy,\n): IterationState {\n if (policy.onMaxIterations === \"throw\") {\n throw new GraphAlgorithmConvergenceError(\n \"labelPropagation\",\n policy.maxIterations,\n { oscillating: true },\n );\n }\n const remaining = policy.maxIterations - iteration;\n if (remaining % 2 === 0) return { ...state, completed: true };\n return { ...state, finishNextRound: true };\n}\n\n/** Marks exactly the nodes whose vote multiset may have changed this round. */\nasync function markActiveNeighbors(\n context: IterativeGraphRunContext,\n iteration: number,\n): Promise<void> {\n const { workingTable, graphId, runId } = context;\n const neighborTable = neighborTableIdentifier(context);\n // The neighbor relation is symmetric — materialization inserts both\n // orientations of every visible edge — so probing the primary-key prefix by\n // target and reading the neighbor columns enumerates the same adjacency as\n // a dedicated reverse index would, without paying for one.\n await context.executeTemporary(sql`\n WITH candidates AS (\n SELECT DISTINCT neighbors.neighbor_id, neighbors.neighbor_kind\n FROM ${workingTable} changed\n JOIN ${neighborTable} neighbors\n ON neighbors.target_id = changed.node_id\n AND neighbors.target_kind = changed.node_kind\n WHERE changed.graph_id = ${graphId}\n AND changed.run_id = ${runId}\n AND changed.changed_round = ${iteration - 1}\n )\n UPDATE ${workingTable} AS target\n SET active_round = ${iteration}\n FROM candidates\n WHERE target.graph_id = ${graphId}\n AND target.run_id = ${runId}\n AND target.node_id = candidates.neighbor_id\n AND target.node_kind = candidates.neighbor_kind\n `);\n}\n\n/**\n * Materializes one bind-budget edge-kind chunk into the immutable neighbor\n * relation. The primary key collapses parallel edges and duplicate neighbors\n * across chunks; self-loops are excluded because a node is not its own\n * neighbor for CDLP.\n */\nasync function materializeChunkNeighbors(\n context: IterativeGraphRunContext,\n edgeKinds: readonly string[],\n): Promise<void> {\n const { operation, workingTable, graphId, runId } = context;\n const expansion = compileWorkingTableEdgeExpansion(\n operation,\n workingTable,\n sql`\n w.graph_id = ${graphId}\n AND w.run_id = ${runId}\n `,\n \"both\",\n edgeKinds,\n );\n const neighborTable = neighborTableIdentifier(context);\n await context.executeTemporary(sql`\n INSERT INTO ${neighborTable}\n (target_id, target_kind, neighbor_id, neighbor_kind)\n SELECT DISTINCT\n expanded.source_id,\n expanded.source_kind,\n expanded.target_id,\n expanded.target_kind\n FROM (${expansion}) expanded\n JOIN ${workingTable} scoped_neighbor\n ON scoped_neighbor.graph_id = ${graphId}\n AND scoped_neighbor.run_id = ${runId}\n AND scoped_neighbor.node_id = expanded.target_id\n AND scoped_neighbor.node_kind = expanded.target_kind\n WHERE expanded.source_id <> expanded.target_id\n OR expanded.source_kind <> expanded.target_kind\n ON CONFLICT (target_kind, target_id, neighbor_kind, neighbor_id)\n DO NOTHING\n `);\n}\n\nasync function selectWinningLabels(\n context: IterativeGraphRunContext,\n iteration: number,\n): Promise<void> {\n const { operation, workingTable, graphId, runId } = context;\n const neighborTable = neighborTableIdentifier(context);\n const targetId = operation.ctx.dialect.binaryText(sql`totals.target_id`);\n const targetKind = operation.ctx.dialect.binaryText(sql`totals.target_kind`);\n const labelId = operation.ctx.dialect.binaryText(sql`totals.label_id`);\n const labelKind = operation.ctx.dialect.binaryText(sql`totals.label_kind`);\n await context.executeTemporary(sql`\n WITH totals AS (\n SELECT\n neighbors.target_id,\n neighbors.target_kind,\n neighbor.label_id,\n neighbor.label_kind,\n COUNT(*) AS total_votes\n FROM ${neighborTable} neighbors\n JOIN ${workingTable} active\n ON active.graph_id = ${graphId}\n AND active.run_id = ${runId}\n AND active.active_round = ${iteration}\n AND active.node_id = neighbors.target_id\n AND active.node_kind = neighbors.target_kind\n JOIN ${workingTable} neighbor\n ON neighbor.graph_id = ${graphId}\n AND neighbor.run_id = ${runId}\n AND neighbor.node_id = neighbors.neighbor_id\n AND neighbor.node_kind = neighbors.neighbor_kind\n GROUP BY\n target_id,\n target_kind,\n neighbor.label_id,\n neighbor.label_kind\n ), ranked AS (\n SELECT\n target_id,\n target_kind,\n label_id,\n label_kind,\n ROW_NUMBER() OVER (\n PARTITION BY ${targetKind}, ${targetId}\n ORDER BY total_votes DESC, ${labelId}, ${labelKind}\n ) AS label_rank\n FROM totals\n )\n UPDATE ${workingTable} AS target\n SET next_label_id = ranked.label_id,\n next_label_kind = ranked.label_kind\n FROM ranked\n WHERE target.graph_id = ${graphId}\n AND target.run_id = ${runId}\n AND target.active_round = ${iteration}\n AND target.node_id = ranked.target_id\n AND target.node_kind = ranked.target_kind\n AND ranked.label_rank = 1\n AND (\n target.next_label_id <> ranked.label_id\n OR target.next_label_kind <> ranked.label_kind\n )\n `);\n}\n\nfunction applyNextLabels(\n context: IterativeGraphRunContext,\n iteration: number,\n): Promise<readonly ChangedRow[]> {\n // Only rows selectWinningLabels staged this round can diverge, and it stages\n // active rows exclusively, so the active index bounds this scan by the\n // frontier instead of the whole working table.\n return context.backend.execute<ChangedRow>(\n asCompiledRowsSql(sql`\n UPDATE ${context.workingTable}\n SET label_id = next_label_id,\n label_kind = next_label_kind,\n changed_round = ${iteration}\n WHERE graph_id = ${context.graphId}\n AND run_id = ${context.runId}\n AND active_round = ${iteration}\n AND (\n label_id <> next_label_id OR label_kind <> next_label_kind\n )\n RETURNING node_id, node_kind, label_id, label_kind\n `),\n );\n}\n\nasync function extractMemberships(\n context: IterativeGraphRunContext,\n): Promise<readonly LabelPropagationMembership[]> {\n const { operation } = context;\n const labelId = operation.ctx.dialect.binaryText(sql`label_id`);\n const labelKind = operation.ctx.dialect.binaryText(sql`label_kind`);\n const nodeId = operation.ctx.dialect.binaryText(sql`node_id`);\n const nodeKind = operation.ctx.dialect.binaryText(sql`node_kind`);\n const rows = await context.backend.execute<MembershipRow>(\n asCompiledRowsSql(sql`\n SELECT\n node_id,\n node_kind,\n label_id,\n label_kind\n FROM ${context.workingTable}\n WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n ORDER BY ${labelId}, ${labelKind}, ${nodeId}, ${nodeKind}\n `),\n );\n\n return rows.map((row) => ({\n id: row.node_id,\n kind: row.node_kind,\n labelId: row.label_id,\n labelKind: row.label_kind,\n }));\n}\n\nasync function dropNeighborTable(\n context: IterativeGraphRunContext,\n): Promise<void> {\n await context.executeTemporary(\n sql`DROP TABLE IF EXISTS ${neighborTableIdentifier(context)}`,\n );\n}\n","import type { GraphDef } from \"../../core/define-graph\";\nimport { ConfigurationError } from \"../../errors\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport {\n type AlgorithmContext,\n assertEdgeKinds,\n assertGraphAnalyticsSupported,\n compileNodeKindSeedFilter,\n type InternalTraversalOptions,\n normalizeNodeKinds,\n pickTemporalOptions,\n resolveMaxIterations,\n} from \"./context\";\nimport {\n compareNodeIdentity,\n compileWorkingTableEdgeExpansion,\n countWorkingTableRows,\n DEFAULT_MAX_BIND_PARAMETERS,\n type IterativeGraphRunContext,\n type NodeIdentityKey,\n nodeIdentityKey,\n runIterativeGraphOperation,\n} from \"./iterative-graph-operation\";\nimport type {\n InternalPageRankOptions,\n InternalPersonalizedPageRankOptions,\n PageRankScore,\n PersonalizedPageRankSeed,\n TraversalDirection,\n} from \"./types\";\n\ntype IterationState = Readonly<{\n activeScoreColumn: ScoreColumn;\n maximumChange: number;\n workingTableSize: number;\n}>;\n\ntype ScoreColumn = \"next_score\" | \"score\";\n\ntype ResolvedPageRankOptions = Readonly<{\n dampingFactor: number;\n tolerance: number;\n maxIterations: number;\n nodeKinds: readonly string[] | undefined;\n}>;\n\ntype PageRankAlgorithm = \"pageRank\" | \"personalizedPageRank\";\n\ntype NormalizedSeed = Readonly<{\n id: string;\n kind: string;\n weight: number;\n}>;\n\ntype MetricRow = Readonly<{ value: number | string | null }>;\ntype IdentityRow = Readonly<{ node_id: string; node_kind: string }>;\ntype ScoreRow = Readonly<{\n node_id: string;\n node_kind: string;\n score: number | string;\n}>;\n\nconst DEFAULT_DAMPING_FACTOR = 0.85;\nconst DEFAULT_TOLERANCE = 1e-8;\nconst DEFAULT_MAX_ITERATIONS = 1000;\n/** Each seed VALUES row binds its id, kind, and weight. */\nconst BIND_PARAMETERS_PER_SEED = 3;\n/** The seed UPDATE statement also binds the graph and run identifiers. */\nconst RESERVED_SEED_STATEMENT_BIND_PARAMETERS = 2;\n\n/** Computes global PageRank with a uniform teleport distribution. */\nexport async function executePageRank<G extends GraphDef>(\n ctx: AlgorithmContext,\n options: InternalPageRankOptions<G>,\n): Promise<readonly PageRankScore[]> {\n return executePageRankOperation(ctx, options, undefined);\n}\n\n/** Computes personalized PageRank with a weighted multi-seed teleport vector. */\nexport async function executePersonalizedPageRank<G extends GraphDef>(\n ctx: AlgorithmContext,\n options: InternalPersonalizedPageRankOptions<G>,\n): Promise<readonly PageRankScore[]> {\n return executePageRankOperation(ctx, options, normalizeSeeds(options.seeds));\n}\n\nfunction executePageRankOperation<G extends GraphDef>(\n ctx: AlgorithmContext,\n options: InternalPageRankOptions<G>,\n seeds: readonly NormalizedSeed[] | undefined,\n): Promise<readonly PageRankScore[]> {\n const algorithm: PageRankAlgorithm =\n seeds === undefined ? \"pageRank\" : \"personalizedPageRank\";\n assertEdgeKinds(options.edges);\n assertGraphAnalyticsSupported(ctx, algorithm);\n const resolved = resolvePageRankOptions(options, algorithm);\n const traversalOptions: InternalTraversalOptions = {\n edges: options.edges,\n direction: options.direction ?? \"out\",\n ...pickTemporalOptions(options),\n ...(options.workingMemory === undefined ?\n {}\n : { workingMemory: options.workingMemory }),\n };\n\n return runIterativeGraphOperation(ctx, traversalOptions, {\n algorithm,\n maxIterations: resolved.maxIterations,\n createWorkingTable,\n initialize: (context) =>\n initializeWorkingTable(context, resolved.nodeKinds, seeds),\n runRound: (context, state) =>\n runPowerIterationRound(context, state, resolved.dampingFactor),\n hasConverged(state) {\n return state.maximumChange <= resolved.tolerance;\n },\n extractResult: extractScores,\n });\n}\n\nfunction resolvePageRankOptions<G extends GraphDef>(\n options: InternalPageRankOptions<G>,\n algorithm: PageRankAlgorithm,\n): ResolvedPageRankOptions {\n const dampingFactor = options.dampingFactor ?? DEFAULT_DAMPING_FACTOR;\n if (\n !Number.isFinite(dampingFactor) ||\n dampingFactor < 0 ||\n dampingFactor >= 1\n ) {\n throw new ConfigurationError(\n `PageRank dampingFactor must be finite and in [0, 1), got ${String(dampingFactor)}.`,\n { dampingFactor },\n );\n }\n\n const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;\n if (!Number.isFinite(tolerance) || tolerance <= 0) {\n throw new ConfigurationError(\n `PageRank tolerance must be finite and greater than 0, got ${String(tolerance)}.`,\n { tolerance },\n );\n }\n\n return {\n dampingFactor,\n tolerance,\n maxIterations: resolveMaxIterations(\n options.maxIterations,\n DEFAULT_MAX_ITERATIONS,\n algorithm,\n ),\n nodeKinds: normalizeNodeKinds(options.nodeKinds),\n };\n}\n\nfunction normalizeSeeds<G extends GraphDef>(\n seeds: readonly PersonalizedPageRankSeed<G>[],\n): readonly NormalizedSeed[] {\n if (seeds.length === 0) {\n throw new ConfigurationError(\n \"Personalized PageRank requires at least one seed.\",\n { seeds },\n );\n }\n\n const combined = new Map<NodeIdentityKey, NormalizedSeed>();\n for (const seed of seeds) {\n // Node-identity keys join kind and id with a NUL separator, so an\n // embedded NUL could alias two distinct seeds onto one key.\n if (\n typeof seed.id !== \"string\" ||\n seed.id.length === 0 ||\n seed.id.includes(\"\\u0000\") ||\n typeof seed.kind !== \"string\" ||\n seed.kind.length === 0 ||\n seed.kind.includes(\"\\u0000\")\n ) {\n throw new ConfigurationError(\n \"Personalized PageRank seed id and kind must be non-empty strings without NUL characters.\",\n { seed },\n );\n }\n const weight = seed.weight ?? 1;\n if (!Number.isFinite(weight) || weight <= 0) {\n throw new ConfigurationError(\n `Personalized PageRank seed weight must be finite and greater than 0, got ${String(weight)}.`,\n { seed },\n );\n }\n const key = nodeIdentityKey(seed);\n const previous = combined.get(key);\n const combinedWeight = (previous?.weight ?? 0) + weight;\n if (!Number.isFinite(combinedWeight)) {\n throw new ConfigurationError(\n \"Personalized PageRank seed weights overflowed while combining duplicate seeds.\",\n { seed },\n );\n }\n combined.set(key, { id: seed.id, kind: seed.kind, weight: combinedWeight });\n }\n\n const combinedSeeds = [...combined.values()];\n let maximumWeight = 0;\n for (const seed of combinedSeeds) {\n maximumWeight = Math.max(maximumWeight, seed.weight);\n }\n const scaledTotal = combinedSeeds.reduce(\n (total, seed) => total + seed.weight / maximumWeight,\n 0,\n );\n return combinedSeeds\n .map((seed) => {\n const weight = seed.weight / maximumWeight / scaledTotal;\n if (weight === 0) {\n throw new ConfigurationError(\n \"Personalized PageRank seed weights differ too much to normalize without underflow.\",\n { seed },\n );\n }\n return { id: seed.id, kind: seed.kind, weight };\n })\n .toSorted((left, right) => compareNodeIdentity(left, right));\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext): SqlFragment {\n return sql`\n CREATE TEMP TABLE ${context.workingTable} (\n graph_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n node_id TEXT NOT NULL,\n node_kind TEXT NOT NULL,\n score DOUBLE PRECISION NOT NULL,\n next_score DOUBLE PRECISION NOT NULL,\n personalization DOUBLE PRECISION NOT NULL,\n out_weight DOUBLE PRECISION NOT NULL,\n PRIMARY KEY (graph_id, run_id, node_kind, node_id)\n )\n `;\n}\n\nasync function initializeWorkingTable(\n context: IterativeGraphRunContext,\n nodeKinds: readonly string[] | undefined,\n seeds: readonly NormalizedSeed[] | undefined,\n): Promise<IterationState> {\n const { operation, workingTable, graphId, runId } = context;\n const nodeKindFilter = compileNodeKindSeedFilter(nodeKinds);\n await context.executeTemporary(sql`\n INSERT INTO ${workingTable}\n (graph_id, run_id, node_id, node_kind, score, next_score,\n personalization, out_weight)\n SELECT ${graphId}, ${runId}, n.id, n.kind, 0.0, 0.0, 0.0, 0.0\n FROM ${operation.schema.nodesTable} n\n WHERE n.graph_id = ${graphId}\n AND ${nodeKindFilter}\n AND ${operation.nodeTemporalFilter}\n `);\n\n const workingTableSize = await countWorkingTableRows(context);\n if (workingTableSize === 0) {\n if (seeds !== undefined) {\n throw missingSeedError(seeds);\n }\n return {\n activeScoreColumn: \"score\",\n maximumChange: 0,\n workingTableSize,\n };\n }\n\n if (seeds === undefined) {\n const uniformWeight = 1 / workingTableSize;\n await context.executeTemporary(sql`\n UPDATE ${workingTable}\n SET score = ${uniformWeight},\n personalization = ${uniformWeight}\n WHERE graph_id = ${graphId} AND run_id = ${runId}\n `);\n } else {\n await initializePersonalization(context, seeds);\n }\n\n for (const edgeKinds of operation.edgeKindChunks) {\n await accumulateOutWeights(context, edgeKinds);\n }\n return {\n activeScoreColumn: \"score\",\n maximumChange: Number.POSITIVE_INFINITY,\n workingTableSize,\n };\n}\n\nasync function initializePersonalization(\n context: IterativeGraphRunContext,\n seeds: readonly NormalizedSeed[],\n): Promise<void> {\n const parameterLimit =\n context.operation.backend.capabilities.maxBindParameters ??\n DEFAULT_MAX_BIND_PARAMETERS;\n const seedChunkSize = Math.floor(\n (parameterLimit - RESERVED_SEED_STATEMENT_BIND_PARAMETERS) /\n BIND_PARAMETERS_PER_SEED,\n );\n if (seedChunkSize < 1) {\n throw new ConfigurationError(\n \"Personalized PageRank cannot fit one seed within the backend bind-parameter limit.\",\n { parameterLimit },\n );\n }\n\n for (let offset = 0; offset < seeds.length; offset += seedChunkSize) {\n const chunk = seeds.slice(offset, offset + seedChunkSize);\n const values = sql.join(\n chunk.map(\n (seed) =>\n sql`(${seed.id}, ${seed.kind}, CAST(${seed.weight} AS DOUBLE PRECISION))`,\n ),\n sql`, `,\n );\n await context.executeTemporary(sql`\n WITH seed_values(node_id, node_kind, weight) AS (VALUES ${values})\n UPDATE ${context.workingTable} AS target\n SET score = seed_values.weight,\n personalization = seed_values.weight\n FROM seed_values\n WHERE target.graph_id = ${context.graphId}\n AND target.run_id = ${context.runId}\n AND target.node_id = seed_values.node_id\n AND target.node_kind = seed_values.node_kind\n `);\n }\n\n const matchedRows = await context.backend.execute<IdentityRow>(\n asCompiledRowsSql(sql`\n SELECT node_id, node_kind\n FROM ${context.workingTable}\n WHERE graph_id = ${context.graphId}\n AND run_id = ${context.runId}\n AND personalization > 0\n `),\n );\n const matched = new Set(\n matchedRows.map((row) =>\n nodeIdentityKey({ id: row.node_id, kind: row.node_kind }),\n ),\n );\n const missing = seeds.filter((seed) => !matched.has(nodeIdentityKey(seed)));\n if (missing.length > 0) throw missingSeedError(missing);\n}\n\nfunction missingSeedError(\n seeds: readonly NormalizedSeed[],\n): ConfigurationError {\n return new ConfigurationError(\n \"Personalized PageRank seeds must identify visible nodes inside the selected induced subgraph.\",\n { missingSeeds: seeds.map((seed) => ({ id: seed.id, kind: seed.kind })) },\n );\n}\n\nasync function accumulateOutWeights(\n context: IterativeGraphRunContext,\n edgeKinds: readonly string[],\n): Promise<void> {\n const { operation, workingTable, graphId, runId } = context;\n const expansion = compileWorkingTableEdgeExpansion(\n operation,\n workingTable,\n sql`w.graph_id = ${graphId} AND w.run_id = ${runId}`,\n operation.direction,\n edgeKinds,\n );\n const transitionWeight = compileTransitionWeight(operation.direction);\n\n await context.executeTemporary(sql`\n WITH scoped_edges AS (\n SELECT\n expanded.source_id,\n expanded.source_kind,\n ${transitionWeight} AS transition_weight\n FROM (${expansion}) expanded\n JOIN ${workingTable} scoped_target\n ON scoped_target.graph_id = ${graphId}\n AND scoped_target.run_id = ${runId}\n AND scoped_target.node_id = expanded.target_id\n AND scoped_target.node_kind = expanded.target_kind\n ), degrees AS (\n SELECT source_id, source_kind, SUM(transition_weight) AS out_weight\n FROM scoped_edges\n GROUP BY source_id, source_kind\n )\n UPDATE ${workingTable} AS target\n SET out_weight = target.out_weight + degrees.out_weight\n FROM degrees\n WHERE target.graph_id = ${graphId}\n AND target.run_id = ${runId}\n AND target.node_id = degrees.source_id\n AND target.node_kind = degrees.source_kind\n `);\n}\n\nfunction compileTransitionWeight(direction: TraversalDirection): SqlFragment {\n if (direction !== \"both\") return sql`1.0`;\n // `both` emits one row per edge endpoint. A self-loop appears in both\n // branches, so each incidence contributes one half and the physical edge\n // retains total transition weight one. Parallel self-loops remain distinct.\n return sql`\n CASE\n WHEN expanded.source_id = expanded.target_id\n AND expanded.source_kind = expanded.target_kind\n THEN 0.5\n ELSE 1.0\n END\n `;\n}\n\nasync function runPowerIterationRound(\n context: IterativeGraphRunContext,\n state: IterationState,\n dampingFactor: number,\n): Promise<IterationState> {\n const sourceScoreColumn = state.activeScoreColumn;\n const targetScoreColumn: ScoreColumn =\n sourceScoreColumn === \"score\" ? \"next_score\" : \"score\";\n await resetTargetScores(\n context,\n sourceScoreColumn,\n targetScoreColumn,\n dampingFactor,\n );\n\n for (const edgeKinds of context.operation.edgeKindChunks) {\n await accumulateContributions(\n context,\n edgeKinds,\n dampingFactor,\n sourceScoreColumn,\n targetScoreColumn,\n );\n }\n\n const maximumChange = await readMaximumChange(\n context,\n sourceScoreColumn,\n targetScoreColumn,\n );\n return {\n activeScoreColumn: targetScoreColumn,\n maximumChange,\n workingTableSize: state.workingTableSize,\n };\n}\n\nasync function resetTargetScores(\n context: IterativeGraphRunContext,\n sourceScoreColumn: ScoreColumn,\n targetScoreColumn: ScoreColumn,\n dampingFactor: number,\n): Promise<void> {\n const sourceScore = sql.identifier(sourceScoreColumn);\n const targetScore = sql.identifier(targetScoreColumn);\n await context.executeTemporary(sql`\n UPDATE ${context.workingTable}\n SET ${targetScore} = personalization * (\n ${1 - dampingFactor} + ${dampingFactor} * (\n SELECT COALESCE(SUM(dangling.${sourceScore}), 0.0)\n FROM ${context.workingTable} dangling\n WHERE dangling.graph_id = ${context.graphId}\n AND dangling.run_id = ${context.runId}\n AND dangling.out_weight = 0.0\n )\n )\n WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n `);\n}\n\nasync function accumulateContributions(\n context: IterativeGraphRunContext,\n edgeKinds: readonly string[],\n dampingFactor: number,\n sourceScoreColumn: ScoreColumn,\n targetScoreColumn: ScoreColumn,\n): Promise<void> {\n const { operation, workingTable, graphId, runId } = context;\n const sourceScore = sql.identifier(sourceScoreColumn);\n const targetScore = sql.identifier(targetScoreColumn);\n const expansion = compileWorkingTableEdgeExpansion(\n operation,\n workingTable,\n sql`w.graph_id = ${graphId} AND w.run_id = ${runId}`,\n operation.direction,\n edgeKinds,\n sql`w.${sourceScore} AS source_score, w.out_weight AS source_out_weight`,\n );\n const transitionWeight = compileTransitionWeight(operation.direction);\n\n await context.executeTemporary(sql`\n WITH scoped_edges AS (\n SELECT\n expanded.target_id,\n expanded.target_kind,\n expanded.source_score,\n expanded.source_out_weight,\n ${transitionWeight} AS transition_weight\n FROM (${expansion}) expanded\n JOIN ${workingTable} scoped_target\n ON scoped_target.graph_id = ${graphId}\n AND scoped_target.run_id = ${runId}\n AND scoped_target.node_id = expanded.target_id\n AND scoped_target.node_kind = expanded.target_kind\n WHERE expanded.source_out_weight > 0.0\n ), contributions AS (\n SELECT\n target_id,\n target_kind,\n SUM(source_score * transition_weight / source_out_weight) AS score\n FROM scoped_edges\n GROUP BY target_id, target_kind\n )\n UPDATE ${workingTable} AS target\n SET ${targetScore} = target.${targetScore} + ${dampingFactor} * contributions.score\n FROM contributions\n WHERE target.graph_id = ${graphId}\n AND target.run_id = ${runId}\n AND target.node_id = contributions.target_id\n AND target.node_kind = contributions.target_kind\n `);\n}\n\nasync function readMaximumChange(\n context: IterativeGraphRunContext,\n sourceScoreColumn: ScoreColumn,\n targetScoreColumn: ScoreColumn,\n): Promise<number> {\n const sourceScore = sql.identifier(sourceScoreColumn);\n const targetScore = sql.identifier(targetScoreColumn);\n const rows = await context.backend.execute<MetricRow>(\n asCompiledRowsSql(sql`\n SELECT COALESCE(MAX(ABS(${targetScore} - ${sourceScore})), 0.0) AS value\n FROM ${context.workingTable}\n WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n `),\n );\n return Number(rows[0]?.value ?? 0);\n}\n\nasync function extractScores(\n context: IterativeGraphRunContext,\n state: IterationState,\n): Promise<readonly PageRankScore[]> {\n const score = sql.identifier(state.activeScoreColumn);\n const nodeId = context.operation.ctx.dialect.binaryText(sql`node_id`);\n const nodeKind = context.operation.ctx.dialect.binaryText(sql`node_kind`);\n const rows = await context.backend.execute<ScoreRow>(\n asCompiledRowsSql(sql`\n SELECT node_id, node_kind, ${score} AS score\n FROM ${context.workingTable}\n WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n ORDER BY ${score} DESC, ${nodeId}, ${nodeKind}\n `),\n );\n return rows.map((row) => ({\n id: row.node_id,\n kind: row.node_kind,\n score: Number(row.score),\n }));\n}\n","import { sql } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport { requireDefined } from \"../../utils/presence\";\nimport type { AlgorithmContext, InternalTraversalOptions } from \"./context\";\nimport {\n compareNodeIdentity,\n compileWorkingTableEdgeExpansion,\n compileWorkingTableExpansion,\n fetchVisibleWorkingNodes,\n type IterativeGraphOperation,\n type IterativeGraphRunContext,\n type NodeExpansion,\n type NodeIdentityKey,\n nodeIdentityKey,\n nodeIdentityKeyFromRow,\n reduceExpandedWorkingSet,\n runIterativeGraphOperation,\n supportsTemporaryIteration,\n withInlineIterativeGraphOperation,\n} from \"./iterative-graph-operation\";\nimport type {\n PathNode,\n ReachableNode,\n ShortestPathResult,\n TraversalDirection,\n} from \"./types\";\n\ntype FrontierCandidate = Readonly<{\n id: string;\n kind: string;\n parentId: string;\n parentKind: string;\n}>;\n\ntype VisitedNode = Readonly<{\n id: string;\n kind: string;\n depth: number;\n parentKey: NodeIdentityKey | undefined;\n}>;\n\ntype WorkingRow = Readonly<{\n side: WorkingSide;\n node_id: string;\n node_kind: string;\n depth: number | string;\n predecessor_id: unknown;\n predecessor_kind: unknown;\n}>;\n\ntype InsertedRow = Readonly<{ node_id: string }>;\ntype SeededRow = Readonly<{ node_id: string; node_kind: string }>;\ntype InsertedFrontierRow = Readonly<{\n node_id: string;\n node_kind: string;\n meeting_depth: unknown;\n}>;\ntype WorkingSide = \"forward\" | \"reverse\";\n\ntype MeetingNode = Readonly<{\n id: string;\n kind: string;\n depth: number;\n}>;\n\ntype FrontierRound = Readonly<{\n insertedCount: number;\n meeting: MeetingNode | undefined;\n}>;\n\nexport async function findReachableNodes(\n ctx: AlgorithmContext,\n sourceId: string,\n maxHops: number,\n options: InternalTraversalOptions,\n): Promise<readonly ReachableNode[]> {\n if (supportsTemporaryIteration(ctx)) {\n return findReachableNodesInWorkingTable(ctx, sourceId, maxHops, options);\n }\n return findReachableNodesInline(ctx, sourceId, maxHops, options);\n}\n\nexport async function findShortestPath(\n ctx: AlgorithmContext,\n sourceId: string,\n targetId: string,\n maxHops: number,\n options: InternalTraversalOptions,\n): Promise<ShortestPathResult | undefined> {\n if (supportsTemporaryIteration(ctx)) {\n return findShortestPathInWorkingTable(\n ctx,\n sourceId,\n targetId,\n maxHops,\n options,\n );\n }\n return findShortestPathInline(ctx, sourceId, targetId, maxHops, options);\n}\n\nasync function findReachableNodesInWorkingTable(\n ctx: AlgorithmContext,\n sourceId: string,\n maxHops: number,\n options: InternalTraversalOptions,\n): Promise<readonly ReachableNode[]> {\n return runIterativeGraphOperation(ctx, options, {\n algorithm: \"reachable\",\n maxIterations: maxHops,\n createWorkingTable,\n async initialize(context) {\n const seeded = await seedWorkingSide(context, sourceId, \"forward\");\n return {\n depth: 0,\n frontierCount: seeded.length,\n workingTableSize: seeded.length,\n };\n },\n async runRound(context, state) {\n const nextDepth = state.depth + 1;\n const frontierCount = await expandReachableWorkingTableRound(\n context,\n \"forward\",\n state.depth,\n nextDepth,\n context.operation.direction,\n );\n return {\n depth: nextDepth,\n frontierCount,\n workingTableSize: state.workingTableSize + frontierCount,\n };\n },\n hasConverged(state) {\n return state.frontierCount === 0 || state.depth >= maxHops;\n },\n async extractResult(context) {\n const rows = await readWorkingRows(context, \"forward\");\n return rows\n .map((row) => ({\n id: row.node_id,\n kind: row.node_kind,\n depth: Number(row.depth),\n }))\n .toSorted(\n (left, right) =>\n left.depth - right.depth || compareNodeIdentity(left, right),\n );\n },\n });\n}\n\nasync function findShortestPathInWorkingTable(\n ctx: AlgorithmContext,\n sourceId: string,\n targetId: string,\n maxHops: number,\n options: InternalTraversalOptions,\n): Promise<ShortestPathResult | undefined> {\n return runIterativeGraphOperation(ctx, options, {\n algorithm: \"shortestPath\",\n maxIterations: maxHops,\n createWorkingTable,\n async initialize(context) {\n const forwardSeeds = await seedWorkingSide(context, sourceId, \"forward\");\n const reverseSeeds = await seedWorkingSide(context, targetId, \"reverse\");\n return {\n forwardDepth: 0,\n reverseDepth: 0,\n forwardFrontierCount: forwardSeeds.length,\n reverseFrontierCount: reverseSeeds.length,\n meeting: findSeedMeeting(forwardSeeds, reverseSeeds),\n workingTableSize: forwardSeeds.length + reverseSeeds.length,\n };\n },\n async runRound(context, state) {\n const expandForward =\n state.forwardFrontierCount <= state.reverseFrontierCount;\n const side = expandForward ? \"forward\" : \"reverse\";\n const currentDepth =\n expandForward ? state.forwardDepth : state.reverseDepth;\n const nextDepth = currentDepth + 1;\n const direction =\n expandForward ?\n context.operation.direction\n : reverseDirection(context.operation.direction);\n const round = await expandWorkingTableRound(\n context,\n side,\n currentDepth,\n nextDepth,\n direction,\n maxHops,\n );\n\n return {\n forwardDepth: expandForward ? nextDepth : state.forwardDepth,\n reverseDepth: expandForward ? state.reverseDepth : nextDepth,\n forwardFrontierCount:\n expandForward ? round.insertedCount : state.forwardFrontierCount,\n reverseFrontierCount:\n expandForward ? state.reverseFrontierCount : round.insertedCount,\n meeting: round.meeting,\n workingTableSize: state.workingTableSize + round.insertedCount,\n };\n },\n hasConverged(state) {\n return (\n state.meeting !== undefined ||\n state.forwardFrontierCount === 0 ||\n state.reverseFrontierCount === 0 ||\n state.forwardDepth + state.reverseDepth >= maxHops\n );\n },\n async extractResult(context, state) {\n if (state.meeting === undefined) return;\n const rows = await readWorkingRows(context);\n return buildShortestPath(\n nodeIdentityKey(state.meeting),\n createVisitedMapFromRows(rows, \"forward\"),\n createVisitedMapFromRows(rows, \"reverse\"),\n );\n },\n });\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext) {\n return sql`\n CREATE TEMP TABLE ${context.workingTable} (\n graph_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n side TEXT NOT NULL,\n node_id TEXT NOT NULL,\n node_kind TEXT NOT NULL,\n depth INTEGER NOT NULL,\n predecessor_id TEXT,\n predecessor_kind TEXT,\n meeting_depth INTEGER,\n PRIMARY KEY (graph_id, run_id, side, node_kind, node_id)\n )\n `;\n}\n\n/**\n * Seeds one traversal side and returns the seeded node identities from the\n * same statement, so the caller reads the frontier size (and, for\n * bidirectional search, the source-equals-target meeting) without a\n * follow-up COUNT round-trip.\n */\nasync function seedWorkingSide(\n context: IterativeGraphRunContext,\n nodeId: string,\n side: WorkingSide,\n): Promise<readonly SeededRow[]> {\n const { operation, workingTable, graphId, runId } = context;\n return context.backend.execute<SeededRow>(\n asCompiledRowsSql(sql`\n INSERT INTO ${workingTable}\n (graph_id, run_id, side, node_id, node_kind, depth,\n predecessor_id, predecessor_kind)\n SELECT ${graphId}, ${runId}, ${side}, n.id, n.kind, 0, NULL, NULL\n FROM ${operation.schema.nodesTable} n\n WHERE n.graph_id = ${graphId}\n AND n.id = ${nodeId}\n AND ${operation.nodeTemporalFilter}\n ON CONFLICT (graph_id, run_id, side, node_kind, node_id) DO NOTHING\n RETURNING node_id, node_kind\n `),\n );\n}\n\n/**\n * Detects the depth-zero meeting for bidirectional search: a node seeded on\n * both sides (source equals target, possibly across kinds sharing that id).\n * Ties break by node id then kind in code-point order — deterministic\n * and identical on both backends, unlike the collation-dependent SQL probe\n * this replaced.\n */\nfunction findSeedMeeting(\n forwardSeeds: readonly SeededRow[],\n reverseSeeds: readonly SeededRow[],\n): MeetingNode | undefined {\n const reverseKeys = new Set(\n reverseSeeds.map((row) =>\n nodeIdentityKey({ id: row.node_id, kind: row.node_kind }),\n ),\n );\n let meeting: MeetingNode | undefined;\n for (const row of forwardSeeds) {\n const candidate = { id: row.node_id, kind: row.node_kind, depth: 0 };\n if (!reverseKeys.has(nodeIdentityKey(candidate))) continue;\n if (meeting === undefined || compareNodeIdentity(candidate, meeting) < 0) {\n meeting = candidate;\n }\n }\n return meeting;\n}\n\n/**\n * Expands one bidirectional round and detects meetings in the same\n * statement. Each inserted frontier row captures the opposite side's depth\n * for the same node identity (`meeting_depth`); a non-null value marks a\n * meeting. Only newly inserted rows can create a new meeting — both sides'\n * existing rows are immutable and any meeting among them would have\n * converged an earlier round — so the returned rows are a complete meeting\n * probe and the separate per-round meeting query is unnecessary.\n */\nasync function expandWorkingTableRound(\n context: IterativeGraphRunContext,\n side: WorkingSide,\n currentDepth: number,\n nextDepth: number,\n direction: TraversalDirection,\n maxHops: number,\n): Promise<FrontierRound> {\n const oppositeSide: WorkingSide = side === \"forward\" ? \"reverse\" : \"forward\";\n let insertedCount = 0;\n let meeting: MeetingNode | undefined;\n const { dialect } = context.operation.ctx;\n const targetKind = dialect.binaryText(sql`expanded.target_kind`);\n const targetId = dialect.binaryText(sql`expanded.target_id`);\n const sourceId = dialect.binaryText(sql`expanded.source_id`);\n const sourceKind = dialect.binaryText(sql`expanded.source_kind`);\n for (const edgeKinds of context.operation.edgeKindChunks) {\n const sourceFilter = sql`\n w.graph_id = ${context.graphId}\n AND w.run_id = ${context.runId}\n AND w.side = ${side}\n AND w.depth = ${currentDepth}\n `;\n const expansion = compileWorkingTableExpansion(\n context.operation,\n context.workingTable,\n sourceFilter,\n direction,\n edgeKinds,\n );\n const rows = await context.backend.execute<InsertedFrontierRow>(\n asCompiledRowsSql(sql`\n INSERT INTO ${context.workingTable}\n (graph_id, run_id, side, node_id, node_kind, depth,\n predecessor_id, predecessor_kind, meeting_depth)\n SELECT\n ${context.graphId}, ${context.runId}, ${side},\n ranked.target_id, ranked.target_kind, ${nextDepth},\n ranked.source_id, ranked.source_kind,\n (\n SELECT opposite.depth\n FROM ${context.workingTable} opposite\n WHERE opposite.graph_id = ${context.graphId}\n AND opposite.run_id = ${context.runId}\n AND opposite.side = ${oppositeSide}\n AND opposite.node_id = ranked.target_id\n AND opposite.node_kind = ranked.target_kind\n )\n FROM (\n SELECT expanded.*,\n ROW_NUMBER() OVER (\n PARTITION BY ${targetKind}, ${targetId}\n ORDER BY ${sourceId}, ${sourceKind}\n ) AS candidate_rank\n FROM (${expansion}) expanded\n ) ranked\n WHERE ranked.candidate_rank = 1\n AND NOT EXISTS (\n SELECT 1\n FROM ${context.workingTable} visited\n WHERE visited.graph_id = ${context.graphId}\n AND visited.run_id = ${context.runId}\n AND visited.side = ${side}\n AND visited.node_id = ranked.target_id\n AND visited.node_kind = ranked.target_kind\n )\n ON CONFLICT (graph_id, run_id, side, node_kind, node_id) DO NOTHING\n RETURNING node_id, node_kind, meeting_depth\n `),\n );\n insertedCount += rows.length;\n meeting = selectRoundMeeting(meeting, rows, nextDepth, maxHops);\n }\n return { insertedCount, meeting };\n}\n\n/**\n * Folds one round's inserted rows into the best meeting so far: smallest\n * total depth within `maxHops`, ties broken by node id then kind in code-point\n * order. That tie-break is deterministic and identical on both\n * backends; the SQL probe it replaced ordered under the database collation,\n * so equal-depth meetings could previously pick a different node on a\n * PostgreSQL cluster with a linguistic default collation.\n */\nfunction selectRoundMeeting(\n currentMeeting: MeetingNode | undefined,\n rows: readonly InsertedFrontierRow[],\n nextDepth: number,\n maxHops: number,\n): MeetingNode | undefined {\n let meeting = currentMeeting;\n for (const row of rows) {\n // Drivers may deliver the INTEGER column as number, text, or bigint\n // (e.g. better-sqlite3 with defaultSafeIntegers); only its absence means\n // \"no meeting\". Number() coerces every numeric shape.\n if (row.meeting_depth === null || row.meeting_depth === undefined) {\n continue;\n }\n const totalDepth = nextDepth + Number(row.meeting_depth);\n if (totalDepth > maxHops) continue;\n const candidate = {\n id: row.node_id,\n kind: row.node_kind,\n depth: totalDepth,\n };\n if (\n meeting === undefined ||\n candidate.depth < meeting.depth ||\n (candidate.depth === meeting.depth &&\n compareNodeIdentity(candidate, meeting) < 0)\n ) {\n meeting = candidate;\n }\n }\n return meeting;\n}\n\n/**\n * Reachability needs only minimum depth, not a reconstructable predecessor.\n * Reduce duplicate edge targets before checking target-node visibility so a\n * dense frontier performs one node lookup per candidate identity rather than\n * one lookup per incident edge.\n */\nasync function expandReachableWorkingTableRound(\n context: IterativeGraphRunContext,\n side: WorkingSide,\n currentDepth: number,\n nextDepth: number,\n direction: TraversalDirection,\n): Promise<number> {\n let insertedCount = 0;\n for (const edgeKinds of context.operation.edgeKindChunks) {\n const sourceFilter = sql`\n w.graph_id = ${context.graphId}\n AND w.run_id = ${context.runId}\n AND w.side = ${side}\n AND w.depth = ${currentDepth}\n `;\n const edgeExpansion = compileWorkingTableEdgeExpansion(\n context.operation,\n context.workingTable,\n sourceFilter,\n direction,\n edgeKinds,\n );\n const rows = await context.backend.execute<InsertedRow>(\n asCompiledRowsSql(sql`\n INSERT INTO ${context.workingTable}\n (graph_id, run_id, side, node_id, node_kind, depth,\n predecessor_id, predecessor_kind)\n SELECT\n ${context.graphId}, ${context.runId}, ${side},\n candidates.target_id, candidates.target_kind, ${nextDepth},\n NULL, NULL\n FROM (\n SELECT DISTINCT expanded.target_id, expanded.target_kind\n FROM (${edgeExpansion}) expanded\n ) candidates\n JOIN ${context.operation.schema.nodesTable} n\n ON n.graph_id = ${context.graphId}\n AND n.id = candidates.target_id\n AND n.kind = candidates.target_kind\n WHERE ${context.operation.nodeTemporalFilter}\n AND NOT EXISTS (\n SELECT 1\n FROM ${context.workingTable} visited\n WHERE visited.graph_id = ${context.graphId}\n AND visited.run_id = ${context.runId}\n AND visited.side = ${side}\n AND visited.node_id = candidates.target_id\n AND visited.node_kind = candidates.target_kind\n )\n ON CONFLICT (graph_id, run_id, side, node_kind, node_id) DO NOTHING\n RETURNING node_id\n `),\n );\n insertedCount += rows.length;\n }\n return insertedCount;\n}\n\nasync function readWorkingRows(\n context: IterativeGraphRunContext,\n side?: WorkingSide,\n): Promise<readonly WorkingRow[]> {\n const sideFilter = side === undefined ? sql`TRUE` : sql`side = ${side}`;\n return context.backend.execute<WorkingRow>(\n asCompiledRowsSql(sql`\n SELECT side, node_id, node_kind, depth,\n predecessor_id, predecessor_kind\n FROM ${context.workingTable}\n WHERE graph_id = ${context.graphId}\n AND run_id = ${context.runId}\n AND ${sideFilter}\n `),\n );\n}\n\nasync function findReachableNodesInline(\n ctx: AlgorithmContext,\n sourceId: string,\n maxHops: number,\n options: InternalTraversalOptions,\n): Promise<readonly ReachableNode[]> {\n return withInlineIterativeGraphOperation(ctx, options, async (operation) => {\n const sources = await fetchVisibleWorkingNodes(operation, [sourceId]);\n if (sources.length === 0) return [];\n\n const reached = new Map<NodeIdentityKey, ReachableNode>(\n sources.map((source) => [\n nodeIdentityKey(source),\n { id: source.id, kind: source.kind, depth: 0 },\n ]),\n );\n let workingSet: readonly PathNode[] = sources;\n\n for (let depth = 1; depth <= maxHops && workingSet.length > 0; depth++) {\n const candidates = await expandInlineWorkingSet(\n operation,\n workingSet,\n operation.direction,\n reached,\n );\n const nextWorkingSet = sortCandidates(candidates);\n for (const candidate of nextWorkingSet) {\n reached.set(nodeIdentityKey(candidate), {\n id: candidate.id,\n kind: candidate.kind,\n depth,\n });\n }\n workingSet = nextWorkingSet;\n }\n\n return [...reached.values()].toSorted(\n (left, right) =>\n left.depth - right.depth || compareNodeIdentity(left, right),\n );\n });\n}\n\nasync function findShortestPathInline(\n ctx: AlgorithmContext,\n sourceId: string,\n targetId: string,\n maxHops: number,\n options: InternalTraversalOptions,\n): Promise<ShortestPathResult | undefined> {\n return withInlineIterativeGraphOperation(ctx, options, async (operation) => {\n const visibleNodes = await fetchVisibleWorkingNodes(operation, [\n sourceId,\n targetId,\n ]);\n const sources = visibleNodes.filter((node) => node.id === sourceId);\n const targets = visibleNodes.filter((node) => node.id === targetId);\n if (sources.length === 0 || targets.length === 0) return;\n if (sourceId === targetId)\n return { nodes: [requireDefined(sources[0])], depth: 0 };\n\n const forwardVisited = createVisitedMap(sources);\n const reverseVisited = createVisitedMap(targets);\n let forwardWorkingSet: readonly PathNode[] = sources;\n let reverseWorkingSet: readonly PathNode[] = targets;\n let forwardDepth = 0;\n let reverseDepth = 0;\n\n while (\n forwardWorkingSet.length > 0 &&\n reverseWorkingSet.length > 0 &&\n forwardDepth + reverseDepth < maxHops\n ) {\n const expandForward =\n forwardWorkingSet.length <= reverseWorkingSet.length;\n const activeVisited = expandForward ? forwardVisited : reverseVisited;\n const oppositeVisited = expandForward ? reverseVisited : forwardVisited;\n const currentWorkingSet =\n expandForward ? forwardWorkingSet : reverseWorkingSet;\n const direction =\n expandForward ?\n operation.direction\n : reverseDirection(operation.direction);\n const candidates = await expandInlineWorkingSet(\n operation,\n currentWorkingSet,\n direction,\n activeVisited,\n );\n const nextDepth = (expandForward ? forwardDepth : reverseDepth) + 1;\n const nextWorkingSet = sortCandidates(candidates);\n\n for (const candidate of nextWorkingSet) {\n activeVisited.set(nodeIdentityKey(candidate), {\n id: candidate.id,\n kind: candidate.kind,\n depth: nextDepth,\n parentKey: nodeIdentityKey({\n id: candidate.parentId,\n kind: candidate.parentKind,\n }),\n });\n }\n\n const meetingKey = findMeetingNodeKey(\n nextWorkingSet,\n activeVisited,\n oppositeVisited,\n );\n if (meetingKey !== undefined) {\n return buildShortestPath(meetingKey, forwardVisited, reverseVisited);\n }\n\n if (expandForward) {\n forwardWorkingSet = nextWorkingSet;\n forwardDepth = nextDepth;\n } else {\n reverseWorkingSet = nextWorkingSet;\n reverseDepth = nextDepth;\n }\n }\n return;\n });\n}\n\nasync function expandInlineWorkingSet(\n operation: IterativeGraphOperation,\n workingSet: readonly PathNode[],\n direction: TraversalDirection,\n visited: ReadonlyMap<NodeIdentityKey, unknown>,\n): Promise<ReadonlyMap<NodeIdentityKey, FrontierCandidate>> {\n return reduceExpandedWorkingSet(\n operation,\n workingSet,\n direction,\n (existing, expansion) => selectPredecessor(existing, expansion, visited),\n );\n}\n\nfunction selectPredecessor(\n existing: FrontierCandidate | undefined,\n expansion: NodeExpansion,\n visited: ReadonlyMap<NodeIdentityKey, unknown>,\n): FrontierCandidate | undefined {\n if (visited.has(nodeIdentityKey(expansion.target))) return existing;\n if (\n existing !== undefined &&\n compareNodeIdentity(expansion.source, {\n id: existing.parentId,\n kind: existing.parentKind,\n }) >= 0\n ) {\n return existing;\n }\n return {\n id: expansion.target.id,\n kind: expansion.target.kind,\n parentId: expansion.source.id,\n parentKind: expansion.source.kind,\n };\n}\n\nfunction sortCandidates(\n candidates: ReadonlyMap<NodeIdentityKey, FrontierCandidate>,\n): readonly FrontierCandidate[] {\n return [...candidates.values()].toSorted((left, right) =>\n compareNodeIdentity(left, right),\n );\n}\n\nfunction findMeetingNodeKey(\n candidates: readonly FrontierCandidate[],\n activeVisited: ReadonlyMap<NodeIdentityKey, VisitedNode>,\n oppositeVisited: ReadonlyMap<NodeIdentityKey, VisitedNode>,\n): NodeIdentityKey | undefined {\n let best:\n | Readonly<{\n key: NodeIdentityKey;\n node: PathNode;\n depth: number;\n }>\n | undefined;\n for (const candidate of candidates) {\n const key = nodeIdentityKey(candidate);\n const active = activeVisited.get(key);\n const opposite = oppositeVisited.get(key);\n if (active === undefined || opposite === undefined) continue;\n const meeting = {\n key,\n node: { id: candidate.id, kind: candidate.kind },\n depth: active.depth + opposite.depth,\n };\n if (\n best === undefined ||\n meeting.depth < best.depth ||\n (meeting.depth === best.depth &&\n compareNodeIdentity(meeting.node, best.node) < 0)\n ) {\n best = meeting;\n }\n }\n return best?.key;\n}\n\nfunction buildShortestPath(\n meetingKey: NodeIdentityKey,\n forwardVisited: ReadonlyMap<NodeIdentityKey, VisitedNode>,\n reverseVisited: ReadonlyMap<NodeIdentityKey, VisitedNode>,\n): ShortestPathResult {\n const forwardKeys: NodeIdentityKey[] = [];\n let cursor: NodeIdentityKey | undefined = meetingKey;\n while (cursor !== undefined) {\n forwardKeys.push(cursor);\n cursor = forwardVisited.get(cursor)?.parentKey;\n }\n forwardKeys.reverse();\n\n const pathKeys = [...forwardKeys];\n cursor = reverseVisited.get(meetingKey)?.parentKey;\n while (cursor !== undefined) {\n pathKeys.push(cursor);\n cursor = reverseVisited.get(cursor)?.parentKey;\n }\n\n const nodes = pathKeys.map((key) => {\n const node = forwardVisited.get(key) ?? reverseVisited.get(key);\n return { id: node?.id ?? \"\", kind: node?.kind ?? \"\" };\n });\n return { nodes, depth: nodes.length - 1 };\n}\n\nfunction createVisitedMap(\n nodes: readonly PathNode[],\n): Map<NodeIdentityKey, VisitedNode> {\n return new Map(\n nodes.map((node) => [\n nodeIdentityKey(node),\n { id: node.id, kind: node.kind, depth: 0, parentKey: undefined },\n ]),\n );\n}\n\nfunction createVisitedMapFromRows(\n rows: readonly WorkingRow[],\n side: WorkingSide,\n): Map<NodeIdentityKey, VisitedNode> {\n return new Map(\n rows\n .filter((row) => row.side === side)\n .map((row) => {\n const parentKey = nodeIdentityKeyFromRow(\n row.predecessor_id,\n row.predecessor_kind,\n );\n const node = {\n id: row.node_id,\n kind: row.node_kind,\n depth: Number(row.depth),\n parentKey,\n } satisfies VisitedNode;\n return [nodeIdentityKey(node), node];\n }),\n );\n}\n\nfunction reverseDirection(direction: TraversalDirection): TraversalDirection {\n switch (direction) {\n case \"out\": {\n return \"in\";\n }\n case \"in\": {\n return \"out\";\n }\n case \"both\": {\n return \"both\";\n }\n }\n}\n","import { findReachableNodes, findShortestPath } from \"./breadth-first\";\nimport {\n type AlgorithmContext,\n assertEdgeKinds,\n DEFAULT_ALGORITHM_MAX_HOPS,\n DEFAULT_NEIGHBOR_DEPTH,\n type InternalTraversalOptions,\n pickTemporalOptions,\n resolveMaxHops,\n} from \"./context\";\nimport type { ReachableNode } from \"./types\";\n\ntype InternalReachableOptions = InternalTraversalOptions &\n Readonly<{ excludeSource?: boolean }>;\n\ntype InternalNeighborsOptions = Omit<InternalTraversalOptions, \"maxHops\"> &\n Readonly<{ depth?: number }>;\n\nexport async function executeReachable(\n ctx: AlgorithmContext,\n sourceId: string,\n options: InternalReachableOptions,\n): Promise<readonly ReachableNode[]> {\n assertEdgeKinds(options.edges);\n const maxHops = resolveMaxHops(\n options.maxHops,\n DEFAULT_ALGORITHM_MAX_HOPS,\n \"maxHops\",\n );\n\n const reached = await findReachableNodes(ctx, sourceId, maxHops, options);\n return options.excludeSource === true ?\n reached.filter((node) => node.id !== sourceId)\n : reached;\n}\n\nexport async function executeCanReach(\n ctx: AlgorithmContext,\n sourceId: string,\n targetId: string,\n options: InternalTraversalOptions,\n): Promise<boolean> {\n assertEdgeKinds(options.edges);\n\n const maxHops = resolveMaxHops(\n options.maxHops,\n DEFAULT_ALGORITHM_MAX_HOPS,\n \"maxHops\",\n );\n\n return (\n (await findShortestPath(ctx, sourceId, targetId, maxHops, options)) !==\n undefined\n );\n}\n\nexport async function executeNeighbors(\n ctx: AlgorithmContext,\n sourceId: string,\n options: InternalNeighborsOptions,\n): Promise<readonly ReachableNode[]> {\n const depth = resolveMaxHops(options.depth, DEFAULT_NEIGHBOR_DEPTH, \"depth\");\n\n return executeReachable(ctx, sourceId, {\n edges: options.edges,\n maxHops: depth,\n direction: options.direction ?? \"out\",\n cyclePolicy: options.cyclePolicy ?? \"prevent\",\n ...pickTemporalOptions(options),\n ...(options.workingMemory !== undefined && {\n workingMemory: options.workingMemory,\n }),\n excludeSource: true,\n });\n}\n","import { findShortestPath } from \"./breadth-first\";\nimport {\n type AlgorithmContext,\n assertEdgeKinds,\n DEFAULT_ALGORITHM_MAX_HOPS,\n type InternalTraversalOptions,\n resolveMaxHops,\n} from \"./context\";\nimport type { ShortestPathResult } from \"./types\";\n\nexport async function executeShortestPath(\n ctx: AlgorithmContext,\n sourceId: string,\n targetId: string,\n options: InternalTraversalOptions,\n): Promise<ShortestPathResult | undefined> {\n assertEdgeKinds(options.edges);\n const maxHops = resolveMaxHops(\n options.maxHops,\n DEFAULT_ALGORITHM_MAX_HOPS,\n \"maxHops\",\n );\n return findShortestPath(ctx, sourceId, targetId, maxHops, options);\n}\n","import type { GraphDef } from \"../../core/define-graph\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport {\n type AlgorithmContext,\n assertEdgeKinds,\n assertGraphAnalyticsSupported,\n compileNodeKindSeedFilter,\n type InternalTraversalOptions,\n normalizeNodeKinds,\n pickTemporalOptions,\n resolveMaxIterations,\n} from \"./context\";\nimport {\n compileWorkingTableEdgeExpansion,\n countWorkingTableRows,\n frontierIndexIdentifier,\n type IterativeGraphRunContext,\n runIterativeGraphOperation,\n} from \"./iterative-graph-operation\";\nimport type {\n InternalWeaklyConnectedComponentsOptions,\n WeaklyConnectedComponentMembership,\n} from \"./types\";\n\ntype IterationState = Readonly<{\n changedCount: number;\n workingTableSize: number;\n}>;\ntype ChangedRow = Readonly<{ node_id: string }>;\ntype MembershipRow = Readonly<{\n node_id: string;\n node_kind: string;\n component_id: string;\n component_kind: string;\n component_size: number | string;\n}>;\n\nconst DEFAULT_WCC_MAX_ITERATIONS = 1000;\n\n/** Runs exact label-min weakly connected components in the shared SQL loop. */\nexport async function executeWeaklyConnectedComponents<G extends GraphDef>(\n ctx: AlgorithmContext,\n options: InternalWeaklyConnectedComponentsOptions<G>,\n): Promise<readonly WeaklyConnectedComponentMembership[]> {\n assertEdgeKinds(options.edges);\n assertGraphAnalyticsSupported(ctx, \"weaklyConnectedComponents\", {\n requiresWindowFunctions: true,\n });\n const maxIterations = resolveMaxIterations(\n options.maxIterations,\n DEFAULT_WCC_MAX_ITERATIONS,\n \"weaklyConnectedComponents\",\n );\n const nodeKinds = normalizeNodeKinds(options.nodeKinds);\n const traversalOptions: InternalTraversalOptions = {\n edges: options.edges,\n direction: \"both\",\n ...pickTemporalOptions(options),\n ...(options.workingMemory === undefined ?\n {}\n : { workingMemory: options.workingMemory }),\n };\n\n return runIterativeGraphOperation(ctx, traversalOptions, {\n algorithm: \"weaklyConnectedComponents\",\n maxIterations,\n createWorkingTable,\n initialize: (context) => initializeWorkingTable(context, nodeKinds),\n runRound: runLabelPropagationRound,\n hasConverged(state) {\n return state.changedCount === 0;\n },\n extractResult: extractMemberships,\n });\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext): SqlFragment {\n return sql`\n CREATE TEMP TABLE ${context.workingTable} (\n graph_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n node_id TEXT NOT NULL,\n node_kind TEXT NOT NULL,\n label_id TEXT NOT NULL,\n label_kind TEXT NOT NULL,\n next_label_id TEXT NOT NULL,\n next_label_kind TEXT NOT NULL,\n improved_round INTEGER NOT NULL,\n PRIMARY KEY (graph_id, run_id, node_kind, node_id)\n )\n `;\n}\n\nasync function initializeWorkingTable(\n context: IterativeGraphRunContext,\n nodeKinds: readonly string[] | undefined,\n): Promise<IterationState> {\n const { operation, workingTable, graphId, runId } = context;\n const nodeKindFilter = compileNodeKindSeedFilter(nodeKinds);\n await context.executeTemporary(sql`\n INSERT INTO ${workingTable}\n (graph_id, run_id, node_id, node_kind, label_id, label_kind,\n next_label_id, next_label_kind, improved_round)\n SELECT\n ${graphId}, ${runId}, n.id, n.kind, n.id, n.kind, n.id, n.kind, 0\n FROM ${operation.schema.nodesTable} n\n WHERE n.graph_id = ${graphId}\n AND ${nodeKindFilter}\n AND ${operation.nodeTemporalFilter}\n `);\n await context.executeTemporary(sql`\n CREATE INDEX ${frontierIndexIdentifier(context)}\n ON ${workingTable} (graph_id, run_id, improved_round)\n `);\n\n const workingTableSize = await countWorkingTableRows(context);\n return { changedCount: workingTableSize, workingTableSize };\n}\n\nasync function runLabelPropagationRound(\n context: IterativeGraphRunContext,\n state: IterationState,\n iteration: number,\n): Promise<IterationState> {\n for (const edgeKinds of context.operation.edgeKindChunks) {\n await propagateChunkLabels(context, edgeKinds, iteration);\n }\n const changedRows = await applyNextLabels(context, iteration);\n return {\n changedCount: changedRows.length,\n workingTableSize: state.workingTableSize,\n };\n}\n\n/**\n * Propagates the minimum neighbor label along one edge-kind chunk. The\n * expansion deliberately skips the target-node visibility join. The working\n * table was seeded through the same graph/kind/temporal filters inside the\n * same snapshot, WCC never inserts rows after seeding, source labels are\n * projected from the frontier, and each target is joined against the working\n * table below. Membership is therefore the visibility-and-scope proof, so a\n * per-edge `typegraph_nodes` lookup would only re-check what the frontier and\n * `scoped_target` already guarantee.\n */\nasync function propagateChunkLabels(\n context: IterativeGraphRunContext,\n edgeKinds: readonly string[],\n iteration: number,\n): Promise<void> {\n const { operation, workingTable, graphId, runId } = context;\n const expansion = compileWorkingTableEdgeExpansion(\n operation,\n workingTable,\n sql`\n w.graph_id = ${graphId}\n AND w.run_id = ${runId}\n AND w.improved_round = ${iteration - 1}\n `,\n \"both\",\n edgeKinds,\n sql`w.label_id AS source_label_id, w.label_kind AS source_label_kind`,\n );\n const candidateId = operation.ctx.dialect.binaryText(sql`ranked.label_id`);\n const candidateKind = operation.ctx.dialect.binaryText(\n sql`ranked.label_kind`,\n );\n const currentId = operation.ctx.dialect.binaryText(sql`target.next_label_id`);\n const currentKind = operation.ctx.dialect.binaryText(\n sql`target.next_label_kind`,\n );\n const sourceId = operation.ctx.dialect.binaryText(sql`source.label_id`);\n const sourceKind = operation.ctx.dialect.binaryText(sql`source.label_kind`);\n const targetId = operation.ctx.dialect.binaryText(sql`source.target_id`);\n const targetKind = operation.ctx.dialect.binaryText(sql`source.target_kind`);\n\n await context.executeTemporary(sql`\n WITH candidates AS (\n SELECT\n expanded.target_id,\n expanded.target_kind,\n expanded.source_label_id AS label_id,\n expanded.source_label_kind AS label_kind\n FROM (${expansion}) expanded\n JOIN ${workingTable} scoped_target\n ON scoped_target.graph_id = ${graphId}\n AND scoped_target.run_id = ${runId}\n AND scoped_target.node_id = expanded.target_id\n AND scoped_target.node_kind = expanded.target_kind\n ), ranked AS (\n SELECT\n target_id,\n target_kind,\n label_id,\n label_kind,\n ROW_NUMBER() OVER (\n PARTITION BY ${targetKind}, ${targetId}\n ORDER BY ${sourceId}, ${sourceKind}\n ) AS candidate_rank\n FROM candidates source\n )\n UPDATE ${workingTable} AS target\n SET next_label_id = ranked.label_id,\n next_label_kind = ranked.label_kind\n FROM ranked\n WHERE target.graph_id = ${graphId}\n AND target.run_id = ${runId}\n AND target.node_id = ranked.target_id\n AND target.node_kind = ranked.target_kind\n AND ranked.candidate_rank = 1\n AND (\n ${candidateId} < ${currentId}\n OR (\n ${candidateId} = ${currentId}\n AND ${candidateKind} < ${currentKind}\n )\n )\n `);\n}\n\nfunction applyNextLabels(\n context: IterativeGraphRunContext,\n iteration: number,\n): Promise<readonly ChangedRow[]> {\n return context.backend.execute<ChangedRow>(\n asCompiledRowsSql(sql`\n UPDATE ${context.workingTable}\n SET label_id = next_label_id,\n label_kind = next_label_kind,\n improved_round = ${iteration}\n WHERE graph_id = ${context.graphId}\n AND run_id = ${context.runId}\n AND (\n label_id <> next_label_id OR label_kind <> next_label_kind\n )\n RETURNING node_id\n `),\n );\n}\n\nasync function extractMemberships(\n context: IterativeGraphRunContext,\n): Promise<readonly WeaklyConnectedComponentMembership[]> {\n const { operation } = context;\n const componentId = operation.ctx.dialect.binaryText(sql`label_id`);\n const componentKind = operation.ctx.dialect.binaryText(sql`label_kind`);\n const nodeId = operation.ctx.dialect.binaryText(sql`node_id`);\n const nodeKind = operation.ctx.dialect.binaryText(sql`node_kind`);\n const rows = await context.backend.execute<MembershipRow>(\n asCompiledRowsSql(sql`\n SELECT\n node_id,\n node_kind,\n label_id AS component_id,\n label_kind AS component_kind,\n COUNT(*) OVER (\n PARTITION BY ${componentKind}, ${componentId}\n ) AS component_size\n FROM ${context.workingTable}\n WHERE graph_id = ${context.graphId} AND run_id = ${context.runId}\n ORDER BY ${componentId}, ${componentKind}, ${nodeId}, ${nodeKind}\n `),\n );\n\n return rows.map((row) => ({\n id: row.node_id,\n kind: row.node_kind,\n componentId: row.component_id,\n componentKind: row.component_kind,\n size: Number(row.component_size),\n }));\n}\n","import type { GraphDef } from \"../../core/define-graph\";\nimport {\n ConfigurationError,\n GraphAlgorithmConvergenceError,\n InvalidEdgeWeightError,\n type InvalidEdgeWeightReason,\n} from \"../../errors\";\nimport { compileKindFilter } from \"../../query/compiler/predicate-utils\";\nimport { jsonPointer } from \"../../query/json-pointer\";\nimport { sql, type SqlFragment } from \"../../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../../query/sql-intent\";\nimport type { AlgorithmContext, InternalTraversalOptions } from \"./context\";\nimport { assertEdgeKinds, resolveMaxIterations } from \"./context\";\nimport {\n compareNodeIdentity,\n compileWorkingTableExpansion,\n fetchVisibleWorkingNodes,\n frontierIndexIdentifier,\n type IterativeGraphOperation,\n type IterativeGraphRunContext,\n type NodeExpansion,\n type NodeIdentityKey,\n nodeIdentityKey,\n reduceExpandedWorkingSet,\n runIterativeGraphOperation,\n supportsTemporaryIteration,\n withInlineIterativeGraphOperation,\n} from \"./iterative-graph-operation\";\nimport type {\n InternalWeightedShortestPathOptions,\n PathNode,\n WeightedShortestPathResult,\n} from \"./types\";\n\nconst DEFAULT_WEIGHTED_SHORTEST_PATH_MAX_ITERATIONS = 1000;\n\nconst WEIGHTED_ALGORITHM_NAME = \"weightedShortestPath\";\n\n/**\n * Largest accepted edge weight (~9.7e289). Auditing weights to this bound\n * makes accumulated overflow impossible rather than merely unlikely: a path\n * gains one working-table row per hop, so it has at most 2^53 hops, and\n * 2^53 · MAX_EDGE_WEIGHT stays far below Number.MAX_VALUE even after\n * float-addition rounding (the 2^64 divisor leaves an ~2000x margin).\n * Without the bound, PostgreSQL's float8 addition would raise a raw 22003\n * overflow mid-round while SQLite silently saturated to Infinity.\n */\nconst MAX_EDGE_WEIGHT = Number.MAX_VALUE / 2 ** 64;\n\n/**\n * Smallest accepted nonzero weight magnitude: the smallest IEEE 754 double\n * (5e-324). PostgreSQL stores smaller nonzero JSON numbers exactly in jsonb\n * and raises a raw underflow when the traversal casts them to float8, so\n * the audit rejects them with the typed error instead. SQLite's JSON parser\n * has already rounded such text to 0 before SQL can observe it — an\n * engine-level difference the audit cannot detect there.\n */\nconst MIN_EDGE_WEIGHT = Number.MIN_VALUE;\n\n/** Traversal options with the weight source guaranteed present. */\ntype WeightedTraversalOptions = InternalTraversalOptions &\n Readonly<{ weightProperty: string }>;\n\ntype WeightedState = Readonly<{\n frontierCount: number;\n workingTableSize: number;\n /**\n * Cheapest known distance to any node with the target id, tracked in JS\n * from each round's RETURNING rows so the next round can prune with a\n * plain bound parameter instead of per-candidate subqueries.\n */\n bestTargetDistance: number | undefined;\n}>;\n\ntype SeededRow = Readonly<{ node_id: string }>;\ntype ImprovedRow = Readonly<{ node_id: string; distance: number | string }>;\n\ntype FrontierRound = Readonly<{\n frontierCount: number;\n bestTargetDistance: number | undefined;\n}>;\n\ntype ChainRow = Readonly<{\n node_id: string;\n node_kind: string;\n distance: number | string;\n hops: number | string;\n}>;\n\ntype WeightAuditRow = Readonly<{\n edge_id: string;\n edge_kind: string;\n weight_text: unknown;\n is_number: unknown;\n is_missing: unknown;\n}>;\n\n/**\n * A node settled by weighted relaxation: its best known distance from the\n * source, the hop count of the path achieving it, and the predecessor along\n * that path.\n */\ntype WeightedVisitedNode = Readonly<{\n id: string;\n kind: string;\n distance: number;\n hops: number;\n parentKey: NodeIdentityKey | undefined;\n}>;\n\ntype WeightedCandidate = Readonly<{\n id: string;\n kind: string;\n distance: number;\n hops: number;\n parentId: string;\n parentKind: string;\n}>;\n\n/**\n * Finds the minimum-total-weight path from `sourceId` to `targetId` by\n * frontier-based label-correcting relaxation: each round relaxes the edges\n * out of the nodes improved in the previous round, keeping one best\n * `(distance, predecessor)` per node identity, until no distance improves.\n * Weights must be non-negative, which makes pruning against the best known\n * target distance safe: a candidate costing strictly more than a path\n * already reaching the target can never win, while equal-cost candidates\n * stay admitted so the result tie-break sees every equal-cost target.\n */\nexport async function executeWeightedShortestPath<G extends GraphDef>(\n ctx: AlgorithmContext,\n sourceId: string,\n targetId: string,\n options: InternalWeightedShortestPathOptions<G>,\n): Promise<WeightedShortestPathResult | undefined> {\n assertEdgeKinds(options.edges);\n assertWeightOptions(options.weightProperty, options.defaultWeight);\n const maxIterations = resolveMaxIterations(\n options.maxIterations,\n DEFAULT_WEIGHTED_SHORTEST_PATH_MAX_ITERATIONS,\n WEIGHTED_ALGORITHM_NAME,\n );\n // Structurally assignable — the internal options are the traversal options\n // plus the algorithm-only `maxIterations`, which the substrate ignores.\n const traversalOptions: WeightedTraversalOptions = options;\n\n // Non-negative weights make distance 0 unbeatable, so a self path needs\n // no relaxation rounds — only the weight audit (for deterministic data\n // errors) and a visibility check on the node itself.\n if (sourceId === targetId) {\n return findWeightedSelfPath(ctx, sourceId, traversalOptions);\n }\n\n if (supportsTemporaryIteration(ctx)) {\n return findWeightedShortestPathInWorkingTable(\n ctx,\n sourceId,\n targetId,\n maxIterations,\n traversalOptions,\n );\n }\n return findWeightedShortestPathInline(\n ctx,\n sourceId,\n targetId,\n maxIterations,\n traversalOptions,\n );\n}\n\nfunction assertWeightOptions(\n weightProperty: string,\n defaultWeight: number | undefined,\n): void {\n if (typeof weightProperty !== \"string\" || weightProperty.length === 0) {\n throw new ConfigurationError(\n `${WEIGHTED_ALGORITHM_NAME} weightProperty must be a non-empty string.`,\n { weightProperty },\n );\n }\n // The same upper bound the audit applies to stored weights: a default\n // above it would reopen the accumulated-overflow gap for missing-weight\n // edges the audit deliberately lets through.\n if (\n defaultWeight !== undefined &&\n (!Number.isFinite(defaultWeight) ||\n defaultWeight < 0 ||\n defaultWeight > MAX_EDGE_WEIGHT)\n ) {\n throw new ConfigurationError(\n `${WEIGHTED_ALGORITHM_NAME} defaultWeight must be a non-negative number no greater than ${MAX_EDGE_WEIGHT}, got ${String(defaultWeight)}.`,\n { defaultWeight, maximum: MAX_EDGE_WEIGHT },\n );\n }\n}\n\n/**\n * Fails fast on the first visible edge of the selected kinds whose weight\n * violates the weighted-traversal contract: a non-numeric value, a negative\n * number, or a missing value with no configured default. Runs inside the\n * operation's snapshot before any relaxation round, so a weighted call\n * either observes a fully valid weight domain or throws — the traversal's\n * own weight cast never sees a value it could silently mangle.\n *\n * The audit deliberately covers every visible edge of the selected kinds,\n * not just edges the traversal happens to reach: reachability-dependent\n * validation would make the error nondeterministic in the data.\n */\nasync function assertValidEdgeWeights(\n operation: IterativeGraphOperation,\n weightProperty: string,\n defaultWeight: number | undefined,\n): Promise<void> {\n const { dialect } = operation.ctx;\n const pointer = jsonPointer([weightProperty]);\n const propsColumn = sql.raw(\"e.props\");\n // The inner projection extracts the JSON path once per edge; the outer\n // violation predicate then works over plain projected columns. Composing\n // the checks directly over `e.props` would re-parse the JSON payload for\n // every predicate branch on the audit's full edge scan.\n //\n // Both type predicates are never-NULL by contract, so the multi-branch\n // violation predicate below stays two-valued.\n const isNumber = dialect.jsonPathIsNumber(propsColumn, pointer);\n const isMissing = dialect.jsonPathIsNull(propsColumn, pointer);\n const weightText = dialect.jsonExtractText(propsColumn, pointer);\n // CASE keeps the numeric extraction unreachable for non-numeric values:\n // PostgreSQL does not short-circuit OR/AND, and casting arbitrary text\n // would error before the audit could produce its typed report. The\n // extraction is jsonExtractNumber (PostgreSQL `numeric`), NOT the double\n // extraction the traversal uses: a JSON number beyond the float8 range\n // must reach the range check below instead of overflowing the cast.\n const weightNumber = sql`CASE WHEN ${isNumber} THEN ${dialect.jsonExtractNumber(propsColumn, pointer)} END`;\n const missingViolation =\n defaultWeight === undefined ?\n sql`audited.is_missing = 1`\n : dialect.booleanLiteral(false);\n const negativeViolation = sql`audited.is_number = 1 AND audited.weight_number < 0`;\n // CAST the bounds to NUMERIC so PostgreSQL compares in the arbitrary-\n // precision domain — a numeric-vs-float8 comparison would coerce the\n // out-of-range value to float8 and overflow before comparing. The lower\n // arm rejects sub-denormal magnitudes (float8 cast underflow on\n // PostgreSQL); on SQLite they parsed to exactly 0 and the arm cannot\n // fire, which is the declared engine caveat on MIN_EDGE_WEIGHT.\n const outOfRangeViolation = sql`audited.is_number = 1 AND (ABS(audited.weight_number) > CAST(${MAX_EDGE_WEIGHT} AS NUMERIC) OR (audited.weight_number <> 0 AND ABS(audited.weight_number) < CAST(${MIN_EDGE_WEIGHT} AS NUMERIC)))`;\n\n for (const edgeKinds of operation.edgeKindChunks) {\n const edgeKindFilter = compileKindFilter(sql.raw(\"e.kind\"), edgeKinds);\n const rows = await operation.backend.execute<WeightAuditRow>(\n asCompiledRowsSql(sql`\n SELECT audited.edge_id, audited.edge_kind, audited.weight_text,\n audited.is_number, audited.is_missing\n FROM (\n SELECT e.id AS edge_id, e.kind AS edge_kind,\n ${weightText} AS weight_text,\n ${weightNumber} AS weight_number,\n CASE WHEN ${isNumber} THEN 1 ELSE 0 END AS is_number,\n CASE WHEN ${isMissing} THEN 1 ELSE 0 END AS is_missing\n FROM ${operation.schema.edgesTable} e\n WHERE e.graph_id = ${operation.ctx.graphId}\n AND ${edgeKindFilter}\n AND ${operation.edgeTemporalFilter}\n ) audited\n WHERE (${missingViolation})\n OR (audited.is_missing = 0 AND audited.is_number = 0)\n OR (${negativeViolation})\n OR (${outOfRangeViolation})\n ORDER BY ${dialect.binaryText(sql`audited.edge_id`)}\n LIMIT 1\n `),\n );\n const row = rows[0];\n if (row !== undefined) {\n throw createInvalidEdgeWeightError(row, weightProperty);\n }\n }\n}\n\nfunction createInvalidEdgeWeightError(\n row: WeightAuditRow,\n weightProperty: string,\n): InvalidEdgeWeightError {\n const reason = resolveInvalidWeightReason(row);\n const value =\n reason === \"missing\" || row.weight_text === null ?\n undefined\n : formatWeightValue(row.weight_text);\n return new InvalidEdgeWeightError({\n edgeId: row.edge_id,\n edgeKind: row.edge_kind,\n property: weightProperty,\n reason,\n ...(value === undefined ? {} : { value }),\n });\n}\n\nfunction resolveInvalidWeightReason(\n row: WeightAuditRow,\n): InvalidEdgeWeightReason {\n if (flagIsSet(row.is_missing)) return \"missing\";\n if (!flagIsSet(row.is_number)) return \"non_numeric\";\n // A numeric violation is either negative or outside the accepted\n // magnitude range; the sign distinguishes them (Number() of an oversized\n // magnitude yields ±Infinity, whose sign still holds).\n return Number(row.weight_text) < 0 ? \"negative\" : \"out_of_range\";\n}\n\n/** Coerces a driver-shaped 0/1 flag (number, bigint, or boolean) to boolean. */\nfunction flagIsSet(value: unknown): boolean {\n return Number(value) !== 0;\n}\n\n/** Renders an extracted weight value for the error message. */\nfunction formatWeightValue(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n ) {\n return String(value);\n }\n return JSON.stringify(value);\n}\n\n// ============================================================\n// Working-table execution\n// ============================================================\n\nasync function findWeightedShortestPathInWorkingTable(\n ctx: AlgorithmContext,\n sourceId: string,\n targetId: string,\n maxIterations: number,\n options: WeightedTraversalOptions,\n): Promise<WeightedShortestPathResult | undefined> {\n return runIterativeGraphOperation<\n WeightedState,\n WeightedShortestPathResult | undefined\n >(ctx, options, {\n algorithm: WEIGHTED_ALGORITHM_NAME,\n maxIterations,\n createWorkingTable,\n async initialize(context) {\n await assertValidEdgeWeights(\n context.operation,\n options.weightProperty,\n options.defaultWeight,\n );\n // A target no visible node carries can never be reached; converge\n // immediately instead of relaxing the source's entire component.\n if (!(await hasVisibleNode(context.operation, targetId))) {\n return {\n frontierCount: 0,\n workingTableSize: 0,\n bestTargetDistance: undefined,\n };\n }\n // Each round scans only the previous round's frontier; without this\n // index that filter re-scans the whole (growing) working table, since\n // the identity primary key cannot serve an improved_round lookup.\n await context.executeTemporary(sql`\n CREATE INDEX ${frontierIndexIdentifier(context)}\n ON ${context.workingTable} (graph_id, run_id, improved_round)\n `);\n const seeded = await seedDistances(context, sourceId);\n return {\n frontierCount: seeded.length,\n workingTableSize: seeded.length,\n // Seeds carry the source id, never the target's — the self-path\n // case is short-circuited before this plan runs.\n bestTargetDistance: undefined,\n };\n },\n async runRound(context, state, iteration) {\n const round = await relaxFrontierRound(\n context,\n targetId,\n iteration,\n state.bestTargetDistance,\n );\n return {\n frontierCount: round.frontierCount,\n // Overcounts by re-improved existing rows (RETURNING includes\n // updates); acceptable because the size only paces the substrate's\n // ANALYZE refresh, where too-early merely refreshes stats sooner.\n workingTableSize: state.workingTableSize + round.frontierCount,\n bestTargetDistance: round.bestTargetDistance,\n };\n },\n hasConverged(state: WeightedState) {\n return state.frontierCount === 0;\n },\n async extractResult(context) {\n return extractPathFromWorkingTable(context, targetId, maxIterations);\n },\n });\n}\n\n/**\n * Point lookup: does any visible node carry this id (under any kind)?\n */\nasync function hasVisibleNode(\n operation: IterativeGraphOperation,\n nodeId: string,\n): Promise<boolean> {\n const rows = await operation.backend.execute<Readonly<{ id: string }>>(\n asCompiledRowsSql(sql`\n SELECT n.id FROM ${operation.schema.nodesTable} n\n WHERE n.graph_id = ${operation.ctx.graphId}\n AND n.id = ${nodeId}\n AND ${operation.nodeTemporalFilter}\n LIMIT 1\n `),\n );\n return rows.length > 0;\n}\n\nfunction createWorkingTable(context: IterativeGraphRunContext): SqlFragment {\n // DOUBLE PRECISION is accepted by both engines: PostgreSQL's float8, and\n // REAL affinity on SQLite — the same IEEE 754 double either way.\n return sql`\n CREATE TEMP TABLE ${context.workingTable} (\n graph_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n node_id TEXT NOT NULL,\n node_kind TEXT NOT NULL,\n distance DOUBLE PRECISION NOT NULL,\n hops INTEGER NOT NULL,\n predecessor_id TEXT,\n predecessor_kind TEXT,\n improved_round INTEGER NOT NULL,\n PRIMARY KEY (graph_id, run_id, node_kind, node_id)\n )\n `;\n}\n\nasync function seedDistances(\n context: IterativeGraphRunContext,\n sourceId: string,\n): Promise<readonly SeededRow[]> {\n const { operation, workingTable, graphId, runId } = context;\n return context.backend.execute<SeededRow>(\n asCompiledRowsSql(sql`\n INSERT INTO ${workingTable}\n (graph_id, run_id, node_id, node_kind, distance, hops,\n predecessor_id, predecessor_kind, improved_round)\n SELECT ${graphId}, ${runId}, n.id, n.kind, 0, 0, NULL, NULL, 0\n FROM ${operation.schema.nodesTable} n\n WHERE n.graph_id = ${graphId}\n AND n.id = ${sourceId}\n AND ${operation.nodeTemporalFilter}\n ON CONFLICT (graph_id, run_id, node_kind, node_id) DO NOTHING\n RETURNING node_id\n `),\n );\n}\n\n/**\n * Relaxes one round: expands the previous round's frontier through visible\n * edges, keeps the cheapest candidate per target identity (ties broken by\n * source id then kind in binary collation, so both backends pick the same\n * predecessor), and upserts only strict distance improvements.\n *\n * Candidates costing strictly more than `roundBound` — the cheapest path to\n * the target known at round start, tracked in JS from RETURNING rows — are\n * pruned. Sound because the audit guarantees non-negative weights: no\n * extension of such a candidate can beat the known path. Equal-cost\n * candidates stay admitted, because zero-weight edges can extend an\n * equal-cost node to another node with the target id, and the documented\n * smallest-identity target tie-break must see that node; strict-improvement\n * upserts keep the equal-cost plateau finite. A bound parameter keeps the\n * pruning O(1) per candidate and applies the same round-start state on both\n * execution paths, so they run identical round sequences.\n */\nasync function relaxFrontierRound(\n context: IterativeGraphRunContext,\n targetId: string,\n iteration: number,\n roundBound: number | undefined,\n): Promise<FrontierRound> {\n const { operation, workingTable, graphId, runId } = context;\n const { dialect } = operation.ctx;\n let frontierCount = 0;\n let bestTargetDistance = roundBound;\n for (const edgeKinds of operation.edgeKindChunks) {\n const sourceFilter = sql`\n w.graph_id = ${graphId}\n AND w.run_id = ${runId}\n AND w.improved_round = ${iteration - 1}\n `;\n const expansion = compileWorkingTableExpansion(\n operation,\n workingTable,\n sourceFilter,\n operation.direction,\n edgeKinds,\n );\n const rows = await context.backend.execute<ImprovedRow>(\n asCompiledRowsSql(sql`\n INSERT INTO ${workingTable}\n (graph_id, run_id, node_id, node_kind, distance, hops,\n predecessor_id, predecessor_kind, improved_round)\n SELECT\n ${graphId}, ${runId}, ranked.target_id, ranked.target_kind,\n ranked.candidate_distance, ranked.candidate_hops,\n ranked.source_id, ranked.source_kind, ${iteration}\n FROM (\n SELECT candidates.*,\n ROW_NUMBER() OVER (\n PARTITION BY ${dialect.binaryText(sql`candidates.target_kind`)},\n ${dialect.binaryText(sql`candidates.target_id`)}\n ORDER BY candidates.candidate_distance,\n ${dialect.binaryText(sql`candidates.source_id`)},\n ${dialect.binaryText(sql`candidates.source_kind`)}\n ) AS candidate_rank\n FROM (\n SELECT expanded.source_id, expanded.source_kind,\n expanded.target_id, expanded.target_kind,\n frontier.distance + expanded.weight AS candidate_distance,\n frontier.hops + 1 AS candidate_hops\n FROM (${expansion}) expanded\n JOIN ${workingTable} frontier\n ON frontier.graph_id = ${graphId}\n AND frontier.run_id = ${runId}\n AND frontier.node_id = expanded.source_id\n AND frontier.node_kind = expanded.source_kind\n ) candidates\n WHERE ${\n roundBound === undefined ?\n sql`TRUE`\n : sql`candidates.candidate_distance <= ${roundBound}`\n }\n ) ranked\n WHERE ranked.candidate_rank = 1\n ON CONFLICT (graph_id, run_id, node_kind, node_id) DO UPDATE SET\n distance = excluded.distance,\n hops = excluded.hops,\n predecessor_id = excluded.predecessor_id,\n predecessor_kind = excluded.predecessor_kind,\n improved_round = excluded.improved_round\n WHERE excluded.distance < ${workingTable}.distance\n RETURNING node_id, distance\n `),\n );\n frontierCount += rows.length;\n for (const row of rows) {\n if (row.node_id !== targetId) continue;\n const distance = Number(row.distance);\n if (bestTargetDistance === undefined || distance < bestTargetDistance) {\n bestTargetDistance = distance;\n }\n }\n }\n return { frontierCount, bestTargetDistance };\n}\n\n/**\n * Extracts the result path directly in SQL: pick the cheapest row carrying\n * the target id (ties by kind in binary collation, matching the inline\n * path's code-point tie-break since the id is fixed), then walk predecessor\n * pointers through a recursive CTE. Transfer and JS memory stay\n * proportional to the path length instead of the visited set. The\n * `position` guard bounds recursion at the round budget — predecessor\n * chains cannot cycle, but a recursive CTE should never rely on that alone.\n */\nasync function extractPathFromWorkingTable(\n context: IterativeGraphRunContext,\n targetId: string,\n maxIterations: number,\n): Promise<WeightedShortestPathResult | undefined> {\n const { operation, workingTable, graphId, runId } = context;\n const { dialect } = operation.ctx;\n const rows = await context.backend.execute<ChainRow>(\n asCompiledRowsSql(sql`\n WITH RECURSIVE chain AS (\n SELECT best.node_id, best.node_kind, best.distance, best.hops,\n best.predecessor_id, best.predecessor_kind, 0 AS position\n FROM (\n SELECT node_id, node_kind, distance, hops,\n predecessor_id, predecessor_kind\n FROM ${workingTable}\n WHERE graph_id = ${graphId}\n AND run_id = ${runId}\n AND node_id = ${targetId}\n ORDER BY distance ASC, ${dialect.binaryText(sql`node_kind`)}\n LIMIT 1\n ) best\n UNION ALL\n SELECT w.node_id, w.node_kind, w.distance, w.hops,\n w.predecessor_id, w.predecessor_kind, c.position + 1\n FROM chain c\n JOIN ${workingTable} w\n ON w.graph_id = ${graphId}\n AND w.run_id = ${runId}\n AND w.node_id = c.predecessor_id\n AND w.node_kind = c.predecessor_kind\n WHERE c.position <= ${maxIterations}\n )\n SELECT node_id, node_kind, distance, hops\n FROM chain\n ORDER BY position DESC\n `),\n );\n // position DESC orders source-first, target-last.\n const target = rows.at(-1);\n if (target === undefined) return undefined;\n return {\n nodes: rows.map((row) => ({ id: row.node_id, kind: row.node_kind })),\n depth: Number(target.hops),\n totalWeight: Number(target.distance),\n };\n}\n\n/**\n * Zero-weight self path: audits the weight domain (so data errors surface\n * identically to a full traversal) and checks the node's visibility, with\n * no relaxation rounds. Multiple kinds sharing the id resolve to the\n * smallest node identity, matching the traversal tie-break.\n */\nasync function findWeightedSelfPath(\n ctx: AlgorithmContext,\n nodeId: string,\n options: WeightedTraversalOptions,\n): Promise<WeightedShortestPathResult | undefined> {\n return withInlineIterativeGraphOperation(ctx, options, async (operation) => {\n await assertValidEdgeWeights(\n operation,\n options.weightProperty,\n options.defaultWeight,\n );\n const nodes = await fetchVisibleWorkingNodes(operation, [nodeId]);\n const node = nodes.toSorted((left, right) =>\n compareNodeIdentity(left, right),\n )[0];\n if (node === undefined) return;\n return { nodes: [node], depth: 0, totalWeight: 0 };\n });\n}\n\n// ============================================================\n// Inline execution (backends without temporary-table support)\n// ============================================================\n\nasync function findWeightedShortestPathInline(\n ctx: AlgorithmContext,\n sourceId: string,\n targetId: string,\n maxIterations: number,\n options: WeightedTraversalOptions,\n): Promise<WeightedShortestPathResult | undefined> {\n return withInlineIterativeGraphOperation(ctx, options, async (operation) => {\n await assertValidEdgeWeights(\n operation,\n options.weightProperty,\n options.defaultWeight,\n );\n const endpoints = await fetchVisibleWorkingNodes(operation, [\n sourceId,\n targetId,\n ]);\n const sources = endpoints.filter((node) => node.id === sourceId);\n // A target no visible node carries can never be reached; skip relaxing\n // the source's entire component.\n if (\n sources.length === 0 ||\n !endpoints.some((node) => node.id === targetId)\n ) {\n return;\n }\n\n const settled = new Map<NodeIdentityKey, WeightedVisitedNode>(\n sources.map((source) => [\n nodeIdentityKey(source),\n {\n id: source.id,\n kind: source.kind,\n distance: 0,\n hops: 0,\n parentKey: undefined,\n },\n ]),\n );\n let bestTargetDistance: number | undefined;\n let frontier: readonly PathNode[] = sources;\n let rounds = 0;\n\n while (frontier.length > 0) {\n if (rounds >= maxIterations) {\n throw new GraphAlgorithmConvergenceError(\n WEIGHTED_ALGORITHM_NAME,\n maxIterations,\n );\n }\n rounds++;\n\n const candidates = await reduceExpandedWorkingSet<WeightedCandidate>(\n operation,\n frontier,\n operation.direction,\n (existing, expansion) =>\n reduceWeightedCandidate(existing, expansion, settled),\n );\n\n // Prune against the best target distance as of the round start, the\n // same state the working-table round's pre-statement snapshot sees, so\n // both execution paths run identical round sequences.\n const roundBound = bestTargetDistance;\n const improved: PathNode[] = [];\n for (const [candidateKey, candidate] of candidates) {\n const existing = settled.get(candidateKey);\n if (existing !== undefined && existing.distance <= candidate.distance) {\n continue;\n }\n // Mirrors the working-table prune: only strictly-worse candidates\n // are dropped. Equal-cost ones stay admitted so zero-weight edges\n // from the equal-cost plateau can still reach a smaller-identity\n // node carrying the target id.\n if (roundBound !== undefined && candidate.distance > roundBound) {\n continue;\n }\n settled.set(candidateKey, {\n id: candidate.id,\n kind: candidate.kind,\n distance: candidate.distance,\n hops: candidate.hops,\n parentKey: nodeIdentityKey({\n id: candidate.parentId,\n kind: candidate.parentKind,\n }),\n });\n improved.push({ id: candidate.id, kind: candidate.kind });\n if (\n candidate.id === targetId &&\n (bestTargetDistance === undefined ||\n candidate.distance < bestTargetDistance)\n ) {\n bestTargetDistance = candidate.distance;\n }\n }\n frontier = improved.toSorted((left, right) =>\n compareNodeIdentity(left, right),\n );\n }\n\n return buildWeightedPathResult(settled, targetId);\n });\n}\n\n/**\n * Keeps the cheapest candidate per target identity; ties break by source id\n * then kind, mirroring the working-table round's ROW_NUMBER ordering.\n */\nfunction reduceWeightedCandidate(\n existing: WeightedCandidate | undefined,\n expansion: NodeExpansion,\n settled: ReadonlyMap<NodeIdentityKey, WeightedVisitedNode>,\n): WeightedCandidate | undefined {\n // Unreachable on a weighted run — the substrate rejects NULL weights with\n // an invariant error — but the field is optional, so narrow it.\n const weight = expansion.weight;\n if (weight === undefined) return existing;\n const sourceEntry = settled.get(nodeIdentityKey(expansion.source));\n if (sourceEntry === undefined) return existing;\n const candidateDistance = sourceEntry.distance + weight;\n if (\n existing !== undefined &&\n (existing.distance < candidateDistance ||\n (existing.distance === candidateDistance &&\n compareNodeIdentity(\n { id: existing.parentId, kind: existing.parentKind },\n expansion.source,\n ) <= 0))\n ) {\n return existing;\n }\n return {\n id: expansion.target.id,\n kind: expansion.target.kind,\n distance: candidateDistance,\n hops: sourceEntry.hops + 1,\n parentId: expansion.source.id,\n parentKind: expansion.source.kind,\n };\n}\n\n// ============================================================\n// Shared result construction\n// ============================================================\n\n/**\n * Selects the cheapest settled node matching the target id (ties by node id\n * then kind) and reconstructs the path by walking predecessors back to the\n * source. Returns `undefined` when the target was never settled.\n */\nfunction buildWeightedPathResult(\n visited: ReadonlyMap<NodeIdentityKey, WeightedVisitedNode>,\n targetId: string,\n): WeightedShortestPathResult | undefined {\n let target: WeightedVisitedNode | undefined;\n for (const node of visited.values()) {\n if (node.id !== targetId) continue;\n if (\n target === undefined ||\n node.distance < target.distance ||\n (node.distance === target.distance &&\n compareNodeIdentity(node, target) < 0)\n ) {\n target = node;\n }\n }\n if (target === undefined) return undefined;\n\n const reversedNodes: PathNode[] = [];\n let cursor: WeightedVisitedNode | undefined = target;\n while (cursor !== undefined) {\n reversedNodes.push({ id: cursor.id, kind: cursor.kind });\n cursor =\n cursor.parentKey === undefined ?\n undefined\n : visited.get(cursor.parentKey);\n }\n\n return {\n nodes: reversedNodes.toReversed(),\n depth: target.hops,\n totalWeight: target.distance,\n };\n}\n","import { type GraphBackend } from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type TemporalMode } from \"../../core/types\";\nimport {\n createSqlSchema,\n type RecordedReadBinding,\n type SqlSchema,\n} from \"../../query/compiler/schema\";\nimport { getDialect } from \"../../query/dialect\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { assertNoRecordedCoordinate } from \"../recorded-coordinate-guard\";\nimport { type AlgorithmContext } from \"./context\";\nimport { executeDegree } from \"./degree\";\nimport { executeLabelPropagation } from \"./label-propagation\";\nimport { executePageRank, executePersonalizedPageRank } from \"./page-rank\";\nimport {\n executeCanReach,\n executeNeighbors,\n executeReachable,\n} from \"./reachable\";\nimport { executeShortestPath } from \"./shortest-path\";\nimport type {\n BaseTraversalOptions,\n DegreeOptions,\n InternalBaseTraversalOptions,\n InternalDegreeOptions,\n InternalLabelPropagationOptions,\n InternalNeighborsOptions,\n InternalPageRankOptions,\n InternalPersonalizedPageRankOptions,\n InternalReachableOptions,\n InternalShortestPathOptions,\n InternalWeaklyConnectedComponentsOptions,\n InternalWeightedShortestPathOptions,\n LabelPropagationMembership,\n LabelPropagationOptions,\n NeighborsOptions,\n PageRankOptions,\n PageRankScore,\n PersonalizedPageRankOptions,\n ReachableNode,\n ReachableOptions,\n ShortestPathOptions,\n ShortestPathResult,\n WeaklyConnectedComponentMembership,\n WeaklyConnectedComponentsOptions,\n WeightedShortestPathOptions,\n WeightedShortestPathResult,\n} from \"./types\";\nimport { executeWeaklyConnectedComponents } from \"./weakly-connected-components\";\nimport { executeWeightedShortestPath } from \"./weighted-shortest-path\";\n\n/**\n * Raw node id or any object with an `id: string` field. Covers `Node`,\n * `NodeRef`, and the lightweight `ReachableNode` / `PathNode` shapes\n * returned by the algorithms themselves.\n *\n * Deliberately kind-agnostic: graph algorithms don't constrain the source\n * node's kind — you can start a traversal from any node reachable via the\n * given edge kinds. `NodeRef<N>` exists for the edge-endpoint case where\n * kind *is* load-bearing; using it here would paint a constraint onto a\n * contract that doesn't need one and would reject common patterns like\n * passing `ReachableNode` / cache entries / `{ id }` records straight\n * through.\n */\nexport type NodeIdentifier = string | Readonly<{ id: string }>;\n\nfunction resolveNodeId(value: NodeIdentifier): string {\n return typeof value === \"string\" ? value : value.id;\n}\n\nexport type GraphAlgorithms<G extends GraphDef> = Readonly<{\n /**\n * Finds the shortest directed path from `from` to `to` using the given\n * edge kinds. Returns `undefined` when no path exists within `maxHops`.\n *\n * @example\n * ```typescript\n * const path = await store.algorithms.shortestPath(alice, bob, {\n * edges: [\"knows\"],\n * maxHops: 6,\n * });\n * if (path) {\n * console.log(`${path.depth} hops via`, path.nodes.map((n) => n.id));\n * }\n * ```\n */\n shortestPath: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: ShortestPathOptions<G>,\n ) => Promise<ShortestPathResult | undefined>;\n\n /**\n * Finds the minimum-total-weight path from `from` to `to`, weighting each\n * traversed edge by the numeric `weightProperty` stored on it. Returns\n * `undefined` when no path exists. Weights must be non-negative; a\n * negative, non-numeric, or (without `defaultWeight`) missing weight on\n * any visible edge of the selected kinds throws `InvalidEdgeWeightError`\n * before traversal starts.\n *\n * @example\n * ```typescript\n * const path = await store.algorithms.weightedShortestPath(alice, bob, {\n * edges: [\"knows\"],\n * weightProperty: \"interactionCost\",\n * direction: \"both\",\n * });\n * if (path) {\n * console.log(`total weight ${path.totalWeight} over ${path.depth} hops`);\n * }\n * ```\n */\n weightedShortestPath: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: WeightedShortestPathOptions<G>,\n ) => Promise<WeightedShortestPathResult | undefined>;\n\n /**\n * Returns every node reachable from `from` within `maxHops` edges of the\n * allowed kinds. Each node carries its minimum discovered depth.\n */\n reachable: (\n from: NodeIdentifier,\n options: ReachableOptions<G>,\n ) => Promise<readonly ReachableNode[]>;\n\n /**\n * Fast boolean check: is `to` reachable from `from` within `maxHops`\n * edges? Uses bidirectional BFS and stops when the frontiers meet.\n */\n canReach: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: BaseTraversalOptions<G>,\n ) => Promise<boolean>;\n\n /**\n * Returns the k-hop neighborhood of a node. The source is always\n * excluded. `depth` defaults to 1, matching the common \"immediate\n * neighbors\" interpretation.\n */\n neighbors: (\n node: NodeIdentifier,\n options: NeighborsOptions<G>,\n ) => Promise<readonly ReachableNode[]>;\n\n /**\n * Counts active edges incident to `node`.\n *\n * With `direction: \"both\"` (default), self-loops contribute once.\n */\n degree: (node: NodeIdentifier, options?: DegreeOptions<G>) => Promise<number>;\n\n /**\n * Runs deterministic synchronous label propagation over an undirected\n * projection of the selected edge kinds.\n */\n labelPropagation: (\n options: LabelPropagationOptions<G>,\n ) => Promise<readonly LabelPropagationMembership[]>;\n\n /**\n * Computes exact weakly connected components over the selected edge kinds.\n *\n * Iterative: runs multiple SQL rounds in one snapshot and requires\n * `backend.capabilities.graphAnalytics.supported`.\n */\n weaklyConnectedComponents: (\n options: WeaklyConnectedComponentsOptions<G>,\n ) => Promise<readonly WeaklyConnectedComponentMembership[]>;\n\n /**\n * Computes global PageRank over the visible induced graph. Scores sum to\n * approximately one and are returned from highest to lowest.\n */\n pageRank: (options: PageRankOptions<G>) => Promise<readonly PageRankScore[]>;\n\n /**\n * Computes PageRank with teleport mass distributed across weighted seeds.\n */\n personalizedPageRank: (\n options: PersonalizedPageRankOptions<G>,\n ) => Promise<readonly PageRankScore[]>;\n}>;\n\nexport type InternalGraphAlgorithms<G extends GraphDef> = Readonly<{\n shortestPath: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: InternalShortestPathOptions<G>,\n ) => Promise<ShortestPathResult | undefined>;\n weightedShortestPath: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: InternalWeightedShortestPathOptions<G>,\n ) => Promise<WeightedShortestPathResult | undefined>;\n reachable: (\n from: NodeIdentifier,\n options: InternalReachableOptions<G>,\n ) => Promise<readonly ReachableNode[]>;\n canReach: (\n from: NodeIdentifier,\n to: NodeIdentifier,\n options: InternalBaseTraversalOptions<G>,\n ) => Promise<boolean>;\n neighbors: (\n node: NodeIdentifier,\n options: InternalNeighborsOptions<G>,\n ) => Promise<readonly ReachableNode[]>;\n degree: (\n node: NodeIdentifier,\n options?: InternalDegreeOptions<G>,\n ) => Promise<number>;\n labelPropagation: (\n options: InternalLabelPropagationOptions<G>,\n ) => Promise<readonly LabelPropagationMembership[]>;\n weaklyConnectedComponents: (\n options: InternalWeaklyConnectedComponentsOptions<G>,\n ) => Promise<readonly WeaklyConnectedComponentMembership[]>;\n pageRank: (\n options: InternalPageRankOptions<G>,\n ) => Promise<readonly PageRankScore[]>;\n personalizedPageRank: (\n options: InternalPersonalizedPageRankOptions<G>,\n ) => Promise<readonly PageRankScore[]>;\n}>;\n\nexport type CreateGraphAlgorithmsParams = Readonly<{\n graphId: string;\n graph: GraphDef;\n registry: KindRegistry;\n backend: GraphBackend;\n schema: SqlSchema | undefined;\n recordedReadBinding: RecordedReadBinding | undefined;\n defaultTemporalMode: TemporalMode;\n allowRecordedAsOf?: boolean;\n}>;\n\nfunction assertRecordedAsOfInternalOnly(\n options: unknown,\n method: string,\n allowRecordedAsOf: boolean,\n): void {\n if (allowRecordedAsOf) return;\n assertNoRecordedCoordinate(options, {\n code: \"ALGORITHM_RECORDED_ASOF_INTERNAL_ONLY\",\n message: `recordedAsOf is only available through store.asOfRecorded(...).${method}(...).`,\n context: { method },\n suggestion:\n \"Use store.asOfRecorded(recordedAt) or a recorded StoreView instead of passing recordedAsOf directly.\",\n });\n}\n\nexport function createGraphAlgorithms<G extends GraphDef>(\n params: CreateGraphAlgorithmsParams,\n): InternalGraphAlgorithms<G> {\n const allowRecordedAsOf = params.allowRecordedAsOf === true;\n const ctx: AlgorithmContext = {\n graphId: params.graphId,\n graph: params.graph,\n registry: params.registry,\n backend: params.backend,\n dialect: getDialect(params.backend.dialect),\n schema: params.schema ?? createSqlSchema(params.backend.tableNames),\n recordedReadBinding: params.recordedReadBinding,\n defaultTemporalMode: params.defaultTemporalMode,\n };\n\n return {\n shortestPath(from, to, options) {\n assertRecordedAsOfInternalOnly(\n options,\n \"shortestPath\",\n allowRecordedAsOf,\n );\n return executeShortestPath(\n ctx,\n resolveNodeId(from),\n resolveNodeId(to),\n options,\n );\n },\n weightedShortestPath(from, to, options) {\n assertRecordedAsOfInternalOnly(\n options,\n \"weightedShortestPath\",\n allowRecordedAsOf,\n );\n return executeWeightedShortestPath(\n ctx,\n resolveNodeId(from),\n resolveNodeId(to),\n options,\n );\n },\n reachable(from, options) {\n assertRecordedAsOfInternalOnly(options, \"reachable\", allowRecordedAsOf);\n return executeReachable(ctx, resolveNodeId(from), options);\n },\n canReach(from, to, options) {\n assertRecordedAsOfInternalOnly(options, \"canReach\", allowRecordedAsOf);\n return executeCanReach(\n ctx,\n resolveNodeId(from),\n resolveNodeId(to),\n options,\n );\n },\n neighbors(node, options) {\n assertRecordedAsOfInternalOnly(options, \"neighbors\", allowRecordedAsOf);\n return executeNeighbors(ctx, resolveNodeId(node), options);\n },\n degree(node, options) {\n assertRecordedAsOfInternalOnly(options, \"degree\", allowRecordedAsOf);\n return executeDegree(ctx, resolveNodeId(node), options ?? {});\n },\n labelPropagation(options) {\n assertRecordedAsOfInternalOnly(\n options,\n \"labelPropagation\",\n allowRecordedAsOf,\n );\n return executeLabelPropagation(ctx, options);\n },\n weaklyConnectedComponents(options) {\n assertRecordedAsOfInternalOnly(\n options,\n \"weaklyConnectedComponents\",\n allowRecordedAsOf,\n );\n return executeWeaklyConnectedComponents(ctx, options);\n },\n pageRank(options) {\n assertRecordedAsOfInternalOnly(options, \"pageRank\", allowRecordedAsOf);\n return executePageRank(ctx, options);\n },\n personalizedPageRank(options) {\n assertRecordedAsOfInternalOnly(\n options,\n \"personalizedPageRank\",\n allowRecordedAsOf,\n );\n return executePersonalizedPageRank(ctx, options);\n },\n };\n}\n\nexport type {\n AlgorithmCyclePolicy,\n BaseTraversalOptions,\n DegreeOptions,\n InternalBaseTraversalOptions,\n InternalDegreeOptions,\n InternalLabelPropagationOptions,\n InternalNeighborsOptions,\n InternalPageRankOptions,\n InternalPersonalizedPageRankOptions,\n InternalReachableOptions,\n InternalShortestPathOptions,\n InternalTemporalAlgorithmOptions,\n InternalWeaklyConnectedComponentsOptions,\n InternalWeightedShortestPathOptions,\n LabelPropagationMembership,\n LabelPropagationOptions,\n NeighborsOptions,\n PageRankOptions,\n PageRankScore,\n PathNode,\n PersonalizedPageRankOptions,\n PersonalizedPageRankSeed,\n ReachableNode,\n ReachableOptions,\n ShortestPathOptions,\n ShortestPathResult,\n TemporalAlgorithmOptions,\n TraversalDirection,\n WeaklyConnectedComponentMembership,\n WeaklyConnectedComponentsOptions,\n WeightedShortestPathOptions,\n WeightedShortestPathResult,\n} from \"./types\";\n","/**\n * EdgeCollection implementation.\n *\n * Provides an ergonomic API for CRUD operations on a specific edge type.\n */\nimport { type z } from \"zod\";\n\nimport {\n type FindEdgesByKindParams,\n type GraphBackend,\n rowPropsToObject,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport { type AnyEdgeType, type TemporalMode } from \"../../core/types\";\nimport { UnsupportedPredicateError } from \"../../errors\";\nimport { type QueryBuilder } from \"../../query/builder\";\nimport type { BatchableQuery } from \"../../query/builder/types\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { getEdgeRowsByIds } from \"../edge-fetch\";\nimport { type EdgeRow } from \"../row-mappers\";\nimport {\n type CreateEdgeInput,\n type Edge,\n type EdgeCollection,\n type EdgeFindByEndpointsOptions,\n type EdgeGetOrCreateByEndpointsOptions,\n type EdgeGetOrCreateByEndpointsResult,\n type GetOrCreateAction,\n type IfExistsMode,\n type NodeRef,\n type QueryOptions,\n} from \"../types\";\nimport {\n type UpsertDirtyCheck,\n type UpsertDirtyCheckFunction,\n} from \"./coalesce\";\nimport {\n resolveTemporalReadParams,\n type TemporalReadParams,\n} from \"./temporal-read-params\";\n\n/**\n * Narrows unparameterized Edge to Edge<E>.\n * Safe: props are validated by Zod at creation/update boundaries.\n */\nfunction narrowEdge<E extends AnyEdgeType>(edge: Edge): Edge<E> {\n return edge as Edge<E>;\n}\n\n/**\n * Narrows a readonly Edge array to Edge<E>[].\n */\nfunction narrowEdges<E extends AnyEdgeType>(edges: readonly Edge[]): Edge<E>[] {\n return edges as Edge<E>[];\n}\n\n/**\n * Config for creating an EdgeCollection.\n */\nexport type EdgeCollectionConfig = Readonly<{\n graphId: string;\n kind: string;\n backend: GraphBackend | TransactionBackend;\n defaultTemporalMode: TemporalMode;\n rowToEdge: (row: EdgeRow) => Edge;\n /** See EdgeOperations.maybeRefreshStatisticsAfterBulk. */\n maybeRefreshStatisticsAfterBulk?:\n ((rowCount: number) => Promise<void>) | undefined;\n executeCreate: (\n input: CreateEdgeInput,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Edge>;\n executeCreateNoReturnBatch: (\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeCreateBatch: (\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<readonly Edge[]>;\n executeUpdate: (\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Edge>;\n executeUpsertUpdate: (\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Edge>;\n /** See EdgeOperations.upsertDirtyCheck. */\n upsertDirtyCheck?: UpsertDirtyCheckFunction;\n executeDelete: (\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeHardDelete: (\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n temporalRowMatcher: (options?: QueryOptions) => (row: EdgeRow) => boolean;\n createQuery?: () => QueryBuilder<GraphDef>;\n executeGetOrCreateByEndpoints: (\n kind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n }>,\n ) => Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>>;\n executeBulkGetOrCreateByEndpoints: (\n kind: string,\n items: readonly Readonly<{\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Record<string, unknown>;\n }>[],\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n }>,\n ) => Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>[]>;\n executeFindByEndpoints: (\n kind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n props?: Record<string, unknown>;\n excludeDeleted?: boolean;\n temporalMode?: TemporalMode;\n asOf?: string;\n }>,\n ) => Promise<Edge | undefined>;\n}>;\n\nfunction buildCreateEdgeInput(\n kind: string,\n from: NodeRef,\n to: NodeRef,\n props: Record<string, unknown>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n): CreateEdgeInput {\n const input: {\n kind: string;\n id?: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Record<string, unknown>;\n validFrom?: string;\n validTo?: string;\n } = {\n kind,\n fromKind: from.kind,\n fromId: from.id,\n toKind: to.kind,\n toId: to.id,\n props,\n };\n if (options?.id !== undefined) input.id = options.id;\n if (options?.validFrom !== undefined) input.validFrom = options.validFrom;\n if (options?.validTo !== undefined) input.validTo = options.validTo;\n return input;\n}\n\ntype EdgeUpdateInput = Readonly<{\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n}>;\n\nfunction buildUpdateEdgeInput(\n id: string,\n props: Record<string, unknown>,\n options?: Readonly<{ validTo?: string }>,\n): EdgeUpdateInput {\n const input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n } = { id, props };\n if (options?.validTo !== undefined) input.validTo = options.validTo;\n return input;\n}\n\nfunction mapBulkEdgeInputs(\n kind: string,\n items: readonly Readonly<{\n from: NodeRef;\n to: NodeRef;\n props?: Record<string, unknown>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n): CreateEdgeInput[] {\n return items.map((item) =>\n buildCreateEdgeInput(kind, item.from, item.to, item.props ?? {}, item),\n );\n}\n\n/**\n * Creates an EdgeCollection for a specific edge type.\n */\nexport function createEdgeCollection<\n G extends GraphDef,\n K extends keyof G[\"edges\"] & string,\n>(config: EdgeCollectionConfig): EdgeCollection<G[\"edges\"][K][\"type\"]> {\n type E = G[\"edges\"][K][\"type\"];\n\n const {\n graphId,\n kind,\n backend,\n defaultTemporalMode,\n rowToEdge,\n executeCreate: executeEdgeCreate,\n executeCreateNoReturnBatch: executeEdgeCreateNoReturnBatch,\n executeCreateBatch: executeEdgeCreateBatch,\n executeUpdate: executeEdgeUpdate,\n executeUpsertUpdate: executeEdgeUpsertUpdate,\n executeDelete: executeEdgeDelete,\n executeHardDelete: executeEdgeHardDelete,\n temporalRowMatcher,\n } = config;\n\n const mapRows = (rows: readonly EdgeRow[]): Edge<E>[] =>\n rows.map((row) => narrowEdge<E>(rowToEdge(row)));\n\n /**\n * Builds the `findEdgesByKind` params for an endpoint lookup, resolving\n * the temporal mode the same way `find` / `getById` do: the per-call\n * `options` win, falling back to the graph's default mode. Keeps\n * `findFrom` / `findTo` honoring the temporal model instead of silently\n * returning every non-deleted edge.\n */\n function buildEndpointFindParams(\n endpoint:\n | Readonly<{ fromKind: string; fromId: string }>\n | Readonly<{ toKind: string; toId: string }>,\n options: QueryOptions | undefined,\n ): FindEdgesByKindParams {\n return {\n graphId,\n kind,\n ...endpoint,\n ...resolveTemporalReadParams(options, defaultTemporalMode),\n };\n }\n\n async function findEdgesFrom(\n from: NodeRef,\n target: GraphBackend | TransactionBackend,\n options?: QueryOptions,\n ): Promise<Edge<E>[]> {\n const rows = await target.findEdgesByKind(\n buildEndpointFindParams(\n { fromKind: from.kind, fromId: from.id },\n options,\n ),\n );\n return mapRows(rows);\n }\n\n async function findEdgesTo(\n to: NodeRef,\n target: GraphBackend | TransactionBackend,\n options?: QueryOptions,\n ): Promise<Edge<E>[]> {\n const rows = await target.findEdgesByKind(\n buildEndpointFindParams({ toKind: to.kind, toId: to.id }, options),\n );\n return mapRows(rows);\n }\n\n function buildFindByEndpointsOptions(\n options?: EdgeFindByEndpointsOptions<E>,\n temporal?: QueryOptions,\n ): Readonly<{\n matchOn?: readonly string[];\n props?: Record<string, unknown>;\n excludeDeleted?: boolean;\n temporalMode?: TemporalMode;\n asOf?: string;\n }> {\n const result: {\n matchOn?: readonly string[];\n props?: Record<string, unknown>;\n excludeDeleted?: boolean;\n temporalMode?: TemporalMode;\n asOf?: string;\n } = { ...resolveTemporalReadParams(temporal, defaultTemporalMode) };\n if (options?.matchOn !== undefined)\n result.matchOn = options.matchOn as readonly string[];\n if (options?.props !== undefined) result.props = options.props;\n return result;\n }\n\n return {\n async create(\n from: NodeRef,\n to: NodeRef,\n props?: z.input<E[\"schema\"]>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n ): Promise<Edge<E>> {\n const result = await executeEdgeCreate(\n buildCreateEdgeInput(kind, from, to, props ?? {}, options),\n backend,\n );\n return narrowEdge<E>(result);\n },\n\n async getById(\n id: string,\n options?: QueryOptions,\n ): Promise<Edge<E> | undefined> {\n const row = await backend.getEdge(graphId, id);\n if (!row) return undefined;\n if (row.kind !== kind) return undefined; // Edge is a different type\n if (!temporalRowMatcher(options)(row)) return undefined;\n return narrowEdge<E>(rowToEdge(row));\n },\n\n async getByIds(\n ids: readonly string[],\n options?: QueryOptions,\n ): Promise<readonly (Edge<E> | undefined)[]> {\n if (ids.length === 0) return [];\n\n const rowsById = await getEdgeRowsByIds(backend, graphId, ids);\n // Resolve the coordinate once so the whole batch observes one instant.\n const matches = temporalRowMatcher(options);\n return ids.map((id) => {\n const row = rowsById.get(id);\n if (!row) return;\n if (row.kind !== kind) return;\n if (!matches(row)) return;\n return narrowEdge<E>(rowToEdge(row));\n });\n },\n\n async update(\n id: string,\n props: Partial<z.input<E[\"schema\"]>>,\n options?: Readonly<{ validTo?: string }>,\n ): Promise<Edge<E>> {\n const result = await executeEdgeUpdate(\n buildUpdateEdgeInput(id, props, options),\n backend,\n );\n return narrowEdge<E>(result);\n },\n\n async findFrom(from: NodeRef, options?: QueryOptions): Promise<Edge<E>[]> {\n return findEdgesFrom(from, backend, options);\n },\n\n async findTo(to: NodeRef, options?: QueryOptions): Promise<Edge<E>[]> {\n return findEdgesTo(to, backend, options);\n },\n\n batchFindFrom(\n from: NodeRef,\n options?: QueryOptions,\n ): BatchableQuery<Edge<E>> {\n return { executeOn: (target) => findEdgesFrom(from, target, options) };\n },\n\n batchFindTo(to: NodeRef, options?: QueryOptions): BatchableQuery<Edge<E>> {\n return { executeOn: (target) => findEdgesTo(to, target, options) };\n },\n\n batchFindByEndpoints(\n from: NodeRef,\n to: NodeRef,\n options?: EdgeFindByEndpointsOptions<E>,\n temporal?: QueryOptions,\n ): BatchableQuery<Edge<E>> {\n return {\n executeOn: async (target) => {\n const result = await config.executeFindByEndpoints(\n kind,\n from.kind,\n from.id,\n to.kind,\n to.id,\n target,\n buildFindByEndpointsOptions(options, temporal),\n );\n return result === undefined ? [] : [narrowEdge<E>(result)];\n },\n };\n },\n\n async delete(id: string): Promise<void> {\n await executeEdgeDelete(id, backend);\n },\n\n async hardDelete(id: string): Promise<void> {\n await executeEdgeHardDelete(id, backend);\n },\n\n async find(\n filter?: Readonly<{\n from?: NodeRef;\n to?: NodeRef;\n limit?: number;\n offset?: number;\n }>,\n temporal?: QueryOptions,\n ): Promise<Edge<E>[]> {\n const untypedFilter = filter as Readonly<{ where?: unknown }> | undefined;\n if (untypedFilter?.where !== undefined) {\n throw new UnsupportedPredicateError(\n `store.edges.${kind}.find({ where }) is not supported. ` +\n `Use store.query().traverse(...).whereEdge(...) for edge property filters.`,\n { kind, operation: \"find\" },\n );\n }\n\n const params: {\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n limit?: number;\n offset?: number;\n } & TemporalReadParams = {\n graphId,\n kind,\n ...resolveTemporalReadParams(temporal, defaultTemporalMode),\n };\n if (filter?.from?.kind !== undefined) params.fromKind = filter.from.kind;\n if (filter?.from?.id !== undefined) params.fromId = filter.from.id;\n if (filter?.to?.kind !== undefined) params.toKind = filter.to.kind;\n if (filter?.to?.id !== undefined) params.toId = filter.to.id;\n if (filter?.limit !== undefined) params.limit = filter.limit;\n if (filter?.offset !== undefined) params.offset = filter.offset;\n\n const rows = await backend.findEdgesByKind(params);\n return mapRows(rows);\n },\n\n async count(\n filter?: Readonly<{\n from?: NodeRef;\n to?: NodeRef;\n }>,\n temporal?: QueryOptions,\n ): Promise<number> {\n const params: {\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n } & TemporalReadParams = {\n graphId,\n kind,\n ...resolveTemporalReadParams(temporal, defaultTemporalMode),\n };\n if (filter?.from?.kind !== undefined) params.fromKind = filter.from.kind;\n if (filter?.from?.id !== undefined) params.fromId = filter.from.id;\n if (filter?.to?.kind !== undefined) params.toKind = filter.to.kind;\n if (filter?.to?.id !== undefined) params.toId = filter.to.id;\n\n return backend.countEdgesByKind(params);\n },\n\n async bulkCreate(\n items: readonly Readonly<{\n from: NodeRef;\n to: NodeRef;\n props?: z.input<E[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ): Promise<Edge<E>[]> {\n const batchInputs = mapBulkEdgeInputs(kind, items);\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n const results = await backend.transaction(async (txBackend) =>\n executeEdgeCreateBatch(batchInputs, txBackend),\n );\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n return narrowEdges<E>(results);\n }\n const results = await executeEdgeCreateBatch(batchInputs, backend);\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n return narrowEdges<E>(results);\n },\n\n async bulkUpsertById(\n items: readonly Readonly<{\n id: string;\n from: NodeRef;\n to: NodeRef;\n props?: z.input<E[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n }>[],\n ): Promise<Edge<E>[]> {\n if (items.length === 0) return [];\n\n const upsertAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<{ results: Edge<E>[]; mutations: number }> => {\n const ids = items.map((item) => item.id);\n const existingMap = await getEdgeRowsByIds(target, graphId, ids);\n\n // Coalesced items are written straight to results (the existing or\n // last-written edge) and skipped from the write batch; see the node\n // collection and BaseStoreOptions.coalesceUnchangedUpserts.\n const results: Edge<E>[] = Array.from({ length: items.length });\n\n // Bucket items into creates and updates\n const toCreate: { index: number; input: CreateEdgeInput }[] = [];\n const toUpdate: {\n index: number;\n input: EdgeUpdateInput;\n clearDeleted: boolean;\n }[] = [];\n\n // Batch-local running state per id so a repeated id coalesces against\n // the value earlier items in this batch would write, preserving\n // last-write-wins. See the node collection for the full rationale.\n const pending = new Map<\n string,\n { props: Record<string, unknown>; sourceIndex: number }\n >();\n const deferred: { index: number; sourceIndex: number }[] = [];\n\n let itemIndex = 0;\n for (const item of items) {\n const pendingEntry = pending.get(item.id);\n const original = existingMap.get(item.id);\n const inputProps = item.props ?? {};\n\n if (pendingEntry === undefined && original === undefined) {\n toCreate.push({\n index: itemIndex,\n input: buildCreateEdgeInput(\n kind,\n item.from,\n item.to,\n inputProps,\n item,\n ),\n });\n itemIndex++;\n continue;\n }\n\n const deletedAt =\n pendingEntry === undefined ?\n requireDefined(original).deleted_at\n : undefined;\n\n let dirty: UpsertDirtyCheck | undefined;\n if (config.upsertDirtyCheck !== undefined) {\n const currentProps =\n pendingEntry?.props ??\n rowPropsToObject(requireDefined(original).props);\n try {\n // The fetched edge carries the authoritative kind (an id may\n // resolve to a different edge kind than this collection).\n dirty = config.upsertDirtyCheck(\n original?.kind ?? kind,\n item.id,\n currentProps,\n inputProps,\n );\n } catch {\n dirty = undefined;\n }\n }\n\n const coalesce =\n dirty?.unchanged === true &&\n deletedAt === undefined &&\n item.validFrom === undefined &&\n item.validTo === undefined;\n\n if (coalesce) {\n if (pendingEntry === undefined) {\n results[itemIndex] = narrowEdge<E>(\n rowToEdge(requireDefined(original)),\n );\n } else {\n deferred.push({\n index: itemIndex,\n sourceIndex: pendingEntry.sourceIndex,\n });\n }\n } else {\n toUpdate.push({\n index: itemIndex,\n input: buildUpdateEdgeInput(item.id, inputProps, item),\n clearDeleted: deletedAt !== undefined,\n });\n if (dirty !== undefined) {\n pending.set(item.id, {\n props: dirty.validatedProps,\n sourceIndex: itemIndex,\n });\n }\n }\n itemIndex++;\n }\n\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const created = await executeEdgeCreateBatch(createInputs, target);\n for (const [index, entry] of toCreate.entries()) {\n results[entry.index] = narrowEdge<E>(\n requireDefined(created[index]),\n );\n }\n }\n\n // Hookless individual updates (executeEdgeUpsertUpdate is already hookless)\n for (const entry of toUpdate) {\n const result = await executeEdgeUpsertUpdate(entry.input, target, {\n clearDeleted: entry.clearDeleted,\n });\n results[entry.index] = narrowEdge<E>(result);\n }\n\n // Items that coalesced against an in-batch write take that write's\n // result (now filled). Its sourceIndex is always a write slot.\n for (const { index, sourceIndex } of deferred) {\n results[index] = requireDefined(results[sourceIndex]);\n }\n\n return { results, mutations: toCreate.length + toUpdate.length };\n };\n\n const { results, mutations } =\n backend.capabilities.transactions && \"transaction\" in backend ?\n await backend.transaction(async (txBackend) => upsertAll(txBackend))\n : await upsertAll(backend);\n // Match bulkCreate/bulkInsert: refresh planner statistics after a large\n // autocommit bulk write. Coalesced items wrote nothing, so only real\n // mutations count toward the threshold. A no-op inside a caller\n // transaction (the hook is intentionally undefined there).\n await config.maybeRefreshStatisticsAfterBulk?.(mutations);\n return results;\n },\n\n async bulkInsert(\n items: readonly Readonly<{\n from: NodeRef;\n to: NodeRef;\n props?: z.input<E[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ): Promise<void> {\n const batchInputs = mapBulkEdgeInputs(kind, items);\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n await backend.transaction(async (txBackend) => {\n await executeEdgeCreateNoReturnBatch(batchInputs, txBackend);\n });\n await config.maybeRefreshStatisticsAfterBulk?.(batchInputs.length);\n return;\n }\n\n await executeEdgeCreateNoReturnBatch(batchInputs, backend);\n await config.maybeRefreshStatisticsAfterBulk?.(batchInputs.length);\n },\n\n async bulkDelete(ids: readonly string[]): Promise<void> {\n if (ids.length === 0) return;\n const deleteAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n for (const id of ids) {\n await executeEdgeDelete(id, target);\n }\n };\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n await backend.transaction(async (txBackend) => deleteAll(txBackend));\n return;\n }\n await deleteAll(backend);\n },\n\n async findByEndpoints(\n from: NodeRef,\n to: NodeRef,\n options?: EdgeFindByEndpointsOptions<E>,\n temporal?: QueryOptions,\n ): Promise<Edge<E> | undefined> {\n const result = await config.executeFindByEndpoints(\n kind,\n from.kind,\n from.id,\n to.kind,\n to.id,\n backend,\n buildFindByEndpointsOptions(options, temporal),\n );\n return result === undefined ? undefined : narrowEdge<E>(result);\n },\n\n async getOrCreateByEndpoints(\n from: NodeRef,\n to: NodeRef,\n props: z.input<E[\"schema\"]>,\n options?: EdgeGetOrCreateByEndpointsOptions<E>,\n ): Promise<EdgeGetOrCreateByEndpointsResult<E>> {\n const getOrCreateOptions: {\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n } = {};\n if (options?.matchOn !== undefined)\n getOrCreateOptions.matchOn = options.matchOn as readonly string[];\n if (options?.ifExists !== undefined)\n getOrCreateOptions.ifExists = options.ifExists;\n\n const result = await config.executeGetOrCreateByEndpoints(\n kind,\n from.kind,\n from.id,\n to.kind,\n to.id,\n props,\n backend,\n getOrCreateOptions,\n );\n return { edge: narrowEdge<E>(result.edge), action: result.action };\n },\n\n async bulkGetOrCreateByEndpoints(\n items: readonly Readonly<{\n from: NodeRef;\n to: NodeRef;\n props: z.input<E[\"schema\"]>;\n }>[],\n options?: EdgeGetOrCreateByEndpointsOptions<E>,\n ): Promise<EdgeGetOrCreateByEndpointsResult<E>[]> {\n if (items.length === 0) return [];\n\n const mappedItems = items.map((item) => ({\n fromKind: item.from.kind,\n fromId: item.from.id,\n toKind: item.to.kind,\n toId: item.to.id,\n props: item.props,\n }));\n\n const getOrCreateOptions: {\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n } = {};\n if (options?.matchOn !== undefined)\n getOrCreateOptions.matchOn = options.matchOn as readonly string[];\n if (options?.ifExists !== undefined)\n getOrCreateOptions.ifExists = options.ifExists;\n\n const getOrCreateAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<EdgeGetOrCreateByEndpointsResult<E>[]> => {\n const results = await config.executeBulkGetOrCreateByEndpoints(\n kind,\n mappedItems,\n target,\n getOrCreateOptions,\n );\n return results.map((result) => ({\n edge: narrowEdge<E>(result.edge),\n action: result.action,\n }));\n };\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n return backend.transaction(async (txBackend) =>\n getOrCreateAll(txBackend),\n );\n }\n return getOrCreateAll(backend);\n },\n };\n}\n","/**\n * Coalesce dirty-check shared by `upsertById` / `bulkUpsertById`.\n *\n * A store created with `coalesceUnchangedUpserts` skips the write for an upsert\n * whose validated props already equal the row's stored props (see\n * {@link file://../types.ts BaseStoreOptions.coalesceUnchangedUpserts}).\n */\n\n/**\n * Result of the dirty check: the props the update WOULD persist (input merged\n * over the current props and run through the kind's Zod schema), and whether\n * they equal the current props (so the write can be skipped). `validatedProps`\n * doubles as the batch-local running value a later same-id item is compared\n * against in the bulk path.\n */\nexport type UpsertDirtyCheck = Readonly<{\n validatedProps: Record<string, unknown>;\n unchanged: boolean;\n}>;\n\n/**\n * The seam collections call to run the dirty check. Present only when the store\n * enabled coalescing; its absence is the off switch. `existingProps` is the\n * PARSED current props — the prefetched row's, or the batch-local running value\n * for a repeated id.\n */\nexport type UpsertDirtyCheckFunction = (\n kind: string,\n id: string,\n existingProps: Record<string, unknown>,\n inputProps: Record<string, unknown>,\n) => UpsertDirtyCheck;\n\n/**\n * Whether a single upsert may be coalesced: coalescing is enabled\n * (`runDirtyCheck` present), the row is live, no explicit temporal override was\n * requested, and the props are unchanged. The dirty check runs last (only when\n * the cheap preconditions pass).\n *\n * A throw from the dirty check is treated as \"do not coalesce\". The check\n * validates the input, so it can throw a `ValidationError`; that must not fail\n * HERE, ahead of the operation hooks. Falling through to the normal write path\n * re-validates inside the hooked pipeline, which raises the error with correct\n * `onError` wiring (matching flag-off) — the error is re-raised there, not\n * swallowed.\n */\nexport function shouldCoalesceUpsert(\n existing: Readonly<{ deleted_at: string | undefined }>,\n options: Readonly<{ validFrom?: string; validTo?: string }> | undefined,\n runDirtyCheck: (() => UpsertDirtyCheck) | undefined,\n): boolean {\n if (\n runDirtyCheck === undefined ||\n existing.deleted_at !== undefined ||\n options?.validFrom !== undefined ||\n options?.validTo !== undefined\n ) {\n return false;\n }\n try {\n return runDirtyCheck().unchanged;\n } catch {\n return false;\n }\n}\n","/**\n * NodeCollection implementation.\n *\n * Provides an ergonomic API for CRUD operations on a specific node type.\n */\nimport { type z } from \"zod\";\n\nimport {\n type GraphBackend,\n rowPropsToObject,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n type NodeId,\n type NodeType,\n type TemporalMode,\n} from \"../../core/types\";\nimport { ConfigurationError } from \"../../errors\";\nimport { type QueryBuilder } from \"../../query/builder\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { getNodeRowsByIds } from \"../node-fetch\";\nimport { type NodeRow } from \"../row-mappers\";\nimport {\n type CreateNodeInput,\n type GetOrCreateAction,\n type Node,\n type NodeBulkFindByIndexOptions,\n type NodeCollection,\n type NodeGetOrCreateByConstraintOptions,\n type NodeGetOrCreateByConstraintResult,\n type QueryOptions,\n type UpdateNodeInput,\n} from \"../types\";\nimport {\n shouldCoalesceUpsert,\n type UpsertDirtyCheck,\n type UpsertDirtyCheckFunction,\n} from \"./coalesce\";\nimport {\n resolveTemporalReadParams,\n type TemporalReadParams,\n} from \"./temporal-read-params\";\n\n/**\n * Narrows unparameterized Node to Node<N>.\n * Safe: props are validated by Zod at creation/update boundaries.\n */\nfunction narrowNode<N extends NodeType>(node: Node): Node<N> {\n return node as Node<N>;\n}\n\n/**\n * Narrows a readonly Node array to Node<N>[].\n */\nfunction narrowNodes<N extends NodeType>(nodes: readonly Node[]): Node<N>[] {\n return nodes as Node<N>[];\n}\n\n/**\n * Config for creating a NodeCollection.\n */\nexport type NodeCollectionConfig = Readonly<{\n graphId: string;\n kind: string;\n backend: GraphBackend | TransactionBackend;\n defaultTemporalMode: TemporalMode;\n rowToNode: (row: NodeRow) => Node;\n /** See NodeOperations.maybeRefreshStatisticsAfterBulk. */\n maybeRefreshStatisticsAfterBulk?:\n ((rowCount: number) => Promise<void>) | undefined;\n executeCreate: (\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Node>;\n executeCreateNoReturnBatch: (\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeCreateBatch: (\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<readonly Node[]>;\n executeUpdate: (\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Node>;\n executeUpsertUpdate: (\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Node>;\n /** See NodeOperations.upsertDirtyCheck. */\n upsertDirtyCheck?: UpsertDirtyCheckFunction;\n executeDelete: (\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeHardDelete: (\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n temporalRowMatcher: (options?: QueryOptions) => (row: NodeRow) => boolean;\n createQuery?: () => QueryBuilder<GraphDef>;\n executeGetOrCreateByConstraint: (\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n options?: NodeGetOrCreateByConstraintOptions,\n ) => Promise<Readonly<{ node: Node; action: GetOrCreateAction }>>;\n executeBulkGetOrCreateByConstraint: (\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeGetOrCreateByConstraintOptions,\n ) => Promise<Readonly<{ node: Node; action: GetOrCreateAction }>[]>;\n executeFindByConstraint: (\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Node | undefined>;\n executeBulkFindByConstraint: (\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<(Node | undefined)[]>;\n executeBulkFindByIndex: (\n kind: string,\n indexName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeBulkFindByIndexOptions,\n ) => Promise<Node[][]>;\n}>;\n\nfunction buildCreateInput(\n kind: string,\n props: Record<string, unknown>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n): CreateNodeInput {\n const input: {\n kind: string;\n id?: string;\n props: Record<string, unknown>;\n validFrom?: string;\n validTo?: string;\n } = { kind, props };\n if (options?.id !== undefined) input.id = options.id;\n if (options?.validFrom !== undefined) input.validFrom = options.validFrom;\n if (options?.validTo !== undefined) input.validTo = options.validTo;\n return input;\n}\n\nfunction buildUpdateInput(\n kind: string,\n id: string,\n props: Record<string, unknown>,\n options?: Readonly<{ validTo?: string }>,\n): UpdateNodeInput {\n const input: {\n kind: string;\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n } = { kind, id, props };\n if (options?.validTo !== undefined) input.validTo = options.validTo;\n return input as UpdateNodeInput;\n}\n\nfunction mapBulkNodeInputs(\n kind: string,\n items: readonly Readonly<{\n props: Record<string, unknown>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n): CreateNodeInput[] {\n return items.map((item) => buildCreateInput(kind, item.props, item));\n}\n\n/**\n * Creates a NodeCollection for a specific node type.\n */\nexport function createNodeCollection<\n G extends GraphDef,\n K extends keyof G[\"nodes\"] & string,\n>(config: NodeCollectionConfig): NodeCollection<G[\"nodes\"][K][\"type\"]> {\n type N = G[\"nodes\"][K][\"type\"];\n\n const {\n graphId,\n kind,\n backend,\n defaultTemporalMode,\n rowToNode,\n executeCreate: executeNodeCreate,\n executeCreateNoReturnBatch: executeNodeCreateNoReturnBatch,\n executeCreateBatch: executeNodeCreateBatch,\n executeUpdate: executeNodeUpdate,\n executeUpsertUpdate: executeNodeUpsertUpdate,\n executeDelete: executeNodeDelete,\n executeHardDelete: executeNodeHardDelete,\n temporalRowMatcher,\n createQuery,\n executeGetOrCreateByConstraint,\n executeBulkGetOrCreateByConstraint,\n executeFindByConstraint,\n executeBulkFindByConstraint,\n executeBulkFindByIndex,\n } = config;\n\n return {\n async create(\n props: z.input<N[\"schema\"]>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n ): Promise<Node<N>> {\n return this.createFromRecord(props, options);\n },\n\n async createFromRecord(\n data: Record<string, unknown>,\n options?: Readonly<{ id?: string; validFrom?: string; validTo?: string }>,\n ): Promise<Node<N>> {\n const result = await executeNodeCreate(\n buildCreateInput(kind, data, options),\n backend,\n );\n return narrowNode<N>(result);\n },\n\n async getById(\n id: NodeId<N>,\n options?: QueryOptions,\n ): Promise<Node<N> | undefined> {\n const row = await backend.getNode(graphId, kind, id);\n if (!row) return undefined;\n if (!temporalRowMatcher(options)(row)) return undefined;\n return narrowNode<N>(rowToNode(row));\n },\n\n async getByIds(\n ids: readonly NodeId<N>[],\n options?: QueryOptions,\n ): Promise<readonly (Node<N> | undefined)[]> {\n if (ids.length === 0) return [];\n\n const rowsById = await getNodeRowsByIds(backend, graphId, kind, ids);\n // Resolve the coordinate once so the whole batch observes one instant.\n const matches = temporalRowMatcher(options);\n return ids.map((id) => {\n const row = rowsById.get(id);\n if (!row) return;\n if (!matches(row)) return;\n return narrowNode<N>(rowToNode(row));\n });\n },\n\n async update(\n id: NodeId<N>,\n props: Partial<z.input<N[\"schema\"]>>,\n options?: Readonly<{ validTo?: string }>,\n ): Promise<Node<N>> {\n const result = await executeNodeUpdate(\n buildUpdateInput(kind, id, props, options),\n backend,\n );\n return narrowNode<N>(result);\n },\n\n async delete(id: NodeId<N>): Promise<void> {\n await executeNodeDelete(kind, id, backend);\n },\n\n async hardDelete(id: NodeId<N>): Promise<void> {\n await executeNodeHardDelete(kind, id, backend);\n },\n\n async find(\n filter?: Readonly<{\n where?: (accessor: never) => unknown;\n limit?: number;\n offset?: number;\n }>,\n temporal?: QueryOptions,\n ): Promise<Node<N>[]> {\n if (filter?.where !== undefined && createQuery === undefined) {\n throw new ConfigurationError(\n `store.nodes.${kind}.find({ where }) requires a query-capable store`,\n { kind, operation: \"find\" },\n );\n }\n if (filter?.where !== undefined && createQuery !== undefined) {\n // Resolve the coordinate through the same helper as the non-where\n // branch and count(), so find({ where }) and find(filter) observe\n // identical rows. `current` / `asOf` both resolve to a concrete instant\n // the backend find path compares against; pin the query to that same\n // instant — `current` would otherwise compile against the DB clock and\n // ignore the resolved asOf. includeEnded / includeTombstones carry no\n // instant. Routing through resolveTemporalReadParams also makes a\n // missing asOf in asOf mode throw here, matching the non-where branch.\n const { temporalMode, asOf } = resolveTemporalReadParams(\n temporal,\n defaultTemporalMode,\n );\n let query = createQuery()\n .from(kind, \"_n\")\n .temporal(asOf === undefined ? temporalMode : \"asOf\", asOf)\n .whereNode(\"_n\", filter.where as never)\n .select((ctx: Record<string, unknown>) => ctx[\"_n\"]);\n if (filter.limit !== undefined) query = query.limit(filter.limit);\n if (filter.offset !== undefined) query = query.offset(filter.offset);\n const results = await query.execute();\n return results as Node<N>[];\n }\n\n const params: {\n graphId: string;\n kind: string;\n limit?: number;\n offset?: number;\n } & TemporalReadParams = {\n graphId,\n kind,\n ...resolveTemporalReadParams(temporal, defaultTemporalMode),\n };\n if (filter?.limit !== undefined) params.limit = filter.limit;\n if (filter?.offset !== undefined) params.offset = filter.offset;\n\n const rows = await backend.findNodesByKind(params);\n return rows.map((row) => narrowNode<N>(rowToNode(row)));\n },\n\n async count(temporal?: QueryOptions): Promise<number> {\n const params: {\n graphId: string;\n kind: string;\n } & TemporalReadParams = {\n graphId,\n kind,\n ...resolveTemporalReadParams(temporal, defaultTemporalMode),\n };\n return backend.countNodesByKind(params);\n },\n\n async upsertById(\n id: string,\n props: z.input<N[\"schema\"]>,\n options?: Readonly<{ validFrom?: string; validTo?: string }>,\n ): Promise<Node<N>> {\n return this.upsertByIdFromRecord(id, props, options);\n },\n\n async upsertByIdFromRecord(\n id: string,\n data: Record<string, unknown>,\n options?: Readonly<{ validFrom?: string; validTo?: string }>,\n ): Promise<Node<N>> {\n const existing = await backend.getNode(graphId, kind, id);\n\n if (existing) {\n // Coalesce a value-identical replay: skip the write entirely (no\n // updateNode, no recorded capture, no revision advance, no hooks) and\n // resolve with the existing node. See\n // BaseStoreOptions.coalesceUnchangedUpserts.\n const runDirtyCheck =\n config.upsertDirtyCheck &&\n (() =>\n requireDefined(config.upsertDirtyCheck)(\n kind,\n id,\n rowPropsToObject(existing.props),\n data,\n ));\n if (shouldCoalesceUpsert(existing, options, runDirtyCheck)) {\n return narrowNode<N>(rowToNode(existing));\n }\n const result = await executeNodeUpdate(\n buildUpdateInput(kind, id, data, options),\n backend,\n { clearDeleted: existing.deleted_at !== undefined },\n );\n return narrowNode<N>(result);\n }\n\n const result = await executeNodeCreate(\n buildCreateInput(kind, data, { ...options, id }),\n backend,\n );\n return narrowNode<N>(result);\n },\n\n async bulkCreate(\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ): Promise<Node<N>[]> {\n const batchInputs = mapBulkNodeInputs(kind, items);\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n const results = await backend.transaction(async (txBackend) =>\n executeNodeCreateBatch(batchInputs, txBackend),\n );\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n return narrowNodes<N>(results);\n }\n const results = await executeNodeCreateBatch(batchInputs, backend);\n await config.maybeRefreshStatisticsAfterBulk?.(results.length);\n return narrowNodes<N>(results);\n },\n\n async bulkUpsertById(\n items: readonly Readonly<{\n id: string;\n props: z.input<N[\"schema\"]>;\n validFrom?: string;\n validTo?: string;\n }>[],\n ): Promise<Node<N>[]> {\n if (items.length === 0) return [];\n\n const upsertAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<{ results: Node<N>[]; mutations: number }> => {\n const ids = items.map((item) => item.id);\n // Full existing rows: the coalesce dirty-check needs their stored\n // props, not just deleted_at.\n const existingMap = new Map<string, NodeRow>();\n\n if (target.getNodes === undefined) {\n const rows = await Promise.all(\n ids.map((id) => target.getNode(graphId, kind, id)),\n );\n for (const row of rows) {\n if (row !== undefined) existingMap.set(row.id, row);\n }\n } else {\n const rows = await target.getNodes(graphId, kind, ids);\n for (const row of rows) {\n existingMap.set(row.id, row);\n }\n }\n\n // Coalesced items are written straight to results (the existing or\n // last-written node) and skipped from the write batch; see the\n // single-upsert path and BaseStoreOptions.coalesceUnchangedUpserts.\n const results: Node<N>[] = Array.from({ length: items.length });\n\n // Bucket items into creates and updates\n const toCreate: { index: number; input: CreateNodeInput }[] = [];\n const toUpdate: {\n index: number;\n input: UpdateNodeInput;\n clearDeleted: boolean;\n }[] = [];\n\n // Batch-local running state per id: the props the row would hold after\n // the writes queued so far, and the item index that queued that write.\n // A later same-id item coalesces against this running value, not the\n // once-prefetched row — otherwise [{x:B},{x:A}] on a row holding A would\n // coalesce the second item against the stale prefetched A and drop the\n // first item's write, breaking last-write-wins.\n const pending = new Map<\n string,\n { props: Record<string, unknown>; sourceIndex: number }\n >();\n // A coalesced item that matched an in-batch write resolves to that\n // write's result (filled once the writes run), not a fabricated row.\n const deferred: { index: number; sourceIndex: number }[] = [];\n\n let itemIndex = 0;\n for (const item of items) {\n const pendingEntry = pending.get(item.id);\n const original = existingMap.get(item.id);\n\n if (pendingEntry === undefined && original === undefined) {\n toCreate.push({\n index: itemIndex,\n input: buildCreateInput(kind, item.props, item),\n });\n itemIndex++;\n continue;\n }\n\n // A prior in-batch write left the row live; only the prefetched row\n // (no prior write) can be soft-deleted and trigger a resurrection.\n const deletedAt =\n pendingEntry === undefined ?\n requireDefined(original).deleted_at\n : undefined;\n\n let dirty: UpsertDirtyCheck | undefined;\n if (config.upsertDirtyCheck !== undefined) {\n const currentProps =\n pendingEntry?.props ??\n rowPropsToObject(requireDefined(original).props);\n try {\n dirty = config.upsertDirtyCheck(\n kind,\n item.id,\n currentProps,\n item.props,\n );\n } catch {\n // Validation error → fall through to the write path, which\n // re-validates and rejects the batch (matching flag-off).\n dirty = undefined;\n }\n }\n\n const coalesce =\n dirty?.unchanged === true &&\n deletedAt === undefined &&\n item.validFrom === undefined &&\n item.validTo === undefined;\n\n if (coalesce) {\n if (pendingEntry === undefined) {\n results[itemIndex] = narrowNode<N>(\n rowToNode(requireDefined(original)),\n );\n } else {\n deferred.push({\n index: itemIndex,\n sourceIndex: pendingEntry.sourceIndex,\n });\n }\n } else {\n toUpdate.push({\n index: itemIndex,\n input: buildUpdateInput(kind, item.id, item.props, item),\n clearDeleted: deletedAt !== undefined,\n });\n if (dirty !== undefined) {\n pending.set(item.id, {\n props: dirty.validatedProps,\n sourceIndex: itemIndex,\n });\n }\n }\n itemIndex++;\n }\n\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const created = await executeNodeCreateBatch(createInputs, target);\n for (const [index, entry] of toCreate.entries()) {\n results[entry.index] = narrowNode<N>(\n requireDefined(created[index]),\n );\n }\n }\n\n // Hookless individual updates\n for (const entry of toUpdate) {\n const result = await executeNodeUpsertUpdate(entry.input, target, {\n clearDeleted: entry.clearDeleted,\n });\n results[entry.index] = narrowNode<N>(result);\n }\n\n // Items that coalesced against an in-batch write take that write's\n // result (now filled). Its sourceIndex is always a write slot.\n for (const { index, sourceIndex } of deferred) {\n results[index] = requireDefined(results[sourceIndex]);\n }\n\n return { results, mutations: toCreate.length + toUpdate.length };\n };\n\n const { results, mutations } =\n backend.capabilities.transactions && \"transaction\" in backend ?\n await backend.transaction(async (txBackend) => upsertAll(txBackend))\n : await upsertAll(backend);\n // Match bulkCreate/bulkInsert: refresh planner statistics after a large\n // autocommit bulk write. Coalesced items wrote nothing, so only real\n // mutations count toward the threshold. A no-op inside a caller\n // transaction (the hook is intentionally undefined there).\n await config.maybeRefreshStatisticsAfterBulk?.(mutations);\n return results;\n },\n\n async bulkInsert(\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n id?: string;\n validFrom?: string;\n validTo?: string;\n }>[],\n ): Promise<void> {\n const batchInputs = mapBulkNodeInputs(kind, items);\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n await backend.transaction(async (txBackend) => {\n await executeNodeCreateNoReturnBatch(batchInputs, txBackend);\n });\n await config.maybeRefreshStatisticsAfterBulk?.(batchInputs.length);\n return;\n }\n\n await executeNodeCreateNoReturnBatch(batchInputs, backend);\n await config.maybeRefreshStatisticsAfterBulk?.(batchInputs.length);\n },\n\n async bulkDelete(ids: readonly NodeId<N>[]): Promise<void> {\n if (ids.length === 0) return;\n const deleteAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n for (const id of ids) {\n await executeNodeDelete(kind, id, target);\n }\n };\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n await backend.transaction(async (txBackend) => deleteAll(txBackend));\n return;\n }\n await deleteAll(backend);\n },\n\n async findByConstraint(\n constraintName: string,\n props: z.input<N[\"schema\"]>,\n ): Promise<Node<N> | undefined> {\n const result = await executeFindByConstraint(\n kind,\n constraintName,\n props,\n backend,\n );\n return result === undefined ? undefined : narrowNode<N>(result);\n },\n\n async bulkFindByConstraint(\n constraintName: string,\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n }>[],\n ): Promise<(Node<N> | undefined)[]> {\n if (items.length === 0) return [];\n\n const mappedItems = items.map((item) => ({\n props: item.props,\n }));\n\n const results = await executeBulkFindByConstraint(\n kind,\n constraintName,\n mappedItems,\n backend,\n );\n return results.map((result) =>\n result === undefined ? undefined : narrowNode<N>(result),\n );\n },\n\n async bulkFindByIndex(\n indexName: string,\n items: readonly Readonly<{\n props: Partial<z.input<N[\"schema\"]>>;\n }>[],\n options?: NodeBulkFindByIndexOptions,\n ): Promise<readonly Node<N>[][]> {\n if (items.length === 0) return [];\n\n const mappedItems = items.map((item) => ({\n props: item.props,\n }));\n\n const results = await executeBulkFindByIndex(\n kind,\n indexName,\n mappedItems,\n backend,\n options,\n );\n return results.map((bucket) => narrowNodes<N>(bucket));\n },\n\n async getOrCreateByConstraint(\n constraintName: string,\n props: z.input<N[\"schema\"]>,\n options?: NodeGetOrCreateByConstraintOptions,\n ): Promise<NodeGetOrCreateByConstraintResult<N>> {\n // No enclosing transaction: the found path is a pure read and must not\n // pay for one, and each write leg (create / upsert) opens its own\n // hooked transaction — nesting them here would fire their hooks before\n // this wrapper's COMMIT. Race convergence lives in\n // executeGetOrCreateByConstraint (re-probe on a create collision).\n const result = await executeGetOrCreateByConstraint(\n kind,\n constraintName,\n props,\n backend,\n options,\n );\n return result as NodeGetOrCreateByConstraintResult<N>;\n },\n\n async bulkGetOrCreateByConstraint(\n constraintName: string,\n items: readonly Readonly<{\n props: z.input<N[\"schema\"]>;\n }>[],\n options?: NodeGetOrCreateByConstraintOptions,\n ): Promise<NodeGetOrCreateByConstraintResult<N>[]> {\n if (items.length === 0) return [];\n\n const mappedItems = items.map((item) => ({\n props: item.props,\n }));\n\n const getOrCreateAll = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<NodeGetOrCreateByConstraintResult<N>[]> => {\n const results = await executeBulkGetOrCreateByConstraint(\n kind,\n constraintName,\n mappedItems,\n target,\n options,\n );\n return results as NodeGetOrCreateByConstraintResult<N>[];\n };\n\n if (backend.capabilities.transactions && \"transaction\" in backend) {\n return backend.transaction(async (txBackend) =>\n getOrCreateAll(txBackend),\n );\n }\n return getOrCreateAll(backend);\n },\n };\n}\n","/**\n * Collection Factory for Store\n *\n * Creates typed node and edge collection proxies for both\n * Store and TransactionContext to reduce code duplication.\n */\nimport { type GraphBackend, type TransactionBackend } from \"../backend/types\";\nimport { type GraphDef } from \"../core/define-graph\";\nimport { type TemporalMode } from \"../core/types\";\nimport { KindNotFoundError } from \"../errors\";\nimport { type QueryBuilder } from \"../query/builder\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { createEdgeCollection, createNodeCollection } from \"./collections\";\nimport { type UpsertDirtyCheckFunction } from \"./collections/coalesce\";\nimport { type EdgeRow, type NodeRow } from \"./row-mappers\";\nimport {\n type CreateEdgeInput,\n type CreateNodeInput,\n type Edge,\n type GetOrCreateAction,\n type GraphEdgeCollections,\n type GraphNodeCollections,\n type IfExistsMode,\n type Node,\n type NodeBulkFindByIndexOptions,\n type NodeGetOrCreateByConstraintOptions,\n type QueryOptions,\n type UpdateNodeInput,\n} from \"./types\";\n\n/**\n * Operation functions passed to collections.\n */\nexport type NodeOperations = Readonly<{\n defaultTemporalMode: TemporalMode;\n rowToNode: (row: NodeRow) => Node;\n /**\n * Store-provided hook run after an autocommit bulk write completes;\n * refreshes planner statistics when the row count crosses the\n * configured threshold. Absent on transaction-scoped collections.\n */\n maybeRefreshStatisticsAfterBulk?:\n ((rowCount: number) => Promise<void>) | undefined;\n executeCreate: (\n input: CreateNodeInput,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Node>;\n executeCreateBatch: (\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<readonly Node[]>;\n executeCreateNoReturnBatch: (\n inputs: readonly CreateNodeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeUpdate: (\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Node>;\n executeUpsertUpdate: (\n input: UpdateNodeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Node>;\n /**\n * Coalesce dirty-check for `upsertById` / `bulkUpsertById`. Present only when\n * the store was created with `coalesceUnchangedUpserts: true`; its absence is\n * the off switch. Given the current (parsed) props, returns the props the\n * upsert would persist and whether they are unchanged; the collection owns\n * the other preconditions.\n */\n upsertDirtyCheck?: UpsertDirtyCheckFunction;\n executeDelete: (\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeHardDelete: (\n kind: string,\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n temporalRowMatcher: (options?: QueryOptions) => (row: NodeRow) => boolean;\n createQuery?: () => QueryBuilder<GraphDef>;\n executeGetOrCreateByConstraint: (\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n options?: NodeGetOrCreateByConstraintOptions,\n ) => Promise<Readonly<{ node: Node; action: GetOrCreateAction }>>;\n executeBulkGetOrCreateByConstraint: (\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeGetOrCreateByConstraintOptions,\n ) => Promise<Readonly<{ node: Node; action: GetOrCreateAction }>[]>;\n executeFindByConstraint: (\n kind: string,\n constraintName: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Node | undefined>;\n executeBulkFindByConstraint: (\n kind: string,\n constraintName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<(Node | undefined)[]>;\n executeBulkFindByIndex: (\n kind: string,\n indexName: string,\n items: readonly Readonly<{ props: Record<string, unknown> }>[],\n backend: GraphBackend | TransactionBackend,\n options?: NodeBulkFindByIndexOptions,\n ) => Promise<Node[][]>;\n}>;\n\nexport type EdgeOperations = Readonly<{\n defaultTemporalMode: TemporalMode;\n rowToEdge: (row: EdgeRow) => Edge;\n /**\n * Store-provided hook run after an autocommit bulk write completes;\n * refreshes planner statistics when the row count crosses the\n * configured threshold. Absent on transaction-scoped collections.\n */\n maybeRefreshStatisticsAfterBulk?:\n ((rowCount: number) => Promise<void>) | undefined;\n executeCreate: (\n input: CreateEdgeInput,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Edge>;\n executeCreateBatch: (\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<readonly Edge[]>;\n executeCreateNoReturnBatch: (\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeUpdate: (\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n ) => Promise<Edge>;\n executeUpsertUpdate: (\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n ) => Promise<Edge>;\n /**\n * Coalesce dirty-check for `bulkUpsertById` (props only — endpoints are the\n * edge's identity). Present only when the store was created with\n * `coalesceUnchangedUpserts: true`; its absence is the off switch.\n */\n upsertDirtyCheck?: UpsertDirtyCheckFunction;\n executeDelete: (\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n executeHardDelete: (\n id: string,\n backend: GraphBackend | TransactionBackend,\n ) => Promise<void>;\n temporalRowMatcher: (options?: QueryOptions) => (row: EdgeRow) => boolean;\n createQuery?: () => QueryBuilder<GraphDef>;\n executeGetOrCreateByEndpoints: (\n kind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n }>,\n ) => Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>>;\n executeBulkGetOrCreateByEndpoints: (\n kind: string,\n items: readonly Readonly<{\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Record<string, unknown>;\n }>[],\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n }>,\n ) => Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>[]>;\n executeFindByEndpoints: (\n kind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n props?: Record<string, unknown>;\n }>,\n ) => Promise<Edge | undefined>;\n}>;\n\n/**\n * Creates a typed node collections proxy.\n *\n * The proxy dynamically creates NodeCollection instances for each node kind\n * when accessed.\n */\nexport function createNodeCollectionsProxy<G extends GraphDef>(\n graph: G,\n graphId: string,\n registry: KindRegistry,\n backend: GraphBackend | TransactionBackend,\n operations: NodeOperations,\n): GraphNodeCollections<G> {\n const collectionCache = new Map<string, unknown>();\n\n // The proxy dynamically returns typed collections for each key.\n // Type assertions are necessary because the proxy pattern doesn't preserve\n // the relationship between keys and their specific node types at compile time.\n return new Proxy({} as unknown as GraphNodeCollections<G>, {\n get: (_, kind: string) => {\n if (!Object.hasOwn(graph.nodes, kind)) {\n throw new KindNotFoundError(kind, \"node\");\n }\n\n const cached = collectionCache.get(kind);\n if (cached !== undefined) {\n return cached;\n }\n\n const collection = createNodeCollection({\n graphId,\n kind,\n backend,\n ...operations,\n });\n collectionCache.set(kind, collection);\n return collection;\n },\n });\n}\n\n/**\n * Creates a typed edge collections proxy.\n *\n * The proxy dynamically creates EdgeCollection instances for each edge kind\n * when accessed.\n */\nexport function createEdgeCollectionsProxy<G extends GraphDef>(\n graph: G,\n graphId: string,\n registry: KindRegistry,\n backend: GraphBackend | TransactionBackend,\n operations: EdgeOperations,\n): GraphEdgeCollections<G> {\n const collectionCache = new Map<string, unknown>();\n\n // The proxy dynamically returns typed collections for each key.\n // Type assertions are necessary because the proxy pattern doesn't preserve\n // the relationship between keys and their specific edge types at compile time.\n return new Proxy({} as unknown as GraphEdgeCollections<G>, {\n get: (_, kind: string) => {\n if (!Object.hasOwn(graph.edges, kind)) {\n throw new KindNotFoundError(kind, \"edge\");\n }\n\n const cached = collectionCache.get(kind);\n if (cached !== undefined) {\n return cached;\n }\n\n const collection = createEdgeCollection({\n graphId,\n kind,\n backend,\n ...operations,\n });\n collectionCache.set(kind, collection);\n return collection;\n },\n });\n}\n","import { projectBackendMembers } from \"../backend/graph-backend-projection\";\nimport { type GraphBackend } from \"../backend/types\";\n\n/**\n * Members that are safe to expose through a history-enabled adapter Store.\n *\n * Graph entity writes remain because the source is the capture-wrapped\n * backend. Direct raw SQL, native import, graph clearing, and nested backend\n * transactions stay internal because each can mutate live rows without a\n * corresponding capture flush.\n */\nconst HISTORY_STORE_BACKEND_KEYS = [\n \"assertRuntimeContributionsInitialized\",\n \"assertVectorSlotInitialized\",\n \"assertVectorSlotsInitialized\",\n \"bootstrapTables\",\n \"capabilities\",\n \"checkUnique\",\n \"checkUniqueBatch\",\n \"claimIndexMaterialization\",\n \"close\",\n \"commitSchemaVersion\",\n \"compileSql\",\n \"countEdgesByKind\",\n \"countEdgesFrom\",\n \"countNodesByKind\",\n \"createVectorIndex\",\n \"deleteEdge\",\n \"deleteEdgesBatch\",\n \"deleteEmbedding\",\n \"deleteFulltext\",\n \"deleteFulltextBatch\",\n \"deleteNode\",\n \"deleteUnique\",\n \"deleteVectorSlotContribution\",\n \"dialect\",\n \"dropVectorIndex\",\n \"edgeExistsBetween\",\n \"ensureContributionMaterializationsTable\",\n \"ensureFulltextTable\",\n \"ensureIndexMaterializationsTable\",\n \"ensureKindRemovalsTable\",\n \"ensureReconciliationMarkersTable\",\n \"ensureRevisionOriginsTable\",\n \"ensureRuntimeContributions\",\n \"ensureVectorSlotContribution\",\n \"ensureVectorSlotContributions\",\n \"execute\",\n \"executeTemporaryStatement\",\n \"findEdgesByKind\",\n \"findEdgesConnectedTo\",\n \"findNodesByKind\",\n \"fulltextSearch\",\n \"fulltextStrategy\",\n \"getActiveSchema\",\n \"getAllKindRemovals\",\n \"getContributionMaterialization\",\n \"getEdge\",\n \"getEdges\",\n \"getIndexMaterialization\",\n \"getIndexMaterializations\",\n \"getNode\",\n \"getNodes\",\n \"getPendingKindRemovals\",\n \"getReconciliationMarker\",\n \"getSchemaVersion\",\n \"hardDeleteEdge\",\n \"hardDeleteEdgesBatch\",\n \"hardDeleteNode\",\n \"hybridSearch\",\n \"insertEdge\",\n \"insertEdgeNoReturn\",\n \"insertEdgesBatch\",\n \"insertEdgesBatchReturning\",\n \"insertNode\",\n \"insertNodeNoReturn\",\n \"insertNodesBatch\",\n \"insertNodesBatchReturning\",\n \"insertUnique\",\n \"insertUniqueBatch\",\n \"recordContributionMaterialization\",\n \"recordIndexMaterialization\",\n \"recordKindRemoval\",\n \"refreshStatistics\",\n \"releaseIndexMaterializationClaim\",\n \"setActiveVersion\",\n \"setReconciliationMarker\",\n \"tableNames\",\n \"updateEdge\",\n \"updateNode\",\n \"upsertEmbedding\",\n \"upsertEmbeddingBatch\",\n \"upsertFulltext\",\n \"upsertFulltextBatch\",\n \"vectorSearch\",\n \"vectorStrategy\",\n] as const satisfies readonly (keyof GraphBackend)[];\n\ntype HistoryStoreBackendMember = (typeof HISTORY_STORE_BACKEND_KEYS)[number];\n\ntype UnsafeHistoryStoreBackendMember =\n | \"clearGraph\"\n | \"executeDdl\"\n | \"executeRaw\"\n | \"executeStatement\"\n | \"transaction\"\n | \"trustedImport\";\n\ntype UnclassifiedHistoryStoreBackendMember = Exclude<\n keyof GraphBackend,\n HistoryStoreBackendMember | UnsafeHistoryStoreBackendMember\n>;\n\nexport type HistoryStoreBackend =\n UnclassifiedHistoryStoreBackendMember extends never ?\n Readonly<Pick<GraphBackend, HistoryStoreBackendMember>>\n : never;\n\n/** @internal */\nexport function createHistoryStoreBackendProjection(\n backend: GraphBackend,\n): HistoryStoreBackend {\n return Object.freeze(\n projectBackendMembers(backend, HISTORY_STORE_BACKEND_KEYS),\n );\n}\n","/**\n * `store.introspect()` — unified read of the merged schema.\n *\n * Returns a coherent snapshot of \"what does my schema look like right\n * now\" suitable for schema-management UIs, codegen, and IDE plugins.\n * The previous surface was fragmented across `registry.hasNodeType`,\n * `store.deprecatedKinds`, and direct graph poking; `introspect()`\n * unifies them with explicit `origin` markers distinguishing\n * compile-time from runtime declarations.\n *\n * Pure read — no I/O. Built from the in-memory `GraphDef` and the\n * persisted-but-already-merged `extension`. `schemaVersion` /\n * `schemaHash` are populated when the loader cached them at\n * construction time and `undefined` otherwise; consumers needing a\n * fresh read should call `backend.getActiveSchema(graphId)` directly.\n */\nimport {\n type AllEdgeTypes,\n type AllNodeTypes,\n type GraphDef,\n} from \"../core/define-graph\";\nimport {\n type Cardinality,\n type Collation,\n type EdgeType,\n type EndpointExistence,\n type KindAnnotations,\n type NodeRegistration,\n type NodeType,\n type UniquenessScope,\n} from \"../core/types\";\nimport { type GraphExtension } from \"../graph-extension/extension-types\";\nimport {\n buildGraphExtensionOntologyKeySet,\n compileTimeOntologyKey,\n extensionKindNames,\n} from \"../graph-extension/ontology-keys\";\nimport { getTypeName } from \"../ontology/types\";\nimport { serializeSchemaProperties } from \"../schema/serializer\";\nimport { type JsonSchema } from \"../schema/types\";\n\nexport type SchemaIntrospection = Readonly<{\n graphId: string;\n /** Active schema version on the backend, when known to the caller. */\n schemaVersion: number | undefined;\n /** Hash of the active schema document, when known to the caller. */\n schemaHash: string | undefined;\n kinds: readonly KindIntrospection[];\n edges: readonly EdgeIntrospection[];\n ontology: readonly OntologyIntrospection[];\n deprecatedKinds: ReadonlySet<string>;\n /**\n * The persisted graph extension, or `undefined` when the store has\n * no extensions. Round-trips: passing this value to\n * `defineGraphExtension` and `evolve` against an empty graph yields\n * a graph with the same extension kinds.\n */\n extension: GraphExtension | undefined;\n}>;\n\nexport type KindIntrospection = Readonly<{\n name: string;\n origin: \"compile-time\" | \"runtime\";\n description: string | undefined;\n annotations: KindAnnotations | undefined;\n deprecated: boolean;\n /**\n * JSON-Schema view of the kind's properties. For extension kinds the\n * lower-level `ExtensionPropertyType` shape (with first-class\n * `searchable` / `embedding` modifiers) is reachable via\n * `introspection.extension.nodes[name].properties`.\n */\n properties: JsonSchema;\n unique: readonly UniqueIntrospection[];\n}>;\n\nexport type EdgeIntrospection = Readonly<{\n name: string;\n origin: \"compile-time\" | \"runtime\";\n description: string | undefined;\n from: readonly string[];\n to: readonly string[];\n cardinality: Cardinality;\n endpointExistence: EndpointExistence;\n properties: JsonSchema;\n annotations: KindAnnotations | undefined;\n deprecated: boolean;\n}>;\n\nexport type OntologyIntrospection = Readonly<{\n metaEdge: string;\n from: string;\n to: string;\n origin: \"compile-time\" | \"runtime\";\n}>;\n\nexport type UniqueIntrospection = Readonly<{\n name: string;\n fields: readonly string[];\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\ntype IntrospectContext = Readonly<{\n graphId: string;\n schemaVersion: number | undefined;\n schemaHash: string | undefined;\n}>;\n\nexport function introspectSchema<G extends GraphDef>(\n graph: G,\n context: IntrospectContext,\n): SchemaIntrospection {\n const extension = graph.extension;\n const { nodes: runtimeNodeNames, edges: runtimeEdgeNames } =\n extensionKindNames(extension);\n const deprecated = graph.deprecatedKinds;\n\n const kinds: KindIntrospection[] = [];\n for (const [name, registration] of Object.entries(graph.nodes)) {\n const reg = registration as NodeRegistration<NodeType>;\n kinds.push({\n name,\n origin: runtimeNodeNames.has(name) ? \"runtime\" : \"compile-time\",\n description: reg.type.description,\n annotations: reg.type.annotations,\n deprecated: deprecated.has(name),\n properties: serializeSchemaProperties(reg.type.schema),\n unique: (reg.unique ?? []).map((constraint) => ({\n name: constraint.name,\n fields: [...constraint.fields],\n scope: constraint.scope,\n collation: constraint.collation,\n })),\n });\n }\n\n const edges: EdgeIntrospection[] = [];\n for (const [name, registration] of Object.entries(graph.edges)) {\n const reg = registration;\n const edgeType = reg.type as AllEdgeTypes<G> & EdgeType;\n edges.push({\n name,\n origin: runtimeEdgeNames.has(name) ? \"runtime\" : \"compile-time\",\n description: edgeType.description,\n from: reg.from.map((entry) => (entry as AllNodeTypes<G> & NodeType).kind),\n to: reg.to.map((entry) => (entry as AllNodeTypes<G> & NodeType).kind),\n cardinality: reg.cardinality ?? \"many\",\n endpointExistence: reg.endpointExistence ?? \"notDeleted\",\n properties: serializeSchemaProperties(edgeType.schema),\n annotations: edgeType.annotations,\n deprecated: deprecated.has(name),\n });\n }\n\n const runtimeOntologyKeys = buildGraphExtensionOntologyKeySet(extension);\n const ontology: OntologyIntrospection[] = graph.ontology.map((relation) => ({\n metaEdge: relation.metaEdge.name,\n from: getTypeName(relation.from),\n to: getTypeName(relation.to),\n origin:\n runtimeOntologyKeys.has(compileTimeOntologyKey(relation)) ? \"runtime\" : (\n \"compile-time\"\n ),\n }));\n\n return {\n graphId: context.graphId,\n schemaVersion: context.schemaVersion,\n schemaHash: context.schemaHash,\n kinds,\n edges,\n ontology,\n deprecatedKinds: new Set(deprecated),\n extension,\n };\n}\n","/**\n * Shared building blocks for the materialize-* verbs (`materializeIndexes`\n * and `materializeRemovals`) and `Store.removeKinds`. Each verb owns a\n * per-deployment status table (`typegraph_index_materializations`,\n * `typegraph_kind_removals`) and bootstraps it lazily; this module\n * centralizes the bootstrap dispatch + parallel orchestration shape so\n * the runners stay thin.\n */\nimport { type GraphBackend } from \"../backend/types\";\n\n/**\n * Idempotently ensure a per-verb status table exists, preferring the\n * focused `ensure*Table` primitive when available and falling back to\n * the full `bootstrapTables` for legacy backends.\n *\n * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n * INDEX IF NOT EXISTS` statements covering every base table. Two\n * concurrent callers (e.g. two replicas of the same `schema_doc` both\n * starting up) deadlock on Postgres SHARE locks. Restricting the\n * ensure-step to a single table eliminates the cross-table race —\n * concurrent `CREATE TABLE IF NOT EXISTS` for one specific table is\n * well-behaved on Postgres.\n */\nexport async function ensureFocusedStatusTable(\n backend: GraphBackend,\n ensureFocused: (() => Promise<void>) | undefined,\n): Promise<void> {\n if (ensureFocused !== undefined) {\n await ensureFocused();\n return;\n }\n await backend.bootstrapTables?.();\n}\n\n/**\n * Bucketed orchestration for index-materialization runners.\n *\n * `stopOnError === true` runs sequentially in input order and\n * short-circuits after the first `failed` entry (returning the partial\n * results). Otherwise items are grouped by `bucketKey` and the groups run\n * concurrently with each group sequential — the shape Postgres requires\n * for `CREATE INDEX CONCURRENTLY` (one in-flight build per relation).\n * Results always come back in input order regardless of how the buckets\n * resolved.\n */\nexport async function runBucketedMaterialization<\n TItem,\n TEntry extends { status: string },\n>(\n items: readonly TItem[],\n options: Readonly<{ stopOnError?: boolean }>,\n bucketKey: (item: TItem) => string,\n runOne: (item: TItem) => Promise<TEntry>,\n): Promise<readonly TEntry[]> {\n if (options.stopOnError === true) {\n const results: TEntry[] = [];\n for (const item of items) {\n const entry = await runOne(item);\n results.push(entry);\n if (entry.status === \"failed\") break;\n }\n return results;\n }\n\n const buckets = new Map<string, [number, TItem][]>();\n for (const [index, item] of items.entries()) {\n const key = bucketKey(item);\n const bucket = buckets.get(key);\n if (bucket === undefined) buckets.set(key, [[index, item]]);\n else bucket.push([index, item]);\n }\n\n const results: TEntry[] = Array.from({ length: items.length });\n await Promise.all(\n [...buckets.values()].map(async (group) => {\n for (const [index, item] of group) {\n results[index] = await runOne(item);\n }\n }),\n );\n return results;\n}\n\n/**\n * Best-effort vs strict orchestration for materialization runners.\n * `stopOnError === true` runs sequentially and short-circuits on the\n * first `failed` entry (mirrors typical schema-migration safety\n * semantics); the default best-effort path runs `runOne` over `items`\n * concurrently. Custom orchestrators bypass this helper and assemble\n * their own Promise topology.\n */\nexport async function runMaterialization<\n TInput,\n TEntry extends { status: string },\n>(\n items: readonly TInput[],\n options: Readonly<{ stopOnError?: boolean }>,\n runOne: (item: TInput) => Promise<TEntry>,\n): Promise<readonly TEntry[]> {\n if (options.stopOnError === true) {\n const results: TEntry[] = [];\n for (const item of items) {\n const entry = await runOne(item);\n results.push(entry);\n if (entry.status === \"failed\") break;\n }\n return results;\n }\n return Promise.all(items.map((item) => runOne(item)));\n}\n","/**\n * Index materialization — runs declared index DDL against the live\n * database and tracks per-deployment status in\n * `typegraph_index_materializations`.\n *\n * Reads `IndexDeclaration[]` from `GraphDef.indexes`, generates DDL via\n * `generateIndexDDL`, executes via `backend.executeDdl` (Postgres path\n * uses `CREATE INDEX CONCURRENTLY`, which cannot run inside a\n * transaction — `executeDdl` runs at the top-level backend, never inside\n * `transaction(...)`), and upserts a status row per index.\n *\n * Caveats baked in to the algorithm:\n *\n * - SQL index names are physical, database-global identifiers.\n * Cross-graph collisions (two graphs declaring the same name with\n * different shapes) surface as a `failed` result with reason\n * \"signature drift\", because the existing recorded signature won't\n * match the new one.\n * - On Postgres, `CREATE INDEX CONCURRENTLY IF NOT EXISTS` does NOT\n * prove the existing physical index has the same shape as ours —\n * only that something with that name exists. Drift detection here\n * relies on TypeGraph's recorded signature, not on PG metadata.\n * - Failed `CONCURRENTLY` builds leave invalid indexes behind\n * (`pg_index.indisvalid = false`). Relational rebuilds self-heal: the\n * claim-holding materializer drops an invalid leftover with the\n * declaration's name before rebuilding (see dropInvalidIndexLeftover).\n * Vector per-field index leftovers remain operator-repair.\n * - Two materializers racing the SAME index name serialize through a\n * durable claim in the status table (see materializeWithClaim) —\n * concurrent same-name expression-index CIC builds deadlock on\n * Postgres (no safe-snapshot exemption).\n */\nimport { type RawBackend } from \"../backend/branded\";\nimport {\n type CreateVectorIndexParams,\n type GraphBackend,\n type IndexMaterializationRow,\n type RecordIndexMaterializationParams,\n} from \"../backend/types\";\nimport { type GraphDef, isKnownKind } from \"../core/define-graph\";\nimport type { IndexEntity } from \"../core/types\";\nimport { ConfigurationError, KindNotFoundError } from \"../errors\";\nimport { generateIndexDDL } from \"../indexes/ddl\";\nimport {\n generateSystemIndexDDL,\n resolveSystemIndexNames,\n resolveSystemIndexTableName,\n SYSTEM_INDEX_DECLARATIONS,\n type SystemIndexDeclaration,\n systemIndexName,\n} from \"../indexes/system\";\nimport {\n type IndexDeclaration,\n type RelationalIndexDeclaration,\n type VectorIndexDeclaration,\n} from \"../indexes/types\";\nimport { sqlValueList } from \"../query/compiler/predicate-utils\";\nimport { type SqlDialect } from \"../query/dialect/types\";\nimport { sql } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql } from \"../query/sql-intent\";\nimport { sortedReplacer } from \"../schema/canonical\";\nimport { serializeIndexDeclaration } from \"../schema/serializer\";\nimport { nowIso } from \"../utils/date\";\nimport { sha256Hex } from \"../utils/hash\";\nimport { requireDefined } from \"../utils/presence\";\nimport {\n ensureFocusedStatusTable,\n runBucketedMaterialization,\n} from \"./materialize-shared\";\n\n/**\n * Cross-caller build claim timing (Postgres).\n *\n * A claim older than the lease is stale (its holder crashed mid-build) and\n * may be taken over; the lease is generous because CREATE INDEX\n * CONCURRENTLY on a large relation legitimately runs for minutes, and a\n * premature takeover would recreate exactly the same-index CIC race the\n * claim exists to prevent. Losers retry the claim on an interval —\n * re-claiming after the winner releases converges through the normal\n * already-materialized check — and give up shortly after the lease bound.\n */\nconst CLAIM_LEASE_MS = 15 * 60_000;\nconst CLAIM_RETRY_DELAY_MS = 200;\nconst CLAIM_WAIT_TIMEOUT_MS = CLAIM_LEASE_MS + 60_000;\n\nconst INDEX_DIALECT_BEHAVIOR = {\n postgres: {\n concurrentBuilds: true,\n hasInvalidIndexState: true,\n supportsGinFamily: true,\n },\n sqlite: {\n concurrentBuilds: false,\n hasInvalidIndexState: false,\n supportsGinFamily: false,\n },\n} as const satisfies Record<\n SqlDialect,\n Readonly<{\n concurrentBuilds: boolean;\n hasInvalidIndexState: boolean;\n supportsGinFamily: boolean;\n }>\n>;\n\n/**\n * Whether the backend implements the FULL cross-caller build-claim\n * protocol. One predicate for both decisions that depend on it — build\n * serialization and the post-create statistics refresh — so a backend\n * implementing only half the surface can never refresh without\n * serializing (the combination that reopens the same-index CIC deadlock).\n */\nfunction hasIndexBuildClaimProtocol(backend: GraphBackend): boolean {\n return (\n backend.claimIndexMaterialization !== undefined &&\n backend.releaseIndexMaterializationClaim !== undefined\n );\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport type MaterializeIndexesOptions = Readonly<{\n /** Restrict to indexes whose `kind` is in this set. */\n kinds?: readonly string[];\n /** Stop on the first failure. Default: false (best-effort). */\n stopOnError?: boolean;\n /**\n * Refresh planner statistics (ANALYZE) after at least one index was\n * created. A fresh index can be ignored by the planner until statistics\n * exist. Default: true. Applied on non-concurrent builders (SQLite) and\n * on concurrent builders that serialize same-index builds via the\n * cross-caller claim primitive (the bundled Postgres backend); a custom\n * concurrent backend without the primitive skips the refresh — see\n * refreshStatisticsAfterCreation — and should call\n * `store.refreshStatistics()` after materializing.\n */\n refreshStatistics?: boolean;\n}>;\n\n/**\n * Per-index outcome from `materializeIndexes()`.\n *\n * Status values:\n * - `created`: DDL ran successfully and a new physical index now exists.\n * - `alreadyMaterialized`: status table shows a prior successful\n * materialization with the same signature; no DDL ran.\n * - `failed`: the DDL or status write failed; `error` carries the\n * captured exception. Best-effort mode continues to the next index;\n * `stopOnError: true` halts.\n * - `skipped`: the backend can't materialize this index variant in its\n * current configuration (e.g. vector indexes against SQLite without\n * sqlite-vec, or `indexType: \"none\"` declared on an embedding). The\n * declaration is recognized but intentionally not acted on. Status\n * table is NOT updated for skipped entries.\n */\nexport type MaterializeIndexesEntry = Readonly<{\n indexName: string;\n entity: IndexEntity;\n kind: string;\n status: \"created\" | \"alreadyMaterialized\" | \"failed\" | \"skipped\";\n error?: Error;\n /**\n * Human-readable reason. Required for `skipped`; optional otherwise.\n */\n reason?: string;\n}>;\n\nexport type MaterializeIndexesResult = Readonly<{\n results: readonly MaterializeIndexesEntry[];\n}>;\n\ntype MaterializeIndexesContext = Readonly<{\n graph: GraphDef;\n graphId: string;\n // Index DDL runs at the top-level backend (CREATE INDEX CONCURRENTLY cannot\n // run in a transaction) and writes no graph entities — it is the raw seam,\n // not the capture wrapper. Passing the graph-write backend here is an error.\n backend: RawBackend;\n schemaVersion: number;\n}>;\n\nexport async function materializeIndexes(\n context: MaterializeIndexesContext,\n options: MaterializeIndexesOptions = {},\n): Promise<MaterializeIndexesResult> {\n const { graph, graphId, backend, schemaVersion } = context;\n\n assertBackendSupportsIndexMaterialization(\n backend,\n \"store.materializeIndexes()\",\n );\n\n const declared = graph.indexes ?? [];\n const kindFilter =\n options.kinds === undefined ? undefined : new Set(options.kinds);\n\n if (kindFilter !== undefined) {\n for (const name of kindFilter) {\n if (!isKnownKind(graph, name)) {\n throw new KindNotFoundError(\n name,\n Object.hasOwn(graph.edges, name) ? \"edge\" : \"node\",\n {\n graphId,\n suggestion:\n \"Only kinds declared on the graph (compile-time or runtime) can be passed to materializeIndexes.\",\n },\n );\n }\n }\n }\n\n const candidates = declared.filter((index) =>\n kindFilter === undefined ? true : kindFilter.has(index.kind),\n );\n\n // Short-circuit before any I/O when there's nothing to do. The\n // ensure-step below issues a CREATE TABLE statement — paying that\n // cost only to return an empty result is wasteful, especially on\n // repeated `evolve(sameExt, { eager: {} })` calls.\n if (candidates.length === 0) {\n return { results: [] };\n }\n\n await ensureFocusedStatusTable(\n backend,\n backend.ensureIndexMaterializationsTable,\n );\n\n const dialect = backend.dialect;\n const tableNames = backend.tableNames;\n const ddlOptions = {\n ifNotExists: true,\n concurrent: INDEX_DIALECT_BEHAVIOR[dialect].concurrentBuilds,\n ...(tableNames?.nodes === undefined ?\n {}\n : { nodesTableName: tableNames.nodes }),\n ...(tableNames?.edges === undefined ?\n {}\n : { edgesTableName: tableNames.edges }),\n } as const;\n\n // Bulk-preload existing materialization rows for every candidate's\n // status key in one round-trip. With 30 declared indexes this drops 30\n // sequential SELECTs to one. Backends without the bulk primitive fall\n // back to per-key lookups inside `materializeOne`.\n const statusKeys = candidates.map((declaration) =>\n statusKeyFor(declaration, graphId),\n );\n const existingByStatusKey = await preloadMaterializations(\n backend,\n statusKeys,\n );\n\n // Bulk-preload INVALID index leftovers (interrupted CONCURRENTLY builds)\n // for the relational candidates in one `pg_index` query. On a warm start\n // `settleAgainstExisting` would otherwise fire one leftover check per\n // already-materialized index — the same N-round-trip cost the status\n // preload above just eliminated. Vector entries are excluded: their\n // per-field physical index leftovers are operator-repair, and\n // `settleAgainstExisting` only consults this set for non-vector\n // declarations. Physical names are the declaration names.\n const relationalPhysicalNames = candidates\n .filter((declaration) => declaration.entity !== \"vector\")\n .map((declaration) => declaration.name);\n const invalidLeftovers = await preloadInvalidIndexLeftovers(\n backend,\n relationalPhysicalNames,\n );\n\n // System index names are reserved: a colliding relational declaration's\n // `CREATE INDEX IF NOT EXISTS` would silently no-op against the\n // (differently shaped) system index while recording a false success.\n // The schema factories reject the same collision at table-definition\n // time; this covers declarations that never pass through them.\n const reservedSystemNames = resolveSystemIndexNames(backend.tableNames);\n\n const materializeEntry = (\n declaration: IndexDeclaration,\n ): Promise<MaterializeIndexesEntry> => {\n if (\n declaration.entity !== \"vector\" &&\n reservedSystemNames.has(declaration.name)\n ) {\n return Promise.resolve(\n entry(\n declaration,\n \"failed\",\n new Error(\n `Index name \"${declaration.name}\" collides with a TypeGraph ` +\n `system index. Rename the declaration — a same-named CREATE ` +\n `INDEX IF NOT EXISTS would silently no-op against the system ` +\n `index instead of creating the declared one.`,\n ),\n ),\n );\n }\n return declaration.entity === \"vector\" ?\n materializeVectorIndex(\n declaration,\n backend,\n graphId,\n schemaVersion,\n existingByStatusKey,\n invalidLeftovers,\n )\n : materializeRelationalIndex(\n declaration,\n backend,\n dialect,\n ddlOptions,\n graphId,\n schemaVersion,\n existingByStatusKey,\n invalidLeftovers,\n );\n };\n\n // Postgres restricts `CREATE INDEX CONCURRENTLY` to one in-flight\n // build per relation, so declarations group by target relation and\n // each group runs sequentially while the groups run in parallel.\n // Typical schemas land in three buckets (nodes, edges, vector\n // embeddings), giving a ~3× round-trip win over fully sequential\n // without ever issuing two CONCURRENTLY builds against the same\n // relation. SQLite ignores the grouping (writes serialize at the\n // engine level either way).\n const results = await runBucketedMaterialization(\n candidates,\n options,\n (declaration) => parallelBucketKey(declaration),\n (declaration) => materializeEntry(declaration),\n );\n await refreshStatisticsAfterCreation(\n backend,\n results,\n options,\n ddlOptions.concurrent,\n );\n return { results };\n}\n\n/**\n * Runs ANALYZE once when at least one index was freshly created (unless the\n * caller opted out): the planner can keep seq-scanning past a brand-new\n * index until statistics for it exist.\n *\n * On backends that build with CREATE INDEX CONCURRENTLY, the refresh runs\n * only when the backend also exposes the cross-caller claim primitive\n * (the bundled Postgres backend does): the claim serializes same-index\n * CIC builds, which used to deadlock under the refresh's timing shift\n * (expression-index CIC gets no safe-snapshot exemption). A custom\n * concurrent backend without the primitive keeps the conservative skip\n * and refreshes manually via `store.refreshStatistics()`.\n *\n * Best-effort: by this point the indexes exist and their status rows are\n * recorded, so a failed statistics refresh must not convert that success\n * into a failure — it degrades to a warning.\n */\nasync function refreshStatisticsAfterCreation(\n backend: RawBackend,\n results: readonly MaterializeIndexesEntry[],\n options: MaterializeIndexesOptions,\n usesConcurrentBuilds: boolean,\n): Promise<void> {\n if (options.refreshStatistics === false) return;\n // Concurrent (Postgres) builds were excluded while two callers racing\n // the SAME expression-index CIC could deadlock — the refresh's timing\n // shift made that latent race fire reliably. With the cross-caller\n // claim protocol serializing same-index builds, backends that expose\n // the claim primitive refresh automatically again; a custom concurrent\n // backend without the primitive keeps the conservative skip.\n if (usesConcurrentBuilds && !hasIndexBuildClaimProtocol(backend)) return;\n if (!results.some((entry) => entry.status === \"created\")) return;\n try {\n await backend.refreshStatistics();\n } catch (error) {\n if (typeof console === \"undefined\" || typeof console.warn !== \"function\") {\n return;\n }\n console.warn(\n \"[typegraph] materializeIndexes created its indexes but the follow-up \" +\n \"statistics refresh failed; run store.refreshStatistics() to give \" +\n \"the planner fresh statistics.\",\n error,\n );\n }\n}\n\nfunction parallelBucketKey(declaration: IndexDeclaration): IndexEntity {\n // Vector indexes now target typed per-`(kind, field)` tables rather\n // than one shared table, so distinct vector declarations could in\n // principle build concurrently. They still share one bucket (keyed by\n // the `\"vector\"` entity) — serializing them is conservative but\n // correct, and keeps Postgres CIC's \"one in-flight build per relation\"\n // rule trivially satisfied without tracking per-table identity here.\n // Relational node and edge indexes split into their own entity buckets.\n return declaration.entity;\n}\n\nasync function materializeRelationalIndex(\n declaration: RelationalIndexDeclaration,\n backend: GraphBackend,\n dialect: SqlDialect,\n ddlOptions: Readonly<{\n ifNotExists: boolean;\n concurrent: boolean;\n nodesTableName?: string;\n edgesTableName?: string;\n }>,\n graphId: string,\n schemaVersion: number,\n existingByStatusKey: ReadonlyMap<string, IndexMaterializationRow>,\n invalidLeftovers: ReadonlySet<string>,\n): Promise<MaterializeIndexesEntry> {\n // GIN-family methods are PostgreSQL expression GINs; SQLite has no\n // equivalent (its substring-search story is FTS5 fulltext), so the\n // declaration is recognized and intentionally not acted on — same\n // contract as vector indexes on engines without vector support.\n if (\n declaration.method !== undefined &&\n !INDEX_DIALECT_BEHAVIOR[dialect].supportsGinFamily\n ) {\n return {\n indexName: declaration.name,\n entity: declaration.entity,\n kind: declaration.kind,\n status: \"skipped\",\n reason:\n `Index method \"${declaration.method}\" requires PostgreSQL ` +\n `(expression GIN${declaration.method === \"trigram\" ? \" + pg_trgm\" : \"\"}); ` +\n \"SQLite serves substring search via FTS5 fulltext instead.\",\n };\n }\n\n const ddl = generateIndexDDL(declaration, dialect, ddlOptions);\n const targetTable =\n declaration.entity === \"node\" ?\n (ddlOptions.nodesTableName ?? \"typegraph_nodes\")\n : (ddlOptions.edgesTableName ?? \"typegraph_edges\");\n const signature = await computeIndexSignature(\n dialect,\n targetTable,\n declaration,\n );\n return materializeOne(declaration, backend, graphId, schemaVersion, {\n statusKey: declaration.name,\n signature,\n driftLabel: \"Index\",\n run: async () => {\n if (declaration.method === \"trigram\") {\n // gin_trgm_ops lives in the pg_trgm extension (contrib — present\n // on stock Postgres and the hosted variants). Idempotent, and a\n // permission failure surfaces as this index's `failed` entry.\n await requireDefined(backend.executeDdl)(\n \"CREATE EXTENSION IF NOT EXISTS pg_trgm;\",\n );\n }\n await requireDefined(backend.executeDdl)(ddl);\n },\n existingByStatusKey,\n physicalRebuildPreload: invalidLeftovers,\n });\n}\n\nasync function materializeVectorIndex(\n declaration: VectorIndexDeclaration,\n backend: GraphBackend,\n graphId: string,\n schemaVersion: number,\n existingByStatusKey: ReadonlyMap<string, IndexMaterializationRow>,\n invalidLeftovers: ReadonlySet<string>,\n): Promise<MaterializeIndexesEntry> {\n // `indexType: \"none\"` is a declarative opt-out — the declaration\n // carries shape metadata (dimensions, metric) for tooling but the\n // operator has signaled \"no automatic index\". Surface as `skipped`.\n if (declaration.indexType === \"none\") {\n return skippedEntry(\n declaration,\n \"indexType: 'none' opts out of automatic materialization\",\n );\n }\n\n // Capability check: backends declare vector support via\n // `capabilities.vector` (derived from the active `VectorStrategy`) and\n // expose that strategy as `backend.vectorStrategy`. When either is\n // absent the backend can't act on the declaration — surface as\n // skipped. The `vectorStrategy` check also narrows it to defined for\n // the per-field table-name resolution below.\n const vectorCapability = backend.capabilities.vector;\n if (\n vectorCapability?.supported !== true ||\n backend.createVectorIndex === undefined ||\n backend.vectorStrategy === undefined\n ) {\n return skippedEntry(\n declaration,\n `Backend (${backend.dialect}) does not support vector indexes in its current configuration`,\n );\n }\n // Capability check (per index type): backends advertise the specific\n // index implementations they support (e.g. SQLite + sqlite-vec\n // accepts vectors but no HNSW/IVFFlat — the brute-force scan IS the\n // \"index\"). Surface unsupported types as skipped so consumers see a\n // clear \"this backend can't materialize this declaration\" signal\n // instead of a silent no-op masquerading as `created`.\n if (!vectorCapability.indexTypes.includes(declaration.indexType)) {\n return skippedEntry(\n declaration,\n `Backend (${backend.dialect}) does not support index type \"${declaration.indexType}\" for vector indexes; supported: ${vectorCapability.indexTypes.join(\", \") || \"(none)\"}`,\n );\n }\n\n // Hash against the strategy's typed per-`(kind, field)` physical table\n // — the storage this declaration's index actually targets. Folding the\n // resolved table name into the signature keeps drift detection honest:\n // if the strategy (and thus the physical table) changes, the recorded\n // signature mismatches and re-materialization is forced.\n const embeddingsTable = backend.vectorStrategy.tableName(\n graphId,\n declaration.kind,\n declaration.fieldPath,\n );\n const signature = await computeIndexSignature(\n backend.dialect,\n embeddingsTable,\n declaration,\n );\n const params: CreateVectorIndexParams = {\n graphId,\n nodeKind: declaration.kind,\n fieldPath: declaration.fieldPath,\n dimensions: declaration.dimensions,\n metric: declaration.metric,\n indexType: declaration.indexType,\n indexParams: {\n m: declaration.indexParams.m,\n efConstruction: declaration.indexParams.efConstruction,\n ...(declaration.indexParams.lists === undefined ?\n {}\n : { lists: declaration.indexParams.lists }),\n },\n concurrent: INDEX_DIALECT_BEHAVIOR[backend.dialect].concurrentBuilds,\n };\n return materializeOne(declaration, backend, graphId, schemaVersion, {\n // Compound status-table key for vector entries. Pgvector creates\n // one physical index per (graphId, kind, field) — so the\n // per-deployment status table needs to disambiguate entries that\n // SHARE a declaration name but belong to different graphs.\n // Applied uniformly to auto-derived AND explicit declarations.\n statusKey: vectorStatusKey(graphId, declaration.name),\n signature,\n driftLabel: \"Vector index\",\n run: () => requireDefined(backend.createVectorIndex)(params),\n existingByStatusKey,\n physicalRebuildPreload: invalidLeftovers,\n });\n}\n\n/**\n * The identity a materialization run needs from its declaration: the\n * physical/status name plus the `(entity, kind)` pair recorded on the\n * status row. Relational and vector declarations satisfy it structurally;\n * system indexes construct it from `SYSTEM_INDEX_DECLARATIONS`.\n */\ntype MaterializableIndexIdentity = Readonly<{\n name: string;\n entity: IndexEntity;\n kind: string;\n}>;\n\n/**\n * Shared \"check existing → run → record\" frame for relational, vector,\n * and system materialization. All paths track a per-deployment status row\n * keyed by `statusKey`, short-circuit on a matching signature, surface\n * signature drift as a recorded failure, and execute `run()` on first\n * materialization. Differences live entirely in the `MaterializeAction`\n * the caller passes.\n */\nasync function materializeOne(\n declaration: MaterializableIndexIdentity,\n backend: GraphBackend,\n graphId: string,\n schemaVersion: number,\n action: Readonly<{\n statusKey: string;\n signature: string;\n driftLabel: string;\n run: () => Promise<void>;\n existingByStatusKey: ReadonlyMap<string, IndexMaterializationRow>;\n /**\n * Physical index names whose catalog state requires a rebuild despite\n * a matching success row. Relational: INVALID `CONCURRENTLY`\n * leftovers. System: leftovers plus physically absent indexes —\n * name-presence identifies a system index, so absence is proof the\n * recorded success is stale (dump/restore, manual drop).\n */\n physicalRebuildPreload: ReadonlySet<string>;\n /**\n * Fresh per-name variant of `physicalRebuildPreload` for the\n * post-claim re-check (the preload is stale after waiting on another\n * builder's claim). Defaults to the Postgres invalid-leftover query.\n */\n freshNeedsPhysicalRebuild?: (physicalIndexName: string) => Promise<boolean>;\n /**\n * Allow the physical-rebuild check to trigger even on backends\n * without the claim protocol (SQLite). Sound only when the rebuild is\n * a plain idempotent CREATE (system indexes); relational leftover\n * healing requires the claim and keeps the default `false`.\n */\n rebuildWithoutClaim?: boolean;\n }>,\n): Promise<MaterializeIndexesEntry> {\n // Narrowed by callsite — guaranteed defined when this is reached\n // (validated in `materializeIndexes`).\n const recordIndexMaterialization = requireDefined(\n backend.recordIndexMaterialization,\n );\n\n const { statusKey, signature, driftLabel, run, existingByStatusKey } = action;\n const statusOverride =\n statusKey === declaration.name ? undefined : { statusName: statusKey };\n\n // Pre-claim physical check reads the bulk-preloaded set (one catalog\n // query for all candidates), not one round-trip per index.\n const settled = await settleAgainstExisting(\n existingByStatusKey.get(statusKey),\n declaration,\n backend,\n graphId,\n schemaVersion,\n {\n statusKey,\n signature,\n driftLabel,\n needsPhysicalRebuild: (physicalIndexName) =>\n action.physicalRebuildPreload.has(physicalIndexName),\n ...(action.rebuildWithoutClaim === undefined ?\n {}\n : { rebuildWithoutClaim: action.rebuildWithoutClaim }),\n },\n );\n if (settled !== undefined) return settled;\n\n // Backends whose concurrent builds can deadlock across callers expose a\n // claim primitive; one caller builds, the rest wait and converge through\n // the already-materialized check on re-claim.\n if (hasIndexBuildClaimProtocol(backend)) {\n return materializeWithClaim(declaration, backend, graphId, schemaVersion, {\n statusKey,\n signature,\n driftLabel,\n run,\n ...(action.freshNeedsPhysicalRebuild === undefined ?\n {}\n : { freshNeedsPhysicalRebuild: action.freshNeedsPhysicalRebuild }),\n ...(action.rebuildWithoutClaim === undefined ?\n {}\n : { rebuildWithoutClaim: action.rebuildWithoutClaim }),\n });\n }\n\n try {\n await run();\n const attemptedAt = nowIso();\n await recordIndexMaterialization(\n buildAttempt({\n declaration,\n graphId,\n signature,\n schemaVersion,\n materializedAt: attemptedAt,\n error: undefined,\n attemptedAt,\n ...statusOverride,\n }),\n );\n return entry(declaration, \"created\");\n } catch (error_) {\n const error = error_ instanceof Error ? error_ : new Error(String(error_));\n await recordIndexMaterialization(\n buildAttempt({\n declaration,\n graphId,\n signature,\n schemaVersion,\n materializedAt: undefined,\n error,\n ...statusOverride,\n }),\n );\n return entry(declaration, \"failed\", error);\n }\n}\n\n/**\n * Applies the existing-status decision: `alreadyMaterialized` on a prior\n * success with a matching signature, a recorded `failed` on signature\n * drift, and `undefined` when a build is needed. Shared by the pre-claim\n * check (against the bulk-preloaded rows) and the post-claim re-check\n * (against a fresh read — the preload is stale after waiting on a claim).\n */\nasync function settleAgainstExisting(\n existing: IndexMaterializationRow | undefined,\n declaration: MaterializableIndexIdentity,\n backend: GraphBackend,\n graphId: string,\n schemaVersion: number,\n action: Readonly<{\n statusKey: string;\n signature: string;\n driftLabel: string;\n /**\n * Whether the physical index behind this name is unusable and must be\n * rebuilt despite the recorded success (INVALID leftover; for system\n * indexes also physically absent). The pre-claim caller reads a\n * bulk-preloaded set (one query for all candidates); the post-claim\n * caller reads fresh (the preload is stale after waiting on another\n * builder's claim).\n */\n needsPhysicalRebuild: (\n physicalIndexName: string,\n ) => boolean | Promise<boolean>;\n /** See `materializeOne`'s action field of the same name. */\n rebuildWithoutClaim?: boolean;\n }>,\n): Promise<MaterializeIndexesEntry | undefined> {\n if (existing?.materializedAt === undefined) return undefined;\n const { statusKey, signature, driftLabel, needsPhysicalRebuild } = action;\n if (existing.signature === signature) {\n // A recorded success is only trustworthy while the physical index is\n // usable: a run interrupted after `CREATE ... IF NOT EXISTS` silently\n // kept an invalid leftover (or a pre-claim-protocol run recorded\n // success over one), and a dump/restore or manual drop can leave a\n // success row for an index that no longer exists. Fall through to the\n // build path — under the claim it drops any leftover and rebuilds;\n // `rebuildWithoutClaim` callers re-run their plain idempotent CREATE.\n if (\n declaration.entity !== \"vector\" &&\n (hasIndexBuildClaimProtocol(backend) ||\n action.rebuildWithoutClaim === true) &&\n (await needsPhysicalRebuild(declaration.name))\n ) {\n return undefined;\n }\n return entry(declaration, \"alreadyMaterialized\");\n }\n const error = new Error(\n `${driftLabel} \"${declaration.name}\" already materialized with a different signature (recorded by graph \"${existing.graphId}\" at version ${existing.schemaVersion}). Drop the index manually and retry, or rename the new declaration.`,\n );\n await requireDefined(backend.recordIndexMaterialization)(\n buildAttempt({\n declaration,\n graphId,\n signature,\n schemaVersion,\n materializedAt: undefined,\n error,\n ...(statusKey === declaration.name ? {} : { statusName: statusKey }),\n }),\n );\n return entry(declaration, \"failed\", error);\n}\n\n/**\n * Builds one index under the cross-caller claim protocol.\n *\n * Claim → re-check → build → record → release. Losers retry the claim on\n * an interval: once the winner records its result and releases, the next\n * claim succeeds and the fresh status re-check settles them as\n * `alreadyMaterialized` (or surfaces the winner's drift failure) without\n * ever issuing a second same-index CONCURRENTLY build — the shape that\n * deadlocks on Postgres (expression-index CIC gets no safe-snapshot\n * exemption). A crashed holder's claim expires after the lease; the\n * takeover drops the invalid leftover its interrupted build left behind\n * (relational indexes — the declaration name IS the physical name) before\n * rebuilding.\n */\nasync function materializeWithClaim(\n declaration: MaterializableIndexIdentity,\n backend: GraphBackend,\n graphId: string,\n schemaVersion: number,\n action: Readonly<{\n statusKey: string;\n signature: string;\n driftLabel: string;\n run: () => Promise<void>;\n freshNeedsPhysicalRebuild?: (physicalIndexName: string) => Promise<boolean>;\n rebuildWithoutClaim?: boolean;\n }>,\n): Promise<MaterializeIndexesEntry> {\n const { statusKey, signature, driftLabel, run } = action;\n const statusOverride =\n statusKey === declaration.name ? undefined : { statusName: statusKey };\n const recordIndexMaterialization = requireDefined(\n backend.recordIndexMaterialization,\n );\n const token = `${statusKey}:${nowIso()}:${Math.floor(performance.now() * 1000)}`;\n const deadline = Date.now() + CLAIM_WAIT_TIMEOUT_MS;\n\n for (;;) {\n const claimed = await requireDefined(backend.claimIndexMaterialization)({\n indexName: statusKey,\n graphId,\n entity: declaration.entity,\n kind: declaration.kind,\n signature,\n schemaVersion,\n token,\n leaseMs: CLAIM_LEASE_MS,\n });\n\n if (!claimed) {\n if (Date.now() >= deadline) {\n return entry(\n declaration,\n \"failed\",\n new Error(\n `Timed out waiting for a concurrent materializer's claim on \"${statusKey}\" (waited ${String(CLAIM_WAIT_TIMEOUT_MS)}ms). If its holder crashed, retry after the lease expires.`,\n ),\n );\n }\n await delay(CLAIM_RETRY_DELAY_MS);\n continue;\n }\n\n try {\n // Fresh re-check: the bulk preload happened before (possibly) waiting\n // on another caller's build.\n const fresh = await requireDefined(backend.getIndexMaterialization)(\n statusKey,\n );\n const settled = await settleAgainstExisting(\n fresh,\n declaration,\n backend,\n graphId,\n schemaVersion,\n {\n statusKey,\n signature,\n driftLabel,\n // Post-claim the bulk preload is stale (we may have waited on\n // another builder's claim), so re-check this index fresh.\n needsPhysicalRebuild:\n action.freshNeedsPhysicalRebuild ??\n ((physicalIndexName) =>\n hasInvalidIndexLeftover(backend, physicalIndexName)),\n ...(action.rebuildWithoutClaim === undefined ?\n {}\n : { rebuildWithoutClaim: action.rebuildWithoutClaim }),\n },\n );\n if (settled !== undefined) return settled;\n\n if (declaration.entity !== \"vector\") {\n await dropInvalidIndexLeftover(backend, declaration.name);\n }\n\n try {\n await run();\n const attemptedAt = nowIso();\n await recordIndexMaterialization(\n buildAttempt({\n declaration,\n graphId,\n signature,\n schemaVersion,\n materializedAt: attemptedAt,\n error: undefined,\n attemptedAt,\n ...statusOverride,\n }),\n );\n return entry(declaration, \"created\");\n } catch (error_) {\n const error =\n error_ instanceof Error ? error_ : new Error(String(error_));\n await recordIndexMaterialization(\n buildAttempt({\n declaration,\n graphId,\n signature,\n schemaVersion,\n materializedAt: undefined,\n error,\n ...statusOverride,\n }),\n );\n return entry(declaration, \"failed\", error);\n }\n } finally {\n // A claim-release failure must not mask the build's own outcome — a\n // successful build must not surface as a thrown rejection, and one\n // bucket's release error must not abort its siblings. The claim carries\n // a lease (CLAIM_LEASE_MS) and self-expires, so a missed release is\n // reclaimed by the next materializer; warn and move on.\n try {\n await requireDefined(backend.releaseIndexMaterializationClaim)({\n indexName: statusKey,\n token,\n });\n } catch (releaseError) {\n console.warn(\n `typegraph: failed to release the index materialization claim for ` +\n `\"${statusKey}\"; it will expire on its lease and be reclaimed ` +\n `automatically.`,\n releaseError,\n );\n }\n }\n }\n}\n\n/**\n * Whether an index with this name exists but is INVALID (an interrupted\n * CONCURRENTLY build's leftover). False for absent or valid indexes and\n * on non-Postgres dialects.\n */\nasync function hasInvalidIndexLeftover(\n backend: GraphBackend,\n physicalIndexName: string,\n): Promise<boolean> {\n if (!INDEX_DIALECT_BEHAVIOR[backend.dialect].hasInvalidIndexState) {\n return false;\n }\n // Scoped to the session search_path like preloadPhysicalIndexStates —\n // an unscoped probe could steer the unqualified DROP INDEX heal at\n // another schema's identically-named (valid) index.\n const rows = await backend.execute<{ invalid: boolean }>(\n asCompiledRowsSql(sql`\n SELECT NOT i.indisvalid AS invalid\n FROM pg_class c\n JOIN pg_index i ON i.indexrelid = c.oid\n WHERE c.relname = ${physicalIndexName}\n AND pg_catalog.pg_table_is_visible(c.oid)\n `),\n );\n return rows[0]?.invalid === true;\n}\n\n/**\n * Bulk variant of `hasInvalidIndexLeftover`: the set of INVALID leftover\n * index names among `physicalIndexNames`, resolved in ONE `pg_index` query.\n * Empty set on non-Postgres dialects or empty input.\n *\n * A warm start (every index already materialized with a matching signature)\n * would otherwise fire `hasInvalidIndexLeftover` once per already-materialized\n * relational index inside `settleAgainstExisting` — N `pg_index` round-trips.\n * Preloading the whole set collapses that to one, mirroring how\n * `preloadMaterializations` batches the status reads it sits beside.\n */\nasync function preloadInvalidIndexLeftovers(\n backend: GraphBackend,\n physicalIndexNames: readonly string[],\n): Promise<ReadonlySet<string>> {\n if (\n !INDEX_DIALECT_BEHAVIOR[backend.dialect].hasInvalidIndexState ||\n physicalIndexNames.length === 0\n ) {\n return new Set();\n }\n const { invalid } = await preloadPhysicalIndexStates(\n backend,\n physicalIndexNames,\n );\n return invalid;\n}\n\n/**\n * The subset of `tableNames` that exist as tables in the engine catalog,\n * in one query — `search_path`-scoped on Postgres like the index probes.\n */\nasync function preloadExistingTables(\n backend: GraphBackend,\n tableNames: readonly string[],\n): Promise<ReadonlySet<string>> {\n if (tableNames.length === 0) return new Set();\n switch (backend.dialect) {\n case \"postgres\": {\n const rows = await backend.execute<{ name: string }>(\n asCompiledRowsSql(sql`\n SELECT c.relname AS name\n FROM pg_class c\n WHERE c.relname IN (${sqlValueList(tableNames)})\n AND c.relkind IN ('r', 'p')\n AND pg_catalog.pg_table_is_visible(c.oid)\n `),\n );\n return new Set(rows.map((row) => row.name));\n }\n case \"sqlite\": {\n const rows = await backend.execute<{ name: string }>(\n asCompiledRowsSql(sql`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN (${sqlValueList(tableNames)})\n `),\n );\n return new Set(rows.map((row) => row.name));\n }\n default: {\n return backend.dialect satisfies never;\n }\n }\n}\n\ntype PhysicalIndexStates = Readonly<{\n /** Names that exist as usable indexes in the engine catalog. */\n valid: ReadonlySet<string>;\n /** Postgres INVALID leftovers from interrupted CONCURRENTLY builds. */\n invalid: ReadonlySet<string>;\n}>;\n\n/**\n * Partitions `physicalIndexNames` by their catalog state in ONE query:\n * `valid` (usable index exists) and `invalid` (Postgres CONCURRENTLY\n * leftover needing the healing build path). SQLite has no invalid state,\n * so its `invalid` set is always empty. The single query serves both the\n * relational runner's leftover preload and the system runner's\n * name-presence fast path — the two predicates are complementary halves\n * of the same `pg_class ⋈ pg_index` probe.\n */\nasync function preloadPhysicalIndexStates(\n backend: GraphBackend,\n physicalIndexNames: readonly string[],\n): Promise<PhysicalIndexStates> {\n const valid = new Set<string>();\n const invalid = new Set<string>();\n if (physicalIndexNames.length === 0) return { valid, invalid };\n switch (backend.dialect) {\n case \"postgres\": {\n // Scope to search_path, matching unqualified CREATE/DROP INDEX DDL.\n const rows = await backend.execute<{ name: string; valid: boolean }>(\n asCompiledRowsSql(sql`\n SELECT c.relname AS name, i.indisvalid AS valid\n FROM pg_class c\n JOIN pg_index i ON i.indexrelid = c.oid\n WHERE c.relname IN (${sqlValueList(physicalIndexNames)})\n AND pg_catalog.pg_table_is_visible(c.oid)\n `),\n );\n for (const row of rows) (row.valid ? valid : invalid).add(row.name);\n return { valid, invalid };\n }\n case \"sqlite\": {\n const rows = await backend.execute<{ name: string }>(\n asCompiledRowsSql(sql`\n SELECT name\n FROM sqlite_master\n WHERE type = 'index'\n AND name IN (${sqlValueList(physicalIndexNames)})\n `),\n );\n for (const row of rows) valid.add(row.name);\n return { valid, invalid };\n }\n default: {\n return backend.dialect satisfies never;\n }\n }\n}\n\n/**\n * Self-heals an interrupted CONCURRENTLY build: a crashed CIC leaves an\n * INVALID index behind, and a later `CREATE INDEX CONCURRENTLY IF NOT\n * EXISTS` would see the name and silently no-op — recording success over an\n * index the planner will never use. Detect via `hasInvalidIndexLeftover` and\n * drop (also CONCURRENTLY — same no-transaction rule). Valid indexes are\n * never touched.\n */\nasync function dropInvalidIndexLeftover(\n backend: GraphBackend,\n physicalIndexName: string,\n): Promise<void> {\n if (backend.executeDdl === undefined) return;\n if (!(await hasInvalidIndexLeftover(backend, physicalIndexName))) return;\n const quoted = `\"${physicalIndexName.replaceAll('\"', '\"\"')}\"`;\n await backend.executeDdl(`DROP INDEX CONCURRENTLY IF EXISTS ${quoted};`);\n}\n\nfunction entry(\n declaration: MaterializableIndexIdentity,\n status: MaterializeIndexesEntry[\"status\"],\n error?: Error,\n): MaterializeIndexesEntry {\n return {\n indexName: declaration.name,\n entity: declaration.entity,\n kind: declaration.kind,\n status,\n ...(error === undefined ? {} : { error }),\n };\n}\n\nfunction skippedEntry(\n declaration: VectorIndexDeclaration,\n reason: string,\n): MaterializeIndexesEntry {\n return {\n indexName: declaration.name,\n entity: \"vector\",\n kind: declaration.kind,\n status: \"skipped\",\n reason,\n };\n}\n\n/**\n * Compose the per-deployment status-table key for a vector index.\n * Pgvector physical indexes are partial-by-graph_id (one per graph),\n * so the status table needs graph-scoped identity to disambiguate\n * two graphs reusing the same declaration name. The `::` separator\n * keeps the compound visually unambiguous when inspecting the table.\n */\nexport function vectorStatusKey(\n graphId: string,\n declarationName: string,\n): string {\n return `${graphId}::${declarationName}`;\n}\n\nfunction statusKeyFor(declaration: IndexDeclaration, graphId: string): string {\n return declaration.entity === \"vector\" ?\n vectorStatusKey(graphId, declaration.name)\n : declaration.name;\n}\n\n/**\n * Bulk-load the recorded materialization rows for `statusKeys` into a\n * Map keyed by status key. Backends that implement\n * `getIndexMaterializations` return everything in one round-trip;\n * legacy backends fall back to per-key parallel `getIndexMaterialization`\n * calls. Missing rows are simply absent from the map.\n */\nasync function preloadMaterializations(\n backend: GraphBackend,\n statusKeys: readonly string[],\n): Promise<ReadonlyMap<string, IndexMaterializationRow>> {\n const map = new Map<string, IndexMaterializationRow>();\n if (statusKeys.length === 0) return map;\n if (backend.getIndexMaterializations !== undefined) {\n const rows = await backend.getIndexMaterializations(statusKeys);\n for (const row of rows) map.set(row.indexName, row);\n return map;\n }\n const getOne = requireDefined(backend.getIndexMaterialization);\n const rows = await Promise.all(statusKeys.map((key) => getOne(key)));\n for (const [index, row] of rows.entries()) {\n if (row !== undefined) map.set(requireDefined(statusKeys[index]), row);\n }\n return map;\n}\n\nfunction buildAttempt(\n args: Readonly<{\n declaration: MaterializableIndexIdentity;\n graphId: string;\n signature: string;\n schemaVersion: number;\n materializedAt: string | undefined;\n error: Error | undefined;\n attemptedAt?: string;\n /**\n * Override the status-table identity. Used by vector entries to\n * inject the graph-scoped compound key (`vectorStatusKey`).\n * Relational entries default to the declaration name because\n * physical CREATE INDEX names are already database-global.\n */\n statusName?: string;\n }>,\n): RecordIndexMaterializationParams {\n return {\n indexName: args.statusName ?? args.declaration.name,\n graphId: args.graphId,\n entity: args.declaration.entity,\n kind: args.declaration.kind,\n signature: args.signature,\n schemaVersion: args.schemaVersion,\n attemptedAt: args.attemptedAt ?? nowIso(),\n materializedAt: args.materializedAt,\n error: args.error?.message,\n };\n}\n\n// ============================================================\n// System indexes\n// ============================================================\n\nexport type MaterializeSystemIndexesOptions = Readonly<{\n /** Stop on the first failure. Default: false (best-effort). */\n stopOnError?: boolean;\n /** Refresh planner statistics after a creation. Default: true. */\n refreshStatistics?: boolean;\n}>;\n\ntype SystemIndexCandidate = Readonly<{\n declaration: SystemIndexDeclaration;\n physicalTable: string;\n name: string;\n}>;\n\n/**\n * Materializes TypeGraph's own base-relation indexes\n * (`SYSTEM_INDEX_DECLARATIONS`) against the live database.\n *\n * Bootstrap DDL runs only on first boot, so a system index added in a new\n * library version never reaches an already-initialized database on its\n * own — this runner is the upgrade path. It rides the same per-deployment\n * status table, drift signatures, invalid-leftover healing, and Postgres\n * `CREATE INDEX CONCURRENTLY` cross-caller claim protocol as\n * graph-declared indexes; on a database whose indexes all exist, a warm\n * call costs three concurrent reads (status, index-catalog, and\n * table-catalog preloads) after the idempotent status-table ensure, and runs no\n * DDL after the first recorded success.\n *\n * Graph-independent: the declarations don't depend on `GraphDef`. The\n * `graphId` is recorded on status rows for observability only (\"who\n * materialized this\"), matching relational rows' semantics.\n *\n * Unlike expression indexes, a system index is fully identified by its\n * physical name, so a candidate that already exists in the engine catalog\n * (valid, with no recorded status row) settles as `alreadyMaterialized`\n * from one bulk catalog read — no claim, no DDL, no status write. Status\n * rows are recorded only for genuine builds and failures, which keeps the\n * common boot (fresh bootstrap or wiped status table) at three concurrent\n * reads. A status row that exists with a mismatching signature still\n * surfaces as drift, exactly like graph-declared indexes.\n */\n/**\n * Whether the backend carries every primitive index materialization\n * requires (DDL execution + status reads/writes). The strict runners\n * throw `ConfigurationError` exactly when this is false; the boot path\n * (`createStoreWithSchema`) consults the same predicate to skip instead\n * — one definition so the two contracts cannot drift apart.\n */\nexport function backendSupportsIndexMaterialization(\n backend: GraphBackend,\n): boolean {\n return (\n backend.executeDdl !== undefined &&\n backend.getIndexMaterialization !== undefined &&\n backend.recordIndexMaterialization !== undefined\n );\n}\n\n/**\n * Strict-side counterpart of {@link backendSupportsIndexMaterialization}:\n * the runners' throw-guard, derived from the same predicate the boot\n * path's skip-guard consults.\n */\nfunction assertBackendSupportsIndexMaterialization(\n backend: GraphBackend,\n surface: string,\n): void {\n if (backendSupportsIndexMaterialization(backend)) return;\n throw new ConfigurationError(\n `${surface} requires a backend with \\`executeDdl\\` and the index ` +\n \"materialization status primitives (`getIndexMaterialization`, \" +\n \"`recordIndexMaterialization`). The bundled SQLite and Postgres \" +\n \"backends provide them; a custom backend must implement all three.\",\n { code: \"MATERIALIZE_BACKEND_UNSUPPORTED\" },\n );\n}\n\nexport async function materializeSystemIndexes(\n context: Readonly<{\n backend: RawBackend;\n graphId: string;\n schemaVersion: number;\n }>,\n options: MaterializeSystemIndexesOptions = {},\n): Promise<MaterializeIndexesResult> {\n const { backend, graphId, schemaVersion } = context;\n\n assertBackendSupportsIndexMaterialization(\n backend,\n \"store.materializeSystemIndexes()\",\n );\n\n await ensureFocusedStatusTable(\n backend,\n backend.ensureIndexMaterializationsTable,\n );\n\n const concurrent = INDEX_DIALECT_BEHAVIOR[backend.dialect].concurrentBuilds;\n const candidates: readonly SystemIndexCandidate[] =\n SYSTEM_INDEX_DECLARATIONS.map((declaration) => {\n const physicalTable = resolveSystemIndexTableName(\n declaration.table,\n backend.tableNames,\n );\n return {\n declaration,\n physicalTable,\n name: systemIndexName(physicalTable, declaration.suffix),\n };\n });\n\n // The three preloads are mutually independent reads (status table +\n // two catalog probes); running them concurrently keeps the warm boot at\n // one round-trip latency after the ensure step.\n const statusKeys = candidates.map((candidate) => candidate.name);\n const targetTables = [\n ...new Set(candidates.map((candidate) => candidate.physicalTable)),\n ];\n const [existingByStatusKey, physicalStates, existingTables] =\n await Promise.all([\n preloadMaterializations(backend, statusKeys),\n preloadPhysicalIndexStates(backend, statusKeys),\n preloadExistingTables(backend, targetTables),\n ]);\n const { valid: physicallyPresent } = physicalStates;\n // Physical state is authoritative for system indexes: absent or INVALID\n // must rebuild even under a matching success row (dump/restore, manual\n // drop). One set serves every candidate's pre-claim check.\n const physicalRebuildPreload: ReadonlySet<string> = new Set(\n statusKeys.filter((name) => !physicallyPresent.has(name)),\n );\n\n const materializeEntry = async (\n candidate: SystemIndexCandidate,\n ): Promise<MaterializeIndexesEntry> => {\n const identity: MaterializableIndexIdentity = {\n name: candidate.name,\n entity: \"system\",\n kind: candidate.declaration.table,\n };\n // Legacy databases can predate optional relations (the recorded\n // tables ship with history support; `operation-backend-core` guards\n // its clears the same way). Their indexes are skipped, not failed —\n // the relation appearing later (bootstrap on a fresh database always\n // creates it) brings the indexes with it.\n if (!existingTables.has(candidate.physicalTable)) {\n return {\n indexName: candidate.name,\n entity: \"system\",\n kind: candidate.declaration.table,\n status: \"skipped\",\n reason: `Relation \"${candidate.physicalTable}\" does not exist in this database`,\n };\n }\n\n const existing = existingByStatusKey.get(candidate.name);\n\n // A status row owned by another entity means a graph-declared index\n // was materialized under this name. Refuse WITHOUT writing: driving\n // this through the drift path would record a system-signature failure\n // over the graph-declared index's row and permanently brick it.\n if (existing !== undefined && existing.entity !== \"system\") {\n return entry(\n identity,\n \"failed\",\n new Error(\n `System index name \"${candidate.name}\" is already recorded by a ` +\n `${existing.entity} index declaration (graph \"${existing.graphId}\"). ` +\n `Rename the graph-declared index — \"typegraph_\"-prefixed names ` +\n `belong to TypeGraph's system indexes.`,\n ),\n );\n }\n\n // Name-presence fast path: valid physical index, no status row — the\n // normal steady state, since bootstrap DDL creates system indexes\n // without recording status rows. Trusting name-presence is sound\n // ONLY here: system index names are library-owned with a stable\n // name→shape contract (reshaping requires a rename), whereas a\n // graph-declared index name could collide with a foreign index whose\n // shape only the recorded signature can vouch for. Known limitation\n // of that contract: a declaration reshaped in place (violating the\n // rename rule) is NOT detected on bootstrap-created databases, since\n // there is no recorded signature to drift against — the rename rule\n // is enforced by review and the parity tests, not at runtime. A row\n // with a mismatching signature must NOT take the fast path — that is\n // drift, and the frame below records it as a failure.\n if (existing === undefined && physicallyPresent.has(candidate.name)) {\n return entry(identity, \"alreadyMaterialized\");\n }\n const signature = await computeSystemIndexSignature(\n backend.dialect,\n candidate.physicalTable,\n candidate.declaration,\n );\n const ddl = generateSystemIndexDDL(\n candidate.declaration,\n candidate.physicalTable,\n { concurrent },\n );\n return materializeOne(identity, backend, graphId, schemaVersion, {\n statusKey: candidate.name,\n signature,\n driftLabel: \"System index\",\n run: () => requireDefined(backend.executeDdl)(ddl),\n existingByStatusKey,\n physicalRebuildPreload,\n freshNeedsPhysicalRebuild: async (physicalIndexName) => {\n const fresh = await preloadPhysicalIndexStates(backend, [\n physicalIndexName,\n ]);\n return !fresh.valid.has(physicalIndexName);\n },\n rebuildWithoutClaim: true,\n });\n };\n\n // Same shape as the relational runner: one CONCURRENTLY build per\n // relation, so buckets key on the physical table.\n const results = await runBucketedMaterialization(\n candidates,\n options,\n (candidate) => candidate.physicalTable,\n (candidate) => materializeEntry(candidate),\n );\n await refreshStatisticsAfterCreation(backend, results, options, concurrent);\n return { results };\n}\n\n/**\n * Canonical hash of `{ dialect, targetTableName, declaration }` for a\n * system-index declaration — same drift contract as\n * `computeIndexSignature`: changing a declaration's shape under the same\n * suffix mismatches the recorded signature and surfaces as a `failed`\n * entry until the operator drops the old physical index (rename instead).\n */\nasync function computeSystemIndexSignature(\n dialect: SqlDialect,\n targetTableName: string,\n declaration: SystemIndexDeclaration,\n): Promise<string> {\n const json = JSON.stringify(\n { dialect, targetTableName, declaration },\n sortedReplacer,\n );\n return sha256Hex(json, 16);\n}\n\n/**\n * Canonical hash of `{ dialect, targetTableName, declaration }`.\n *\n * Includes the physical target table name because custom backends can\n * remap `typegraph_nodes` / `typegraph_edges` — a declaration-only\n * signature would falsely report \"already materialized\" after a table\n * rename. Excludes execution flags (`CONCURRENTLY`, `IF NOT EXISTS`)\n * because those are runtime modifiers, not shape.\n *\n * `declaration` is canonicalized via `serializeIndexDeclaration` before\n * hashing — `defineGraph` accepts pre-built `IndexDeclaration`s directly\n * (bypassing `defineNodeIndex`'s own canonicalization), so a raw\n * declaration with e.g. a present-but-empty `keySystemColumns: []` would\n * otherwise hash differently from the same declaration with the field\n * omitted, spuriously forcing re-materialization for no real shape change.\n */\nexport async function computeIndexSignature(\n dialect: SqlDialect,\n targetTableName: string,\n declaration: IndexDeclaration,\n): Promise<string> {\n const hashable = {\n dialect,\n targetTableName,\n declaration: serializeIndexDeclaration(declaration),\n };\n const json = JSON.stringify(hashable, sortedReplacer);\n return sha256Hex(json, 16);\n}\n","/**\n * Data-cleanup phase for `store.removeKinds()`.\n *\n * The removeKinds verb commits the new schema atomically (millisecond\n * budget); the data deletion happens here, scoped per-deployment via\n * the `typegraph_kind_removals` status table. Splitting the verbs\n * mirrors how `materializeIndexes` complements `evolve`: schema\n * commits are atomic and fast, data work is bounded by row count and\n * deferrable / parallelizable.\n */\nimport { type RawBackend } from \"../backend/branded\";\nimport {\n type GraphBackend,\n type KindRemovalRow,\n type RecordKindRemovalParams,\n type TransactionBackend,\n} from \"../backend/types\";\nimport type { KindEntity } from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { createSqlSchema, type SqlSchema } from \"../query/compiler/schema\";\nimport type {\n VectorSlot,\n VectorStrategy,\n} from \"../query/dialect/vector-strategy\";\nimport { sql } from \"../query/sql-fragment\";\nimport { asCompiledStatementSql } from \"../query/sql-intent\";\nimport { parseSerializedSchema } from \"../schema/manager\";\nimport { nowIso } from \"../utils/date\";\nimport { requireDefined } from \"../utils/presence\";\nimport { isMissingTableError } from \"../utils/sql-errors\";\nimport {\n ensureFocusedStatusTable,\n runMaterialization,\n} from \"./materialize-shared\";\nimport { closeRecordedHardDeletedKind } from \"./recorded-capture\";\n\nconst ENTITY_KINDS: readonly KindEntity[] = [\"node\", \"edge\"];\n\n/**\n * Build the \"pending\" `recordKindRemoval` payload shared by\n * `Store.removeKinds` (the original commit-time write) and\n * `materializeRemovals` reconciliation (the catch-up write for kinds\n * that crashed before their queue row landed). Centralizes the\n * `removedAt: undefined, error: undefined` constants so a future\n * status-table column expansion has one site to update.\n */\nexport function buildPendingKindRemoval(\n args: Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n attemptedAt: string;\n }>,\n): RecordKindRemovalParams {\n return { ...args, removedAt: undefined, error: undefined };\n}\n\nexport type MaterializeRemovalsOptions = Readonly<{\n /** Restrict to specific kind names. */\n kinds?: readonly string[];\n /** Halt on first failure. Default: false (best-effort). */\n stopOnError?: boolean;\n}>;\n\nexport type MaterializeRemovalsEntry = Readonly<{\n kind: string;\n entity: KindEntity;\n status: \"removed\" | \"failed\";\n error?: Error;\n}>;\n\n/**\n * Outcome of reclaiming one per-`(graphId, kind, field)` vector table that\n * was orphaned when its embedding field was dropped from a *surviving*\n * kind's schema. Distinct from {@link MaterializeRemovalsEntry} (whole\n * kinds) because the unit is a single embedding field, not a kind.\n */\nexport type ReclaimedVectorFieldEntry = Readonly<{\n kind: string;\n fieldPath: string;\n status: \"reclaimed\" | \"failed\";\n error?: Error;\n}>;\n\nexport type MaterializeRemovalsResult = Readonly<{\n results: readonly MaterializeRemovalsEntry[];\n /**\n * Embedding fields removed from a *surviving* kind whose per-field vector\n * table this pass dropped (or confirmed already absent). Empty when the\n * backend has no vector strategy or no embedding field has ever been\n * dropped. Re-derived from immutable schema history each call, so it lists\n * the same removed fields on repeat passes — the underlying drop is\n * idempotent (`DROP ... IF EXISTS`). See {@link reclaimRemovedVectorFieldTables}.\n */\n reclaimedVectorFields: readonly ReclaimedVectorFieldEntry[];\n}>;\n\ntype MaterializeRemovalsContext = Readonly<{\n graphId: string;\n // Bulk kind-removal deletes live rows directly and closes recorded intervals\n // by kind — it deliberately bypasses the per-row capture wrapper, so it takes\n // the raw seam. Passing the graph-write backend here is a type error.\n backend: RawBackend;\n captureRecordedRemovals?: boolean;\n // The store's resolved SQL schema, so recorded-interval closes target the\n // same relations recorded reads do (honoring a custom `schema` option, not\n // just `backend.tableNames`). Falls back to the backend's table names.\n recordedSchema?: SqlSchema;\n}>;\n\ntype MaterializeOneContext = Readonly<{\n backend: GraphBackend;\n graphId: string;\n nodesTable: string;\n edgesTable: string;\n fulltextTable: string;\n uniquesTable: string;\n captureRecordedRemovals: boolean;\n // Resolved once per removal pass (not per kind) and threaded into each\n // recorded-interval close. Undefined when recorded capture is off.\n recordedSchema: SqlSchema | undefined;\n}>;\n\nexport async function materializeRemovals(\n context: MaterializeRemovalsContext,\n options: MaterializeRemovalsOptions = {},\n): Promise<MaterializeRemovalsResult> {\n const { backend, graphId } = context;\n\n if (\n backend.executeDdl === undefined ||\n backend.recordKindRemoval === undefined ||\n backend.getPendingKindRemovals === undefined\n ) {\n throw new ConfigurationError(\n \"store.materializeRemovals() requires a backend with kind-removal \" +\n \"primitives (executeDdl, recordKindRemoval, getPendingKindRemovals). \" +\n \"The bundled SQLite and Postgres backends provide them.\",\n { code: \"MATERIALIZE_REMOVALS_BACKEND_UNSUPPORTED\" },\n );\n }\n\n await ensureFocusedStatusTable(backend, backend.ensureKindRemovalsTable);\n\n // Recovery path: `removeKinds()` commits the schema-version diff\n // (kind dropped from `nodes`/`edges`) BEFORE recording the cleanup\n // queue rows. If the queue write fails between those two steps the\n // schema is durable but the queue is missing rows — and a retry of\n // `removeKinds()` short-circuits on the no-op path because the kind\n // is already absent. Atomicity isn't an option (the schema-commit\n // path takes dialect-specific advisory locks that can't be extended\n // across the status-table write), so reconcile here against schema\n // history: walk every transition, find kinds whose removal isn't\n // reflected in the queue, and re-record them.\n await reconcilePendingRemovals(context);\n\n // Independent of pending kind removals: a per-field vector table is\n // orphaned the moment its embedding field is dropped from a *surviving*\n // kind (an `evolve` that removes the field, with no kind removal at all).\n // The add-only `materializeIndexes` path never reclaims it and the\n // candidate loop below only handles whole kinds, so reclaim here before\n // the no-candidates short-circuit.\n const reclaimedVectorFields = await reclaimRemovedVectorFieldTables(context);\n\n const pending = await backend.getPendingKindRemovals(graphId);\n\n const kindFilter =\n options.kinds === undefined ? undefined : new Set(options.kinds);\n const candidates = pending.filter((row) =>\n kindFilter === undefined ? true : kindFilter.has(row.kindName),\n );\n\n if (candidates.length === 0) return { results: [], reclaimedVectorFields };\n\n const tableNames = backend.tableNames;\n const nodesTable = tableNames?.nodes ?? \"typegraph_nodes\";\n const edgesTable = tableNames?.edges ?? \"typegraph_edges\";\n const fulltextTable = tableNames?.fulltext ?? \"typegraph_node_fulltext\";\n const uniquesTable = tableNames?.uniques ?? \"typegraph_node_uniques\";\n\n const captureRecordedRemovals = context.captureRecordedRemovals === true;\n const ctx = {\n backend,\n graphId,\n nodesTable,\n edgesTable,\n fulltextTable,\n uniquesTable,\n captureRecordedRemovals,\n recordedSchema:\n captureRecordedRemovals ?\n (context.recordedSchema ?? createSqlSchema(backend.tableNames))\n : undefined,\n } as const;\n\n // Each kind targets a disjoint row set (DELETEs filtered by kindName),\n // so the default best-effort path runs them concurrently — Postgres\n // parallelizes round-trips across pool connections, SQLite serializes\n // writes at the engine level either way. `stopOnError` honors strict\n // sequential semantics; the first failure short-circuits the rest.\n return {\n results: await runMaterialization(candidates, options, (removal) =>\n materializeOne(removal, ctx),\n ),\n reclaimedVectorFields,\n };\n}\n\n/**\n * Walks the schema-version history backward from the active version\n * and re-records any kind-removal whose queue row is missing entirely.\n *\n * Handles the full crash-window recovery: a `removeKinds()` call that\n * commits the schema diff but fails before recording the queue row\n * can be followed by any number of additional schema transitions\n * (evolve, deprecate, further removes) — the lost queue row is still\n * recoverable from schema history because the kind diff at that\n * specific transition is permanent metadata.\n *\n * Uses `getAllKindRemovals` to distinguish \"row missing entirely\" (the\n * crash window — needs recovery) from \"row already completed\" (a\n * successful prior cleanup — re-recording would churn\n * `last_attempted_at` even though COALESCE preserves the success).\n * Backends without that primitive fall back to the pending-only set,\n * which keeps reconciliation correct (the COALESCE rule preserves the\n * completed state) but does churn `last_attempted_at` on already-\n * completed rows. The bundled SQLite and Postgres backends implement\n * `getAllKindRemovals`.\n */\nasync function reconcilePendingRemovals(\n context: MaterializeRemovalsContext,\n): Promise<void> {\n const { backend, graphId } = context;\n const recordKindRemoval = backend.recordKindRemoval;\n if (recordKindRemoval === undefined) return;\n\n const activeRow = await backend.getActiveSchema(graphId);\n if (activeRow === undefined || activeRow.version <= 1) return;\n\n // Watermark short-circuit: when a previous reconciliation pass\n // verified history through some version M, only walk transitions\n // newer than M. Without the watermark this loop walked from active\n // down to version 1 on every call — N round-trips + N Zod parses\n // per call — and re-verified already-good history every time.\n // Backends without the marker primitives fall back to walking from\n // version 1 (the legacy behavior) so existing custom backends\n // keep working.\n //\n // Bootstrap the marker table BEFORE the read — DBs that pre-date\n // this slice would otherwise SELECT from a missing table and throw\n // before they got the chance to create it.\n if (backend.ensureReconciliationMarkersTable !== undefined) {\n await backend.ensureReconciliationMarkersTable();\n }\n const marker =\n backend.getReconciliationMarker === undefined ?\n undefined\n : await backend.getReconciliationMarker(graphId);\n if (marker !== undefined && marker >= activeRow.version) return;\n\n // Existence map: a (entity, kindName, schemaVersion) is recorded if\n // a row exists in any state (pending or completed). The rows we want\n // to reconcile are the ones missing from this set entirely.\n const allRemovals = await (backend.getAllKindRemovals === undefined ?\n requireDefined(backend.getPendingKindRemovals)(graphId)\n : backend.getAllKindRemovals(graphId));\n const recorded = new Set(\n allRemovals.map((row) =>\n kindRemovalKey(row.entity, row.kindName, row.schemaVersion),\n ),\n );\n\n const reconciliations: {\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n }[] = [];\n\n // Walk backward through transitions, stopping at the watermark.\n // At each pair (priorRow, currentRow) we compute \"kinds removed at\n // currentRow.version\" and check the existence map — any missing\n // entry needs an idempotent upsert. The marker bounds the walk so\n // long-running deployments with hundreds of schema versions skip\n // the bulk of the round-trips after their first reconciliation.\n const stopAtVersion = marker ?? 1;\n let currentRow = activeRow;\n let currentSchema = parseSerializedSchema(activeRow.schema_doc);\n while (currentRow.version > stopAtVersion) {\n const priorRow = await backend.getSchemaVersion(\n graphId,\n currentRow.version - 1,\n );\n if (priorRow === undefined) break;\n const priorSchema = parseSerializedSchema(priorRow.schema_doc);\n\n for (const entity of ENTITY_KINDS) {\n const priorEntries = priorSchema[entity === \"node\" ? \"nodes\" : \"edges\"];\n const currentEntries =\n currentSchema[entity === \"node\" ? \"nodes\" : \"edges\"];\n for (const kindName of Object.keys(priorEntries)) {\n if (kindName in currentEntries) continue;\n if (\n recorded.has(kindRemovalKey(entity, kindName, currentRow.version))\n ) {\n continue;\n }\n reconciliations.push({\n kindName,\n entity,\n schemaVersion: currentRow.version,\n });\n }\n }\n\n currentRow = priorRow;\n currentSchema = priorSchema;\n }\n\n if (reconciliations.length > 0) {\n const attemptedAt = nowIso();\n await Promise.all(\n reconciliations.map((entry) =>\n recordKindRemoval(\n buildPendingKindRemoval({\n graphId,\n kindName: entry.kindName,\n entity: entry.entity,\n schemaVersion: entry.schemaVersion,\n attemptedAt,\n }),\n ),\n ),\n );\n }\n\n // Persist the new high-water mark so the next call walks only\n // versions newer than this one. Done after the reconciliation\n // upserts succeed — a crash before this point leaves the marker\n // unchanged, so the next call re-walks (idempotent — recorded\n // rows skip via the existence-map check above).\n if (backend.setReconciliationMarker !== undefined) {\n await backend.setReconciliationMarker(graphId, activeRow.version);\n }\n}\n\nfunction kindRemovalKey(\n entity: KindEntity,\n kindName: string,\n version: number,\n): string {\n return `${entity}|${kindName}|${version}`;\n}\n\nasync function materializeOne(\n row: KindRemovalRow,\n ctx: MaterializeOneContext,\n): Promise<MaterializeRemovalsEntry> {\n const recordKindRemoval = requireDefined(ctx.backend.recordKindRemoval);\n try {\n await closeRecordedAndDeleteLiveRows(ctx, row);\n await Promise.all(buildEmbeddingTableCleanup(ctx, row));\n\n const removedAt = nowIso();\n await recordKindRemoval({\n graphId: ctx.graphId,\n kindName: row.kindName,\n entity: row.entity,\n schemaVersion: row.schemaVersion,\n attemptedAt: removedAt,\n removedAt,\n error: undefined,\n });\n return {\n kind: row.kindName,\n entity: row.entity,\n status: \"removed\",\n };\n } catch (error_) {\n const error = error_ instanceof Error ? error_ : new Error(String(error_));\n await recordKindRemoval({\n graphId: ctx.graphId,\n kindName: row.kindName,\n entity: row.entity,\n schemaVersion: row.schemaVersion,\n attemptedAt: nowIso(),\n removedAt: undefined,\n error: error.message,\n });\n return {\n kind: row.kindName,\n entity: row.entity,\n status: \"failed\",\n error,\n };\n }\n}\n\n/**\n * Closes recorded-time intervals for a hard-removed kind and deletes the live\n * rows in one transaction. Without the shared transaction, a crash after the\n * recorded close but before the live deletes leaves broad live reads able to see\n * rows whose kind the active schema has removed.\n *\n * Tolerates absent recorded relations exactly as `clear()` and\n * `refreshStatistics()` do: a history-enabled store whose recorded tables\n * predate recorded-time history (bring-your-own-pool, no DDL re-run) skips only\n * the close, then still deletes the live rows. A no-op close when\n * recorded-removal capture is off.\n */\nasync function closeRecordedAndDeleteLiveRows(\n ctx: MaterializeOneContext,\n row: KindRemovalRow,\n): Promise<void> {\n const deleteStatements = buildRemovedKindLiveDeleteStatements(ctx, row);\n if (!ctx.captureRecordedRemovals || ctx.recordedSchema === undefined) {\n await executeDeleteStatements(ctx.backend, deleteStatements);\n return;\n }\n\n const recordedSchema = ctx.recordedSchema;\n try {\n await ctx.backend.transaction(async (target) => {\n await closeRecordedHardDeletedKind(\n target,\n recordedSchema,\n ctx.graphId,\n { entity: row.entity, kind: row.kindName },\n false,\n );\n await executeDeleteStatements(target, deleteStatements);\n });\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n await executeDeleteStatements(ctx.backend, deleteStatements);\n }\n}\n\nfunction buildRemovedKindLiveDeleteStatements(\n ctx: MaterializeOneContext,\n row: KindRemovalRow,\n): readonly string[] {\n const graphLit = literal(ctx.graphId);\n const kindLit = literal(row.kindName);\n if (row.entity === \"node\") {\n return [\n `DELETE FROM ${quote(ctx.nodesTable)} WHERE graph_id = ${graphLit} AND kind = ${kindLit}`,\n `DELETE FROM ${quote(ctx.edgesTable)} WHERE graph_id = ${graphLit} AND (from_kind = ${kindLit} OR to_kind = ${kindLit})`,\n `DELETE FROM ${quote(ctx.fulltextTable)} WHERE graph_id = ${graphLit} AND node_kind = ${kindLit}`,\n `DELETE FROM ${quote(ctx.uniquesTable)} WHERE graph_id = ${graphLit} AND node_kind = ${kindLit}`,\n ];\n }\n return [\n `DELETE FROM ${quote(ctx.edgesTable)} WHERE graph_id = ${graphLit} AND kind = ${kindLit}`,\n ];\n}\n\nasync function executeDeleteStatements(\n target: GraphBackend | TransactionBackend,\n statements: readonly string[],\n): Promise<void> {\n if (target.executeStatement !== undefined) {\n await Promise.all(\n statements.map((statement) =>\n requireDefined(target.executeStatement)(\n asCompiledStatementSql(sql.raw(statement)),\n ),\n ),\n );\n return;\n }\n\n if (target.executeDdl === undefined) {\n throw new ConfigurationError(\n \"store.materializeRemovals() requires a backend that can execute cleanup statements.\",\n { code: \"MATERIALIZE_REMOVALS_BACKEND_UNSUPPORTED\" },\n );\n }\n await Promise.all(\n statements.map((statement) => requireDefined(target.executeDdl)(statement)),\n );\n}\n\n/**\n * Builds the embedding-storage cleanup for a removed node kind.\n *\n * With per-`(graphId, kind, field)` storage there is no single shared\n * embeddings table to filter by `node_kind`; each embedding field of the\n * removed kind has its own typed, graph-scoped table. We resolve those fields\n * from the schema version that still *had* the kind (`schemaVersion - 1`) and\n * drop each per-field table via the strategy — the same teardown the\n * removed-*field* reclamation uses — so the kind's table and any ANN index it\n * owns are fully reclaimed (a stale empty table would otherwise collide with a\n * re-added kind at a different dimension).\n *\n * Backends without a vector strategy, or schema history that can't be\n * read, yield no cleanup — there is no embedding storage to reclaim.\n * Returned as a single combined promise so the caller can issue it\n * alongside the other disjoint DELETEs.\n */\nfunction buildEmbeddingTableCleanup(\n ctx: Readonly<{\n backend: GraphBackend;\n graphId: string;\n }>,\n row: KindRemovalRow,\n): readonly Promise<void>[] {\n const vectorStrategy = ctx.backend.vectorStrategy;\n if (vectorStrategy === undefined) return [];\n\n const executeDdl = requireDefined(ctx.backend.executeDdl);\n const cleanup = (async () => {\n const slots = await resolveRemovedKindEmbeddingSlots(ctx.backend, row);\n await Promise.all(\n slots.map((slot) =>\n dropVectorSlotStorage(ctx.backend, vectorStrategy, executeDdl, slot),\n ),\n );\n })();\n return [cleanup];\n}\n\n/**\n * Drops a per-field vector slot's storage via the strategy (table + any ANN\n * index it owns), tolerating an already-absent table — a declared field whose\n * per-field table was never materialized (no write, no index build) has nothing\n * to reclaim. Runs as autocommit statements, so swallowing a missing-table\n * failure can't poison a sibling drop. Shared by removed-kind cleanup and\n * removed-field reclamation so both reclaim storage the same way.\n */\nasync function dropVectorSlotStorage(\n backend: GraphBackend,\n strategy: VectorStrategy,\n executeDdl: (statement: string) => Promise<void>,\n slot: VectorSlot,\n): Promise<void> {\n try {\n for (const ddl of strategy.buildDropStorage(slot)) {\n await executeDdl(ddl);\n }\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n }\n // Forget the slot's durable contribution marker(s) in lockstep with the\n // table drop (#135), so a later re-add of the same `(kind, field)` field\n // re-creates the table instead of trusting an orphaned \"initialized\"\n // marker. Runs even when the table was already absent — the marker can\n // outlive the table. No-op on backends without the vector marker method.\n await backend.deleteVectorSlotContribution?.(slot);\n}\n\n/**\n * Resolves the embedding field paths a removed node kind declared, read\n * from the persisted vector index declarations in the schema version\n * just before the removal (`schemaVersion - 1`). Returns `[]` when the\n * prior version is unavailable or declared no embedding fields for the\n * kind.\n */\nasync function resolveRemovedKindEmbeddingSlots(\n backend: GraphBackend,\n row: KindRemovalRow,\n): Promise<readonly VectorSlot[]> {\n const priorVersion = row.schemaVersion - 1;\n if (priorVersion < 1) return [];\n const priorRow = await backend.getSchemaVersion(row.graphId, priorVersion);\n if (priorRow === undefined) return [];\n\n const priorSchema = parseSerializedSchema(priorRow.schema_doc);\n const slots = new Map<string, VectorSlot>();\n for (const declaration of priorSchema.indexes ?? []) {\n if (declaration.entity === \"vector\" && declaration.kind === row.kindName) {\n slots.set(declaration.fieldPath, {\n graphId: row.graphId,\n nodeKind: row.kindName,\n fieldPath: declaration.fieldPath,\n dimensions: declaration.dimensions,\n metric: declaration.metric,\n indexType: declaration.indexType,\n });\n }\n }\n return [...slots.values()];\n}\n\n/** Stable key for a `(kind, fieldPath)` embedding-field pair. */\nfunction vectorFieldKey(kind: string, fieldPath: string): string {\n return `${kind}\\u0000${fieldPath}`;\n}\n\n/**\n * The historical declaration of a vector field, carrying everything\n * {@link VectorStrategy.buildDropStorage} needs to tear the storage down —\n * notably `indexType`, which libSQL reads to also drop its DiskANN index.\n */\ntype HistoricalVectorField = Readonly<{\n kind: string;\n fieldPath: string;\n slot: VectorSlot;\n}>;\n\n/**\n * Reclaims per-`(graphId, kind, field)` vector tables orphaned by embedding-\n * field removals on *surviving* kinds.\n *\n * Per-field storage means every embedding field owns a typed table. When a\n * field is dropped from a kind that still exists (an `evolve` that removes the\n * embedding), nothing reclaims that table: the add-only `materializeIndexes`\n * path ignores removals and the kind-scoped cleanup above only fires for whole\n * removed kinds. Left alone the table lingers with dead rows that no query\n * reads again, and — worse — a later re-add of the field at a different\n * dimension would collide with the stale table.\n *\n * The orphan set is derived from schema history: every vector field ever\n * declared, minus the ones still declared in the *active* schema, restricted\n * to kinds that still exist (removed-kind fields are the kind path's job).\n * Using the active schema as the \"still declared\" source of truth makes\n * remove-then-re-add safe — a re-added field is current, so it is never\n * dropped. `buildDropStorage` emits `DROP ... IF EXISTS`, so the pass is\n * idempotent and a never-materialized field is a clean no-op; deriving from\n * full history each call also reclaims tables orphaned before this shipped.\n *\n * Backends without a vector strategy or `executeDdl` have no per-field tables\n * to reclaim and yield an empty result.\n */\nasync function reclaimRemovedVectorFieldTables(\n context: MaterializeRemovalsContext,\n): Promise<readonly ReclaimedVectorFieldEntry[]> {\n const { backend, graphId } = context;\n const vectorStrategy = backend.vectorStrategy;\n const executeDdl = backend.executeDdl;\n if (vectorStrategy === undefined || executeDdl === undefined) return [];\n\n const activeRow = await backend.getActiveSchema(graphId);\n if (activeRow === undefined) return [];\n\n // The orphan set is a pure function of (graphId, active version) over\n // immutable schema history and the drops are idempotent, so re-walking the\n // whole history on every materializeRemovals call is wasted O(versions) work.\n // Memoize per (backend, graphId:version); an evolve bumps the version and\n // invalidates. Only fully-successful passes are cached (a failed drop must be\n // retried), and the cache is in-process so a fresh backend re-walks once.\n const cacheKey = `${graphId}\\u0000${activeRow.version}`;\n let perBackend = reclaimCache.get(backend);\n const cached = perBackend?.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const activeSchema = parseSerializedSchema(activeRow.schema_doc);\n\n const activeVectorFields = new Set<string>();\n for (const declaration of activeSchema.indexes ?? []) {\n if (declaration.entity === \"vector\") {\n activeVectorFields.add(\n vectorFieldKey(declaration.kind, declaration.fieldPath),\n );\n }\n }\n const survivingKinds = new Set(Object.keys(activeSchema.nodes));\n\n // Walk history backward, keeping the most-recent declaration of each\n // vector field (first seen wins) so `buildDropStorage` gets a faithful\n // `indexType`/`dimensions`.\n const historical = new Map<string, HistoricalVectorField>();\n for (let version = activeRow.version - 1; version >= 1; version -= 1) {\n const priorRow = await backend.getSchemaVersion(graphId, version);\n if (priorRow === undefined) continue;\n const priorSchema = parseSerializedSchema(priorRow.schema_doc);\n for (const declaration of priorSchema.indexes ?? []) {\n if (declaration.entity !== \"vector\") continue;\n const key = vectorFieldKey(declaration.kind, declaration.fieldPath);\n if (historical.has(key)) continue;\n historical.set(key, {\n kind: declaration.kind,\n fieldPath: declaration.fieldPath,\n slot: {\n graphId,\n nodeKind: declaration.kind,\n fieldPath: declaration.fieldPath,\n dimensions: declaration.dimensions,\n metric: declaration.metric,\n indexType: declaration.indexType,\n },\n });\n }\n }\n\n const orphans = [...historical.values()].filter(\n (field) =>\n !activeVectorFields.has(vectorFieldKey(field.kind, field.fieldPath)) &&\n survivingKinds.has(field.kind),\n );\n\n const results: ReclaimedVectorFieldEntry[] = [];\n for (const field of orphans) {\n // dropVectorSlotStorage swallows the missing-table case (a never-\n // materialized field has nothing to reclaim), so reaching the catch means\n // a genuine failure.\n try {\n await dropVectorSlotStorage(\n backend,\n vectorStrategy,\n executeDdl,\n field.slot,\n );\n results.push({\n kind: field.kind,\n fieldPath: field.fieldPath,\n status: \"reclaimed\",\n });\n } catch (error) {\n results.push({\n kind: field.kind,\n fieldPath: field.fieldPath,\n status: \"failed\",\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n }\n\n // Cache only a fully-successful pass — a failed drop must be retried.\n if (results.every((entry) => entry.status === \"reclaimed\")) {\n if (perBackend === undefined) {\n perBackend = new Map();\n reclaimCache.set(backend, perBackend);\n }\n perBackend.set(cacheKey, results);\n }\n return results;\n}\n\n/**\n * In-process memo for {@link reclaimRemovedVectorFieldTables}, keyed by backend\n * then `graphId:activeVersion`. See that function for why version-keying is\n * sound (the orphan set is a pure function of immutable history + the version).\n */\nconst reclaimCache = new WeakMap<\n GraphBackend,\n Map<string, readonly ReclaimedVectorFieldEntry[]>\n>();\n\n// `executeDdl` accepts a raw SQL string. The DELETE statements built\n// here are dialect-neutral (no SQLite/Postgres-specific syntax) and\n// use single-quote string literals for graph_id / kind names. Both\n// values come from the schema — never untrusted user input — but we\n// still escape single quotes defensively to avoid surprises if a\n// future kind-name validator narrows beyond `[A-Za-z_][A-Za-z0-9_]*`.\nfunction quote(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction literal(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n","/**\n * Edge Operations for Store\n *\n * Handles edge CRUD operations: create, update, delete.\n */\nimport {\n createBackendOverlay,\n type EdgeRow as BackendEdgeRow,\n type GraphBackend,\n type GraphReadBackend,\n type InsertEdgeParams,\n rowPropsToObject,\n type TransactionBackend,\n} from \"../../backend/types\";\nimport { validateEdgeEndpoints } from \"../../constraints\";\nimport { type GraphDef } from \"../../core/define-graph\";\nimport {\n type Cardinality,\n type KindEntity,\n type TemporalMode,\n} from \"../../core/types\";\nimport {\n CardinalityError,\n DatabaseOperationError,\n EdgeNotFoundError,\n EndpointNotFoundError,\n KindNotFoundError,\n ValidationError,\n} from \"../../errors\";\nimport { validateEdgeProps } from \"../../errors/validation\";\nimport { type SqlSchema } from \"../../query/compiler/schema\";\nimport { type KindRegistry } from \"../../registry/kind-registry\";\nimport { canonicalEqual } from \"../../schema/canonical\";\nimport { validateOptionalCanonicalIsoDate } from \"../../utils/date\";\nimport { generateId } from \"../../utils/id\";\nimport { requireDefined } from \"../../utils/presence\";\nimport { type UpsertDirtyCheck } from \"../collections/coalesce\";\nimport {\n checkCardinalityConstraint,\n type ConstraintContext,\n} from \"../constraints\";\nimport {\n edgeInsertDispatch,\n runInsertBatch,\n runInsertBatchReturning,\n runInsertNoReturn,\n} from \"../insert-dispatch\";\nimport { type EdgeRow, rowToEdge } from \"../row-mappers\";\nimport {\n type CreateEdgeInput,\n type Edge,\n type GetOrCreateAction,\n type IfExistsMode,\n type OperationHookContext,\n} from \"../types\";\nimport {\n runHookedWriteOperation,\n runInWriteTransaction,\n} from \"./write-transaction\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Context for edge operations.\n */\nexport type EdgeOperationContext<G extends GraphDef> = Readonly<{\n graph: G;\n graphId: string;\n historyEnabled: boolean;\n revisionTrackingEnabled: boolean;\n revisionSchema: SqlSchema;\n registry: KindRegistry;\n createOperationContext: (\n operation: \"create\" | \"update\" | \"delete\",\n entity: KindEntity,\n kind: string,\n id: string,\n ) => OperationHookContext;\n withOperationHooks: <T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n ) => Promise<T>;\n}>;\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\nfunction getEdgeRegistration<G extends GraphDef>(graph: G, kind: string) {\n const registration = graph.edges[kind];\n if (registration === undefined) throw new KindNotFoundError(kind, \"edge\");\n return registration;\n}\n\ntype EdgeCreatePrepared = Readonly<{\n insertParams: InsertEdgeParams;\n cardinality: Cardinality;\n}>;\n\nfunction buildEdgeEndpointCacheKey(\n graphId: string,\n kind: string,\n id: string,\n): string {\n return `${graphId}\\u0000${kind}\\u0000${id}`;\n}\n\nfunction buildEdgeFromCacheKey(\n graphId: string,\n edgeKind: string,\n fromKind: string,\n fromId: string,\n): string {\n return `${graphId}\\u0000${edgeKind}\\u0000${fromKind}\\u0000${fromId}`;\n}\n\nfunction buildEdgeBetweenCacheKey(\n graphId: string,\n edgeKind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n): string {\n return `${graphId}\\u0000${edgeKind}\\u0000${fromKind}\\u0000${fromId}\\u0000${toKind}\\u0000${toId}`;\n}\n\nfunction buildCountEdgesFromCacheKey(\n params: Parameters<GraphBackend[\"countEdgesFrom\"]>[0],\n): string {\n const activeOnly = params.activeOnly === true ? \"1\" : \"0\";\n return `${params.graphId}\\u0000${params.edgeKind}\\u0000${params.fromKind}\\u0000${params.fromId}\\u0000${activeOnly}`;\n}\n\nfunction buildInsertEdgeParams(\n graphId: string,\n id: string,\n kind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n props: Record<string, unknown>,\n validFrom: string | undefined,\n validTo: string | undefined,\n): InsertEdgeParams {\n const insertParams: {\n graphId: string;\n id: string;\n kind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Record<string, unknown>;\n validFrom?: string;\n validTo?: string;\n } = {\n graphId,\n id,\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n props,\n };\n if (validFrom !== undefined) insertParams.validFrom = validFrom;\n if (validTo !== undefined) insertParams.validTo = validTo;\n return insertParams;\n}\n\nfunction incrementPendingCount(counts: Map<string, number>, key: string): void {\n const previous = counts.get(key) ?? 0;\n counts.set(key, previous + 1);\n}\n\nfunction createEdgeBatchValidationBackend(\n backend: GraphBackend | TransactionBackend,\n): Readonly<{\n backend: GraphBackend | TransactionBackend;\n registerPendingEdgeForCardinality: (\n insertParams: InsertEdgeParams,\n cardinality: Cardinality,\n ) => void;\n seedEndpointRow: (\n graphId: string,\n kind: string,\n id: string,\n row: Awaited<ReturnType<GraphBackend[\"getNode\"]>>,\n ) => void;\n}> {\n const endpointCache = new Map<\n string,\n Awaited<ReturnType<GraphBackend[\"getNode\"]>>\n >();\n const countEdgesFromCache = new Map<string, number>();\n const edgeExistsCache = new Map<string, boolean>();\n const pendingOneCounts = new Map<string, number>();\n const pendingOneActiveCounts = new Map<string, number>();\n const pendingUniquePairs = new Set<string>();\n\n async function getNodeCached(\n graphId: string,\n kind: string,\n id: string,\n ): Promise<Awaited<ReturnType<GraphBackend[\"getNode\"]>>> {\n const cacheKey = buildEdgeEndpointCacheKey(graphId, kind, id);\n if (endpointCache.has(cacheKey)) {\n return endpointCache.get(cacheKey);\n }\n const node = await backend.getNode(graphId, kind, id);\n endpointCache.set(cacheKey, node);\n return node;\n }\n\n // Lets batch preparation prime the endpoint cache from one getNodes\n // round trip per (kind) instead of a per-edge getNode probe for each\n // from/to endpoint — mirrors seedNodeRow in createNodeBatchValidationBackend.\n // Seeding an absent result (`undefined`) is meaningful — it marks the key\n // as known-missing so the per-edge check skips the backend read. An\n // earlier lookup or seed always wins; seeding never overwrites.\n function seedEndpointRow(\n graphId: string,\n kind: string,\n id: string,\n row: Awaited<ReturnType<GraphBackend[\"getNode\"]>>,\n ): void {\n const cacheKey = buildEdgeEndpointCacheKey(graphId, kind, id);\n if (endpointCache.has(cacheKey)) return;\n endpointCache.set(cacheKey, row);\n }\n\n async function countEdgesFromCached(\n params: Parameters<GraphBackend[\"countEdgesFrom\"]>[0],\n ): Promise<number> {\n const cacheKey = buildCountEdgesFromCacheKey(params);\n let baseCount = countEdgesFromCache.get(cacheKey);\n if (baseCount === undefined) {\n baseCount = await backend.countEdgesFrom(params);\n countEdgesFromCache.set(cacheKey, baseCount);\n }\n const pendingKey = buildEdgeFromCacheKey(\n params.graphId,\n params.edgeKind,\n params.fromKind,\n params.fromId,\n );\n const pendingCount =\n params.activeOnly === true ?\n (pendingOneActiveCounts.get(pendingKey) ?? 0)\n : (pendingOneCounts.get(pendingKey) ?? 0);\n return baseCount + pendingCount;\n }\n\n async function edgeExistsBetweenCached(\n params: Parameters<GraphBackend[\"edgeExistsBetween\"]>[0],\n ): Promise<boolean> {\n const cacheKey = buildEdgeBetweenCacheKey(\n params.graphId,\n params.edgeKind,\n params.fromKind,\n params.fromId,\n params.toKind,\n params.toId,\n );\n if (pendingUniquePairs.has(cacheKey)) {\n return true;\n }\n if (edgeExistsCache.has(cacheKey)) {\n return edgeExistsCache.get(cacheKey) ?? false;\n }\n const exists = await backend.edgeExistsBetween(params);\n edgeExistsCache.set(cacheKey, exists);\n return exists;\n }\n\n function registerPendingEdgeForCardinality(\n insertParams: InsertEdgeParams,\n cardinality: Cardinality,\n ): void {\n const fromCacheKey = buildEdgeFromCacheKey(\n insertParams.graphId,\n insertParams.kind,\n insertParams.fromKind,\n insertParams.fromId,\n );\n if (cardinality === \"one\") {\n incrementPendingCount(pendingOneCounts, fromCacheKey);\n return;\n }\n if (cardinality === \"oneActive\") {\n if (insertParams.validTo === undefined) {\n incrementPendingCount(pendingOneActiveCounts, fromCacheKey);\n }\n return;\n }\n if (cardinality === \"unique\") {\n const uniqueCacheKey = buildEdgeBetweenCacheKey(\n insertParams.graphId,\n insertParams.kind,\n insertParams.fromKind,\n insertParams.fromId,\n insertParams.toKind,\n insertParams.toId,\n );\n pendingUniquePairs.add(uniqueCacheKey);\n }\n }\n\n const validationBackend = createBackendOverlay(backend, {\n getNode: getNodeCached,\n countEdgesFrom: countEdgesFromCached,\n edgeExistsBetween: edgeExistsBetweenCached,\n } satisfies Partial<GraphBackend | TransactionBackend>);\n\n return {\n backend: validationBackend,\n registerPendingEdgeForCardinality,\n seedEndpointRow,\n };\n}\n\nasync function validateAndPrepareEdgeCreate<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: CreateEdgeInput,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<EdgeCreatePrepared> {\n const kind = input.kind;\n const fromKind = input.fromKind;\n const toKind = input.toKind;\n\n // Validate kind exists and get registration\n const registration = getEdgeRegistration(ctx.graph, kind);\n const edgeKind = registration.type;\n\n // Validate endpoint types\n const endpointError = validateEdgeEndpoints(\n kind,\n fromKind,\n toKind,\n registration,\n ctx.registry,\n );\n if (endpointError) throw endpointError;\n\n // Validate source node exists\n const fromNode = await backend.getNode(ctx.graphId, fromKind, input.fromId);\n if (!fromNode || fromNode.deleted_at) {\n throw new EndpointNotFoundError({\n edgeKind: kind,\n endpoint: \"from\",\n nodeKind: fromKind,\n nodeId: input.fromId,\n });\n }\n\n // Validate target node exists\n const toNode = await backend.getNode(ctx.graphId, toKind, input.toId);\n if (!toNode || toNode.deleted_at) {\n throw new EndpointNotFoundError({\n edgeKind: kind,\n endpoint: \"to\",\n nodeKind: toKind,\n nodeId: input.toId,\n });\n }\n\n // Validate props with full context\n const validatedProps = validateEdgeProps(edgeKind.schema, input.props, {\n kind,\n operation: \"create\",\n });\n\n // Validate temporal fields\n const validFrom = validateOptionalCanonicalIsoDate(\n input.validFrom,\n \"validFrom\",\n );\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n\n // Check cardinality constraints\n const cardinality = registration.cardinality ?? \"many\";\n const constraintContext: ConstraintContext = {\n graphId: ctx.graphId,\n registry: ctx.registry,\n backend,\n };\n await checkCardinalityConstraint(\n constraintContext,\n kind,\n cardinality,\n fromKind,\n input.fromId,\n toKind,\n input.toId,\n validTo,\n );\n\n return {\n cardinality,\n insertParams: buildInsertEdgeParams(\n ctx.graphId,\n id,\n kind,\n fromKind,\n input.fromId,\n toKind,\n input.toId,\n validatedProps,\n validFrom,\n validTo,\n ),\n };\n}\n\n// ============================================================\n// Edge Operations\n// ============================================================\n\n/**\n * Executes an edge create operation.\n */\nasync function executeEdgeCreateInternal<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: CreateEdgeInput,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ returnRow?: boolean }>,\n): Promise<Edge | undefined> {\n const kind = input.kind;\n const id = input.id ?? generateId();\n const opContext = ctx.createOperationContext(\"create\", \"edge\", kind, id);\n const shouldReturnRow = options?.returnRow ?? true;\n\n return runHookedWriteOperation(ctx, opContext, backend, async (target) => {\n const prepared = await validateAndPrepareEdgeCreate(ctx, input, id, target);\n\n let row: BackendEdgeRow | undefined;\n if (shouldReturnRow) {\n row = await target.insertEdge(prepared.insertParams);\n } else {\n await runInsertNoReturn(\n edgeInsertDispatch(target),\n prepared.insertParams,\n );\n }\n\n if (row === undefined) return;\n return rowToEdge(row);\n });\n}\n\n/**\n * Executes an edge create operation and returns the created edge.\n */\nexport async function executeEdgeCreate<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: CreateEdgeInput,\n backend: GraphBackend | TransactionBackend,\n): Promise<Edge> {\n const result = await executeEdgeCreateInternal(ctx, input, backend, {\n returnRow: true,\n });\n if (!result) {\n throw new DatabaseOperationError(\n \"Edge create failed: expected created edge row\",\n { operation: \"insert\", entity: \"edge\" },\n );\n }\n return result;\n}\n\n/**\n * Executes an edge create operation without returning the created edge payload.\n */\nexport async function executeEdgeCreateNoReturn<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: CreateEdgeInput,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n await executeEdgeCreateInternal(ctx, input, backend, { returnRow: false });\n}\n\n/**\n * Batch-primes an edge batch's endpoint validation cache with one\n * `getNodes` round trip per distinct (kind) referenced across every\n * from/to endpoint in the batch, instead of a `getNode` probe per edge.\n * Mirrors `primeBatchValidationCaches`'s node-existence priming.\n */\nasync function primeEdgeBatchValidationCache<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n seedEndpointRow: (\n graphId: string,\n kind: string,\n id: string,\n row: Awaited<ReturnType<GraphBackend[\"getNode\"]>>,\n ) => void,\n): Promise<void> {\n if (backend.getNodes === undefined) return;\n\n const idsByKind = new Map<string, Set<string>>();\n const addEndpoint = (kind: string, id: string): void => {\n const ids = idsByKind.get(kind) ?? new Set<string>();\n ids.add(id);\n idsByKind.set(kind, ids);\n };\n for (const input of inputs) {\n addEndpoint(input.fromKind, input.fromId);\n addEndpoint(input.toKind, input.toId);\n }\n\n for (const [kind, ids] of idsByKind) {\n const orderedIds = [...ids];\n const rows = await backend.getNodes(ctx.graphId, kind, orderedIds);\n const rowsById = new Map(rows.map((row) => [row.id, row]));\n for (const id of orderedIds) {\n seedEndpointRow(ctx.graphId, kind, id, rowsById.get(id));\n }\n }\n}\n\n/**\n * Shared batch preparation for edge creates: primes the endpoint\n * validation cache with one `getNodes` call per referenced kind, then\n * validates every input against the primed cache in order (so later\n * inputs see earlier ones' pending cardinality/uniqueness registrations).\n * Shared between the non-returning and RETURNING batch paths so both get\n * the same batched-prefetch treatment.\n */\nasync function prepareEdgeBatchCreates<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<{\n preparedCreates: EdgeCreatePrepared[];\n batchInsertParams: InsertEdgeParams[];\n}> {\n const {\n backend: validationBackend,\n registerPendingEdgeForCardinality,\n seedEndpointRow,\n } = createEdgeBatchValidationBackend(backend);\n\n await primeEdgeBatchValidationCache(ctx, inputs, backend, seedEndpointRow);\n\n const preparedCreates: EdgeCreatePrepared[] = [];\n for (const input of inputs) {\n const id = input.id ?? generateId();\n const prepared = await validateAndPrepareEdgeCreate(\n ctx,\n input,\n id,\n validationBackend,\n );\n preparedCreates.push(prepared);\n registerPendingEdgeForCardinality(\n prepared.insertParams,\n prepared.cardinality,\n );\n }\n\n const batchInsertParams = preparedCreates.map(\n (prepared) => prepared.insertParams,\n );\n\n return { preparedCreates, batchInsertParams };\n}\n\n/**\n * Executes batched edge creates without returning inserted edge payloads.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeEdgeCreateNoReturnBatch<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n if (inputs.length === 0) {\n return;\n }\n\n await runInWriteTransaction(ctx, backend, async (target) => {\n const { batchInsertParams } = await prepareEdgeBatchCreates(\n ctx,\n inputs,\n target,\n );\n await runInsertBatch(edgeInsertDispatch(target), batchInsertParams);\n });\n}\n\n/**\n * Executes batched edge creates and returns the inserted edge payloads.\n *\n * Uses batch validation caching and a single multi-row INSERT with RETURNING\n * when the backend supports it. Falls back to sequential inserts otherwise.\n *\n * Note: `withOperationHooks` is intentionally skipped for batch throughput.\n * Per-item hooks would negate the performance benefit of batching.\n */\nexport async function executeEdgeCreateBatch<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n inputs: readonly CreateEdgeInput[],\n backend: GraphBackend | TransactionBackend,\n): Promise<readonly Edge[]> {\n if (inputs.length === 0) {\n return [];\n }\n\n return runInWriteTransaction(ctx, backend, async (target) => {\n const { batchInsertParams } = await prepareEdgeBatchCreates(\n ctx,\n inputs,\n target,\n );\n\n const rows = await runInsertBatchReturning(\n edgeInsertDispatch(target),\n batchInsertParams,\n );\n\n return rows.map((row) => rowToEdge(row));\n });\n}\n\n/**\n * The exact props an edge update would persist: the caller's partial input\n * merged over the current props and run through the edge kind's Zod schema.\n * Operates on PARSED props so the write path and the coalesce dirty-check\n * (which may compare against a batch-local running value, never a row) share\n * one validation. Endpoints are the edge's identity and are not part of an\n * upsert-by-id update, so only props are involved.\n */\nfunction computeEdgeUpdate<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n kind: string,\n id: string,\n existingProps: Record<string, unknown>,\n inputProps: Partial<Record<string, unknown>>,\n): Record<string, unknown> {\n const registration = getEdgeRegistration(ctx.graph, kind);\n return validateEdgeProps(\n registration.type.schema,\n { ...existingProps, ...inputProps },\n { kind, operation: \"update\", id },\n );\n}\n\n/**\n * Row-based wrapper over {@link computeEdgeUpdate} for the write path.\n */\nfunction resolveEdgeUpdateProps<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n existing: Pick<EdgeRow, \"kind\" | \"id\" | \"props\">,\n inputProps: Partial<Record<string, unknown>>,\n): Readonly<{\n existingProps: Record<string, unknown>;\n validatedProps: Record<string, unknown>;\n}> {\n const existingProps = rowPropsToObject(existing.props);\n const validatedProps = computeEdgeUpdate(\n ctx,\n existing.kind,\n existing.id,\n existingProps,\n inputProps,\n );\n return { existingProps, validatedProps };\n}\n\n/**\n * The edge coalesce dirty-check: returns the props an upsert would persist and\n * whether they equal `existingProps`. `existingProps` is the PARSED current\n * props — the edge's, or the batch-local running value for a repeated id.\n */\nexport function edgeUpsertDirtyCheck<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n kind: string,\n id: string,\n existingProps: Record<string, unknown>,\n inputProps: Record<string, unknown>,\n): UpsertDirtyCheck {\n const validatedProps = computeEdgeUpdate(\n ctx,\n kind,\n id,\n existingProps,\n inputProps,\n );\n return {\n validatedProps,\n unchanged: canonicalEqual(validatedProps, existingProps),\n };\n}\n\n/**\n * Shared edge-update body: re-reads the edge inside the transaction, merges\n * and validates props, and writes. A plain update requires a live edge; a\n * resurrecting upsert (`clearDeleted`) may target a tombstoned one.\n */\nasync function performEdgeUpdate<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n target: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Edge> {\n const id = input.id;\n\n const existing = await target.getEdge(ctx.graphId, id);\n if (!existing || (!options?.clearDeleted && existing.deleted_at)) {\n throw new EdgeNotFoundError(\"unknown\", id);\n }\n\n const { validatedProps } = resolveEdgeUpdateProps(ctx, existing, input.props);\n\n const validTo = validateOptionalCanonicalIsoDate(input.validTo, \"validTo\");\n\n const updateParams: {\n graphId: string;\n id: string;\n props: Record<string, unknown>;\n validTo?: string;\n clearDeleted?: boolean;\n } = {\n graphId: ctx.graphId,\n id,\n props: validatedProps,\n };\n if (validTo !== undefined) updateParams.validTo = validTo;\n if (options?.clearDeleted) updateParams.clearDeleted = true;\n\n const row = await target.updateEdge(updateParams);\n\n return rowToEdge(row);\n}\n\n/**\n * Executes an edge update operation.\n */\nexport async function executeEdgeUpdate<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n): Promise<Edge> {\n const id = input.id;\n\n // Read outside the transaction: the hook context needs the edge kind, and\n // hooks must WRAP the transaction (matching node operations and edge\n // create) so onOperationEnd reports success only after COMMIT — a hook\n // that fires inside the transaction would report success for a write that\n // a failed commit then rolls back. An absent edge also never opens an empty\n // transaction. The body re-reads inside the transaction, so a concurrent\n // delete between this gate and the write lock is still handled correctly.\n const gate = await backend.getEdge(ctx.graphId, id);\n if (!gate || gate.deleted_at) {\n throw new EdgeNotFoundError(\"unknown\", id);\n }\n\n const opContext = ctx.createOperationContext(\"update\", \"edge\", gate.kind, id);\n\n return runHookedWriteOperation(ctx, opContext, backend, (target) =>\n performEdgeUpdate(ctx, input, target),\n );\n}\n\n/**\n * Executes an edge update for upsert — bypasses the soft-delete check\n * and optionally clears `deleted_at`.\n */\nexport async function executeEdgeUpsertUpdate<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n input: {\n id: string;\n props: Partial<Record<string, unknown>>;\n validTo?: string;\n },\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{ clearDeleted?: boolean }>,\n): Promise<Edge> {\n return runInWriteTransaction(ctx, backend, (target) =>\n performEdgeUpdate(ctx, input, target, options),\n );\n}\n\n/**\n * Executes an edge delete operation.\n */\nexport async function executeEdgeDelete<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n // Gate outside the transaction so an absent/tombstoned edge never opens an\n // empty one; the gate row also supplies the kind for the hook context,\n // because hooks must WRAP the transaction (matching node operations and\n // edge create) so onOperationEnd reports success only after COMMIT.\n const gate = await backend.getEdge(ctx.graphId, id);\n if (!gate || gate.deleted_at) return;\n\n const opContext = ctx.createOperationContext(\"delete\", \"edge\", gate.kind, id);\n\n return runHookedWriteOperation(ctx, opContext, backend, async (target) => {\n // No in-transaction preflight: the tombstone UPDATE is guarded by\n // `deleted_at IS NULL`, so a concurrent delete between the gate and\n // the write lock is a 0-row no-op — the statement itself is the\n // concurrency-correct check, and nothing here consumes the row.\n await target.deleteEdge({\n graphId: ctx.graphId,\n id,\n });\n });\n}\n\n/**\n * Executes an edge hard delete operation (permanent removal).\n *\n * Unlike soft delete, this permanently removes the edge from the database.\n */\nexport async function executeEdgeHardDelete<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n id: string,\n backend: GraphBackend | TransactionBackend,\n): Promise<void> {\n // Gate outside the transaction so an absent edge never opens an empty one;\n // hooks wrap the transaction (see executeEdgeDelete).\n const gate = await backend.getEdge(ctx.graphId, id);\n if (!gate) return;\n\n const opContext = ctx.createOperationContext(\"delete\", \"edge\", gate.kind, id);\n\n return runHookedWriteOperation(ctx, opContext, backend, async (target) => {\n // No in-transaction preflight: DELETE by primary key is idempotent\n // (0 rows when concurrently removed) and nothing here consumes the\n // row.\n await target.hardDeleteEdge({\n graphId: ctx.graphId,\n id,\n });\n });\n}\n\n// ============================================================\n// Get-Or-Create Operations\n// ============================================================\n\n// Delimiters for composite match keys\nconst RECORD_SEP = \"\\u001E\";\nconst UNIT_SEP = \"\\u001F\";\nconst UNDEFINED_SENTINEL = \"\\u001D\";\n\n/**\n * Validates that all `matchOn` fields exist in the edge schema shape.\n * Throws a ValidationError for invalid fields.\n */\nfunction validateMatchOnFields(\n schema: { shape?: Record<string, unknown> },\n matchOn: readonly string[],\n edgeKind: string,\n): void {\n if (matchOn.length === 0) return;\n const shape = schema.shape;\n if (shape === undefined) {\n throw new ValidationError(\n `Edge kind \"${edgeKind}\" has no schema shape to validate matchOn fields against`,\n {\n kind: edgeKind,\n operation: \"create\",\n issues: matchOn.map((field) => ({\n path: field,\n message: `Field \"${field}\" does not exist in edge schema`,\n })),\n },\n );\n }\n\n const invalidFields = matchOn.filter((field) => !(field in shape));\n if (invalidFields.length > 0) {\n throw new ValidationError(\n `Invalid matchOn fields for edge kind \"${edgeKind}\": ${invalidFields.join(\", \")}`,\n {\n kind: edgeKind,\n operation: \"create\",\n issues: invalidFields.map((field) => ({\n path: field,\n message: `Field \"${field}\" does not exist in edge schema`,\n })),\n },\n );\n }\n}\n\n/**\n * Serializes a value for composite key construction.\n * Sorts object keys for deterministic ordering of nested values.\n */\nfunction stableStringify(value: unknown): string {\n if (value === undefined) return UNDEFINED_SENTINEL;\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n const sorted = Object.keys(value).toSorted();\n const entries = sorted.map(\n (key) =>\n `${JSON.stringify(key)}:${stableStringify((value as Record<string, unknown>)[key])}`,\n );\n return `{${entries.join(\",\")}}`;\n}\n\n/**\n * Builds a deterministic composite key for edge matching.\n *\n * Format: `fromKind\\u001EfromId\\u001EtoKind\\u001EtoId[\\u001Efield\\u001Fvalue]*`\n */\nfunction buildEdgeCompositeKey(\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n props: Record<string, unknown>,\n matchOn: readonly string[],\n): string {\n const endpointPart = `${fromKind}${RECORD_SEP}${fromId}${RECORD_SEP}${toKind}${RECORD_SEP}${toId}`;\n if (matchOn.length === 0) return endpointPart;\n\n const sortedFields = [...matchOn].toSorted();\n const propertyParts = sortedFields.map(\n (field) =>\n `${RECORD_SEP}${field}${UNIT_SEP}${stableStringify(props[field])}`,\n );\n return endpointPart + propertyParts.join(\"\");\n}\n\n/**\n * Endpoint-only key for grouping findEdgesByKind queries.\n */\nfunction buildEndpointPairKey(\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n): string {\n return `${fromKind}${RECORD_SEP}${fromId}${RECORD_SEP}${toKind}${RECORD_SEP}${toId}`;\n}\n\ntype EdgeMatch = Readonly<{\n liveRow: BackendEdgeRow | undefined;\n deletedRow: BackendEdgeRow | undefined;\n}>;\n\n/**\n * Finds the best matching edge from candidate rows.\n * Partitions into live vs deleted; prefers live.\n */\nfunction findMatchingEdge(\n rows: readonly BackendEdgeRow[],\n matchOn: readonly string[],\n inputProps: Record<string, unknown>,\n): EdgeMatch {\n let liveRow: BackendEdgeRow | undefined;\n let deletedRow: BackendEdgeRow | undefined;\n\n for (const row of rows) {\n if (matchOn.length > 0) {\n const rowProps = rowPropsToObject(row.props);\n const matches = matchOn.every(\n (field) =>\n stableStringify(rowProps[field]) ===\n stableStringify(inputProps[field]),\n );\n if (!matches) continue;\n }\n\n if (row.deleted_at === undefined) {\n liveRow ??= row;\n } else {\n deletedRow ??= row;\n }\n\n if (liveRow !== undefined) break;\n }\n\n return { liveRow, deletedRow };\n}\n\n/**\n * Executes a single findByEndpoints operation.\n *\n * Looks up an edge by endpoints and optional matchOn fields, honoring the\n * temporal coordinate in `options` (mode / asOf / excludeDeleted) the same way\n * `findFrom` / `findTo` do. Returns the matching edge, or undefined. By default\n * soft-deleted and out-of-window edges are excluded; under `includeTombstones`\n * (excludeDeleted = false) a soft-deleted edge can be returned.\n */\nexport async function executeEdgeFindByEndpoints<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n kind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n backend: GraphReadBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n props?: Record<string, unknown>;\n excludeDeleted?: boolean;\n temporalMode?: TemporalMode;\n asOf?: string;\n }>,\n): Promise<Edge | undefined> {\n const matchOn = options?.matchOn ?? [];\n const props = options?.props ?? {};\n\n const registration = getEdgeRegistration(ctx.graph, kind);\n const edgeKind = registration.type;\n\n if (matchOn.length > 0) {\n validateMatchOnFields(edgeKind.schema, matchOn, kind);\n }\n\n const candidateRows = await backend.findEdgesByKind({\n graphId: ctx.graphId,\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n excludeDeleted: options?.excludeDeleted ?? true,\n ...(options?.temporalMode !== undefined && {\n temporalMode: options.temporalMode,\n }),\n ...(options?.asOf !== undefined && { asOf: options.asOf }),\n });\n\n if (candidateRows.length === 0) return undefined;\n\n if (matchOn.length === 0) return rowToEdge(requireDefined(candidateRows[0]));\n\n const { liveRow } = findMatchingEdge(candidateRows, matchOn, props);\n return liveRow === undefined ? undefined : rowToEdge(liveRow);\n}\n\n/**\n * Executes a single getOrCreateByEndpoints operation.\n */\nexport async function executeEdgeGetOrCreateByEndpoints<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n kind: string,\n fromKind: string,\n fromId: string,\n toKind: string,\n toId: string,\n props: Record<string, unknown>,\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n }>,\n): Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>> {\n const ifExists = options?.ifExists ?? \"return\";\n const matchOn = options?.matchOn ?? [];\n\n const registration = getEdgeRegistration(ctx.graph, kind);\n const edgeKind = registration.type;\n\n // Validate props\n const validatedProps = validateEdgeProps(edgeKind.schema, props, {\n kind,\n operation: \"create\",\n });\n\n // Validate matchOn fields\n validateMatchOnFields(edgeKind.schema, matchOn, kind);\n\n // Probe outside the transaction: with ifExists \"return\", the common found\n // path performs no write, so it must not pay for a write transaction\n // (BEGIN IMMEDIATE on SQLite, the per-graph advisory lock under history).\n // The transactional body re-queries, so a concurrent create between this\n // probe and the write lock is still handled correctly.\n if (ifExists === \"return\") {\n const probeRows = await backend.findEdgesByKind({\n graphId: ctx.graphId,\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n excludeDeleted: false,\n temporalMode: \"includeTombstones\",\n });\n const { liveRow: probedLiveRow } = findMatchingEdge(\n probeRows,\n matchOn,\n validatedProps,\n );\n if (probedLiveRow !== undefined) {\n return { edge: rowToEdge(probedLiveRow), action: \"found\" };\n }\n }\n\n // No enclosing transaction: each write leg opens its own (hooked, for the\n // create leg) transaction. An outer transaction here would make the nested\n // operation run directly inside it and fire its success hooks before THIS\n // wrapper's COMMIT — the durability contract hooks promise would be false.\n // A concurrent create that wins between the lookup and the write surfaces\n // as a cardinality conflict and is converged by one retry of the lookup.\n async function attempt(): Promise<\n Readonly<{ edge: Edge; action: GetOrCreateAction }>\n > {\n // Query all edges of this kind between (from, to) including tombstones\n const candidateRows = await backend.findEdgesByKind({\n graphId: ctx.graphId,\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n excludeDeleted: false,\n temporalMode: \"includeTombstones\",\n });\n\n const { liveRow, deletedRow } = findMatchingEdge(\n candidateRows,\n matchOn,\n validatedProps,\n );\n\n // No match → create new edge\n if (liveRow === undefined && deletedRow === undefined) {\n const input: CreateEdgeInput = {\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n props: validatedProps,\n };\n const edge = await executeEdgeCreate(ctx, input, backend);\n return { edge, action: \"created\" };\n }\n\n // Live match found\n if (liveRow !== undefined) {\n if (ifExists === \"return\") {\n return { edge: rowToEdge(liveRow), action: \"found\" };\n }\n // ifExists === \"update\"\n const edge = await executeEdgeUpsertUpdate(\n ctx,\n { id: liveRow.id, props: validatedProps },\n backend,\n );\n return { edge, action: \"updated\" };\n }\n\n // Deleted match only → check cardinality before resurrect\n const cardinality = registration.cardinality ?? \"many\";\n if (deletedRow === undefined) {\n throw new Error(\"Expected deletedRow to be defined\");\n }\n const matchedDeletedRow = deletedRow;\n const effectiveValidTo = matchedDeletedRow.valid_to;\n const constraintContext: ConstraintContext = {\n graphId: ctx.graphId,\n registry: ctx.registry,\n backend,\n };\n await checkCardinalityConstraint(\n constraintContext,\n kind,\n cardinality,\n fromKind,\n fromId,\n toKind,\n toId,\n effectiveValidTo,\n );\n\n const edge = await executeEdgeUpsertUpdate(\n ctx,\n { id: matchedDeletedRow.id, props: validatedProps },\n backend,\n { clearDeleted: true },\n );\n return { edge, action: \"resurrected\" };\n }\n\n try {\n return await attempt();\n } catch (error) {\n if (!(error instanceof CardinalityError)) throw error;\n return attempt();\n }\n}\n\n/**\n * Executes a bulk getOrCreateByEndpoints operation.\n */\nexport async function executeEdgeBulkGetOrCreateByEndpoints<G extends GraphDef>(\n ctx: EdgeOperationContext<G>,\n kind: string,\n items: readonly Readonly<{\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Record<string, unknown>;\n }>[],\n backend: GraphBackend | TransactionBackend,\n options?: Readonly<{\n matchOn?: readonly string[];\n ifExists?: IfExistsMode;\n }>,\n): Promise<Readonly<{ edge: Edge; action: GetOrCreateAction }>[]> {\n if (items.length === 0) return [];\n\n const ifExists = options?.ifExists ?? \"return\";\n const matchOn = options?.matchOn ?? [];\n\n const registration = getEdgeRegistration(ctx.graph, kind);\n const edgeKind = registration.type;\n const cardinality = registration.cardinality ?? \"many\";\n\n // Validate matchOn fields once\n validateMatchOnFields(edgeKind.schema, matchOn, kind);\n\n // Step 1: Validate all props and compute composite keys\n const validated: {\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n validatedProps: Record<string, unknown>;\n compositeKey: string;\n endpointKey: string;\n }[] = [];\n\n for (const item of items) {\n const validatedProps = validateEdgeProps(edgeKind.schema, item.props, {\n kind,\n operation: \"create\",\n });\n\n const compositeKey = buildEdgeCompositeKey(\n item.fromKind,\n item.fromId,\n item.toKind,\n item.toId,\n validatedProps,\n matchOn,\n );\n const endpointKey = buildEndpointPairKey(\n item.fromKind,\n item.fromId,\n item.toKind,\n item.toId,\n );\n\n validated.push({\n fromKind: item.fromKind,\n fromId: item.fromId,\n toKind: item.toKind,\n toId: item.toId,\n validatedProps,\n compositeKey,\n endpointKey,\n });\n }\n\n // Step 2: Group by unique endpoint pair\n const uniqueEndpoints = new Map<\n string,\n { fromKind: string; fromId: string; toKind: string; toId: string }\n >();\n for (const entry of validated) {\n if (!uniqueEndpoints.has(entry.endpointKey)) {\n uniqueEndpoints.set(entry.endpointKey, {\n fromKind: entry.fromKind,\n fromId: entry.fromId,\n toKind: entry.toKind,\n toId: entry.toId,\n });\n }\n }\n\n // Fetch all candidate rows, grouped by endpoint pair. Shared by the\n // outside-transaction probe (reading the root backend) and the\n // transactional body (re-reading through the transaction target).\n async function fetchRowsByEndpoint(\n reader: GraphReadBackend,\n ): Promise<ReadonlyMap<string, readonly BackendEdgeRow[]>> {\n const rowsByEndpoint = new Map<string, readonly BackendEdgeRow[]>();\n for (const [endpointKey, endpoint] of uniqueEndpoints) {\n const rows = await reader.findEdgesByKind({\n graphId: ctx.graphId,\n kind,\n fromKind: endpoint.fromKind,\n fromId: endpoint.fromId,\n toKind: endpoint.toKind,\n toId: endpoint.toId,\n excludeDeleted: false,\n temporalMode: \"includeTombstones\",\n });\n rowsByEndpoint.set(endpointKey, rows);\n }\n return rowsByEndpoint;\n }\n\n interface CreateEntry {\n index: number;\n input: CreateEdgeInput;\n }\n interface FetchEntry {\n index: number;\n row: BackendEdgeRow;\n isDeleted: boolean;\n validatedProps: Record<string, unknown>;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n }\n interface DuplicateEntry {\n index: number;\n sourceIndex: number;\n }\n interface Result {\n readonly edge: Edge;\n readonly action: GetOrCreateAction;\n }\n\n // Step 3: Partition into toCreate, toFetch, and duplicates\n function partitionEntries(\n rowsByEndpoint: ReadonlyMap<string, readonly BackendEdgeRow[]>,\n ): Readonly<{\n toCreate: CreateEntry[];\n toFetch: FetchEntry[];\n duplicateOf: DuplicateEntry[];\n }> {\n const toCreate: CreateEntry[] = [];\n const toFetch: FetchEntry[] = [];\n const duplicateOf: DuplicateEntry[] = [];\n const seenKeys = new Map<string, number>();\n\n for (const [index, entry] of validated.entries()) {\n // Check within-batch duplicate\n const previousIndex = seenKeys.get(entry.compositeKey);\n if (previousIndex !== undefined) {\n duplicateOf.push({ index, sourceIndex: previousIndex });\n continue;\n }\n seenKeys.set(entry.compositeKey, index);\n\n const candidateRows = rowsByEndpoint.get(entry.endpointKey) ?? [];\n const { liveRow, deletedRow } = findMatchingEdge(\n candidateRows,\n matchOn,\n entry.validatedProps,\n );\n\n if (liveRow === undefined && deletedRow === undefined) {\n toCreate.push({\n index,\n input: {\n kind,\n fromKind: entry.fromKind,\n fromId: entry.fromId,\n toKind: entry.toKind,\n toId: entry.toId,\n props: entry.validatedProps,\n },\n });\n } else {\n // At least one of liveRow/deletedRow is defined (both-undefined handled above)\n const bestRow = liveRow ?? deletedRow;\n if (bestRow === undefined) {\n throw new Error(\"Expected at least one of liveRow or deletedRow\");\n }\n toFetch.push({\n index,\n row: bestRow,\n isDeleted: liveRow === undefined,\n validatedProps: entry.validatedProps,\n fromKind: entry.fromKind,\n fromId: entry.fromId,\n toKind: entry.toKind,\n toId: entry.toId,\n });\n }\n }\n\n return { toCreate, toFetch, duplicateOf };\n }\n\n // Probe outside the transaction: with ifExists \"return\" and every entry\n // matching a live edge, the whole call performs no write, so it must not\n // pay for a write transaction (BEGIN IMMEDIATE on SQLite, the per-graph\n // advisory lock under history). The transactional body re-queries, so a\n // concurrent write between this probe and the write lock is still handled\n // correctly.\n if (ifExists === \"return\") {\n const probe = partitionEntries(await fetchRowsByEndpoint(backend));\n const allFoundLive =\n probe.toCreate.length === 0 &&\n probe.toFetch.every((entry) => !entry.isDeleted);\n if (allFoundLive) {\n const found: Result[] = Array.from({ length: items.length });\n for (const entry of probe.toFetch) {\n found[entry.index] = { edge: rowToEdge(entry.row), action: \"found\" };\n }\n for (const { index, sourceIndex } of probe.duplicateOf) {\n found[index] = {\n edge: requireDefined(found[sourceIndex]).edge,\n action: \"found\",\n };\n }\n return found;\n }\n }\n\n return runInWriteTransaction(ctx, backend, async (target) => {\n const { toCreate, toFetch, duplicateOf } = partitionEntries(\n await fetchRowsByEndpoint(target),\n );\n const results: Result[] = Array.from({ length: items.length });\n\n // Step 4: Execute creates in batch\n if (toCreate.length > 0) {\n const createInputs = toCreate.map((entry) => entry.input);\n const createdEdges = await executeEdgeCreateBatch(\n ctx,\n createInputs,\n target,\n );\n for (const [batchIndex, entry] of toCreate.entries()) {\n results[entry.index] = {\n edge: requireDefined(createdEdges[batchIndex]),\n action: \"created\",\n };\n }\n }\n\n // Step 5: Handle existing edges (update/skip/resurrect)\n for (const entry of toFetch) {\n if (entry.isDeleted) {\n // Check cardinality before resurrect\n const effectiveValidTo = entry.row.valid_to;\n const constraintContext: ConstraintContext = {\n graphId: ctx.graphId,\n registry: ctx.registry,\n backend: target,\n };\n await checkCardinalityConstraint(\n constraintContext,\n kind,\n cardinality,\n entry.fromKind,\n entry.fromId,\n entry.toKind,\n entry.toId,\n effectiveValidTo,\n );\n\n const edge = await executeEdgeUpsertUpdate(\n ctx,\n { id: entry.row.id, props: entry.validatedProps },\n target,\n { clearDeleted: true },\n );\n results[entry.index] = { edge, action: \"resurrected\" };\n } else if (ifExists === \"update\") {\n const edge = await executeEdgeUpsertUpdate(\n ctx,\n { id: entry.row.id, props: entry.validatedProps },\n target,\n );\n results[entry.index] = { edge, action: \"updated\" };\n } else {\n results[entry.index] = { edge: rowToEdge(entry.row), action: \"found\" };\n }\n }\n\n // Step 6: Resolve within-batch duplicates\n for (const { index, sourceIndex } of duplicateOf) {\n const sourceResult = requireDefined(results[sourceIndex]);\n results[index] = { edge: sourceResult.edge, action: \"found\" };\n }\n\n return results;\n });\n}\n","import { createGraphBackendProjection } from \"../backend/graph-backend-projection\";\nimport {\n createBackendOverlay,\n type EdgeRow,\n type GraphBackend,\n type NodeRow,\n} from \"../backend/types\";\nimport { type ReadCoordinate } from \"../core/temporal\";\nimport {\n type AnyEdgeType,\n type EdgeId,\n type NodeId,\n type NodeType,\n} from \"../core/types\";\nimport { ConfigurationError, ValidationError } from \"../errors\";\nimport { sqlValueList } from \"../query/compiler/predicate-utils\";\nimport {\n type RecordedReadBinding,\n recordedReadSqlSchema,\n requireRecordedReadBinding,\n} from \"../query/compiler/schema\";\nimport {\n compileTemporalFilter,\n currentReadInstant,\n} from \"../query/compiler/temporal\";\nimport { decodeCursor, encodeCursor } from \"../query/cursor\";\nimport { sql, type SqlFragment } from \"../query/sql-fragment\";\nimport { asCompiledRowsSql, type CompiledRowsSql } from \"../query/sql-intent\";\nimport { chunk } from \"../utils/array\";\nimport { requireDefined } from \"../utils/presence\";\nimport { withRecordedRelationsPrecondition } from \"../utils/sql-errors\";\nimport { recordedBindParamBudget } from \"./recorded-capture/relations\";\nimport { rowToEdge, rowToNode } from \"./row-mappers\";\nimport {\n type Edge,\n type Node,\n type RecordedScanOptions,\n type RecordedScanPage,\n} from \"./types\";\n\nconst RECORDED_POINT_READ_FIXED_BIND_PARAMS = 8;\nconst RECORDED_SCAN_LIMIT = 1000;\n\ntype RecordedReadServiceParams = Readonly<{\n graphId: string;\n backend: GraphBackend;\n recordedReadBinding: RecordedReadBinding | undefined;\n mapRecordedNodeRow: (row: Record<string, unknown>) => NodeRow;\n mapRecordedEdgeRow: (row: Record<string, unknown>) => EdgeRow;\n}>;\n\ntype RecordedGetByIdsParams<T extends Readonly<{ id: string }>> = Readonly<{\n entity: \"node\" | \"edge\";\n table: SqlFragment;\n alias: string;\n kind: string;\n ids: readonly string[];\n coordinate: ReadCoordinate;\n toEntity: (row: Record<string, unknown>) => T;\n}>;\n\ntype RecordedScanParams<T extends Readonly<{ id: string }>> = Readonly<{\n entity: \"node\" | \"edge\";\n table: SqlFragment;\n alias: string;\n kind: string;\n coordinate: ReadCoordinate;\n options: RecordedScanOptions | undefined;\n toEntity: (row: Record<string, unknown>) => T;\n}>;\n\nexport type RecordedReadService = Readonly<{\n backendForCoordinate: (\n coordinate: ReadCoordinate,\n surface: string,\n ) => GraphBackend;\n nodeGetById: <N extends NodeType>(\n kind: string,\n id: NodeId<N>,\n coordinate: ReadCoordinate,\n ) => Promise<Node<N> | undefined>;\n nodeGetByIds: <N extends NodeType>(\n kind: string,\n ids: readonly NodeId<N>[],\n coordinate: ReadCoordinate,\n ) => Promise<readonly (Node<N> | undefined)[]>;\n nodeScan: <N extends NodeType>(\n kind: string,\n coordinate: ReadCoordinate,\n options?: RecordedScanOptions,\n ) => Promise<RecordedScanPage<Node<N>>>;\n edgeGetById: <E extends AnyEdgeType>(\n kind: string,\n id: EdgeId<E>,\n coordinate: ReadCoordinate,\n ) => Promise<Edge<E> | undefined>;\n edgeGetByIds: <E extends AnyEdgeType>(\n kind: string,\n ids: readonly EdgeId<E>[],\n coordinate: ReadCoordinate,\n ) => Promise<readonly (Edge<E> | undefined)[]>;\n edgeScan: <E extends AnyEdgeType>(\n kind: string,\n coordinate: ReadCoordinate,\n options?: RecordedScanOptions,\n ) => Promise<RecordedScanPage<Edge<E>>>;\n}>;\n\n/**\n * Per-chunk id count for a recorded point read: the backend's real\n * bound-parameter ceiling less the statement's fixed binds, so Postgres point\n * reads page thousands of ids per round-trip instead of a dialect-blind 900.\n */\nfunction recordedPointReadIdChunk(backend: GraphBackend): number {\n const budget = recordedBindParamBudget(backend);\n return Math.max(1, budget - RECORDED_POINT_READ_FIXED_BIND_PARAMS);\n}\n\nfunction recordedRelationErrorDetails(\n backend: Pick<GraphBackend, \"dialect\">,\n surface: string,\n): Readonly<{ dialect: GraphBackend[\"dialect\"]; surface: string }> {\n return { dialect: backend.dialect, surface };\n}\n\nfunction withRelationsPrecondition<T>(\n backend: Pick<GraphBackend, \"dialect\">,\n promise: Promise<T>,\n surface: string,\n): Promise<T> {\n return withRecordedRelationsPrecondition(\n promise,\n recordedRelationErrorDetails(backend, surface),\n );\n}\n\nfunction createRecordedReadBackend(\n backend: GraphBackend,\n surface: string,\n): GraphBackend {\n // A public AdapterStore backend is frozen. Decorate a fresh allowlist\n // projection so Proxy invariants do not prevent the execute guards from\n // replacing non-configurable function properties.\n const projectedBackend = createGraphBackendProjection(backend);\n return createBackendOverlay(projectedBackend, {\n execute: <T>(query: CompiledRowsSql): Promise<readonly T[]> =>\n withRelationsPrecondition(backend, backend.execute<T>(query), surface),\n ...(backend.executeRaw === undefined ?\n {}\n : {\n executeRaw: <T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> =>\n withRelationsPrecondition(\n backend,\n requireDefined(backend.executeRaw)<T>(sqlText, params),\n surface,\n ),\n }),\n });\n}\n\nfunction recordedTemporalFilter(\n backend: GraphBackend,\n coordinate: ReadCoordinate,\n tableAlias: string,\n): SqlFragment {\n const recordedAsOf = coordinate.recorded?.asOf;\n if (recordedAsOf === undefined) {\n throw new ConfigurationError(\n \"Recorded point reads require a recorded-time coordinate.\",\n { code: \"RECORDED_POINT_READ_MISSING_COORDINATE\" },\n );\n }\n return compileTemporalFilter({\n mode: coordinate.valid.mode,\n asOf: coordinate.valid.asOf,\n recordedAsOf,\n tableAlias,\n currentTimestamp: currentReadInstant(),\n });\n}\n\nfunction recordedRelationInvariantError(\n params: Readonly<{\n graphId: string;\n entity: \"node\" | \"edge\";\n kind: string;\n id: string;\n coordinate: ReadCoordinate;\n }>,\n): ConfigurationError {\n return new ConfigurationError(\n \"Recorded relation invariant violation: more than one recorded row matched the requested read.\",\n {\n code: \"RECORDED_RELATION_INVARIANT_VIOLATION\",\n graphId: params.graphId,\n entity: params.entity,\n kind: params.kind,\n id: params.id,\n validMode: params.coordinate.valid.mode,\n validAsOf: params.coordinate.valid.asOf,\n recordedAsOf: params.coordinate.recorded?.asOf,\n },\n {\n suggestion:\n \"Repair overlapping recorded_from/recorded_to intervals for this entity before using recorded-time reads.\",\n },\n );\n}\n\nfunction validateRecordedScanLimit(limit: number | undefined): number {\n if (limit === undefined) return RECORDED_SCAN_LIMIT;\n if (!Number.isInteger(limit) || limit <= 0 || limit > RECORDED_SCAN_LIMIT) {\n throw new ValidationError(\n `Recorded scan limit must be an integer between 1 and ${RECORDED_SCAN_LIMIT}, got: ${String(limit)}`,\n {\n issues: [\n {\n path: \"limit\",\n message: `Must be an integer between 1 and ${RECORDED_SCAN_LIMIT}.`,\n },\n ],\n },\n );\n }\n return limit;\n}\n\nfunction recordedScanCursorScope(\n graphId: string,\n entity: \"node\" | \"edge\",\n kind: string,\n coordinate: ReadCoordinate,\n): string {\n return JSON.stringify([\n \"recorded-scan\",\n graphId,\n entity,\n kind,\n coordinate.valid.mode,\n coordinate.valid.asOf,\n coordinate.recorded?.asOf,\n ]);\n}\n\nfunction invalidRecordedScanCursor(): ValidationError {\n return new ValidationError(\n \"Recorded scan cursor does not match this graph, collection, or temporal coordinate.\",\n {\n issues: [\n {\n path: \"after\",\n message:\n \"Use a cursor returned by the same recorded collection scan.\",\n },\n ],\n },\n );\n}\n\nfunction decodeRecordedScanCursor(\n cursor: string,\n expectedScope: string,\n): string {\n const decoded = decodeCursor(cursor);\n if (\n decoded.d !== \"f\" ||\n decoded.cols.length !== 1 ||\n decoded.cols[0] !== expectedScope ||\n decoded.vals.length !== 1 ||\n typeof decoded.vals[0] !== \"string\"\n ) {\n throw invalidRecordedScanCursor();\n }\n return decoded.vals[0];\n}\n\nfunction encodeRecordedScanCursor(id: string, scope: string): string {\n return encodeCursor({ v: 1, d: \"f\", vals: [id], cols: [scope] });\n}\n\nexport function createRecordedReadService(\n params: RecordedReadServiceParams,\n): RecordedReadService {\n const {\n graphId,\n backend,\n recordedReadBinding,\n mapRecordedNodeRow,\n mapRecordedEdgeRow,\n } = params;\n const recordedSchema =\n recordedReadBinding === undefined ? undefined : (\n recordedReadSqlSchema(recordedReadBinding)\n );\n\n function schemaForRecordedRead(surface: string) {\n return (\n recordedSchema ??\n recordedReadSqlSchema(\n requireRecordedReadBinding(recordedReadBinding, surface),\n )\n );\n }\n\n async function recordedGetByIds<T extends Readonly<{ id: string }>>(\n read: RecordedGetByIdsParams<T>,\n ): Promise<readonly (T | undefined)[]> {\n const { table, alias, kind, ids, coordinate, toEntity, entity } = read;\n if (ids.length === 0) return [];\n\n const uniqueIds = [...new Set(ids)];\n const aliasSql = sql.raw(alias);\n const temporalFilter = recordedTemporalFilter(backend, coordinate, alias);\n const chunkResults = await withRelationsPrecondition(\n backend,\n Promise.all(\n chunk(uniqueIds, recordedPointReadIdChunk(backend)).map((idChunk) =>\n backend.execute<Record<string, unknown>>(\n asCompiledRowsSql(sql`\n SELECT * FROM ${table} ${aliasSql}\n WHERE ${aliasSql}.graph_id = ${graphId}\n AND ${aliasSql}.kind = ${kind}\n AND ${aliasSql}.id IN (${sqlValueList(idChunk)})\n AND ${temporalFilter}\n ORDER BY ${aliasSql}.recorded_from\n `),\n ),\n ),\n ),\n \"recorded-point-read\",\n );\n\n const byId = new Map<string, T>();\n for (const rows of chunkResults) {\n for (const row of rows) {\n const entityRow = toEntity(row);\n if (byId.has(entityRow.id)) {\n throw recordedRelationInvariantError({\n graphId,\n entity,\n kind,\n id: entityRow.id,\n coordinate,\n });\n }\n byId.set(entityRow.id, entityRow);\n }\n }\n return ids.map((id) => byId.get(id));\n }\n\n async function recordedScan<T extends Readonly<{ id: string }>>(\n scan: RecordedScanParams<T>,\n ): Promise<RecordedScanPage<T>> {\n const { table, alias, kind, coordinate, options, toEntity, entity } = scan;\n const limit = validateRecordedScanLimit(options?.limit);\n const scope = recordedScanCursorScope(graphId, entity, kind, coordinate);\n const after =\n options?.after === undefined ?\n undefined\n : decodeRecordedScanCursor(options.after, scope);\n const aliasSql = sql.raw(alias);\n const temporalFilter = recordedTemporalFilter(backend, coordinate, alias);\n const rows = await withRelationsPrecondition(\n backend,\n backend.execute<Record<string, unknown>>(\n asCompiledRowsSql(sql`\n SELECT * FROM ${table} ${aliasSql}\n WHERE ${aliasSql}.graph_id = ${graphId}\n AND ${aliasSql}.kind = ${kind}\n ${after === undefined ? sql.raw(\"\") : sql`AND ${aliasSql}.id > ${after}`}\n AND ${temporalFilter}\n ORDER BY ${aliasSql}.id ASC, ${aliasSql}.recorded_from ASC\n LIMIT ${limit + 1}\n `),\n ),\n \"recorded-scan\",\n );\n const entities = rows.map((row) => toEntity(row));\n for (let index = 1; index < entities.length; index += 1) {\n const previous = requireDefined(entities[index - 1]);\n const current = requireDefined(entities[index]);\n if (previous.id !== current.id) continue;\n throw recordedRelationInvariantError({\n graphId,\n entity,\n kind,\n id: current.id,\n coordinate,\n });\n }\n\n const hasNextPage = entities.length > limit;\n const data = hasNextPage ? entities.slice(0, limit) : entities;\n return {\n data,\n nextCursor:\n hasNextPage ?\n encodeRecordedScanCursor(requireDefined(data.at(-1)).id, scope)\n : undefined,\n hasNextPage,\n };\n }\n\n function nodeGetByIds<N extends NodeType>(\n kind: string,\n ids: readonly NodeId<N>[],\n coordinate: ReadCoordinate,\n ): Promise<readonly (Node<N> | undefined)[]> {\n const schema = schemaForRecordedRead(\"recorded-point-read\");\n return recordedGetByIds({\n entity: \"node\",\n table: schema.nodesTable,\n alias: \"n\",\n kind,\n ids,\n coordinate,\n toEntity: (row) => rowToNode(mapRecordedNodeRow(row)) as Node<N>,\n });\n }\n\n function edgeGetByIds<E extends AnyEdgeType>(\n kind: string,\n ids: readonly EdgeId<E>[],\n coordinate: ReadCoordinate,\n ): Promise<readonly (Edge<E> | undefined)[]> {\n const schema = schemaForRecordedRead(\"recorded-point-read\");\n return recordedGetByIds({\n entity: \"edge\",\n table: schema.edgesTable,\n alias: \"e\",\n kind,\n ids,\n coordinate,\n toEntity: (row) => rowToEdge(mapRecordedEdgeRow(row)) as Edge<E>,\n });\n }\n\n function nodeScan<N extends NodeType>(\n kind: string,\n coordinate: ReadCoordinate,\n options?: RecordedScanOptions,\n ): Promise<RecordedScanPage<Node<N>>> {\n const schema = schemaForRecordedRead(\"recorded-scan\");\n return recordedScan({\n entity: \"node\",\n table: schema.nodesTable,\n alias: \"n\",\n kind,\n coordinate,\n options,\n toEntity: (row) => rowToNode(mapRecordedNodeRow(row)) as Node<N>,\n });\n }\n\n function edgeScan<E extends AnyEdgeType>(\n kind: string,\n coordinate: ReadCoordinate,\n options?: RecordedScanOptions,\n ): Promise<RecordedScanPage<Edge<E>>> {\n const schema = schemaForRecordedRead(\"recorded-scan\");\n return recordedScan({\n entity: \"edge\",\n table: schema.edgesTable,\n alias: \"e\",\n kind,\n coordinate,\n options,\n toEntity: (row) => rowToEdge(mapRecordedEdgeRow(row)) as Edge<E>,\n });\n }\n\n return {\n backendForCoordinate(\n coordinate: ReadCoordinate,\n surface: string,\n ): GraphBackend {\n if (coordinate.recorded === undefined) return backend;\n requireRecordedReadBinding(recordedReadBinding, surface);\n return createRecordedReadBackend(backend, surface);\n },\n\n async nodeGetById<N extends NodeType>(\n kind: string,\n id: NodeId<N>,\n coordinate: ReadCoordinate,\n ): Promise<Node<N> | undefined> {\n const results = await nodeGetByIds(kind, [id], coordinate);\n return results[0];\n },\n\n nodeGetByIds,\n nodeScan,\n\n async edgeGetById<E extends AnyEdgeType>(\n kind: string,\n id: EdgeId<E>,\n coordinate: ReadCoordinate,\n ): Promise<Edge<E> | undefined> {\n const results = await edgeGetByIds(kind, [id], coordinate);\n return results[0];\n },\n\n edgeGetByIds,\n edgeScan,\n };\n}\n","import { type GraphDef } from \"../core/define-graph\";\nimport { type AnyEdgeType, type NodeType } from \"../core/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { type Assert, type Equal } from \"../utils/type-assert\";\nimport { EDGE_WRITE_NAMES, NODE_WRITE_NAMES } from \"./collection-surface\";\nimport type {\n EdgeWrites,\n GraphEdgeCollections,\n GraphNodeCollections,\n NodeWrites,\n TransactionReceipt,\n} from \"./types\";\n\ntype NodeWriteMethodName = (typeof NODE_WRITE_NAMES)[number];\ntype EdgeWriteMethodName = (typeof EDGE_WRITE_NAMES)[number];\n\n// If these fail, the receipt wrapper drifted away from the collection write\n// surface that defines NodeWrites / EdgeWrites.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- compile-time assertion\ntype _receiptNodeSurfaceIsComplete = Assert<\n Equal<NodeWriteMethodName, keyof NodeWrites<NodeType, string>>\n>;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- compile-time assertion\ntype _receiptEdgeSurfaceIsComplete = Assert<\n Equal<EdgeWriteMethodName, keyof EdgeWrites<AnyEdgeType, NodeType, NodeType>>\n>;\n\nexport type TransactionReceiptRecorder = Readonly<{\n recordNode: (kind: string, count: number) => void;\n recordEdge: (kind: string, count: number) => void;\n snapshot: (recorded?: TransactionReceipt[\"recorded\"]) => TransactionReceipt;\n /**\n * Seals the recorder: every subsequent write through a collection wrapped with\n * it (see {@link wrapTransactionCollections}) throws. Used to fail loud when a\n * transaction context is retained and written through *after* its callback\n * returned — where the receipt is already snapshotted and the write would\n * otherwise persist uncounted.\n */\n seal: () => void;\n /**\n * Throws {@link ConfigurationError} once {@link seal} has been called. Invoked\n * at the top of every wrapped write method, before the live write runs, so a\n * post-seal write never reaches the backend.\n */\n assertWritable: () => void;\n}>;\n\ntype WrappedMethod = (...args: unknown[]) => Promise<unknown>;\n\ntype WriteIntentCounter = (args: readonly unknown[]) => number;\n\nfunction inputLength(value: unknown): number {\n return Array.isArray(value) ? value.length : 0;\n}\n\nfunction countSingleWrite(): number {\n return 1;\n}\n\nfunction countBulkInputAt(index: number): WriteIntentCounter {\n return (args) => inputLength(args[index]);\n}\n\n// `satisfies Record<...MethodName, ...>` forces a per-method decision: a new\n// write method fails to compile here until its intent count is chosen, so a\n// future bulk method cannot silently fall back to counting 1 per call.\nconst NODE_WRITE_INTENT_COUNTERS = {\n create: countSingleWrite,\n createFromRecord: countSingleWrite,\n update: countSingleWrite,\n delete: countSingleWrite,\n hardDelete: countSingleWrite,\n upsertById: countSingleWrite,\n upsertByIdFromRecord: countSingleWrite,\n bulkCreate: countBulkInputAt(0),\n bulkUpsertById: countBulkInputAt(0),\n bulkInsert: countBulkInputAt(0),\n bulkDelete: countBulkInputAt(0),\n getOrCreateByConstraint: countSingleWrite,\n bulkGetOrCreateByConstraint: countBulkInputAt(1),\n} as const satisfies Record<NodeWriteMethodName, WriteIntentCounter>;\n\nconst EDGE_WRITE_INTENT_COUNTERS = {\n create: countSingleWrite,\n update: countSingleWrite,\n delete: countSingleWrite,\n hardDelete: countSingleWrite,\n bulkCreate: countBulkInputAt(0),\n bulkUpsertById: countBulkInputAt(0),\n bulkInsert: countBulkInputAt(0),\n bulkDelete: countBulkInputAt(0),\n getOrCreateByEndpoints: countSingleWrite,\n bulkGetOrCreateByEndpoints: countBulkInputAt(0),\n} as const satisfies Record<EdgeWriteMethodName, WriteIntentCounter>;\n\n// Null-prototype buckets: kind names are arbitrary identifiers, so\n// `constructor`, `toString`, or `__proto__` are valid kinds. On a plain `{}`\n// they would read inherited Object.prototype members (corrupting the count)\n// or trigger the `__proto__` setter (dropping it).\nfunction createCountBucket(): Record<string, number> {\n return Object.create(null) as Record<string, number>;\n}\n\nfunction increment(\n counts: Record<string, number>,\n kind: string,\n count: number,\n): void {\n if (count === 0) return;\n counts[kind] = (counts[kind] ?? 0) + count;\n}\n\n/**\n * One receipt's running counts. Each recorder owns exactly one: the outer\n * transaction's receipt, or the sub-receipt of one `tx.measure` scope. Scope\n * attribution is structural — a scope is a *second* recorder wrapping the outer\n * collections again (see `attachMeasure` in store.ts) — so no recorder ever\n * needs to know about another's scopes.\n */\ninterface WriteCounters {\n readonly nodes: Record<string, number>;\n readonly edges: Record<string, number>;\n total: number;\n}\n\nexport function createTransactionReceiptRecorder(): TransactionReceiptRecorder {\n const counters: WriteCounters = {\n nodes: createCountBucket(),\n edges: createCountBucket(),\n total: 0,\n };\n let sealed = false;\n\n return {\n recordNode(kind, count): void {\n increment(counters.nodes, kind, count);\n counters.total += count;\n },\n\n recordEdge(kind, count): void {\n increment(counters.edges, kind, count);\n counters.total += count;\n },\n\n snapshot(recorded): TransactionReceipt {\n // Object.assign onto a fresh null-prototype bucket (rather than spread)\n // keeps prototype-colliding kind names readable on the returned receipt.\n return Object.freeze({\n writes: Object.freeze({\n nodes: Object.freeze(\n Object.assign(createCountBucket(), counters.nodes),\n ),\n edges: Object.freeze(\n Object.assign(createCountBucket(), counters.edges),\n ),\n total: counters.total,\n }),\n ...(recorded === undefined ? {} : { recorded }),\n });\n },\n\n seal(): void {\n sealed = true;\n },\n\n assertWritable(): void {\n if (sealed) {\n throw new ConfigurationError(\n \"Transaction context is sealed: a write happened through the receipt-tracked collections after the transaction callback returned.\",\n {},\n {\n suggestion:\n \"Perform all writes inside the transactionWithReceipt / withRecordedTransaction callback; do not reuse the transaction context after it returns.\",\n },\n );\n }\n },\n };\n}\n\nfunction isWrappedMethod(value: unknown): value is WrappedMethod {\n return typeof value === \"function\";\n}\n\nfunction isObject(value: unknown): value is object {\n return typeof value === \"object\" && Boolean(value);\n}\n\n/**\n * Which methods on a node/edge collection count as writes, and how each\n * counts its intent. Bundled into one value per entity kind (below) rather\n * than passed as separate `methodNames`/`counters` parameters, so a call\n * site can only pick \"the node surface\" or \"the edge surface\" as a unit —\n * it cannot independently mismatch a method-name set against the wrong\n * counter table.\n */\ntype WriteIntentSurface<M extends string> = Readonly<{\n methodNames: ReadonlySet<string>;\n counters: Record<M, WriteIntentCounter>;\n}>;\n\nconst NODE_WRITE_SURFACE: WriteIntentSurface<NodeWriteMethodName> = {\n methodNames: new Set(NODE_WRITE_NAMES),\n counters: NODE_WRITE_INTENT_COUNTERS,\n};\n\nconst EDGE_WRITE_SURFACE: WriteIntentSurface<EdgeWriteMethodName> = {\n methodNames: new Set(EDGE_WRITE_NAMES),\n counters: EDGE_WRITE_INTENT_COUNTERS,\n};\n\n/**\n * Proxies `target`, memoizing the wrapped value for each string-keyed\n * property after first access. `shouldWrap` gates which properties run\n * through `wrap`; everything else (including symbol keys) passes through\n * via `Reflect.get` untouched. Shared by `wrapWriteCollection` (wraps write\n * methods on one collection) and `wrapCollections` (wraps every collection\n * in a kind-keyed map) — both are \"lazily transform and cache one property\n * of an object\" with a different `shouldWrap`/`wrap` pair.\n */\nfunction memoizedProxyGet<T extends object>(\n target: T,\n shouldWrap: (property: string) => boolean,\n wrap: (value: unknown, property: string) => unknown,\n): T {\n const cache = new Map<string, unknown>();\n\n return new Proxy(target, {\n get(proxyTarget, property, receiver) {\n if (typeof property !== \"string\" || !shouldWrap(property)) {\n return Reflect.get(proxyTarget, property, receiver);\n }\n\n const cached = cache.get(property);\n if (cached !== undefined) return cached;\n\n const value = Reflect.get(proxyTarget, property, receiver);\n const wrapped = wrap(value, property);\n cache.set(property, wrapped);\n return wrapped;\n },\n });\n}\n\n/**\n * Wraps one node/edge collection so every write method on it (per\n * `surface.methodNames`) fails loud once the recorder is sealed, then counts\n * its intent through `record` on resolution.\n */\nfunction wrapWriteCollection<T extends object, M extends string>(\n collection: T,\n kind: string,\n surface: WriteIntentSurface<M>,\n record: (kind: string, count: number) => void,\n assertWritable: () => void,\n): T {\n return memoizedProxyGet(\n collection,\n (property) => surface.methodNames.has(property),\n (value, property) => {\n if (!isWrappedMethod(value)) return value;\n\n const method = property as M;\n const wrapped: WrappedMethod = async (...args) => {\n // Reject before the live write: a context retained past its callback\n // must not persist a row the already-snapshotted receipt cannot count.\n assertWritable();\n // Pin the intent count at call time: a caller may mutate a bulk input\n // array while the write is in flight, and the backend has already\n // snapshotted the items. Recording still waits for resolution so a\n // rejected write counts 0.\n const count = surface.counters[method](args);\n const result = await Reflect.apply(value, collection, args);\n record(kind, count);\n return result;\n };\n return wrapped;\n },\n );\n}\n\n/**\n * Wraps a kind-keyed collection map (`GraphNodeCollections<G>` /\n * `GraphEdgeCollections<G>`), lazily wrapping each collection with\n * `wrapOne` on first access.\n */\nfunction wrapCollections<T extends object>(\n collections: T,\n wrapOne: (collection: object, kind: string) => unknown,\n): T {\n return memoizedProxyGet(\n collections,\n () => true,\n (collection, kind) =>\n isObject(collection) ? wrapOne(collection, kind) : collection,\n );\n}\n\nexport function wrapTransactionCollections<G extends GraphDef>(\n nodes: GraphNodeCollections<G>,\n edges: GraphEdgeCollections<G>,\n recorder: TransactionReceiptRecorder,\n): Readonly<{\n nodes: GraphNodeCollections<G>;\n edges: GraphEdgeCollections<G>;\n}> {\n return {\n nodes: wrapCollections(nodes, (collection, kind) =>\n wrapWriteCollection(\n collection,\n kind,\n NODE_WRITE_SURFACE,\n recorder.recordNode,\n recorder.assertWritable,\n ),\n ),\n edges: wrapCollections(edges, (collection, kind) =>\n wrapWriteCollection(\n collection,\n kind,\n EDGE_WRITE_SURFACE,\n recorder.recordEdge,\n recorder.assertWritable,\n ),\n ),\n };\n}\n","/**\n * Main Store implementation for TypeGraph.\n *\n * The Store is the primary interface for interacting with a TypeGraph.\n * It coordinates:\n * - Node and edge CRUD operations\n * - Constraint validation\n * - Schema management\n * - Transaction handling\n */\nimport type { z } from \"zod\";\n\nimport {\n asGraphWriteBackend,\n asRawBackend,\n type GraphWriteBackend,\n type RawBackend,\n} from \"../backend/branded\";\nimport { createGraphBackendProjection } from \"../backend/graph-backend-projection\";\nimport {\n createEdgeRowMapper,\n createNodeRowMapper,\n POSTGRES_ROW_MAPPER_CONFIG,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"../backend/row-mappers\";\nimport {\n type AdapterBackend,\n type BackendCapabilities,\n createTransactionReadBackend,\n type GraphBackend,\n runOptionallyInTransaction,\n type SchemaVersionRow,\n type TransactionBackend,\n type TransactionOptions,\n} from \"../backend/types\";\nimport {\n type AllNodeTypes,\n type EdgeKinds,\n type GraphDef,\n isKnownKind,\n type NodeKinds,\n} from \"../core/define-graph\";\nimport {\n resolveEmbeddingFields,\n resolveGraphVectorSlots,\n} from \"../core/embedding\";\nimport {\n asRecordedInstant,\n type ReadCoordinate,\n type RecordedInstant,\n resolveReadCoordinate,\n withRecordedCoordinate,\n} from \"../core/temporal\";\nimport type {\n AnyEdgeType,\n EdgeId,\n KindEntity,\n NodeId,\n NodeType,\n} from \"../core/types\";\nimport {\n ConfigurationError,\n EagerMaterializationError,\n KindNotFoundError,\n} from \"../errors\";\nimport {\n buildIncompatibleChangeError,\n classifyModifications,\n type RequireEmptyEntry,\n} from \"../graph-extension/classify\";\nimport { IncompatibleChangeError } from \"../graph-extension/errors\";\nimport { type GraphExtension } from \"../graph-extension/extension-types\";\nimport { mergeGraphExtension } from \"../graph-extension/merge\";\nimport { planRemovals, stripGraphExtension } from \"../graph-extension/remove\";\nimport { type VectorIndexDeclaration } from \"../indexes/types\";\nimport type { TraversalExpansion } from \"../query/ast\";\nimport {\n type BatchableQuery,\n type BatchResults,\n createInternalQueryBuilder,\n type InitialQueryBuilder,\n type QueryCoordinateState,\n} from \"../query/builder\";\nimport {\n createRecordedReadBinding,\n createSqlSchema,\n type RecordedReadBinding,\n requireExternalRecordedReadSource,\n requireSqlSchema,\n type SqlSchema,\n} from \"../query/compiler/schema\";\nimport { getDialect } from \"../query/dialect\";\nimport type { SqlDialect } from \"../query/dialect/types\";\nimport { type VectorSlot } from \"../query/dialect/vector-strategy\";\nimport { buildKindRegistry, type KindRegistry } from \"../registry\";\nimport {\n applyDeprecatedKinds,\n commitNewSchemaVersion,\n ensureSchema as ensureSchemaImpl,\n loadActiveSchemaWithBootstrap,\n loadAndMergeGraphExtensionDocument,\n loadAndVerifyGraph,\n parseSerializedSchema,\n type SchemaManagerOptions,\n type SchemaValidationResult,\n} from \"../schema/manager\";\nimport { type SerializedSchema } from \"../schema/types\";\nimport { nowIso } from \"../utils/date\";\nimport { generateId } from \"../utils/id\";\nimport { requireDefined } from \"../utils/presence\";\nimport {\n createGraphAlgorithms,\n type GraphAlgorithms,\n type InternalGraphAlgorithms,\n} from \"./algorithms\";\nimport {\n createEdgeCollectionsProxy,\n createNodeCollectionsProxy,\n type EdgeOperations,\n type NodeOperations,\n} from \"./collection-factory\";\nimport { resolveTemporalReadParams } from \"./collections/temporal-read-params\";\nimport {\n createHistoryStoreBackendProjection,\n type HistoryStoreBackend,\n} from \"./history-store-backend\";\nimport { introspectSchema, type SchemaIntrospection } from \"./introspect\";\nimport {\n backendSupportsIndexMaterialization,\n computeIndexSignature,\n materializeIndexes as materializeIndexesImpl,\n type MaterializeIndexesOptions,\n type MaterializeIndexesResult,\n materializeSystemIndexes as materializeSystemIndexesImpl,\n type MaterializeSystemIndexesOptions,\n vectorStatusKey,\n} from \"./materialize-indexes\";\nimport {\n buildPendingKindRemoval,\n materializeRemovals as materializeRemovalsImpl,\n type MaterializeRemovalsOptions,\n type MaterializeRemovalsResult,\n} from \"./materialize-removals\";\nimport {\n type EdgeOperationContext,\n edgeUpsertDirtyCheck,\n executeEdgeBulkGetOrCreateByEndpoints,\n executeEdgeCreate,\n executeEdgeCreateBatch,\n executeEdgeCreateNoReturnBatch,\n executeEdgeDelete,\n executeEdgeFindByEndpoints,\n executeEdgeGetOrCreateByEndpoints,\n executeEdgeHardDelete,\n executeEdgeUpdate,\n executeEdgeUpsertUpdate,\n executeNodeBulkFindByConstraint,\n executeNodeBulkFindByIndex,\n executeNodeBulkGetOrCreateByConstraint,\n executeNodeCreate,\n executeNodeCreateBatch,\n executeNodeCreateNoReturnBatch,\n executeNodeDelete,\n executeNodeFindByConstraint,\n executeNodeGetOrCreateByConstraint,\n executeNodeHardDelete,\n executeNodeUpdate,\n executeNodeUpsertUpdate,\n type NodeOperationContext,\n nodeUpsertDirtyCheck,\n} from \"./operations\";\nimport {\n advanceRevisionClock,\n assertRecordedCaptureTransactionIsolation,\n assertRevisionTrackableBackend,\n createRecordedBackend,\n createRecordedTransactionScope,\n ensureRevisionOrigin,\n lockRecordedGraphWrite,\n readRecordedClock,\n recordedCaptureRequiresCallbackTransactionError,\n type RecordedFlushInstants,\n throwHistoryUnsafeSqlAccess,\n throwRevisionTrackingUnsafeSqlAccess,\n withRecordedFlushObserver,\n withRecordedRelationsPrecondition,\n} from \"./recorded-capture\";\nimport { assertNoRecordedCoordinate } from \"./recorded-coordinate-guard\";\nimport {\n createRecordedReadService,\n type RecordedReadService,\n} from \"./recorded-read-service\";\nimport { rowToEdge, rowToNode } from \"./row-mappers\";\nimport { STORE_RUNTIME, type StoreRuntime } from \"./runtime-port\";\nimport { StoreSearch } from \"./search-facade\";\nimport {\n RecordedStoreView,\n StoreView,\n type StoreViewCoordinate,\n} from \"./store-view\";\nimport {\n executeSubgraph,\n type InternalSubgraphOptions,\n type SubgraphOptions,\n type SubgraphProject,\n type SubgraphResult,\n} from \"./subgraph\";\nimport {\n createTransactionReceiptRecorder,\n type TransactionReceiptRecorder,\n wrapTransactionCollections,\n} from \"./transaction-receipt\";\nimport {\n type AdapterTransactionContext,\n AUTO_REFRESH_STATISTICS_ROW_THRESHOLD,\n type DynamicEdgeCollection,\n type DynamicNodeCollection,\n type Edge,\n type GraphEdgeCollections,\n type GraphNodeCollections,\n type HistoryStoreOptions,\n type HookContext,\n type LiveStoreOptions,\n type MeasurableAdapterTransactionContext,\n type MeasurableTransactionContext,\n type Node,\n type OperationHookContext,\n type QueryOptions,\n type RecordedReadStoreOptions,\n type RecordedScanOptions,\n type RecordedScanPage,\n type ScopedMeasure,\n type StoreHooks,\n type StoreOptions,\n type StoreRef,\n TRANSACTION_RUNTIME,\n type TransactionContext,\n type TransactionOutcome,\n type UnboundLiveStoreOptions,\n} from \"./types\";\n\ntype StoreSchemaMetadata = Readonly<{\n schemaVersion: number | undefined;\n schemaHash: string | undefined;\n}>;\n\nconst UNKNOWN_SCHEMA_METADATA: StoreSchemaMetadata = Object.freeze({\n schemaVersion: undefined,\n schemaHash: undefined,\n});\n\ntype CaughtUpVerb =\n \"evolve\" | \"materialize\" | \"deprecate\" | \"undeprecate\" | \"remove\" | \"reembed\";\n\n/** Default page size for the {@link Store.reembedVectorField} re-embed loop. */\nconst DEFAULT_REEMBED_BATCH_SIZE = 200;\n\nconst CAUGHT_UP_VERB_DETAILS: Readonly<\n Record<CaughtUpVerb, Readonly<{ phrase: string; code: string }>>\n> = {\n evolve: { phrase: \"evolve\", code: \"EVOLVE_BEFORE_INITIALIZE\" },\n materialize: {\n phrase: \"materialize indexes on\",\n code: \"MATERIALIZE_BEFORE_INITIALIZE\",\n },\n remove: { phrase: \"remove kinds on\", code: \"REMOVE_BEFORE_INITIALIZE\" },\n deprecate: {\n phrase: \"deprecate kinds on\",\n code: \"DEPRECATE_BEFORE_INITIALIZE\",\n },\n undeprecate: {\n phrase: \"undeprecate kinds on\",\n code: \"DEPRECATE_BEFORE_INITIALIZE\",\n },\n reembed: {\n phrase: \"re-embed a vector field on\",\n code: \"REEMBED_BEFORE_INITIALIZE\",\n },\n};\n\nconst ROW_MAPPER_CONFIGS = {\n postgres: POSTGRES_ROW_MAPPER_CONFIG,\n sqlite: SQLITE_ROW_MAPPER_CONFIG,\n} satisfies Record<SqlDialect, typeof POSTGRES_ROW_MAPPER_CONFIG>;\n\nfunction rowMapperConfigFor(backend: GraphBackend | TransactionBackend) {\n return ROW_MAPPER_CONFIGS[backend.dialect];\n}\n\n// ============================================================\n// Store Class\n// ============================================================\n\n/**\n * The Store provides typed access to a TypeGraph database.\n *\n * @example\n * ```typescript\n * const store = createStore(myGraph, backend);\n *\n * // Create nodes using collection API\n * const person = await store.nodes.Person.create({\n * name: \"Alice\",\n * email: \"alice@example.com\",\n * });\n *\n * const company = await store.nodes.Company.create({\n * name: \"Acme\",\n * industry: \"Technology\",\n * });\n *\n * // Create edges\n * await store.edges.worksAt.create(\n * { kind: \"Person\", id: person.id },\n * { kind: \"Company\", id: company.id },\n * { role: \"Engineer\" }\n * );\n *\n * // Query with the fluent API\n * const results = await store.query()\n * .from(\"Person\", \"p\")\n * .whereNode(\"p\", (p) => p.name.eq(\"Alice\"))\n * .select((ctx) => ctx.p)\n * .execute();\n * ```\n */\n\n/**\n * Optional embedder for {@link Store.reembedVectorField}. Receives a batch of\n * the kind's nodes and returns a map of `nodeId → new embedding vector` (omit\n * an id to leave that node without an embedding). Called once per page; the\n * page size is `batchSize`.\n */\nexport type ReembedFunction = (\n nodes: readonly Node[],\n) =>\n | Promise<ReadonlyMap<string, readonly number[]>>\n | ReadonlyMap<string, readonly number[]>;\n\n/** Options for {@link Store.reembedVectorField}. */\nexport type ReembedVectorFieldOptions = Readonly<{\n /**\n * When supplied, drives a batched re-embed loop after recreating storage:\n * pages the kind's nodes, calls `embed(batch)`, and upserts the returned\n * vectors. When omitted, storage is recreated empty and the caller\n * re-embeds via normal `update()` / `upsertEmbedding` writes.\n */\n embed?: ReembedFunction;\n /** Re-embed page size. Default 200. */\n batchSize?: number;\n}>;\n\n/** Result of {@link Store.reembedVectorField}. */\nexport type ReembedVectorFieldResult = Readonly<{\n /** Whether the per-field storage was dropped and recreated. */\n recreated: boolean;\n /** Number of nodes whose embedding was re-written (0 without `embed`). */\n reembedded: number;\n}>;\n\n/** One place for the hooks' error normalization. */\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n/** The `(hook context, operation body)` wrapper shape operation contexts carry. */\ntype OperationHookRunner = <T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n) => Promise<T>;\n\n/** A committed-inside-the-transaction operation awaiting the outer COMMIT. */\ntype PendingOperationOutcome = Readonly<{\n ctx: OperationHookContext;\n durationMs: number;\n}>;\n\ntype TransactionRunResult<T> = Readonly<{\n result: T;\n recordedByGraph: RecordedFlushInstants | undefined;\n}>;\n\n/**\n * The flush result for a `withRecordedTransaction` on a store without history\n * capture: no recorded rows were closed, so no graph maps to an instant. Shared\n * (rather than allocated per call) — a `ReadonlyMap` is never mutated.\n */\nconst EMPTY_RECORDED_FLUSH_INSTANTS: RecordedFlushInstants = new Map();\n\nfunction transactionOutcome<T>(\n result: T,\n recorder: TransactionReceiptRecorder,\n recordedByGraph: RecordedFlushInstants | undefined,\n graphId: string,\n): TransactionOutcome<T> {\n const recorded = recordedByGraph?.get(graphId);\n return {\n result,\n receipt: recorder.snapshot(\n recorded === undefined ? undefined : asRecordedInstant(recorded),\n ),\n };\n}\n\n/** Clones an internal context without evaluating accessor properties. */\nfunction overlayPropertyDescriptors<\n TBase extends object,\n TOverlay extends object,\n>(base: TBase, overlay: TOverlay): TBase & TOverlay {\n return Object.defineProperties(Object.create(Reflect.getPrototypeOf(base)), {\n ...Object.getOwnPropertyDescriptors(base),\n ...Object.getOwnPropertyDescriptors(overlay),\n }) as TBase & TOverlay;\n}\n\n/** Keeps suppressed/JavaScript raw-SQL access fail-loud without advertising it. */\nfunction defineUnavailableSqlGuard(context: object, guard: () => never): void {\n Object.defineProperty(context, \"sql\", {\n configurable: false,\n enumerable: true,\n get: guard,\n });\n}\n\ntype StoreCore<G extends GraphDef> = Readonly<{\n [STORE_RUNTIME]: StoreRuntime<G>;\n graph: G;\n graphId: string;\n capabilities: BackendCapabilities;\n registry: KindRegistry;\n historyEnabled: boolean;\n revisionTrackingEnabled: boolean;\n revisionSchema: SqlSchema;\n recordedReadBound: boolean;\n nodes: GraphNodeCollections<G>;\n edges: GraphEdgeCollections<G>;\n algorithms: GraphAlgorithms<G>;\n search: StoreSearch<G>;\n getNodeCollection: (kind: string) => DynamicNodeCollection | undefined;\n getNodeCollectionOrThrow: (kind: string) => DynamicNodeCollection;\n getEdgeCollection: (kind: string) => DynamicEdgeCollection | undefined;\n getEdgeCollectionOrThrow: (kind: string) => DynamicEdgeCollection;\n getNodePropsSchema: (kind: string) => z.ZodObject<z.ZodRawShape> | undefined;\n getNodePropsSchemaOrThrow: (kind: string) => z.ZodObject<z.ZodRawShape>;\n getEdgePropsSchema: (kind: string) => z.ZodObject<z.ZodRawShape> | undefined;\n getEdgePropsSchemaOrThrow: (kind: string) => z.ZodObject<z.ZodRawShape>;\n introspect: () => SchemaIntrospection;\n query: () => InitialQueryBuilder<G, \"open\">;\n asOf: (asOf: string) => StoreView<G>;\n asOfRecorded: (recordedAsOf: RecordedInstant) => RecordedStoreView<G>;\n recordedNow: () => Promise<RecordedInstant | undefined>;\n revisionNow: () => Promise<string | undefined>;\n revisionOriginNow: () => Promise<string>;\n view: (coordinate: StoreViewCoordinate) => StoreView<G>;\n snapshot: () => StoreView<G>;\n batch: <\n const Queries extends readonly [\n BatchableQuery<unknown>,\n BatchableQuery<unknown>,\n ...BatchableQuery<unknown>[],\n ],\n >(\n ...queries: Queries\n ) => Promise<BatchResults<Queries>>;\n subgraph: <\n const EK extends EdgeKinds<G>,\n const NK extends NodeKinds<G> = NodeKinds<G>,\n const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n >(\n rootId: NodeId<AllNodeTypes<G>>,\n options: SubgraphOptions<G, EK, NK, P>,\n ) => Promise<SubgraphResult<G, NK, EK, P>>;\n clear: () => Promise<void>;\n refreshStatistics: () => Promise<void>;\n materializeIndexes: (\n options?: MaterializeIndexesOptions,\n ) => Promise<MaterializeIndexesResult>;\n materializeSystemIndexes: (\n options?: MaterializeSystemIndexesOptions,\n ) => Promise<MaterializeIndexesResult>;\n reembedVectorField: (\n kind: string,\n fieldPath: string,\n options?: ReembedVectorFieldOptions,\n ) => Promise<ReembedVectorFieldResult>;\n materializeRemovals: (\n options?: MaterializeRemovalsOptions,\n ) => Promise<MaterializeRemovalsResult>;\n close: () => Promise<void>;\n}>;\n\ntype StoreTransactions<G extends GraphDef> = Readonly<{\n transaction: <T>(\n fn: (tx: TransactionContext<G>) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n transactionWithReceipt: <T>(\n fn: (tx: MeasurableTransactionContext<G>) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<TransactionOutcome<T>>;\n}>;\n\ninterface StoreEvolution<G extends GraphDef, TStore extends StoreCore<G>> {\n readonly evolve: <TRefStore extends StoreCore<G> = TStore>(\n extension: GraphExtension,\n options?: Readonly<{\n ref?: TStore extends TRefStore ? StoreRef<TRefStore> : never;\n eager?: MaterializeIndexesOptions;\n }>,\n ) => Promise<TStore>;\n readonly deprecateKinds: <TRefStore extends StoreCore<G> = TStore>(\n names: readonly string[],\n options?: Readonly<{\n ref?: TStore extends TRefStore ? StoreRef<TRefStore> : never;\n }>,\n ) => Promise<TStore>;\n readonly undeprecateKinds: <TRefStore extends StoreCore<G> = TStore>(\n names: readonly string[],\n options?: Readonly<{\n ref?: TStore extends TRefStore ? StoreRef<TRefStore> : never;\n }>,\n ) => Promise<TStore>;\n readonly removeKinds: <TRefStore extends StoreCore<G> = TStore>(\n names: readonly string[],\n options?: Readonly<{\n ref?: TStore extends TRefStore ? StoreRef<TRefStore> : never;\n eager?: MaterializeRemovalsOptions;\n }>,\n ) => Promise<TStore>;\n}\n\nfunction syncStoreReplacementRef<\n G extends GraphDef,\n TRefStore extends StoreCore<G>,\n>(ref: StoreRef<TRefStore> | undefined, replacement: StoreCore<G>): void {\n if (ref === undefined) return;\n // StoreEvolution admits only refs whose value is a supertype of the returned\n // Store flavor. Runtime implementations use one broader class for every\n // overload, so the compiler cannot recover that public conditional here.\n ref.current = replacement as unknown as TRefStore;\n}\n\n/**\n * The default TypeGraph Store contract. It contains the complete graph API and\n * graph-owned transactions while keeping adapter-native handles, backend\n * internals, and caller-owned transaction adoption out of the public surface.\n */\nexport type Store<G extends GraphDef> = StoreCore<G> &\n StoreTransactions<G> &\n StoreEvolution<G, Store<G>>;\n\n/**\n * A Store with explicit adapter interoperability. Adapter entrypoints return\n * this surface so native transaction handles remain precisely typed without\n * leaking into the default Store contract.\n */\nexport type AdapterStore<\n G extends GraphDef,\n TNativeTransaction,\n> = StoreCore<G> &\n StoreEvolution<G, AdapterStore<G, TNativeTransaction>> &\n AdapterStoreTransactions<G, TNativeTransaction> &\n Readonly<{ backend: GraphBackend }>;\n\ntype AdapterStoreTransactions<\n G extends GraphDef,\n TNativeTransaction,\n> = Readonly<{\n transaction: <T>(\n fn: (tx: AdapterTransactionContext<G, TNativeTransaction>) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n transactionWithReceipt: <T>(\n fn: (\n tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<TransactionOutcome<T>>;\n withTransaction: (\n externalTransaction: TNativeTransaction,\n ) => AdapterTransactionContext<G, TNativeTransaction>;\n withRecordedTransaction: <T>(\n externalTransaction: TNativeTransaction,\n fn: (\n tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n ) => Promise<TransactionOutcome<T>>;\n}>;\n\nclass StoreImplementation<G extends GraphDef, TNativeTransaction = unknown> {\n readonly [STORE_RUNTIME]: StoreRuntime<G>;\n readonly #graph: G;\n /**\n * Bare backend for DDL, vector-storage, and bulk-materialization work that must\n * bypass recorded capture. Graph-entity writes use `#backend` instead.\n */\n readonly #baseBackend: RawBackend;\n readonly #backend: GraphWriteBackend;\n readonly #adapterBackend: AdapterBackend<TNativeTransaction> | undefined;\n readonly #captureEnabled: boolean;\n readonly #revisionTrackingEnabled: boolean;\n #revisionOrigin: Promise<string> | undefined;\n readonly #recordedReadBinding: RecordedReadBinding | undefined;\n readonly #registry: KindRegistry;\n readonly #hooks: StoreHooks;\n readonly #schema: StoreOptions[\"schema\"];\n readonly #recordedReads: RecordedReadService;\n readonly #schemaMetadata: StoreSchemaMetadata;\n readonly #defaultTraversalExpansion: TraversalExpansion;\n // Stored verbatim so `evolve()` can construct the next Store with\n // identical options. Reconstructing from the individual private\n // fields would silently drop any future StoreOptions field a\n // maintainer adds without also threading it through evolve.\n readonly #options: StoreOptions | undefined;\n #nodeCollections: GraphNodeCollections<G> | undefined;\n #edgeCollections: GraphEdgeCollections<G> | undefined;\n #algorithms: GraphAlgorithms<G> | undefined;\n #search: StoreSearch<G> | undefined;\n\n constructor(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions,\n schemaMetadata?: StoreSchemaMetadata,\n adapterBackend?: AdapterBackend<TNativeTransaction>,\n ) {\n this.#graph = graph;\n this.#baseBackend = asRawBackend(backend);\n this.#adapterBackend = adapterBackend;\n this.#captureEnabled = options?.history === true;\n this.#revisionTrackingEnabled =\n this.#captureEnabled || options?.revisionTracking === true;\n if (this.#revisionTrackingEnabled) {\n assertRevisionTrackableBackend(backend);\n }\n // Resolve the schema before wrapping so recorded-time capture targets the\n // same relations recorded reads do (the explicit `schema` option, not just\n // `backend.tableNames`).\n const explicitSchema =\n options?.schema === undefined ?\n undefined\n : requireSqlSchema(options.schema, \"store schema\");\n const resolvedSchema =\n explicitSchema ??\n (backend.tableNames ? createSqlSchema(backend.tableNames) : undefined);\n const readSchema = resolvedSchema ?? createSqlSchema(backend.tableNames);\n if (this.#captureEnabled && options?.recordedRead !== undefined) {\n throw new ConfigurationError(\n \"recordedRead cannot be combined with history: true.\",\n { code: \"RECORDED_READ_CONFLICTS_WITH_HISTORY\" },\n {\n suggestion:\n \"Use { history: true } for TypeGraph-managed capture, or omit history and pass { recordedRead: recordedRelation({ schema }) } for an externally populated recorded relation.\",\n },\n );\n }\n const externalRecordedRead = requireExternalRecordedReadSource(\n options?.recordedRead,\n );\n this.#recordedReadBinding =\n this.#captureEnabled ?\n createRecordedReadBinding(readSchema)\n : externalRecordedRead;\n this.#backend =\n this.#captureEnabled ?\n asGraphWriteBackend(createRecordedBackend(backend, resolvedSchema))\n : asGraphWriteBackend(backend);\n this.#schema = resolvedSchema;\n const rowMapperConfig = rowMapperConfigFor(this.#backend);\n this.#recordedReads = createRecordedReadService({\n graphId: graph.id,\n backend: this.#backend,\n recordedReadBinding: this.#recordedReadBinding,\n mapRecordedNodeRow: createNodeRowMapper(rowMapperConfig),\n mapRecordedEdgeRow: createEdgeRowMapper(rowMapperConfig),\n });\n this.#registry = buildKindRegistry(graph);\n this.#hooks = options?.hooks ?? {};\n this.#defaultTraversalExpansion =\n options?.queryDefaults?.traversalExpansion ?? \"inverse\";\n this.#options = options;\n this.#schemaMetadata = schemaMetadata ?? UNKNOWN_SCHEMA_METADATA;\n this[STORE_RUNTIME] = {\n backend: this.#backend,\n sealedQuery: (coordinate) => this.sealedQuery(coordinate),\n recordedNodeGetById: (kind, id, coordinate) =>\n this.recordedNodeGetById(kind, id, coordinate),\n recordedNodeGetByIds: (kind, ids, coordinate) =>\n this.recordedNodeGetByIds(kind, ids, coordinate),\n recordedNodeScan: (kind, coordinate, options) =>\n this.recordedNodeScan(kind, coordinate, options),\n recordedEdgeGetById: (kind, id, coordinate) =>\n this.recordedEdgeGetById(kind, id, coordinate),\n recordedEdgeGetByIds: (kind, ids, coordinate) =>\n this.recordedEdgeGetByIds(kind, ids, coordinate),\n recordedEdgeScan: (kind, coordinate, options) =>\n this.recordedEdgeScan(kind, coordinate, options),\n subgraphAtCoordinate: (rootId, subgraphOptions) =>\n this.subgraphAtCoordinate(rootId, subgraphOptions),\n algorithmsAtCoordinate: (coordinate) =>\n this.algorithmsAtCoordinate(coordinate),\n };\n Object.defineProperty(this, STORE_RUNTIME, {\n configurable: false,\n enumerable: false,\n writable: false,\n });\n }\n\n // === Accessors ===\n\n /** The graph definition */\n get graph(): G {\n return this.#graph;\n }\n\n /** The graph ID */\n get graphId(): string {\n return this.#graph.id;\n }\n\n /** Runtime features available through this store's configured backend. */\n get capabilities(): BackendCapabilities {\n return this.#baseBackend.capabilities;\n }\n\n /** The kind registry for ontology lookups */\n get registry(): KindRegistry {\n return this.#registry;\n }\n\n /**\n * Whether recorded-time capture is enabled for this store.\n *\n * @internal\n */\n get historyEnabled(): boolean {\n return this.#captureEnabled;\n }\n\n /**\n * Whether this Store advances a durable revision anchor for graph writes.\n *\n * @internal\n */\n get revisionTrackingEnabled(): boolean {\n return this.#revisionTrackingEnabled;\n }\n\n /**\n * SQL schema that owns the durable revision clock relation.\n *\n * @internal\n */\n get revisionSchema(): SqlSchema {\n return this.#sqlSchema();\n }\n\n /**\n * Whether this store has a recorded read relation bound for reconstruction.\n *\n * @internal\n */\n get recordedReadBound(): boolean {\n return this.#recordedReadBinding !== undefined;\n }\n\n // === Collections ===\n\n /**\n * Node collections for ergonomic CRUD operations.\n *\n * @example\n * ```typescript\n * // Create a node\n * const person = await store.nodes.Person.create({ name: \"Alice\" });\n *\n * // Get by ID\n * const fetched = await store.nodes.Person.getById(person.id);\n *\n * // Find all\n * const people = await store.nodes.Person.find({ limit: 10 });\n * ```\n */\n get nodes(): GraphNodeCollections<G> {\n if (this.#nodeCollections === undefined) {\n this.#nodeCollections = createNodeCollectionsProxy(\n this.#graph,\n this.graphId,\n this.#registry,\n this.#backend,\n this.#nodeOperations,\n );\n }\n\n return this.#nodeCollections;\n }\n\n /**\n * Edge collections for ergonomic CRUD operations.\n *\n * @example\n * ```typescript\n * // Create an edge\n * const edge = await store.edges.worksAt.create(\n * { kind: \"Person\", id: person.id },\n * { kind: \"Company\", id: company.id },\n * { role: \"Engineer\" }\n * );\n *\n * // Find edges from a node\n * const edges = await store.edges.worksAt.findFrom({ kind: \"Person\", id: person.id });\n * ```\n */\n get edges(): GraphEdgeCollections<G> {\n if (this.#edgeCollections === undefined) {\n this.#edgeCollections = createEdgeCollectionsProxy(\n this.#graph,\n this.graphId,\n this.#registry,\n this.#backend,\n this.#edgeOperations,\n );\n }\n\n return this.#edgeCollections;\n }\n\n // === Graph Algorithms ===\n\n /**\n * Tier 1 graph algorithms: shortest path, reachability, neighborhoods, and\n * degree centrality.\n *\n * Traversal calls use the iterative graph-operation substrate: a set-based\n * breadth-first frontier backed by a temporary working table, or a chunked\n * inline relation when the backend cannot pin a transactional connection.\n * `degree` uses a single count query. The facade is built lazily on first\n * access and cached for the lifetime of the store.\n *\n * @example\n * ```typescript\n * const path = await store.algorithms.shortestPath(alice, bob, {\n * edges: [\"knows\"],\n * });\n *\n * const friends = await store.algorithms.neighbors(alice, {\n * edges: [\"knows\"],\n * depth: 2,\n * });\n * ```\n */\n get algorithms(): GraphAlgorithms<G> {\n if (this.#algorithms === undefined) {\n this.#algorithms = createGraphAlgorithms<G>({\n graphId: this.graphId,\n graph: this.#graph,\n registry: this.#registry,\n backend: this.#backend,\n schema: this.#schema,\n recordedReadBinding: this.#recordedReadBinding,\n defaultTemporalMode: this.#graph.defaults.temporalMode,\n });\n }\n return this.#algorithms;\n }\n\n // === Dynamic Collection Access ===\n\n /**\n * Resolves `kind` against `collections` (either `this.nodes` or a\n * transaction-scoped — and possibly receipt-wrapped — node collection map),\n * or `undefined` when the kind is not registered in this graph. Shared by\n * `getNodeCollection` and both transaction contexts' `getNodeCollection` so\n * a receipt-wrapped transaction counts writes made through the dynamic\n * lookup exactly like `this.#graph.nodes` membership is checked everywhere\n * else.\n */\n #resolveDynamicNodeCollection(\n collections: GraphNodeCollections<G>,\n kind: string,\n ): DynamicNodeCollection | undefined {\n if (!Object.hasOwn(this.#graph.nodes, kind)) return undefined;\n return collections[\n kind as keyof G[\"nodes\"] & string\n ] as unknown as DynamicNodeCollection;\n }\n\n /**\n * Returns the node collection for the given kind, or undefined if the kind\n * is not registered in this graph.\n *\n * Use this for runtime string-keyed access when the kind is not known at\n * compile time (e.g., iterating all kinds, resolving from edge metadata,\n * dynamic admin UIs). For the post-evolve \"I just added this kind, give\n * me the collection\" pattern, prefer `getNodeCollectionOrThrow` — it\n * throws `KindNotFoundError` instead of forcing a null-check.\n */\n getNodeCollection(kind: string): DynamicNodeCollection | undefined {\n return this.#resolveDynamicNodeCollection(this.nodes, kind);\n }\n\n /**\n * Returns the node collection for the given kind. Throws\n * `KindNotFoundError` when the kind is not registered.\n *\n * The dominant graph-extension-kind access pattern: `await store.evolve(...)`\n * returns a new store, the caller immediately operates on the new\n * kind, and the null-check the optional variant requires is busywork.\n */\n getNodeCollectionOrThrow(kind: string): DynamicNodeCollection {\n const collection = this.getNodeCollection(kind);\n if (collection === undefined) {\n throw new KindNotFoundError(kind, \"node\", {\n graphId: this.graphId,\n });\n }\n return collection;\n }\n\n /**\n * Returns the edge collection for the given kind, or undefined if the kind\n * is not registered in this graph.\n *\n * Use this for runtime string-keyed access when the kind is not known at\n * compile time. For post-evolve access, prefer `getEdgeCollectionOrThrow`.\n */\n getEdgeCollection(kind: string): DynamicEdgeCollection | undefined {\n if (!Object.hasOwn(this.#graph.edges, kind)) return undefined;\n return this.edges[\n kind as keyof G[\"edges\"] & string\n ] as unknown as DynamicEdgeCollection;\n }\n\n /**\n * Returns the edge collection for the given kind. Throws\n * `KindNotFoundError` when the kind is not registered.\n */\n getEdgeCollectionOrThrow(kind: string): DynamicEdgeCollection {\n const collection = this.getEdgeCollection(kind);\n if (collection === undefined) {\n throw new KindNotFoundError(kind, \"edge\", {\n graphId: this.graphId,\n });\n }\n return collection;\n }\n\n // === Dynamic Props Schema Access ===\n\n /**\n * Returns the Zod props schema for the given node kind, or `undefined`\n * if the kind is not registered. Identity-preserving: returns the\n * exact instance used by `.create()` / `.update()`, so a `parse()`\n * surfaces the same underlying Zod issues that `ValidationError`\n * wraps (operation-level checks like uniqueness and endpoints stay\n * in `collection.create`).\n */\n getNodePropsSchema(kind: string): z.ZodObject<z.ZodRawShape> | undefined {\n if (!Object.hasOwn(this.#graph.nodes, kind)) return undefined;\n return requireDefined(this.#graph.nodes[kind]).type.schema;\n }\n\n /**\n * Returns the Zod props schema for the given node kind. Throws\n * `KindNotFoundError` when the kind is not registered.\n */\n getNodePropsSchemaOrThrow(kind: string): z.ZodObject<z.ZodRawShape> {\n const schema = this.getNodePropsSchema(kind);\n if (schema === undefined) {\n throw new KindNotFoundError(kind, \"node\", {\n graphId: this.graphId,\n });\n }\n return schema;\n }\n\n /**\n * Returns the Zod props schema for the given edge kind, or `undefined`\n * if the kind is not registered. Symmetric with `getNodePropsSchema`.\n */\n getEdgePropsSchema(kind: string): z.ZodObject<z.ZodRawShape> | undefined {\n if (!Object.hasOwn(this.#graph.edges, kind)) return undefined;\n return requireDefined(this.#graph.edges[kind]).type.schema;\n }\n\n /**\n * Returns the Zod props schema for the given edge kind. Throws\n * `KindNotFoundError` when the kind is not registered.\n */\n getEdgePropsSchemaOrThrow(kind: string): z.ZodObject<z.ZodRawShape> {\n const schema = this.getEdgePropsSchema(kind);\n if (schema === undefined) {\n throw new KindNotFoundError(kind, \"edge\", {\n graphId: this.graphId,\n });\n }\n return schema;\n }\n\n /**\n * Returns a unified read of the merged schema — every compile-time\n * and graph-extension kind, every edge, every ontology relation,\n * with explicit `origin: \"compile-time\" | \"runtime\"` markers — plus\n * the persisted `extension` for round-tripping.\n *\n * Pure synchronous read built from the in-memory graph and the\n * already-merged graph-extension document. `schemaVersion` and `schemaHash`\n * are populated when the loader cached them at construction or after\n * `evolve` returns; consumers needing a fresh read should call\n * `backend.getActiveSchema(graphId)`.\n *\n * The return shape is the canonical schema-introspection surface:\n * the prior standalone `store.deprecatedKinds` accessor is replaced\n * by `introspect().deprecatedKinds`.\n */\n introspect(): SchemaIntrospection {\n return introspectSchema(this.#graph, {\n graphId: this.graphId,\n schemaVersion: this.#schemaMetadata.schemaVersion,\n schemaHash: this.#schemaMetadata.schemaHash,\n });\n }\n\n /**\n * Node operations bound to this store instance.\n */\n get #nodeOperations(): NodeOperations {\n return this.#buildNodeOperations(this.#createNodeOperationContext());\n }\n\n /**\n * Refreshes planner statistics after an autocommit bulk write that\n * reached the configured row threshold. A refresh failure must never\n * fail the (already committed) write — it degrades to a warning.\n */\n async #maybeRefreshStatisticsAfterBulk(rowCount: number): Promise<void> {\n const configured = this.#options?.autoRefreshStatistics;\n if (configured === false) return;\n const threshold = configured ?? AUTO_REFRESH_STATISTICS_ROW_THRESHOLD;\n if (rowCount < threshold) return;\n try {\n await this.refreshStatistics();\n } catch (error) {\n console.warn(\n \"typegraph: statistics refresh after bulk write failed; run \" +\n \"store.refreshStatistics() to avoid stale planner statistics.\",\n error,\n );\n }\n }\n\n #buildNodeOperations(ctx: NodeOperationContext<G>): NodeOperations {\n return {\n defaultTemporalMode: this.#graph.defaults.temporalMode,\n rowToNode: (row) => rowToNode(row),\n maybeRefreshStatisticsAfterBulk: (rowCount) =>\n this.#maybeRefreshStatisticsAfterBulk(rowCount),\n executeCreate: (input, backend) => executeNodeCreate(ctx, input, backend),\n executeCreateBatch: (inputs, backend) =>\n executeNodeCreateBatch(ctx, inputs, backend),\n executeCreateNoReturnBatch: (inputs, backend) =>\n executeNodeCreateNoReturnBatch(ctx, inputs, backend),\n executeUpdate: (input, backend, options) =>\n executeNodeUpdate(ctx, { ...input, id: input.id }, backend, options),\n executeUpsertUpdate: (input, backend, options) =>\n executeNodeUpsertUpdate(\n ctx,\n { ...input, id: input.id },\n backend,\n options,\n ),\n // Present only when opted in; its absence is the coalesce off switch.\n ...(this.#options?.coalesceUnchangedUpserts === true && {\n upsertDirtyCheck: (kind, id, existingProps, inputProps) =>\n nodeUpsertDirtyCheck(ctx, kind, id, existingProps, inputProps),\n }),\n executeDelete: (kind, id, backend) =>\n executeNodeDelete(ctx, kind, id, backend),\n executeHardDelete: (kind, id, backend) =>\n executeNodeHardDelete(ctx, kind, id, backend),\n temporalRowMatcher: (options) => this.#temporalRowMatcher(options),\n createQuery: () => this.query(),\n executeGetOrCreateByConstraint: (\n kind,\n constraintName,\n props,\n backend,\n options,\n ) =>\n executeNodeGetOrCreateByConstraint(\n ctx,\n kind,\n constraintName,\n props,\n backend,\n options,\n ),\n executeBulkGetOrCreateByConstraint: (\n kind,\n constraintName,\n items,\n backend,\n options,\n ) =>\n executeNodeBulkGetOrCreateByConstraint(\n ctx,\n kind,\n constraintName,\n items,\n backend,\n options,\n ),\n executeFindByConstraint: (kind, constraintName, props, backend) =>\n executeNodeFindByConstraint(ctx, kind, constraintName, props, backend),\n executeBulkFindByConstraint: (kind, constraintName, items, backend) =>\n executeNodeBulkFindByConstraint(\n ctx,\n kind,\n constraintName,\n items,\n backend,\n ),\n executeBulkFindByIndex: (kind, indexName, items, backend, options) =>\n executeNodeBulkFindByIndex(\n ctx,\n kind,\n indexName,\n items,\n backend,\n options,\n ),\n };\n }\n\n /**\n * Edge operations bound to this store instance.\n */\n get #edgeOperations(): EdgeOperations {\n return this.#buildEdgeOperations(this.#createEdgeOperationContext());\n }\n\n #buildEdgeOperations(ctx: EdgeOperationContext<G>): EdgeOperations {\n return {\n defaultTemporalMode: this.#graph.defaults.temporalMode,\n rowToEdge: (row) => rowToEdge(row),\n maybeRefreshStatisticsAfterBulk: (rowCount) =>\n this.#maybeRefreshStatisticsAfterBulk(rowCount),\n executeCreate: (input, backend) => executeEdgeCreate(ctx, input, backend),\n executeCreateBatch: (inputs, backend) =>\n executeEdgeCreateBatch(ctx, inputs, backend),\n executeCreateNoReturnBatch: (inputs, backend) =>\n executeEdgeCreateNoReturnBatch(ctx, inputs, backend),\n executeUpdate: (input, backend) => executeEdgeUpdate(ctx, input, backend),\n executeUpsertUpdate: (input, backend, options) =>\n executeEdgeUpsertUpdate(ctx, input, backend, options),\n // Present only when opted in; its absence is the coalesce off switch.\n ...(this.#options?.coalesceUnchangedUpserts === true && {\n upsertDirtyCheck: (kind, id, existingProps, inputProps) =>\n edgeUpsertDirtyCheck(ctx, kind, id, existingProps, inputProps),\n }),\n executeDelete: (id, backend) => executeEdgeDelete(ctx, id, backend),\n executeHardDelete: (id, backend) =>\n executeEdgeHardDelete(ctx, id, backend),\n temporalRowMatcher: (options) => this.#temporalRowMatcher(options),\n createQuery: () => this.query(),\n executeGetOrCreateByEndpoints: (\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n props,\n backend,\n options,\n ) =>\n executeEdgeGetOrCreateByEndpoints(\n ctx,\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n props,\n backend,\n options,\n ),\n executeBulkGetOrCreateByEndpoints: (kind, items, backend, options) =>\n executeEdgeBulkGetOrCreateByEndpoints(\n ctx,\n kind,\n items,\n backend,\n options,\n ),\n executeFindByEndpoints: (\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n backend,\n options,\n ) =>\n executeEdgeFindByEndpoints(\n ctx,\n kind,\n fromKind,\n fromId,\n toKind,\n toId,\n backend,\n options,\n ),\n };\n }\n\n // === Query Builder ===\n\n /**\n * Creates a query builder for this store.\n *\n * @example\n * ```typescript\n * const results = await store.query()\n * .from(\"Person\", \"p\")\n * .whereNode(\"p\", (p) => p.name.eq(\"Alice\"))\n * .select((ctx) => ctx.p)\n * .execute();\n * ```\n */\n query(): InitialQueryBuilder<G, \"open\"> {\n return this.#createQueryForBackend(this.#backend);\n }\n\n /**\n * Internal seam for {@link StoreView.query}: a query builder pinned to a\n * view's {@link ReadCoordinate} with its temporal axis sealed\n * (`.temporal()` throws). Not part of the stable public API — construct a\n * view via {@link Store.view} / {@link Store.asOf} and call `.query()`.\n */\n sealedQuery(coordinate: ReadCoordinate): InitialQueryBuilder<G, \"sealed\"> {\n return this.#createQueryForBackend(\n this.#recordedReads.backendForCoordinate(coordinate, \"recorded-query\"),\n coordinate,\n );\n }\n\n #sqlSchema(): SqlSchema {\n return this.#schema ?? createSqlSchema(this.#backend.tableNames);\n }\n\n /**\n * Internal seam for {@link RecordedStoreView}: reconstruct a node point read\n * from the recorded-time relation while preserving live getById ordering and\n * duplicate-input behavior.\n *\n * @internal\n */\n async recordedNodeGetById<N extends NodeType>(\n kind: string,\n id: NodeId<N>,\n coordinate: ReadCoordinate,\n ): Promise<Node<N> | undefined> {\n return this.#recordedReads.nodeGetById(kind, id, coordinate);\n }\n\n /**\n * Internal seam for {@link RecordedStoreView}: reconstruct node point reads\n * from the recorded-time relation while preserving input order.\n *\n * @internal\n */\n async recordedNodeGetByIds<N extends NodeType>(\n kind: string,\n ids: readonly NodeId<N>[],\n coordinate: ReadCoordinate,\n ): Promise<readonly (Node<N> | undefined)[]> {\n return this.#recordedReads.nodeGetByIds(kind, ids, coordinate);\n }\n\n /** @internal Bounded recorded-time node enumeration for RecordedStoreView. */\n async recordedNodeScan<N extends NodeType>(\n kind: string,\n coordinate: ReadCoordinate,\n options?: RecordedScanOptions,\n ): Promise<RecordedScanPage<Node<N>>> {\n return this.#recordedReads.nodeScan(kind, coordinate, options);\n }\n\n /**\n * Internal seam for {@link RecordedStoreView}: reconstruct an edge point read\n * from the recorded-time relation while preserving live getById behavior.\n *\n * @internal\n */\n async recordedEdgeGetById<E extends AnyEdgeType>(\n kind: string,\n id: EdgeId<E>,\n coordinate: ReadCoordinate,\n ): Promise<Edge<E> | undefined> {\n return this.#recordedReads.edgeGetById(kind, id, coordinate);\n }\n\n /**\n * Internal seam for {@link RecordedStoreView}: reconstruct edge point reads\n * from the recorded-time relation while preserving input order.\n *\n * @internal\n */\n async recordedEdgeGetByIds<E extends AnyEdgeType>(\n kind: string,\n ids: readonly EdgeId<E>[],\n coordinate: ReadCoordinate,\n ): Promise<readonly (Edge<E> | undefined)[]> {\n return this.#recordedReads.edgeGetByIds(kind, ids, coordinate);\n }\n\n /** @internal Bounded recorded-time edge enumeration for RecordedStoreView. */\n async recordedEdgeScan<E extends AnyEdgeType>(\n kind: string,\n coordinate: ReadCoordinate,\n options?: RecordedScanOptions,\n ): Promise<RecordedScanPage<Edge<E>>> {\n return this.#recordedReads.edgeScan(kind, coordinate, options);\n }\n\n // === Temporal Views ===\n\n /**\n * Returns a read-only {@link StoreView} pinned to a valid-time instant.\n *\n * The view routes every supported read — `nodes` / `edges` collections,\n * `query()`, `subgraph()`, and the graph algorithms — through the\n * `asOf` coordinate, so they observe the graph as it was valid at `T`.\n * Writes stay on the live `Store`. Mirrors Datomic's `(d/as-of db t)`.\n *\n * @example\n * ```typescript\n * const past = store.asOf(\"2026-01-01T00:00:00.000Z\");\n * const alice = await past.nodes.Person.getById(aliceId);\n * const names = await past\n * .query()\n * .from(\"Person\", \"p\")\n * .whereNode(\"p\", (p) => p.name.eq(\"Alice\"))\n * .select((ctx) => ctx.p.name)\n * .execute();\n * ```\n *\n * @param asOf - ISO-8601 timestamp to pin the valid-time coordinate to.\n */\n asOf(asOf: string): StoreView<G> {\n return new StoreView(this, { mode: \"asOf\", asOf });\n }\n\n /**\n * Returns a narrow read-only view pinned to a recorded/system-time instant.\n *\n * Direct `store.asOfRecorded(T)` is diagonal bitemporal sugar: it reads the\n * recorded-time relation as of `T` and uses the same `T` for the valid-time\n * axis. Use `store.asOf(validT).asOfRecorded(recordedT)` when the valid and\n * recorded axes should differ.\n *\n * The returned view exposes only reconstructing-safe reads: query,\n * subgraph, graph algorithms, and collection point reads.\n *\n * Prefer `await store.recordedNow()` as the anchor over a wall-clock\n * timestamp: recorded instants are monotonic and can run briefly ahead of the\n * wall clock under bursty writes, so a `new Date().toISOString()` passed here\n * may sort before the most recent commits and silently omit them.\n */\n asOfRecorded(recordedAsOf: RecordedInstant): RecordedStoreView<G> {\n const validCoordinate = resolveReadCoordinate(\n \"asOf\",\n recordedAsOf,\n \"Use await store.recordedNow() as the anchor, or asRecordedInstant(value) only for an instant previously read from recordedNow().\",\n );\n return new RecordedStoreView(\n this,\n withRecordedCoordinate(validCoordinate, recordedAsOf),\n );\n }\n\n /**\n * Returns the latest recorded-time instant captured for this graph — the\n * recorded high-water mark. After guarding the `undefined` case,\n * `store.asOfRecorded(checkpoint)` reconstructs everything committed so far, a\n * deterministic anchor that avoids guessing with the wall clock (recorded\n * instants are monotonic and can run briefly ahead of wall-clock time under\n * bursty writes). Capture each anchor right after the writes it should cover.\n *\n * Returns `undefined` until the first write has been captured, so on a\n * brand-new graph guard the composition — `asOfRecorded(undefined)` rejects\n * (an instant is required) rather than reconstructing an empty view. Read the\n * value first and only pass it to `asOfRecorded` once it is defined.\n *\n * **Graph-global, not caller-scoped.** This is the single high-water mark for\n * the whole graph, advanced by every committed capture from any writer — not\n * a per-write or per-caller value. An advance between two reads means\n * \"something committed to this graph in between,\" *not* \"the write this caller\n * just made landed.\" Do not use a `recordedNow()` advance as a \"did my write\n * succeed?\" signal: under any concurrent writer to the same graph it both\n * misses dropped writes and misfires on no-op writes. Confirm a specific write\n * by observing the write itself (its return value, or `store.transaction(...)`\n * success), not the global clock.\n */\n async recordedNow(): Promise<RecordedInstant | undefined> {\n if (!this.#captureEnabled) {\n throw new ConfigurationError(\n \"recordedNow() requires a store created with { history: true }.\",\n { code: \"RECORDED_NOW_REQUIRES_HISTORY\" },\n {\n suggestion:\n \"Create the store with createStore(graph, backend, { history: true }) to enable recorded-time capture.\",\n },\n );\n }\n const recordedAt = await withRecordedRelationsPrecondition(\n readRecordedClock(this.#backend, this.#sqlSchema(), this.graphId),\n { dialect: this.#backend.dialect, surface: \"recorded-now\" },\n );\n // The clock high-water mark is already a canonical recorded instant; brand\n // it so `asOfRecorded` accepts it without the caller re-wrapping.\n return recordedAt === undefined ? undefined : asRecordedInstant(recordedAt);\n }\n\n /**\n * Returns the durable graph revision used by graph branching. It is undefined\n * until the first successful tracked write, which is itself a stable initial\n * anchor. Unlike {@link recordedNow}, this is also available on a live Store\n * created with `{ revisionTracking: true }`.\n *\n * @internal\n */\n async revisionNow(): Promise<string | undefined> {\n if (!this.#revisionTrackingEnabled) return undefined;\n return readRecordedClock(this.#backend, this.#sqlSchema(), this.graphId);\n }\n\n /**\n * Returns the durable random namespace for this graph's revision clock. A\n * tracked base token combines it with {@link revisionNow}, preventing a\n * branch from one independent store from matching a coincident timestamp in\n * another store.\n *\n * @internal\n */\n async revisionOriginNow(): Promise<string> {\n if (!this.#revisionTrackingEnabled) {\n throw new ConfigurationError(\n \"revisionOriginNow() requires revisionTracking: true or history: true.\",\n { code: \"REVISION_ORIGIN_REQUIRES_TRACKING\" },\n );\n }\n const pendingOrigin =\n this.#revisionOrigin ??\n ensureRevisionOrigin(this.#baseBackend, this.#sqlSchema(), this.graphId);\n this.#revisionOrigin = pendingOrigin;\n try {\n return await pendingOrigin;\n } catch (error) {\n // A transient DDL/connection failure must not permanently poison this\n // Store's cached initialization promise. Preserve a newer in-flight\n // attempt if another caller replaced it before this rejection arrived.\n if (this.#revisionOrigin === pendingOrigin) {\n this.#revisionOrigin = undefined;\n }\n throw error;\n }\n }\n\n /**\n * Returns a read-only {@link StoreView} pinned to an arbitrary public\n * temporal mode. Use {@link Store.asOf} for the common valid-time case;\n * reach for `view` to pin `\"current\"`, `\"includeEnded\"`, or\n * `\"includeTombstones\"`.\n *\n * @example\n * ```typescript\n * const withTombstones = store.view({ mode: \"includeTombstones\" });\n * const everyEverVersion = await withTombstones.nodes.Person.find();\n * ```\n *\n * @param coordinate - The `(mode, asOf)` coordinate to pin. `asOf` is\n * required when `mode` is `\"asOf\"` and rejected for every other mode.\n */\n view(coordinate: StoreViewCoordinate): StoreView<G> {\n return new StoreView(this, coordinate);\n }\n\n /**\n * Returns a read-only {@link StoreView} pinned to the current instant,\n * captured once at construction — a stable point-in-time snapshot. Unlike\n * `store.view({ mode: \"current\" })` (which tracks \"now\" live and can read\n * different surfaces against slightly different clocks), a snapshot pins one\n * `asOf` timestamp, so every surface observes the same instant. Sugar for\n * `store.asOf(new Date().toISOString())`; mirrors Datomic's `(d/db conn)`.\n *\n * @example\n * ```typescript\n * const snap = store.snapshot();\n * // Every read on `snap` sees the graph as of one fixed instant.\n * const a = await snap.nodes.Person.find();\n * const r = await snap.reachable(rootId, { edges: [\"knows\"] });\n * ```\n */\n snapshot(): StoreView<G> {\n return this.asOf(nowIso());\n }\n\n // === Search ===\n\n /**\n * Search-related operations (fulltext, hybrid, and rebuild).\n *\n * All search methods live under this facade to keep the top-level\n * Store API focused on CRUD + graph traversal. The facade is\n * lazy-initialized and cached for the lifetime of the store.\n *\n * @example\n * ```typescript\n * // Fulltext\n * const hits = await store.search.fulltext(\"Document\", {\n * query: \"climate warming\",\n * limit: 10,\n * includeSnippets: true,\n * });\n *\n * // Hybrid (vector + fulltext fused with RRF)\n * const ranked = await store.search.hybrid(\"Document\", {\n * limit: 10,\n * vector: { fieldPath: \"embedding\", queryEmbedding: vec },\n * fulltext: { query: \"climate warming\" },\n * });\n *\n * // Rebuild index after schema change\n * const stats = await store.search.rebuildFulltext();\n * ```\n */\n get search(): StoreSearch<G> {\n if (this.#search === undefined) {\n this.#search = new StoreSearch<G>({\n graphId: this.graphId,\n backend: this.#backend,\n registry: this.#registry,\n createQuery: () => this.query(),\n });\n }\n return this.#search;\n }\n\n // === Batch Query Execution ===\n\n /**\n * Executes multiple queries and returns a typed tuple of results.\n *\n * Each query preserves its own result type, projection, filtering, sorting,\n * and pagination.\n *\n * **Snapshot consistency is conditional.** When\n * `backend.capabilities.transactions` is `true`, queries run sequentially\n * on a single connection inside an implicit transaction and observe the\n * same database snapshot. When transactions are unavailable\n * (Cloudflare D1, `drizzle-orm/neon-http`), queries run sequentially over\n * independent connections and may observe writes that landed between them.\n * Branch on `backend.capabilities.transactions` if you need a guaranteed\n * snapshot.\n *\n * Read-only — use `bulkCreate`, `bulkInsert`, etc. for write batching.\n *\n * @example\n * ```typescript\n * const [people, companies] = await store.batch(\n * store.query()\n * .from(\"Person\", \"p\")\n * .select((ctx) => ({ id: ctx.p.id, name: ctx.p.name })),\n * store.query()\n * .from(\"Company\", \"c\")\n * .select((ctx) => ({ id: ctx.c.id, name: ctx.c.name }))\n * .orderBy(\"c\", \"name\", \"asc\")\n * .limit(5),\n * );\n * // people: readonly { id: string; name: string }[]\n * // companies: readonly { id: string; name: string }[]\n * ```\n *\n * @param queries - Two or more executable queries (from `.select()` or set operations)\n * @returns A tuple with per-query typed results, preserving input order\n */\n async batch<\n const Queries extends readonly [\n BatchableQuery<unknown>,\n BatchableQuery<unknown>,\n ...BatchableQuery<unknown>[],\n ],\n >(...queries: Queries): Promise<BatchResults<Queries>> {\n // batch() is read-only, so it routes through the uncaptured backend. Going\n // through the capture wrapper would open a recorded-capture transaction\n // scope — which demands executeStatement on the transaction target — for a\n // path that performs no writes and needs no capture.\n return runOptionallyInTransaction(this.#baseBackend, async (target) => {\n const results: unknown[] = [];\n for (const query of queries) {\n const result = await query.executeOn(target);\n results.push(result);\n }\n return results as BatchResults<Queries>;\n });\n }\n\n // === Subgraph Extraction ===\n\n /**\n * Extracts a typed subgraph by traversing from a root node.\n *\n * Performs a BFS traversal from `rootId` following the specified edge kinds,\n * returning an indexed result with adjacency maps for immediate traversal.\n *\n * @example\n * ```typescript\n * const sg = await store.subgraph(run.id, {\n * edges: [\"has_task\", \"runs_agent\", \"uses_skill\"],\n * maxDepth: 4,\n * });\n *\n * // Root node (the traversal starting point)\n * console.log(sg.root?.kind);\n *\n * // Lookup by ID\n * const task = sg.nodes.get(taskId);\n *\n * // Forward adjacency: edges of a kind from a node\n * const taskEdges = sg.adjacency.get(run.id)?.get(\"has_task\") ?? [];\n *\n * // Reverse adjacency: edges of a kind pointing to a node\n * const parentEdges = sg.reverseAdjacency.get(taskId)?.get(\"has_task\") ?? [];\n * ```\n */\n async subgraph<\n const EK extends EdgeKinds<G>,\n const NK extends NodeKinds<G> = NodeKinds<G>,\n const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n >(\n rootId: NodeId<AllNodeTypes<G>>,\n options: SubgraphOptions<G, EK, NK, P>,\n ): Promise<SubgraphResult<G, NK, EK, P>> {\n // The public surface is valid-time only (`recordedAsOf` is typed `never`).\n // Guard JS callers who bypass the type so a leaked recorded pin can't\n // silently switch this read onto the recorded relation; recorded subgraph\n // reads come through subgraphAtCoordinate (store.asOfRecorded(...).subgraph).\n assertNoRecordedCoordinate(options, {\n code: \"SUBGRAPH_RECORDED_ASOF_INTERNAL_ONLY\",\n message:\n \"recordedAsOf is only available through store.asOfRecorded(...).subgraph(...).\",\n suggestion:\n \"Use store.asOfRecorded(recordedAt).subgraph(rootId, options) instead of passing recordedAsOf directly.\",\n });\n // After the guard, the public read is just the coordinate path with no\n // recorded pin — delegate so the executeSubgraph wiring lives in one place.\n return this.subgraphAtCoordinate(rootId, options);\n }\n\n /**\n * Internal seam for {@link StoreView} / {@link RecordedStoreView}: runs a\n * subgraph with a coordinate already flattened into the options (including a\n * recorded/system-time pin). Trusted caller — the public {@link Store.subgraph}\n * is the guarded entry point.\n *\n * @internal\n */\n subgraphAtCoordinate<\n const EK extends EdgeKinds<G>,\n const NK extends NodeKinds<G> = NodeKinds<G>,\n const P extends SubgraphProject<G, NK, EK> | undefined = undefined,\n >(\n rootId: NodeId<AllNodeTypes<G>>,\n options: InternalSubgraphOptions<G, EK, NK, P>,\n ): Promise<SubgraphResult<G, NK, EK, P>> {\n const coordinate = resolveReadCoordinate(\n options.temporalMode ?? this.#graph.defaults.temporalMode,\n options.asOf,\n );\n const readCoordinate =\n options.recordedAsOf === undefined ?\n coordinate\n : withRecordedCoordinate(coordinate, options.recordedAsOf);\n return executeSubgraph({\n graph: this.#graph,\n graphId: this.graphId,\n rootId,\n backend: this.#recordedReads.backendForCoordinate(\n readCoordinate,\n \"recorded-subgraph\",\n ),\n dialect: getDialect(this.#backend.dialect),\n schema: this.#schema,\n recordedReadBinding: this.#recordedReadBinding,\n options,\n });\n }\n\n /**\n * Internal seam for StoreView graph algorithms at a pinned coordinate.\n *\n * @internal\n */\n algorithmsAtCoordinate(\n coordinate: ReadCoordinate,\n ): InternalGraphAlgorithms<G> {\n return createGraphAlgorithms<G>({\n graphId: this.graphId,\n graph: this.#graph,\n registry: this.#registry,\n backend: this.#recordedReads.backendForCoordinate(\n coordinate,\n \"recorded-graph-algorithm\",\n ),\n schema: this.#schema,\n recordedReadBinding: this.#recordedReadBinding,\n defaultTemporalMode: this.#graph.defaults.temporalMode,\n allowRecordedAsOf: coordinate.recorded !== undefined,\n });\n }\n\n // === Transactions ===\n\n /**\n * Executes a function within a transaction.\n *\n * The transaction context provides the same collection API as the Store:\n * - `tx.nodes.Person.create(...)` - Create a node\n * - `tx.edges.worksAt.create(...)` - Create an edge\n * - `tx.backend` - a read-only backend projection bound to this transaction\n *\n * {@link AdapterStore} transaction callbacks additionally expose `tx.sql`,\n * the adapter-native handle bound to the same atomic boundary. Branch on\n * `tx.sqlAvailability`: `\"available\"` carries the handle and `\"unavailable\"`\n * carries `undefined`. History and revision-tracking contexts make `tx.sql`\n * unusable in their public types; reflective or type-suppressed runtime\n * access throws because raw SQL would bypass capture or the revision anchor.\n * Use typed collections or {@link AdapterStore.withRecordedTransaction} in\n * those modes.\n *\n * @example\n * ```typescript\n * await store.transaction(async (tx) => {\n * const person = await tx.nodes.Person.create({ name: \"Alice\" });\n * const company = await tx.nodes.Company.create({ name: \"Acme\" });\n * await tx.edges.worksAt.create(\n * { kind: \"Person\", id: person.id },\n * { kind: \"Company\", id: company.id },\n * { role: \"Engineer\" }\n * );\n * });\n * ```\n *\n * @example Cross-store write via `tx.sql` (graph-owned boundary):\n * ```typescript\n * await store.transaction(async (tx) => {\n * await tx.nodes.Document.update(documentId, props);\n * if (tx.sqlAvailability !== \"available\") {\n * throw new Error(\"This operation requires a SQL-backed transaction\");\n * }\n * // Narrowing makes the precisely typed native handle available.\n * const sqlTx = tx.sql as NodePgDatabase;\n * await sqlTx.insert(documentVersions).values(versionRow);\n * });\n * ```\n *\n * **`tx.sql` shares the one pinned connection — await it, don't overlap it.**\n * TypeGraph serializes the statements *its own* collections issue, so a\n * `Promise.all` of graph writes is safe. A statement you issue through\n * `tx.sql` bypasses that queue: run it concurrently with a graph write (or\n * with another `tx.sql` statement) and two queries race on the one\n * transaction connection — the exact overlap Postgres removes in `pg@9`.\n * Await each `tx.sql` statement before starting the next write. TypeGraph\n * cannot police this: it never sees the raw handle's traffic, so it also\n * cannot drain a raw statement still in flight when the transaction commits.\n *\n * **Backends without transactions.** When `backend.capabilities.transactions`\n * is `false` (Cloudflare D1, `drizzle-orm/neon-http`), this method runs the\n * callback against the same backend used outside `transaction()` — writes\n * are applied as they happen and a thrown error does **not** roll back\n * earlier writes inside the callback. Branch on\n * `backend.capabilities.transactions` if you require atomicity:\n *\n * ```typescript\n * if (backend.capabilities.transactions) {\n * await store.transaction(async (tx) => { ... });\n * } else {\n * // sequential, non-atomic — handle partial-failure recovery yourself\n * }\n * ```\n *\n * @param fn The callback run inside the transaction boundary.\n * @param options Optional {@link TransactionOptions} forwarded to the\n * backend (e.g. `isolationLevel: \"serializable\"` on Postgres). Backends\n * without isolation-level support ignore it; the non-transactional\n * fallback ignores it entirely. Stores created with `{ history: true }`\n * require read-committed semantics for PostgreSQL recorded-clock capture and\n * reject stronger snapshot isolation levels.\n */\n transaction<T>(\n this: AdapterHistoryStore<G, TNativeTransaction>,\n fn: (\n tx: AdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<T>;\n\n transaction<T>(\n fn: (tx: AdapterTransactionContext<G, TNativeTransaction>) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<T>;\n\n async transaction<T>(\n fn:\n | ((tx: AdapterTransactionContext<G, TNativeTransaction>) => Promise<T>)\n | ((\n tx: AdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>),\n options?: TransactionOptions,\n ): Promise<T> {\n const invoke = fn as (\n tx: AdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>;\n const { result } = await this.#runTransaction(invoke, options, undefined);\n return result;\n }\n\n /**\n * Runs a transaction exactly like {@link transaction} and additionally\n * returns a {@link TransactionOutcome} whose receipt summarizes the\n * completed write intents on the transaction-scoped collection surface.\n *\n * A dedicated method (rather than an option on `transaction()`) keeps the\n * return type tied to static dispatch: forwarding options through wrappers\n * can never change what a call returns. See {@link TransactionReceipt} for\n * exact count semantics.\n *\n * The receipt does not count writes that bypass the `tx.nodes.*` /\n * `tx.edges.*` collections, such as direct backend writes, raw SQL, or\n * import helpers. The adopted-commit sibling\n * {@link AdapterStore.withRecordedTransaction} also returns a\n * {@link TransactionOutcome}; only `withTransaction` (whose commit belongs\n * entirely to the caller with no flush point) produces no receipt. On\n * non-transactional backends, the receipt is still returned, but it describes\n * operations that individually committed rather than one atomic commit; if the\n * callback rejects on such a backend, no receipt is returned even though\n * earlier operations committed individually.\n *\n * For stores created with `{ history: true }`, `receipt.recorded` is the\n * recorded commit instant this transaction allocated for the store's\n * graph, or `undefined` when nothing was captured.\n *\n * The callback receives a {@link MeasurableTransactionContext}: call\n * `tx.measure((scoped) => ...)` to scope a sub-receipt to the writes made\n * through the `scoped` context (e.g. to attribute writes to user code the\n * caller invokes, excluding its own bookkeeping written through `tx`). See\n * {@link MeasurableTransactionContext} for semantics.\n *\n * @example\n * ```typescript\n * const outcome = await store.transactionWithReceipt(async (tx) => {\n * const alice = await tx.nodes.Person.create({ name: \"Alice\" });\n * return alice.id;\n * });\n * outcome.result; // Alice's id\n * outcome.receipt.writes; // { nodes: { Person: 1 }, edges: {}, total: 1 }\n * ```\n */\n transactionWithReceipt<T>(\n this: AdapterHistoryStore<G, TNativeTransaction>,\n fn: (\n tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<TransactionOutcome<T>>;\n\n transactionWithReceipt<T>(\n fn: (\n tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<TransactionOutcome<T>>;\n\n async transactionWithReceipt<T>(\n fn:\n | ((\n tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>)\n | ((\n tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>),\n options?: TransactionOptions,\n ): Promise<TransactionOutcome<T>> {\n const invoke = fn as (\n tx: AdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>;\n const receiptRecorder = createTransactionReceiptRecorder();\n const { result, recordedByGraph } = await this.#runTransaction(\n invoke,\n options,\n receiptRecorder,\n );\n return transactionOutcome(\n result,\n receiptRecorder,\n recordedByGraph,\n this.graphId,\n );\n }\n\n async #runTransaction<T>(\n invoke: (\n tx: AdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n backendOptions: TransactionOptions | undefined,\n receiptRecorder: TransactionReceiptRecorder | undefined,\n ): Promise<TransactionRunResult<T>> {\n // Without a real transaction the tx-scoped collections would be\n // bound to the same backend as this.nodes/this.edges and exposing\n // the cached versions avoids rebuilding the proxies on every call.\n // An isolation-level request in the options is equally meaningless here.\n if (!this.#backend.capabilities.transactions) {\n let nodes = this.nodes;\n let edges = this.edges;\n if (receiptRecorder !== undefined) {\n ({ nodes, edges } = wrapTransactionCollections(\n nodes,\n edges,\n receiptRecorder,\n ));\n }\n const fallbackContext: AdapterTransactionContext<G, TNativeTransaction> =\n {\n nodes,\n edges,\n // No real transaction: `tx.sql` is absent and there is no atomicity.\n sqlAvailability: \"unavailable\",\n backend: createTransactionReadBackend(this.#backend),\n [TRANSACTION_RUNTIME]: {\n backend: this.#backend,\n runNodeOperationHooks: (operation, kind, id, hookedFunction) =>\n this.#withOperationHooks(\n this.#createOperationContext(operation, \"node\", kind, id),\n hookedFunction,\n ),\n },\n getNodeCollection: (kind: string) =>\n this.#resolveDynamicNodeCollection(nodes, kind),\n };\n Object.defineProperty(fallbackContext, TRANSACTION_RUNTIME, {\n configurable: false,\n enumerable: false,\n writable: false,\n });\n // `measure` on this non-transactional fallback scopes writes that\n // individually committed rather than one atomic commit, mirroring the\n // receipt caveat.\n const result = await invoke(\n receiptRecorder === undefined ? fallbackContext : (\n this.#attachMeasure(fallbackContext)\n ),\n );\n return { result, recordedByGraph: undefined };\n }\n\n // #134/#135: no gate here. The backend's transaction() wraps the\n // tx-scoped fulltext methods so the durable-marker assert fires at\n // point of use (a cached SELECT, never DDL). A transaction that\n // never touches fulltext requires no fulltext initialization.\n //\n // No per-graph write lock here either: under history capture the lock is\n // taken at each write boundary (runInWriteTransaction before any row work;\n // the recorded overlay before each row write), so a transaction whose\n // callback only reads never serializes against writers. Callers that need\n // read-before-write serialization across the whole callback (provenance\n // transitions) acquire the lock explicitly at callback start.\n //\n // Operation hooks inside the callback run BUFFERED: an operation nested\n // in this transaction completes only when the transaction commits, so its\n // onOperationEnd is held back until after COMMIT — and converted into\n // onError when the transaction fails — keeping \"success\" synonymous with\n // \"durable\" even for tx-scoped collection operations.\n const pending: PendingOperationOutcome[] = [];\n const runHooks = this.#createBufferedHookRunner(pending);\n let recordedByGraph: RecordedFlushInstants | undefined;\n const transactionOptions =\n receiptRecorder !== undefined && this.#captureEnabled ?\n withRecordedFlushObserver(backendOptions, (instants) => {\n recordedByGraph = instants;\n })\n : backendOptions;\n try {\n const run = async (\n txBackend: TransactionBackend,\n nativeTransaction: TNativeTransaction | undefined,\n ): Promise<T> =>\n invoke(\n this.#buildTransactionContext(\n txBackend,\n nativeTransaction,\n runHooks,\n receiptRecorder,\n ),\n );\n const result =\n this.#captureEnabled || this.#adapterBackend === undefined ?\n await this.#backend.transaction(\n (txBackend) => run(txBackend, undefined),\n transactionOptions,\n )\n : await this.#adapterBackend.transactionWithNative(\n (txBackend, nativeTransaction) => run(txBackend, nativeTransaction),\n transactionOptions,\n );\n for (const outcome of pending) {\n this.#hooks.onOperationEnd?.(outcome.ctx, {\n durationMs: outcome.durationMs,\n });\n }\n return { result, recordedByGraph };\n } catch (error) {\n const failure = asError(error);\n for (const outcome of pending) {\n this.#hooks.onError?.(outcome.ctx, failure);\n }\n throw error;\n }\n }\n\n /**\n * Adopts a caller-owned, already-open Drizzle transaction so the graph\n * store and the caller's relational writes commit or roll back as one\n * Postgres/SQLite transaction (#134).\n *\n * Use this when the **relational layer owns the transaction**: the\n * caller has opened a transaction and needs TypeGraph writes enlisted\n * on the *same* connection. Unlike {@link transaction}, this opens no\n * transaction — the caller's transaction is the single commit/rollback\n * boundary.\n *\n * `withTransaction` is driver-agnostic; how the caller opens the\n * transaction is not. **Async drivers** (node-postgres,\n * `neon-serverless` Pool, libsql) use `db.transaction(async …)`.\n * **Synchronous `better-sqlite3`** cannot — its driver rejects an\n * `async` transaction callback (`Transaction function cannot return a\n * promise`) and the async continuation would run outside the\n * rolled-back transaction — so the caller opens the transaction with\n * explicit `BEGIN`/`COMMIT`/`ROLLBACK` on the single connection\n * instead. See the \"Cross-Store Transactions\" recipe for both shapes.\n *\n * The returned context reuses this store's already-resolved\n * schema/registry: it runs **no** schema bootstrap, `evolve`, or\n * migration, and emits **no DDL** inside the caller's transaction.\n * Fulltext operations assert the durable materialization marker (a\n * cached SELECT) and throw {@link StoreNotInitializedError} on a\n * missing/stale/failed marker rather than migrating mid-transaction —\n * so boot the parent store via `createAdapterStoreWithSchema` once at\n * startup.\n *\n * @example\n * ```typescript\n * // Async driver (Postgres / libsql):\n * await db.transaction(async (sqlTx) => {\n * const connector = await createConnectorRow(sqlTx, input); // Drizzle\n * const txStore = store.withTransaction(sqlTx);\n * await txStore.nodes.ArtifactSource.create({ // TypeGraph\n * connectorId: connector.id,\n * });\n * }); // one COMMIT / ROLLBACK across both layers\n * ```\n *\n * **The caller owns the connection — don't overlap writes on it.** The graph\n * store and your Drizzle writes share the one connection the caller's\n * transaction pinned. TypeGraph serializes the statements *its* collections\n * issue, but your raw Drizzle statements (and any graph write run alongside\n * them) are yours to sequence: a `Promise.all` mixing the two races two\n * queries on that connection — the overlap Postgres removes in `pg@9`. Await\n * each write before starting the next.\n *\n * Not available when the store was created with `{ history: true }`: a\n * caller-owned transaction context would let writes happen after capture has\n * lost its flush point. {@link AdapterHistoryStore} omits this method, while\n * the runtime guard still throws `ConfigurationError` if the public contract\n * is bypassed\n * (`RECORDED_CAPTURE_REQUIRES_CALLBACK_TRANSACTION`) if the check is\n * suppressed. Use {@link AdapterStore.withRecordedTransaction} on a history-enabled\n * store, which adopts the same external transaction but flushes recorded-time\n * capture before the caller commits.\n *\n * @throws {ConfigurationError} when the store has history capture enabled\n * (use {@link AdapterStore.withRecordedTransaction} instead), or when the backend\n * cannot adopt an external transaction — either it is not a Drizzle\n * Postgres/SQLite backend, or `backend.capabilities.transactions` is `false`\n * (`drizzle-orm/neon-http`, Cloudflare D1, SQLite\n * `transactionMode: \"none\"`). A non-atomic fallback is deliberately\n * not offered here: the caller's relational write *would* still\n * commit, defeating the purpose of cross-store atomicity.\n * @throws {StoreNotInitializedError} at point of use, when a fulltext\n * operation on the returned context observes a missing/stale/failed\n * durable materialization marker (parent store not booted via\n * `createAdapterStoreWithSchema`). Rolls back the caller's transaction\n * without emitting any DDL.\n */\n withTransaction(\n externalTx: TNativeTransaction,\n ): AdapterTransactionContext<G, TNativeTransaction> {\n if (this.#captureEnabled) {\n throw recordedCaptureRequiresCallbackTransactionError();\n }\n const adopt = this.#adapterBackend?.adoptTransaction;\n if (adopt === undefined) {\n throw new ConfigurationError(\n \"This backend cannot adopt an external transaction for cross-store \" +\n \"atomicity. adoptTransaction is provided only by the Drizzle \" +\n \"Postgres/SQLite backends with transaction support. Check \" +\n \"backend.capabilities.transactions, or run the relational and \" +\n \"graph writes as separate transactions with manual compensation.\",\n { capability: \"adoptTransaction\" },\n );\n }\n // The caller already owns the boundary, so `externalTx` *is* the\n // bound handle — surface it as `tx.sql` for symmetry with the\n // graph-owned `transaction()` path.\n return this.#buildTransactionContext(adopt(externalTx), externalTx);\n }\n\n /**\n * Adopts a caller-owned transaction while giving recorded-time capture a\n * flush point before the caller commits. Required when `history: true` is\n * enabled because returning a long-lived transaction context would let writes\n * happen after TypeGraph has lost the chance to close/open recorded rows.\n *\n * Capture flushes once, when `fn` resolves. The flush seals the capture\n * session, so a graph write made through the transaction context *after* `fn`\n * returns (e.g. retaining `tx` and writing once more before the caller's\n * COMMIT) throws rather than committing uncaptured — the post-flush write\n * cannot silently diverge history from live state. This sealing behavior is\n * unchanged by the receipt return.\n *\n * Returns a {@link TransactionOutcome} — the adopted path is the only way to\n * get exactly-once cursors and graph writes atomically on a history store, so\n * it surfaces the same receipt `transactionWithReceipt` does: `receipt.writes`\n * for drop detection (a non-delete change that wrote nothing) and\n * `receipt.recorded` as the per-transaction replay anchor. Destructure\n * `{ result, receipt }`:\n *\n * ```typescript\n * const { result, receipt } = await store.withRecordedTransaction(\n * externalTx,\n * async (tx) => tx.nodes.Document.update(documentId, props),\n * );\n * ```\n *\n * `receipt.recorded` is the recorded commit instant this transaction allocated\n * for the store's graph at the flush point (when `fn` resolved), and is\n * `undefined` when nothing was captured — a read-only `fn`, or a non-history\n * store (where the receipt still counts write intents but there is no recorded\n * time). To attribute writes when `fn` invokes user code that also\n * bookkeeps, use `tx.measure((scoped) => ...)` and have that code write\n * through the `scoped` context (see {@link MeasurableTransactionContext}).\n *\n * Write your own relational tables through the **external transaction handle\n * you passed in** (`externalTx`) — it *is* the pinned connection. `tx.sql` is\n * unavailable here (it is a fail-loud guard under history capture, since raw\n * SQL bypasses recorded-time capture, and `AdapterHistoryTransactionContext` types it\n * `sql?: never`). Writing through `externalTx` is the sanctioned way to get\n * cross-store atomicity on a history-enabled store:\n *\n * ```typescript\n * // Async driver (Postgres / libsql):\n * await db.transaction(async (pgTx) => {\n * const { receipt } = await store.withRecordedTransaction(pgTx, async (tx) => {\n * await tx.nodes.Document.update(documentId, props); // graph write\n * });\n * await pgTx.insert(streamCursors).values(cursorRow); // your own table\n * }); // one COMMIT / ROLLBACK across both layers\n * ```\n *\n * The graph writes and your `externalTx` statements share the caller's one\n * pinned connection. TypeGraph serializes the statements its collections\n * issue; sequence your own raw statements (and don't `Promise.all` them with\n * graph writes) so two queries never race on that connection.\n */\n withRecordedTransaction<T>(\n this: AdapterHistoryStore<G, TNativeTransaction>,\n externalTx: TNativeTransaction,\n fn: (\n tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n ): Promise<TransactionOutcome<T>>;\n\n withRecordedTransaction<T>(\n externalTx: TNativeTransaction,\n fn: (\n tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n ): Promise<TransactionOutcome<T>>;\n\n async withRecordedTransaction<T>(\n externalTx: TNativeTransaction,\n fn:\n | ((\n tx: MeasurableAdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>)\n | ((\n tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>),\n ): Promise<TransactionOutcome<T>> {\n const adopt = this.#adapterBackend?.adoptTransaction;\n if (adopt === undefined) {\n throw new ConfigurationError(\n \"This backend cannot adopt an external transaction for recorded-time capture.\",\n { capability: \"adoptTransaction\" },\n {\n suggestion:\n \"Use a Drizzle PostgreSQL/SQLite backend with transaction support, or run writes through store.transaction(...).\",\n },\n );\n }\n const txBackend = adopt(externalTx);\n if (this.#captureEnabled) {\n await assertRecordedCaptureTransactionIsolation(txBackend);\n }\n // A uniform `flush → RecordedFlushInstants` shape on both branches keeps the\n // outcome-building path identical; the non-history branch has no recorded\n // rows to close, so it flushes to an empty instant map.\n const scope =\n this.#captureEnabled ?\n createRecordedTransactionScope(txBackend, this.#sqlSchema())\n : {\n backend: txBackend,\n flush: (): Promise<RecordedFlushInstants> =>\n Promise.resolve(EMPTY_RECORDED_FLUSH_INSTANTS),\n };\n if (this.#captureEnabled) {\n await lockRecordedGraphWrite(scope.backend, this.graphId);\n }\n const receiptRecorder = createTransactionReceiptRecorder();\n const invoke = fn as (\n tx: AdapterTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>;\n const result = await invoke(\n this.#buildTransactionContext(\n scope.backend,\n externalTx,\n undefined,\n receiptRecorder,\n ),\n );\n // Flush allocates the recorded commit instant for this transaction's graph;\n // `transactionOutcome` reads this store's instant out of the returned map\n // (undefined when nothing was captured) into `receipt.recorded`.\n const recordedByGraph = await scope.flush();\n // Seal the context so a write through a retained `tx` after this returns\n // fails loud instead of persisting a row the snapshotted receipt can't\n // count. Under history capture the capture session already sealed on flush\n // (its guard throws before the live write); this covers the non-history\n // path, which has no capture session.\n if (!this.#captureEnabled) receiptRecorder.seal();\n return transactionOutcome(\n result,\n receiptRecorder,\n recordedByGraph,\n this.graphId,\n );\n }\n\n /**\n * Decorates a receipt-enabled transaction `context` with `measure`.\n * Attribution is structural: `measure` wraps the context's *own* (already\n * outer-recording) collections a second time with a fresh scope recorder, so a\n * write through the scoped context counts in the scope and — via the inner\n * wrapper it delegates to — the outer receipt, while a write through the outer\n * `context` never reaches the scope recorder. This makes overlapping/concurrent\n * measures safe by construction (each holds its own scope recorder) and lets\n * scopes nest: the scoped context is itself decorated, so `scoped.measure(...)`\n * chains one more wrapper. The scoped context's `getNodeCollection` resolves\n * against the scope-wrapped map too, so dynamic-kind writes are attributed like\n * `scoped.nodes.<Kind>`. The scope receipt's `recorded` is always undefined —\n * the recorded instant is a whole-transaction flush concern.\n */\n #attachMeasure(\n context: AdapterTransactionContext<G, TNativeTransaction>,\n ): MeasurableAdapterTransactionContext<G, TNativeTransaction> {\n const measure: ScopedMeasure<\n MeasurableAdapterTransactionContext<G, TNativeTransaction>\n > = async (fn) => {\n const scopeRecorder = createTransactionReceiptRecorder();\n const { nodes, edges } = wrapTransactionCollections(\n context.nodes,\n context.edges,\n scopeRecorder,\n );\n const scoped = this.#attachMeasure(\n overlayPropertyDescriptors(context, {\n nodes,\n edges,\n getNodeCollection: (kind: string) =>\n this.#resolveDynamicNodeCollection(nodes, kind),\n }),\n );\n const result = await fn(scoped);\n return { result, receipt: scopeRecorder.snapshot() };\n };\n return overlayPropertyDescriptors(context, { measure });\n }\n\n /**\n * Builds the `{ nodes, edges, sql }` projection bound to a\n * transaction-scoped backend. Shared verbatim by {@link transaction}\n * (TypeGraph opens the tx) and {@link withTransaction} (#134 — the\n * caller opened it) so both surfaces resolve collections, query\n * factories, and the reused graph/registry identically. When history capture\n * is disabled, `sql` is the raw Drizzle handle bound to the same transaction\n * (#140); when history capture is enabled it is replaced with a fail-loud\n * guard because raw graph writes would bypass recorded-time capture.\n */\n #buildTransactionContext(\n txBackend: TransactionBackend,\n sql?: TNativeTransaction,\n runHooks: OperationHookRunner = this.#immediateHookRunner(),\n receiptRecorder?: TransactionReceiptRecorder,\n ): AdapterTransactionContext<G, TNativeTransaction> {\n // No statistics auto-refresh inside a caller-provided transaction:\n // ANALYZE from another connection cannot see the uncommitted rows,\n // so it would only reset the counter without fixing the estimates.\n const txNodeOperations: NodeOperations = {\n ...this.#buildNodeOperations(this.#createNodeOperationContext(runHooks)),\n createQuery: () => this.#createQueryForBackend(txBackend),\n maybeRefreshStatisticsAfterBulk: undefined,\n };\n const txEdgeOperations: EdgeOperations = {\n ...this.#buildEdgeOperations(this.#createEdgeOperationContext(runHooks)),\n createQuery: () => this.#createQueryForBackend(txBackend),\n maybeRefreshStatisticsAfterBulk: undefined,\n };\n\n const runNodeOperationHooks = <T>(\n operation: \"create\" | \"update\" | \"delete\",\n kind: string,\n id: string,\n fn: () => Promise<T>,\n ): Promise<T> =>\n runHooks(this.#createOperationContext(operation, \"node\", kind, id), fn);\n\n let nodes = createNodeCollectionsProxy(\n this.#graph,\n this.graphId,\n this.#registry,\n txBackend,\n txNodeOperations,\n );\n\n let edges = createEdgeCollectionsProxy(\n this.#graph,\n this.graphId,\n this.#registry,\n txBackend,\n txEdgeOperations,\n );\n\n if (receiptRecorder !== undefined) {\n ({ nodes, edges } = wrapTransactionCollections(\n nodes,\n edges,\n receiptRecorder,\n ));\n }\n\n const getNodeCollection = (\n kind: string,\n ): DynamicNodeCollection | undefined =>\n this.#resolveDynamicNodeCollection(nodes, kind);\n\n // Honest capability discriminant for `tx.sql`. Capture/revision tracking\n // take precedence because they replace `tx.sql` with a fail-loud guard even\n // though the transaction itself is real; only a genuinely absent handle is\n // \"unavailable\" (this method runs on transactional backends — the\n // non-transactional fallback context is built in #runTransaction).\n const base = {\n nodes,\n edges,\n backend: createTransactionReadBackend(txBackend),\n [TRANSACTION_RUNTIME]: { backend: txBackend, runNodeOperationHooks },\n getNodeCollection,\n };\n\n let withSql: AdapterTransactionContext<G, TNativeTransaction>;\n if (this.#captureEnabled) {\n withSql = {\n ...base,\n sqlAvailability: \"history\",\n };\n defineUnavailableSqlGuard(withSql, () => throwHistoryUnsafeSqlAccess());\n } else if (this.#revisionTrackingEnabled) {\n withSql = {\n ...base,\n sqlAvailability: \"revisionTracking\",\n };\n defineUnavailableSqlGuard(withSql, () =>\n throwRevisionTrackingUnsafeSqlAccess(),\n );\n } else if (sql === undefined) {\n withSql = { ...base, sqlAvailability: \"unavailable\" };\n } else {\n withSql = { ...base, sql, sqlAvailability: \"available\" };\n }\n Object.defineProperty(withSql, TRANSACTION_RUNTIME, {\n configurable: false,\n enumerable: false,\n writable: false,\n });\n\n // Scoped write measurement (`tx.measure`) is only meaningful with a recorder\n // to scope; the plain `transaction()` path stays free of a `measure` the\n // caller has no receiver for.\n return receiptRecorder === undefined ? withSql : (\n this.#attachMeasure(withSql)\n );\n }\n\n // === Graph Lifecycle ===\n\n /**\n * Hard-deletes all data for this graph from the database.\n *\n * Removes all nodes, edges, uniqueness entries, embeddings, and schema versions\n * for this graph's ID. No hooks, no per-row logic. Wrapped in a transaction\n * when the backend supports it.\n *\n * The store is usable after clearing — new data can be created immediately.\n */\n async clear(): Promise<void> {\n const doClear = async (\n target: GraphBackend | TransactionBackend,\n ): Promise<void> => {\n if (this.#revisionTrackingEnabled) {\n await lockRecordedGraphWrite(target, this.graphId);\n }\n const previousRevision =\n this.#revisionTrackingEnabled && !this.#captureEnabled ?\n await readRecordedClock(target, this.#sqlSchema(), this.graphId)\n : undefined;\n await target.clearGraph(this.graphId);\n // `clearGraph` deletes the recorded-clock row alongside graph data.\n // Live revision tracking immediately seeds a fresh anchor so a pre-clear\n // branch cannot match a now-empty graph. History capture intentionally\n // preserves its long-standing `recordedNow() === undefined` clear\n // contract; a pre-clear history branch already carries a non-empty clock\n // value and therefore still fails the base-version precondition.\n if (this.#revisionTrackingEnabled && !this.#captureEnabled) {\n await advanceRevisionClock(\n target,\n this.#sqlSchema(),\n this.graphId,\n this.#baseBackend.capabilities.transactions,\n previousRevision,\n );\n }\n };\n\n await (this.#baseBackend.capabilities.transactions ?\n this.#baseBackend.transaction(async (tx) => doClear(tx))\n : doClear(this.#baseBackend));\n\n // `clearGraph` is graph-agnostic and can't reach the strategy-owned\n // per-`(kind, field)` vector tables, so reset them here — otherwise cleared\n // embeddings leak and a reused node id would resurface a stale vector.\n await this.#clearVectorStorage();\n\n // Reset lazy-initialized collection caches\n this.#nodeCollections = undefined;\n this.#edgeCollections = undefined;\n this.#algorithms = undefined;\n this.#search = undefined;\n }\n\n /**\n * Resets every declared embedding field's per-field storage for this graph by\n * dropping and recreating it empty. Drop+recreate (rather than DELETE) mirrors\n * `reembedVectorField` and keeps the backend's storage-ensure latch valid: the\n * table still exists after clear, so a later write finds it. Enumerated from\n * the in-memory registry (not the DB schema, which `clearGraph` just wiped).\n */\n async #clearVectorStorage(): Promise<void> {\n const backend = this.#baseBackend;\n const strategy = backend.vectorStrategy;\n if (strategy === undefined || backend.executeDdl === undefined) return;\n\n for (const [nodeKind, nodeType] of this.#registry.nodeKinds) {\n for (const field of resolveEmbeddingFields(nodeType.schema)) {\n const slot: VectorSlot = {\n graphId: this.graphId,\n nodeKind,\n fieldPath: field.fieldPath,\n dimensions: field.dimensions,\n metric: field.metric,\n indexType: field.indexType,\n };\n for (const ddl of strategy.buildDropStorage(slot)) {\n await backend.executeDdl(ddl);\n }\n for (const contribution of strategy.ownedTables(slot)) {\n for (const ddl of contribution.createDdl) {\n await backend.executeDdl(ddl);\n }\n }\n }\n }\n }\n\n // === Lifecycle ===\n\n /**\n * Refreshes the backend's query-planner statistics.\n *\n * Call this once after a large initial import or bulk backfill. The\n * planner uses table statistics to choose between TypeGraph's\n * multi-column indexes; without fresh stats a forward traversal can\n * pick a reverse index and run an order of magnitude slower than\n * needed. Autovacuum / background statistics will catch up\n * eventually, but calling this explicitly after a bulk load gives\n * you correct latencies immediately.\n *\n * Implementations:\n * - SQLite runs `ANALYZE`, populating `sqlite_stat1`\n * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n *\n * Costs a few tens of milliseconds at the sizes this library is\n * designed for. Safe to call at any time.\n *\n * @example\n * ```typescript\n * // After a bulk import\n * for (const batch of batches) {\n * await store.nodes.Document.bulkCreate(batch);\n * }\n * await store.refreshStatistics();\n * ```\n */\n async refreshStatistics(): Promise<void> {\n await this.#backend.refreshStatistics();\n }\n\n /**\n * Evolves the graph at runtime by merging a graph extension into the\n * current schema, atomically committing a new schema version, and\n * returning a fresh `Store` constructed against the merged graph.\n *\n * The `Store` is immutable — its registry, collections, and operation\n * contexts close over the graph at construction time — so callers\n * must use the returned store (or pass a `ref` to be re-pointed) for\n * any work involving the new kinds.\n *\n * **Cost for purely additive extensions is proportional to schema\n * document size, not row count.** The commit is a single CAS write.\n * Tightening changes against existing graph-extension-declared kinds run\n * row-count probes for those affected kinds so populated kinds can\n * be rejected without a backfill.\n *\n * **Concurrent evolve recovery.** On `StaleVersionError`, refetch the\n * current active schema (or dereference your `StoreRef`),\n * reconstruct your `Store`, and re-call `evolve(extension)` against\n * the new store. Re-validation may now surface deterministic errors\n * (e.g., another caller just added a kind that collides with yours,\n * or redeclared one of yours with a different shape). Don't loop\n * blindly — surface the error.\n *\n * @param extension - Graph extension produced by\n * `defineGraphExtension(...)`.\n * @param options.ref - Optional handle whose `current` is overwritten\n * atomically with the schema commit. Long-lived consumers\n * (request handlers, background workers) that dereference through\n * the ref see the new kinds on the *next* call.\n *\n * @throws {GraphExtensionValidationError} when the extension is\n * structurally invalid.\n * @throws {KindCollisionError} when an extension kind shadows a\n * compile-time kind (code `KIND_COLLISION`).\n * @throws {IncompatibleChangeError} when a redeclared kind narrows\n * in a way the existing rows can't satisfy\n * (code `INCOMPATIBLE_CHANGE`).\n * @throws {GraphExtensionUnresolvedEndpointError} when an edge\n * endpoint references a kind that exists in neither the extension\n * nor the host graph\n * (code `GRAPH_EXTENSION_UNRESOLVED_ENDPOINT`).\n * @throws {StaleVersionError} when another writer has advanced the\n * schema since this store was constructed; recovery as above.\n * @throws {SchemaContentConflictError} when a row already exists at\n * the target version with a different content hash.\n */\n async evolve<TRefStore extends StoreCore<G>>(\n extension: GraphExtension,\n options?: Readonly<{\n ref?: StoreRef<TRefStore>;\n /**\n * When set, automatically run `materializeIndexes()` on the new\n * Store after the schema commit succeeds. Pass `{}` for default\n * behavior (all declared indexes, best-effort) or a populated\n * options object for finer control. Omit to defer materialization\n * to a later `materializeIndexes()` call.\n *\n * The schema-version write is NOT rolled back if materialization\n * produces failed entries — failure surfaces as\n * `EagerMaterializationError` thrown AFTER the new Store is\n * constructed and `ref.current` is updated, so the caller can\n * recover via the ref handle.\n */\n eager?: MaterializeIndexesOptions;\n }>,\n ): Promise<StoreImplementation<G, TNativeTransaction>> {\n // Catch up to the persisted state first (extension AND deprecated\n // set). Without this, a stale store applying an extension on top\n // of an out-of-date baseline would make ensureSchema diff against\n // the persisted schema and either treat missing-locally kinds as\n // removed (breaking MigrationError) or silently drop another\n // writer's deprecation flags. The CAS guard inside\n // commitSchemaVersion still serializes the actual commit. If the\n // stored extension redefines a local extension kind with a\n // different shape, classifyModifications throws\n // IncompatibleChangeError here — surfacing the divergence rather\n // than overwriting.\n const { activeRow, baseline } = await this.#loadCaughtUp(\"evolve\");\n\n // Merge first so the \"I evolved with the same extension again\"\n // hot path short-circuits before we walk every property in\n // `classifyModifications`. The merge itself canonicalEqual-checks\n // and returns the input graph unchanged for no-op re-evolves.\n const merged = mergeGraphExtension(baseline, extension);\n\n // No-op evolve (extension already applied to the persisted state):\n // skip the schema commit. We compare against `baseline` (the\n // caught-up graph), not `this.#graph` (the local one). When\n // another writer has just committed the same extension, the local\n // store is stale — `baseline !== this.#graph` — but the merge is\n // still a structural no-op, so re-committing would only churn the\n // schema version. When the local store is also fresh\n // (`baseline === this.#graph`) we return `this` so repeated\n // `evolve(sameExt)` calls keep warm registry,\n // collection, and query caches; otherwise we return a clone\n // wrapping the caught-up baseline so `introspect()` reflects the\n // persisted version. Eager still runs in either case because the\n // contract is \"schema committed AND indexes materialized\" — the\n // local DB may have unmaterialized indexes even when the local\n // graph hasn't changed (restart-parity flow, prior failed\n // materialize).\n if (merged === baseline) {\n if (baseline === this.#graph) {\n syncStoreReplacementRef(options?.ref, this);\n if (options?.eager !== undefined) {\n await this.#runEagerOrThrow(this, options.eager);\n }\n return this;\n }\n const caughtUp = this.#cloneWithGraph(\n baseline,\n options?.ref,\n schemaMetadataFromRow(activeRow),\n );\n if (options?.eager !== undefined) {\n await this.#runEagerOrThrow(caughtUp, options.eager);\n }\n return caughtUp;\n }\n\n // Classification gates the schema commit. Same-shape re-evolves\n // already short-circuited above; here we know there's at least\n // one delta. Additive changes produce `allowed` deltas (no entry);\n // tightening changes produce `requireEmpty` entries that we\n // promote to incompatible only when the kind has rows; genuinely\n // incompatible changes (REMOVE_PROPERTY, TYPE_CHANGE) are\n // rejected unconditionally.\n const baselineDocument = baseline.extension ?? Object.freeze({});\n const classification = classifyModifications(baselineDocument, extension);\n if (classification.incompatible.length > 0) {\n throw new IncompatibleChangeError(\n classification.incompatible,\n this.graphId,\n );\n }\n if (classification.requireEmpty.length > 0) {\n const nonEmpty = await this.#probeEmptyKinds(classification.requireEmpty);\n const error = buildIncompatibleChangeError(\n classification,\n nonEmpty,\n this.graphId,\n );\n if (error !== undefined) throw error;\n }\n\n // Commit via `commitNewSchemaVersion` directly (the row-returning\n // sibling of `migrateSchema`). The classification step above is the\n // authoritative compatibility gate — `ensureSchema`'s\n // `isBackwardsCompatible` check would over-restrict ADD-required-\n // on-empty / TIGHTEN-on-empty modifications that the classifier\n // already approved.\n const committed = await commitNewSchemaVersion(\n this.#backend,\n merged,\n activeRow.version,\n );\n // Provision per-field vector tables + durable markers for any embedding\n // fields this evolution introduced (idempotent for fields that already\n // existed). `evolve()` is a privileged migrator path — it commits schema\n // versions and runs index DDL in eager mode — so emitting the table DDL\n // here mirrors how `createStoreWithSchema` provisions at first boot, and\n // keeps a runtime write to a freshly-added embedding field from hitting\n // an unmaterialized slot. The shared fulltext table needs no such step\n // (one table for all kinds); vectors are per-`(kind, field)`.\n await materializeVectorContributions(this.#backend, merged);\n const evolved = this.#cloneWithGraph(\n merged,\n options?.ref,\n schemaMetadataFromRow(committed),\n );\n if (options?.eager !== undefined) {\n await this.#runEagerOrThrow(evolved, options.eager);\n }\n return evolved;\n }\n\n async #runEagerOrThrow(\n store: StoreImplementation<G, TNativeTransaction>,\n eager: MaterializeIndexesOptions,\n ): Promise<void> {\n const result = await store.materializeIndexes(eager);\n if (result.results.some((entry) => entry.status === \"failed\")) {\n throw new EagerMaterializationError(result, this.graphId);\n }\n }\n\n /**\n * Marks the named node and edge kinds as soft-deprecated. Surfaces in\n * `store.introspect().deprecatedKinds` for introspection (codegen,\n * UI tooling, lints) but does not gate reads, writes, or queries —\n * deprecation is a signal, not a removal.\n *\n * Atomically commits a new schema version through the same primitive\n * `evolve()` uses, so concurrent deprecate/evolve calls produce\n * `StaleVersionError | SchemaContentConflictError` race losers that\n * the caller refetches and retries. Idempotent: re-deprecating a\n * kind that's already marked is a no-op (no version bump).\n *\n * @param names - Node or edge kind names to mark as deprecated.\n * @param options.ref - Optional handle to be re-pointed atomically\n * with the schema commit, mirroring `evolve()`.\n *\n * @throws {ConfigurationError} on `DEPRECATE_BEFORE_INITIALIZE` (no\n * schema yet) or `DEPRECATE_UNKNOWN_KIND` (name not on the graph).\n * @throws {StaleVersionError} when another writer has advanced the\n * schema since this store was constructed; refetch and retry per\n * the same recipe `evolve()` documents.\n * @throws {SchemaContentConflictError} when a row already exists at\n * the target version with a different content hash.\n */\n async deprecateKinds<TRefStore extends StoreCore<G>>(\n names: readonly string[],\n options?: Readonly<{ ref?: StoreRef<TRefStore> }>,\n ): Promise<StoreImplementation<G, TNativeTransaction>> {\n return this.#updateDeprecatedKinds(\"add\", names, options);\n }\n\n /**\n * Reverses `deprecateKinds(...)` for the named kinds. Same race +\n * idempotency semantics: removing a name that isn't currently\n * deprecated is a no-op for that name (the call as a whole is a\n * no-op only if every name was already absent).\n *\n * @param names - Node or edge kind names to remove from the\n * deprecated set.\n * @param options.ref - Optional handle to be re-pointed atomically\n * with the schema commit.\n *\n * @throws {ConfigurationError} on `DEPRECATE_BEFORE_INITIALIZE`.\n * @throws {StaleVersionError} on a CAS race with another writer.\n * @throws {SchemaContentConflictError} on a same-version content\n * conflict.\n */\n async undeprecateKinds<TRefStore extends StoreCore<G>>(\n names: readonly string[],\n options?: Readonly<{ ref?: StoreRef<TRefStore> }>,\n ): Promise<StoreImplementation<G, TNativeTransaction>> {\n return this.#updateDeprecatedKinds(\"remove\", names, options);\n }\n\n /**\n * Runs `CREATE INDEX` DDL for the indexes declared on this graph and\n * records per-deployment status in `typegraph_index_materializations`.\n * The status table is per-database (two replicas of the same\n * `schema_doc` are still two different databases for DDL purposes),\n * so the same call against two replicas materializes independently.\n *\n * Idempotent. Re-running the verb against an already-materialized\n * index is a no-op (`status: \"alreadyMaterialized\"`). Postgres uses\n * `CREATE INDEX CONCURRENTLY` so live tables never take an\n * `AccessExclusiveLock`. SQLite is single-writer regardless.\n *\n * Best-effort by default: a failed index records `status: \"failed\"`\n * with the error and the loop continues. Pass `{ stopOnError: true }`\n * to halt on the first failure.\n *\n * @param options.kinds - Restrict to indexes whose `kind` is in this\n * set. Throws `ConfigurationError` (`code:\n * \"MATERIALIZE_UNKNOWN_KIND\"`) if any name doesn't match a known\n * compile-time or extension kind.\n * @param options.stopOnError - Halt on first failure. Default false.\n *\n * @throws {ConfigurationError} `MATERIALIZE_BACKEND_UNSUPPORTED` if\n * the backend lacks `executeDdl`, `getIndexMaterialization`, or\n * `recordIndexMaterialization`; `MATERIALIZE_UNKNOWN_KIND` for an\n * unknown kind name; `MATERIALIZE_BEFORE_INITIALIZE` if the store\n * has no schema yet.\n */\n async materializeIndexes(\n options?: MaterializeIndexesOptions,\n ): Promise<MaterializeIndexesResult> {\n const { activeRow, baseline } = await this.#loadCaughtUp(\"materialize\");\n return materializeIndexesImpl(\n {\n graph: baseline,\n graphId: this.graphId,\n backend: this.#baseBackend,\n schemaVersion: activeRow.version,\n },\n options ?? {},\n );\n }\n\n /**\n * Materializes TypeGraph's own base-relation indexes\n * (`SYSTEM_INDEX_DECLARATIONS`) against the live database.\n *\n * Bootstrap DDL runs only on first boot, so a system index shipped in a\n * newer library version never reaches an already-initialized database on\n * its own. `createStoreWithSchema` runs this automatically; deployments\n * that boot with plain `createStore` / `createVerifiedStore` (zero-DDL by\n * contract) adopt new system indexes by calling this once under a role\n * that may run DDL. Same status-table, drift-signature, and Postgres\n * `CREATE INDEX CONCURRENTLY` claim semantics as `materializeIndexes`.\n */\n async materializeSystemIndexes(\n options?: MaterializeSystemIndexesOptions,\n ): Promise<MaterializeIndexesResult> {\n const { activeRow } = await this.#loadCaughtUp(\"materialize\");\n return materializeSystemIndexesImpl(\n {\n backend: this.#baseBackend,\n graphId: this.graphId,\n schemaVersion: activeRow.version,\n },\n options ?? {},\n );\n }\n\n /**\n * Recreate a vector field's per-field storage at its current declared\n * dimension, then optionally re-embed existing rows.\n *\n * Use this after changing a field's `embedding(N)` to `embedding(M)` (e.g. a\n * new embedding model): the stored N-dim vectors are invalid under the new\n * dimension and must be recomputed, not converted. This drops and recreates\n * the per-`(graphId, kind, field)` table at the new dimension — a brief\n * window where the field returns no vector hits — resets its materialization\n * marker, then, when `options.embed` is supplied, pages the kind's nodes,\n * calls `embed(batch)`, and upserts the returned vectors. Without `embed`,\n * storage is recreated empty and the caller re-embeds via normal\n * `update()` / `upsertEmbedding` writes.\n *\n * @throws {ConfigurationError} when the backend has no vector strategy or\n * cannot execute DDL, or `(kind, fieldPath)` is not a declared embedding.\n */\n async reembedVectorField(\n kind: string,\n fieldPath: string,\n options?: ReembedVectorFieldOptions,\n ): Promise<ReembedVectorFieldResult> {\n // Validate up front, before any drop/recreate side effects.\n if (\n options?.batchSize !== undefined &&\n (!Number.isInteger(options.batchSize) || options.batchSize <= 0)\n ) {\n throw new RangeError(\n `reembedVectorField batchSize must be a positive integer, got: ${options.batchSize}`,\n );\n }\n const { activeRow, baseline } = await this.#loadCaughtUp(\"reembed\");\n const backend = this.#baseBackend;\n const strategy = backend.vectorStrategy;\n if (strategy === undefined || backend.executeDdl === undefined) {\n throw new ConfigurationError(\n \"reembedVectorField requires a backend with a vector strategy and executeDdl.\",\n {\n backend: backend.dialect,\n capability: \"vector\",\n operation: \"reembed\",\n },\n );\n }\n const declaration = (baseline.indexes ?? []).find(\n (candidate): candidate is VectorIndexDeclaration =>\n candidate.entity === \"vector\" &&\n candidate.kind === kind &&\n candidate.fieldPath === fieldPath,\n );\n if (declaration === undefined) {\n throw new ConfigurationError(\n `No embedding field \"${kind}.${fieldPath}\" is declared in the active schema.`,\n { kind, fieldPath, operation: \"reembed\" },\n );\n }\n\n const slot: VectorSlot = {\n graphId: this.graphId,\n nodeKind: kind,\n fieldPath,\n dimensions: declaration.dimensions,\n metric: declaration.metric,\n indexType: declaration.indexType,\n };\n\n // Recreate storage at the new dimension: drop, then re-create the per-\n // field table the strategy owns (libSQL/sqlite-vec also (re)create their\n // index/vtable here; pgvector's index is built via createVectorIndex\n // below). `ensureVectorSlotContribution({ force: true })` re-runs the\n // table DDL AND re-stamps the durable contribution marker at the new\n // signature, bypassing the drift-guard — this is the sanctioned shape\n // change. Without the marker reset, the post-reembed runtime assert would\n // see a stale marker and refuse every write. Backends without the marker\n // method (custom, pre-#135) fall back to raw recreate DDL.\n for (const ddl of strategy.buildDropStorage(slot)) {\n await backend.executeDdl(ddl);\n }\n if (backend.ensureVectorSlotContribution === undefined) {\n for (const contribution of strategy.ownedTables(slot)) {\n for (const ddl of contribution.createDdl) {\n await backend.executeDdl(ddl);\n }\n }\n } else {\n await backend.ensureVectorSlotContribution(slot, { force: true });\n }\n\n // Whether this backend would actually materialize an ANN index for the\n // declared slot — brute-force-only (\"none\") slots and index types the\n // backend doesn't advertise are skipped. Gates both the index (re)build\n // and the materialization-marker reset below so they stay in lockstep.\n const declaredIndexMaterializes =\n declaration.indexType !== \"none\" &&\n backend.capabilities.vector?.indexTypes.includes(\n declaration.indexType,\n ) === true;\n\n // (Re)build the ANN index with the field's DECLARED tuning. The table was\n // just recreated above, so createVectorIndex's own ensure is a safe no-op\n // even if the latch is stale.\n if (declaredIndexMaterializes && backend.createVectorIndex !== undefined) {\n await backend.createVectorIndex({\n graphId: this.graphId,\n nodeKind: kind,\n fieldPath,\n dimensions: declaration.dimensions,\n metric: declaration.metric,\n indexType: declaration.indexType,\n indexParams: {\n m: declaration.indexParams.m,\n efConstruction: declaration.indexParams.efConstruction,\n ...(declaration.indexParams.lists === undefined ?\n {}\n : { lists: declaration.indexParams.lists }),\n },\n });\n }\n\n // Reset the index-materialization marker so a later materializeIndexes()\n // sees the new-dimension signature as already materialized, not as drift.\n if (\n declaredIndexMaterializes &&\n backend.recordIndexMaterialization !== undefined\n ) {\n const tableName = strategy.tableName(this.graphId, kind, fieldPath);\n const signature = await computeIndexSignature(\n backend.dialect,\n tableName,\n declaration,\n );\n const now = nowIso();\n await backend.recordIndexMaterialization({\n indexName: vectorStatusKey(this.graphId, declaration.name),\n graphId: this.graphId,\n entity: \"vector\",\n kind,\n signature,\n schemaVersion: activeRow.version,\n attemptedAt: now,\n materializedAt: now,\n error: undefined,\n });\n }\n\n if (options?.embed === undefined) {\n return { recreated: true, reembedded: 0 };\n }\n\n if (backend.upsertEmbedding === undefined) {\n throw new ConfigurationError(\n \"reembedVectorField with an `embed` callback requires a backend that supports upsertEmbedding.\",\n {\n backend: backend.dialect,\n capability: \"vector\",\n operation: \"reembed\",\n },\n );\n }\n\n // Re-embed: page the kind's nodes, compute vectors, upsert. Offset paging\n // is stable because upserts target the per-field table, not the nodes table.\n const upsertEmbedding = backend.upsertEmbedding;\n const batchSize = options.batchSize ?? DEFAULT_REEMBED_BATCH_SIZE;\n const collection = this.getNodeCollectionOrThrow(kind);\n let reembedded = 0;\n let offset = 0;\n for (;;) {\n const batch = (await collection.find({\n limit: batchSize,\n offset,\n })) as readonly Node[];\n if (batch.length === 0) break;\n const vectors = await options.embed(batch);\n for (const node of batch) {\n const embedding = vectors.get(node.id);\n if (embedding === undefined) continue;\n await upsertEmbedding({\n graphId: this.graphId,\n nodeKind: kind,\n nodeId: node.id,\n fieldPath,\n embedding,\n dimensions: declaration.dimensions,\n metric: declaration.metric,\n indexType: declaration.indexType,\n });\n reembedded += 1;\n }\n offset += batch.length;\n if (batch.length < batchSize) break;\n }\n return { recreated: true, reembedded };\n }\n\n /**\n * Removes extension kinds from the schema with cascading edge and\n * ontology cleanup. Two-phase by design:\n *\n * 1. **Schema commit (this method).** Validates the removal,\n * rebuilds the persisted extension without the named kinds\n * (and without extension edges that lose their last endpoint),\n * CAS-commits the new schema version, and queues\n * per-deployment data-cleanup status. Millisecond budget.\n * 2. **Data cleanup (`materializeRemovals`).** Deletes the orphan\n * rows from the nodes/edges tables. Bounded by row count.\n *\n * Pass `{ eager: {} }` to run the data-cleanup pass inline with\n * default options, or `{ eager: { ... } }` to scope it; otherwise\n * call `materializeRemovals()` later.\n *\n * Idempotent: removing a name that doesn't exist is a no-op (no\n * version bump). Removing an extension kind referenced by a compile-\n * time edge or ontology relation throws `KindHasReferentsError`.\n * Removing a compile-time kind throws `RemoveCompileTimeKindError` —\n * compile-time kinds are removed by recompiling and redeploying.\n *\n * @throws {RemoveCompileTimeKindError} when `names` includes a\n * compile-time kind.\n * @throws {KindHasReferentsError} when an extension kind being\n * removed is referenced by a compile-time declaration.\n * @throws {StaleVersionError} on a CAS race with another writer.\n * @throws {SchemaContentConflictError} on a same-version content\n * conflict.\n */\n async removeKinds<TRefStore extends StoreCore<G>>(\n names: readonly string[],\n options?: Readonly<{\n ref?: StoreRef<TRefStore>;\n eager?: MaterializeRemovalsOptions;\n }>,\n ): Promise<StoreImplementation<G, TNativeTransaction>> {\n const { activeRow, baseline } = await this.#loadCaughtUp(\"remove\");\n const plan = planRemovals(baseline, names);\n\n // True no-op: every name was either absent or already removed.\n // Mirrors the (un)deprecateKinds same-set short-circuit.\n if (\n plan.removedNodeKinds.length === 0 &&\n plan.removedEdgeKinds.length === 0\n ) {\n if (baseline === this.#graph) {\n syncStoreReplacementRef(options?.ref, this);\n return this;\n }\n return this.#cloneWithGraph(\n baseline,\n options?.ref,\n schemaMetadataFromRow(activeRow),\n );\n }\n\n // Build the post-removal graph: rebuild from the new\n // extension by re-applying the merge against the host\n // graph's compile-time slice. Take the host's compile-time\n // graph (the `Store<G>`'s original `#graph` minus extension\n // kinds) and merge the planned extension on top of it.\n const compileTimeGraph = stripGraphExtension(this.#graph);\n const merged =\n plan.document === undefined ?\n compileTimeGraph\n : mergeGraphExtension(compileTimeGraph, plan.document);\n const finalGraph = applyDeprecatedKinds(merged, baseline.deprecatedKinds);\n\n // Atomic schema commit via the lower-level `migrateSchema`\n // primitive — `ensureSchema`'s breaking-change check would\n // reject the kind removal as a destructive diff. The removal IS\n // destructive by design; that's why removeKinds is a separate\n // verb. Concurrent commits surface as `StaleVersionError` from\n // `commitSchemaVersion` (CAS check).\n const committedRow = await commitNewSchemaVersion(\n this.#backend,\n finalGraph,\n activeRow.version,\n );\n\n // Queue per-deployment data-cleanup status — one row per removed\n // kind. The status table is best-effort: if recordKindRemoval\n // throws, the schema commit is already done and the rows just\n // become invisible (queries against the kind go through the new\n // store). Operators reconcile via materializeRemovals later.\n const recordKindRemoval = this.#backend.recordKindRemoval;\n if (recordKindRemoval !== undefined) {\n if (this.#backend.ensureKindRemovalsTable !== undefined) {\n await this.#backend.ensureKindRemovalsTable();\n }\n const attemptedAt = nowIso();\n const newSchemaVersion = committedRow.version;\n const queue = (kindName: string, entity: KindEntity): Promise<void> =>\n recordKindRemoval(\n buildPendingKindRemoval({\n graphId: this.graphId,\n kindName,\n entity,\n schemaVersion: newSchemaVersion,\n attemptedAt,\n }),\n );\n // Independent rows on independent primary keys — issue in parallel.\n // For typical cascades (one kind + a few edges) this drops the\n // schema-commit budget by 30-100ms on Postgres.\n await Promise.all([\n ...plan.removedNodeKinds.map((name) => queue(name, \"node\")),\n ...plan.removedEdgeKinds.map((name) => queue(name, \"edge\")),\n ]);\n }\n\n const evolved = this.#cloneWithGraph(\n finalGraph,\n options?.ref,\n schemaMetadataFromRow(committedRow),\n );\n if (options?.eager !== undefined) {\n // Scope to just the kinds removed by THIS call (other pending\n // removals from prior calls aren't this caller's concern).\n const kinds = [...plan.removedNodeKinds, ...plan.removedEdgeKinds];\n await evolved.materializeRemovals({\n ...options.eager,\n kinds: options.eager.kinds ?? kinds,\n });\n }\n return evolved;\n }\n\n /**\n * Runs the data-cleanup phase for any kinds removed via\n * `removeKinds()` whose data has not yet been deleted on this\n * deployment. Safe to call repeatedly; idempotent.\n */\n async materializeRemovals(\n options?: MaterializeRemovalsOptions,\n ): Promise<MaterializeRemovalsResult> {\n return materializeRemovalsImpl(\n {\n graphId: this.graphId,\n backend: this.#baseBackend,\n captureRecordedRemovals: this.#captureEnabled,\n ...(this.#captureEnabled && { recordedSchema: this.#sqlSchema() }),\n },\n options ?? {},\n );\n }\n\n async #updateDeprecatedKinds<TRefStore extends StoreCore<G>>(\n direction: \"add\" | \"remove\",\n names: readonly string[],\n options: Readonly<{ ref?: StoreRef<TRefStore> }> | undefined,\n ): Promise<StoreImplementation<G, TNativeTransaction>> {\n const verb = direction === \"add\" ? \"deprecate\" : \"undeprecate\";\n const { activeRow, storedSchema, baseline } =\n await this.#loadCaughtUp(verb);\n const nextSet = new Set(baseline.deprecatedKinds);\n\n if (direction === \"add\") {\n for (const name of names) {\n if (!isKnownKind(baseline, name)) {\n // Deprecate accepts either node OR edge kinds — the runtime\n // kind type is reported as \"node\" here for the error\n // message default; consumers branch on `kindName` not\n // `entity` for this code path.\n throw new KindNotFoundError(\n name,\n isKnownEdgeKind(baseline, name) ? \"edge\" : \"node\",\n {\n graphId: this.graphId,\n suggestion:\n \"Only kinds declared on the graph (compile-time or runtime) can be deprecated.\",\n },\n );\n }\n nextSet.add(name);\n }\n } else {\n for (const name of names) nextSet.delete(name);\n }\n\n if (setsEqual(nextSet, baseline.deprecatedKinds)) {\n // True no-op only when the catch-up didn't change anything\n // either. Otherwise the caller's `this` reference is stale\n // relative to the persisted state — return a clone of the\n // caught-up baseline so they pick up another writer's\n // extension kinds and deprecation flags.\n if (baseline === this.#graph) {\n syncStoreReplacementRef(options?.ref, this);\n return this;\n }\n return this.#cloneWithGraph(\n baseline,\n options?.ref,\n schemaMetadataFromRow(activeRow),\n );\n }\n\n const merged = applyDeprecatedKinds(baseline, nextSet);\n const result = await ensureSchemaImpl(this.#backend, merged, {\n preloaded: { activeRow, storedSchema },\n autoMigrate: true,\n });\n // Use the committed row from the migration result when available,\n // skipping the post-commit `getActiveSchema` round-trip. The\n // `unchanged` / `pending` / `breaking` branches don't write a new\n // version, so the existing `activeRow` metadata is still authoritative.\n const metadata =\n result.status === \"migrated\" || result.status === \"initialized\" ?\n schemaMetadataFromRow(result.committedRow)\n : schemaMetadataFromRow(activeRow);\n return this.#cloneWithGraph(merged, options?.ref, metadata);\n }\n\n #catchUpToStored(storedSchema: SerializedSchema): G {\n // Strip the local extension slice before re-applying the persisted\n // extension. Otherwise a stale store whose `this.#graph` carries\n // extension kinds another writer has since removed would resurrect\n // them: `unionDocuments` unions local extension nodes/edges back in,\n // and the absent-from-stored kinds win the spread. Stripping first\n // makes the merge a function of the persisted document alone, so\n // removeKinds on one store cannot be silently undone by a stale peer.\n const compileTimeGraph = stripGraphExtension(this.#graph);\n const withGraphExtension =\n storedSchema.extension === undefined ?\n compileTimeGraph\n : mergeGraphExtension(compileTimeGraph, storedSchema.extension);\n return applyDeprecatedKinds(\n withGraphExtension,\n storedSchema.deprecatedKinds,\n );\n }\n\n /**\n * Loads the active schema row, parses it, and catches the in-memory\n * graph up to the persisted state — the shared preamble for\n * `evolve`, `materializeIndexes`, and `(un)deprecateKinds`.\n *\n * Throws `ConfigurationError` with a verb-specific code when the\n * graph has not been initialized yet. The catch-up step replays the\n * persisted graph-extension document and deprecation set on top of the\n * compile-time graph so we diff against the same baseline another\n * writer would; the CAS guard inside `commitSchemaVersion` still\n * serializes the actual commit.\n */\n async #loadCaughtUp(verb: CaughtUpVerb): Promise<{\n activeRow: SchemaVersionRow;\n storedSchema: SerializedSchema;\n baseline: G;\n }> {\n const activeRow = await loadActiveSchemaWithBootstrap(\n this.#backend,\n this.graphId,\n );\n if (activeRow === undefined) {\n const { phrase, code } = CAUGHT_UP_VERB_DETAILS[verb];\n throw new ConfigurationError(\n `Cannot ${phrase} graph \"${this.graphId}\": no schema has been initialized. Call createStoreWithSchema first.`,\n { code },\n );\n }\n const storedSchema = parseSerializedSchema(activeRow.schema_doc);\n const baseline = this.#catchUpToStored(storedSchema);\n return { activeRow, storedSchema, baseline };\n }\n\n /**\n * Probes each `requireEmpty` entry for any rows. Returns the set of\n * composite keys (`${entity}:${kindName}`) that have at least one\n * row — those entries need to be promoted from \"allowed-on-empty\"\n * to incompatible. Dispatches to `countNodesByKind` for `node`\n * entries and `countEdgesByKind` for `edge` entries (a single-\n * primitive probe would always return 0 for the wrong-entity case\n * and silently bypass the gate).\n *\n * Probes run in parallel; each entry is independent. Race window\n * (probe → CAS commit): another writer can insert a row into a\n * previously-empty kind. The schema commit still succeeds (CAS\n * guards on schema version, not row count); the new schema rejects\n * the inserted row at next read, which the operator inspects and\n * either deletes or reverts. Rare in practice; tighter elimination\n * would require `SELECT FOR UPDATE` on the rows table, too\n * heavyweight for a millisecond-budget operation.\n */\n async #probeEmptyKinds(\n requireEmpty: readonly RequireEmptyEntry[],\n ): Promise<Set<RequireEmptyEntry>> {\n const probes = requireEmpty.map(\n async (entry): Promise<readonly [RequireEmptyEntry, number]> => {\n const count =\n entry.entity === \"node\" ?\n await this.#backend.countNodesByKind({\n graphId: this.graphId,\n kind: entry.kindName,\n })\n : await this.#backend.countEdgesByKind({\n graphId: this.graphId,\n kind: entry.kindName,\n });\n return [entry, count];\n },\n );\n const results = await Promise.all(probes);\n const nonEmpty = new Set<RequireEmptyEntry>();\n for (const [entry, count] of results) {\n if (count > 0) nonEmpty.add(entry);\n }\n return nonEmpty;\n }\n\n #cloneWithGraph<TRefStore extends StoreCore<G>>(\n graph: G,\n ref: StoreRef<TRefStore> | undefined,\n schemaMetadata: StoreSchemaMetadata = this.#schemaMetadata,\n ): StoreImplementation<G, TNativeTransaction> {\n const next: StoreImplementation<G, TNativeTransaction> =\n this.#adapterBackend === undefined ?\n new StoreImplementation<G, TNativeTransaction>(\n graph,\n this.#baseBackend,\n this.#options,\n schemaMetadata,\n )\n : new AdapterStoreImplementation(\n graph,\n this.#adapterBackend,\n this.#options,\n schemaMetadata,\n );\n syncStoreReplacementRef(ref, next);\n return next;\n }\n\n /**\n * Closes the store and releases underlying resources.\n *\n * Note: When using the Drizzle adapter, this method does not close the database\n * connection itself, as Drizzle delegates connection management to the user.\n * You should close the underlying database connection (e.g., better-sqlite3 or pg pool)\n * using their respective APIs.\n */\n async close(): Promise<void> {\n await this.#backend.close();\n }\n\n // === Internal: Operation Contexts ===\n\n #immediateHookRunner(): OperationHookRunner {\n return <T>(ctx: OperationHookContext, fn: () => Promise<T>) =>\n this.#withOperationHooks(ctx, fn);\n }\n\n #createNodeOperationContext(\n runHooks: OperationHookRunner = this.#immediateHookRunner(),\n ): NodeOperationContext<G> {\n return {\n graph: this.#graph,\n graphId: this.graphId,\n historyEnabled: this.#captureEnabled,\n revisionTrackingEnabled: this.#revisionTrackingEnabled,\n revisionSchema: this.#sqlSchema(),\n registry: this.#registry,\n createOperationContext: (operation, entity, kind, id) =>\n this.#createOperationContext(operation, entity, kind, id),\n withOperationHooks: runHooks,\n };\n }\n\n #createEdgeOperationContext(\n runHooks: OperationHookRunner = this.#immediateHookRunner(),\n ): EdgeOperationContext<G> {\n return {\n graph: this.#graph,\n graphId: this.graphId,\n historyEnabled: this.#captureEnabled,\n revisionTrackingEnabled: this.#revisionTrackingEnabled,\n revisionSchema: this.#sqlSchema(),\n registry: this.#registry,\n createOperationContext: (operation, entity, kind, id) =>\n this.#createOperationContext(operation, entity, kind, id),\n withOperationHooks: runHooks,\n };\n }\n\n // === Internal: Hook Helpers ===\n\n #createHookContext(): HookContext {\n return {\n operationId: generateId(),\n graphId: this.graphId,\n startedAt: new Date(),\n };\n }\n\n #createOperationContext(\n operation: \"create\" | \"update\" | \"delete\",\n entity: KindEntity,\n kind: string,\n id: string,\n ): OperationHookContext {\n return {\n ...this.#createHookContext(),\n operation,\n entity,\n kind,\n id,\n };\n }\n\n async #withOperationHooks<T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n ): Promise<T> {\n this.#hooks.onOperationStart?.(ctx);\n const startTime = Date.now();\n try {\n const result = await fn();\n this.#hooks.onOperationEnd?.(ctx, {\n durationMs: Date.now() - startTime,\n });\n return result;\n } catch (error) {\n this.#hooks.onError?.(ctx, asError(error));\n throw error;\n }\n }\n\n /**\n * A hook runner for operations that execute INSIDE an explicit\n * `store.transaction`: `onOperationStart` (and a failed operation's\n * `onError`) fire immediately — the attempt and the failure are real when\n * they happen — but a successful operation's `onOperationEnd` is only\n * BUFFERED. `transaction()` flushes the buffer after the backend COMMIT\n * succeeds, or converts every buffered success into `onError` when the\n * transaction fails, so `onOperationEnd` always means durably committed\n * even for operations nested in a caller-controlled transaction.\n */\n #createBufferedHookRunner(\n pending: PendingOperationOutcome[],\n ): OperationHookRunner {\n return async <T>(\n ctx: OperationHookContext,\n fn: () => Promise<T>,\n ): Promise<T> => {\n this.#hooks.onOperationStart?.(ctx);\n const startTime = Date.now();\n try {\n const result = await fn();\n pending.push({ ctx, durationMs: Date.now() - startTime });\n return result;\n } catch (error) {\n this.#hooks.onError?.(ctx, asError(error));\n throw error;\n }\n };\n }\n\n // === Internal: Temporal Filtering ===\n\n #temporalRowMatcher(options?: QueryOptions): (\n row: Readonly<{\n deleted_at: string | undefined;\n valid_from: string | undefined;\n valid_to: string | undefined;\n }>,\n ) => boolean {\n // Resolve the coordinate ONCE (via the shared resolveTemporalReadParams, so\n // the in-memory getById/getByIds filter cannot drift from the SQL-side\n // filter, and a non-canonical asOf is rejected here too). Returning a\n // predicate lets getByIds pin one instant for the whole batch instead of\n // recomputing nowIso() — and re-validating — per row.\n const { temporalMode, asOf } = resolveTemporalReadParams(\n options,\n this.#graph.defaults.temporalMode,\n );\n\n return (row) => {\n switch (temporalMode) {\n case \"current\":\n case \"asOf\": {\n // resolveTemporalReadParams always resolves an instant for these modes.\n if (row.deleted_at) return false;\n if (asOf !== undefined && row.valid_from && asOf < row.valid_from)\n return false;\n if (asOf !== undefined && row.valid_to && asOf >= row.valid_to)\n return false;\n return true;\n }\n case \"includeEnded\": {\n return !row.deleted_at;\n }\n case \"includeTombstones\": {\n return true;\n }\n }\n };\n }\n\n #createQueryForBackend<CoordinateState extends QueryCoordinateState = \"open\">(\n backend: GraphBackend | TransactionBackend,\n sealedCoordinate?: ReadCoordinate,\n ): InitialQueryBuilder<G, CoordinateState> {\n return createInternalQueryBuilder<G, CoordinateState>(\n this.graphId,\n this.#registry,\n {\n // TransactionBackend omits transaction/close, but query execution only needs\n // the read-path/query capabilities shared with GraphBackend.\n backend: backend as GraphBackend,\n dialect: backend.dialect,\n defaultTraversalExpansion: this.#defaultTraversalExpansion,\n ...(this.#schema !== undefined && { schema: this.#schema }),\n ...(this.#recordedReadBinding !== undefined && {\n recordedReadBinding: this.#recordedReadBinding,\n }),\n ...(sealedCoordinate !== undefined && { sealedCoordinate }),\n },\n );\n }\n}\n\n/** Runtime implementation for the explicit adapter-interoperability surface. */\nclass AdapterStoreImplementation<\n G extends GraphDef,\n TNativeTransaction,\n> extends StoreImplementation<G, TNativeTransaction> {\n readonly backend: GraphBackend | HistoryStoreBackend;\n\n constructor(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options?: StoreOptions,\n schemaMetadata?: StoreSchemaMetadata,\n ) {\n super(graph, backend, options, schemaMetadata, backend);\n // Projections remain mutable while they serve as internal overlay targets;\n // freeze only the final object exposed at this public boundary.\n this.backend =\n options?.history === true ?\n createHistoryStoreBackendProjection(this[STORE_RUNTIME].backend)\n : Object.freeze(\n createGraphBackendProjection(this[STORE_RUNTIME].backend),\n );\n }\n\n override async evolve<TRefStore extends StoreCore<G>>(\n extension: GraphExtension,\n options?: Readonly<{\n ref?: StoreRef<TRefStore>;\n eager?: MaterializeIndexesOptions;\n }>,\n ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n return this.#withAdapterReplacement(options?.ref, (replacementRef) =>\n super.evolve(\n extension,\n options?.eager === undefined ?\n { ref: replacementRef }\n : { eager: options.eager, ref: replacementRef },\n ),\n );\n }\n\n override async deprecateKinds<TRefStore extends StoreCore<G>>(\n names: readonly string[],\n options?: Readonly<{\n ref?: StoreRef<TRefStore>;\n }>,\n ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n return this.#withAdapterReplacement(options?.ref, (replacementRef) =>\n super.deprecateKinds(names, { ref: replacementRef }),\n );\n }\n\n override async undeprecateKinds<TRefStore extends StoreCore<G>>(\n names: readonly string[],\n options?: Readonly<{\n ref?: StoreRef<TRefStore>;\n }>,\n ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n return this.#withAdapterReplacement(options?.ref, (replacementRef) =>\n super.undeprecateKinds(names, { ref: replacementRef }),\n );\n }\n\n override async removeKinds<TRefStore extends StoreCore<G>>(\n names: readonly string[],\n options?: Readonly<{\n ref?: StoreRef<TRefStore>;\n eager?: MaterializeRemovalsOptions;\n }>,\n ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n return this.#withAdapterReplacement(options?.ref, (replacementRef) =>\n super.removeKinds(\n names,\n options?.eager === undefined ?\n { ref: replacementRef }\n : { eager: options.eager, ref: replacementRef },\n ),\n );\n }\n\n async #withAdapterReplacement<TRefStore extends StoreCore<G>>(\n ref: StoreRef<TRefStore> | undefined,\n operation: (ref: StoreRef<Store<G>>) => Promise<Store<G>>,\n ): Promise<AdapterStoreImplementation<G, TNativeTransaction>> {\n const tracked = createTrackedReplacementRef<G>(this);\n try {\n await operation(tracked.ref);\n } catch (error) {\n if (tracked.wasReplaced()) {\n const replacement = requireAdapterStoreImplementation<\n G,\n TNativeTransaction\n >(tracked.ref.current);\n syncAdapterReplacementRef(ref, replacement);\n }\n throw error;\n }\n const replacement = requireAdapterStoreImplementation<\n G,\n TNativeTransaction\n >(tracked.ref.current);\n syncAdapterReplacementRef(ref, replacement);\n return replacement;\n }\n}\n\nfunction createTrackedReplacementRef<G extends GraphDef>(\n initial: Store<G>,\n): Readonly<{\n ref: StoreRef<Store<G>>;\n wasReplaced: () => boolean;\n}> {\n let current = initial;\n let replaced = false;\n return {\n ref: {\n get current(): Store<G> {\n return current;\n },\n set current(next: Store<G>) {\n current = next;\n replaced = true;\n },\n },\n wasReplaced: () => replaced,\n };\n}\n\nfunction syncAdapterReplacementRef<\n G extends GraphDef,\n TNativeTransaction,\n TRefStore extends StoreCore<G>,\n>(\n ref: StoreRef<TRefStore> | undefined,\n replacement: AdapterStoreImplementation<G, TNativeTransaction>,\n): void {\n if (ref === undefined) return;\n // Public StoreEvolution only accepts refs whose value is a supertype of the\n // returned Store flavor. This implementation class is deliberately broader\n // because one runtime class backs live, recorded-read, and history overloads.\n ref.current = replacement as unknown as TRefStore;\n}\n\nfunction requireAdapterStoreImplementation<\n G extends GraphDef,\n TNativeTransaction,\n>(store: Store<G>): AdapterStoreImplementation<G, TNativeTransaction> {\n if (isAdapterStoreImplementation<G, TNativeTransaction>(store)) return store;\n throw new ConfigurationError(\n \"Adapter store replacement lost its adapter capabilities.\",\n { code: \"ADAPTER_STORE_REPLACEMENT_INVARIANT\" },\n );\n}\n\nfunction isAdapterStoreImplementation<G extends GraphDef, TNativeTransaction>(\n store: Store<G>,\n): store is AdapterStoreImplementation<G, TNativeTransaction> {\n return store instanceof AdapterStoreImplementation;\n}\n\nfunction asAdapterStoreSurface<G extends GraphDef, TNativeTransaction>(\n store: AdapterStoreImplementation<G, TNativeTransaction>,\n):\n | AdapterStore<G, TNativeTransaction>\n | AdapterHistoryStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction> {\n // One runtime implementation backs the three option-discriminated overloads.\n // It constructs the matching backend projection and replacement flavor, but\n // TypeScript cannot derive that structural union from constructor options.\n return store as unknown as\n | AdapterStore<G, TNativeTransaction>\n | AdapterHistoryStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>;\n}\n\n// ============================================================\n// Factory Function\n// ============================================================\n\nexport type AdapterHistoryTransactionContext<\n G extends GraphDef,\n TNativeTransaction,\n> = Omit<\n AdapterTransactionContext<G, TNativeTransaction>,\n \"sql\" | \"sqlAvailability\"\n> &\n Readonly<{\n sqlAvailability: \"history\";\n }>;\n\n/**\n * The {@link AdapterHistoryTransactionContext} handed to a `withRecordedTransaction`\n * callback, extended with {@link ScopedMeasure}. Its `measure` scopes to a child\n * {@link MeasurableAdapterHistoryTransactionContext} (so nested scopes keep the\n * history-safe absent-`sql` / backend typing). Assignable to\n * {@link MeasurableTransactionContext} (and hence to {@link TransactionContext}),\n * so a projector helper typed against either still accepts it.\n */\nexport type MeasurableAdapterHistoryTransactionContext<\n G extends GraphDef,\n TNativeTransaction,\n> = AdapterHistoryTransactionContext<G, TNativeTransaction> &\n Readonly<{\n measure: ScopedMeasure<\n MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>\n >;\n }>;\n\nexport type AdapterRecordedReadStore<\n G extends GraphDef,\n TNativeTransaction,\n> = StoreCore<G> &\n StoreEvolution<G, AdapterRecordedReadStore<G, TNativeTransaction>> &\n AdapterStoreTransactions<G, TNativeTransaction> &\n Readonly<{\n backend: GraphBackend;\n recordedReadBound: true;\n }>;\n\nexport type RecordedReadStore<G extends GraphDef> = StoreCore<G> &\n StoreTransactions<G> &\n StoreEvolution<G, RecordedReadStore<G>> &\n Readonly<{ recordedReadBound: true }>;\n\nexport type HistoryStore<G extends GraphDef> = StoreCore<G> &\n StoreTransactions<G> &\n StoreEvolution<G, HistoryStore<G>> &\n Readonly<{\n historyEnabled: true;\n recordedReadBound: true;\n }>;\n\nexport type AdapterHistoryStore<\n G extends GraphDef,\n TNativeTransaction,\n> = StoreCore<G> &\n StoreEvolution<G, AdapterHistoryStore<G, TNativeTransaction>> &\n AdapterHistoryStoreTransactions<G, TNativeTransaction> &\n Readonly<{\n backend: HistoryStoreBackend;\n historyEnabled: true;\n recordedReadBound: true;\n }>;\n\ntype AdapterHistoryStoreTransactions<\n G extends GraphDef,\n TNativeTransaction,\n> = Readonly<{\n transaction: <T>(\n fn: (\n tx: AdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n transactionWithReceipt: <T>(\n fn: (\n tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<TransactionOutcome<T>>;\n withRecordedTransaction: <T>(\n externalTransaction: TNativeTransaction,\n fn: (\n tx: MeasurableAdapterHistoryTransactionContext<G, TNativeTransaction>,\n ) => Promise<T>,\n ) => Promise<TransactionOutcome<T>>;\n}>;\n\n/**\n * Creates a new Store instance.\n *\n * @param graph - The graph definition\n * @param backend - The database backend\n * @param options - Optional store configuration including observability hooks\n * @returns A new Store instance\n *\n * @example\n * ```typescript\n * // Basic usage\n * const store = createStore(graph, backend);\n *\n * // With observability hooks\n * const store = createStore(graph, backend, {\n * hooks: {\n * onOperationStart: (ctx) => {\n * console.log(`Starting ${ctx.operation} on ${ctx.entity}:${ctx.kind}`);\n * },\n * onOperationEnd: (ctx, result) => {\n * console.log(`Completed in ${result.durationMs}ms`);\n * },\n * onError: (ctx, error) => {\n * console.error(`Operation ${ctx.operationId} failed:`, error);\n * },\n * },\n * });\n * ```\n */\nexport function createStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: HistoryStoreOptions,\n): HistoryStore<G>;\nexport function createStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: RecordedReadStoreOptions,\n): RecordedReadStore<G>;\nexport function createStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: UnboundLiveStoreOptions,\n): Store<G>;\nexport function createStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: LiveStoreOptions | undefined,\n): Store<G> | RecordedReadStore<G>;\nexport function createStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: StoreOptions | undefined,\n): Store<G> | HistoryStore<G> | RecordedReadStore<G>;\nexport function createStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions,\n): Store<G> | HistoryStore<G> | RecordedReadStore<G> {\n return new StoreImplementation<G>(graph, backend, options);\n}\n\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: HistoryStoreOptions,\n): AdapterHistoryStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: RecordedReadStoreOptions,\n): AdapterRecordedReadStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options?: UnboundLiveStoreOptions,\n): AdapterStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: LiveStoreOptions | undefined,\n):\n | AdapterStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: StoreOptions | undefined,\n):\n | AdapterStore<G, TNativeTransaction>\n | AdapterHistoryStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>;\nexport function createAdapterStore<G extends GraphDef, TNativeTransaction>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options?: StoreOptions,\n):\n | AdapterStore<G, TNativeTransaction>\n | AdapterHistoryStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction> {\n return asAdapterStoreSurface(\n new AdapterStoreImplementation(graph, backend, options),\n );\n}\n\nfunction isKnownEdgeKind(graph: GraphDef, name: string): boolean {\n return Object.hasOwn(graph.edges, name);\n}\n\nfunction setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {\n if (a.size !== b.size) return false;\n for (const value of a) if (!b.has(value)) return false;\n return true;\n}\n\nfunction schemaMetadataFromRow(\n row: SchemaVersionRow | undefined,\n): StoreSchemaMetadata {\n if (row === undefined) return UNKNOWN_SCHEMA_METADATA;\n return Object.freeze({\n schemaVersion: row.version,\n schemaHash: row.schema_hash,\n });\n}\n\nfunction schemaMetadataForResult(\n activeRow: SchemaVersionRow | undefined,\n result: SchemaValidationResult,\n): StoreSchemaMetadata {\n if (result.status === \"initialized\" || result.status === \"migrated\") {\n return schemaMetadataFromRow(result.committedRow);\n }\n return schemaMetadataFromRow(activeRow);\n}\n\n/**\n * Prefer the #129 contribution path; fall back to the pre-#129\n * `ensureFulltextTable` for backends that predate it. Idempotent and\n * cheap on a warm re-call (per-instance cache + recorded-signature\n * short-circuit).\n */\nasync function materializeRuntimeContributions(\n backend: GraphBackend,\n graphId: string,\n): Promise<void> {\n if (backend.ensureRuntimeContributions) {\n await backend.ensureRuntimeContributions(graphId);\n return;\n }\n await backend.ensureFulltextTable?.(graphId);\n}\n\n/**\n * Privileged boot step: materialize every embedding `(kind, field)` slot's\n * per-field vector table + durable marker, enumerated from the graph via\n * {@link resolveGraphVectorSlots}. The vector counterpart of\n * {@link materializeRuntimeContributions} (fulltext) — runs once under the\n * privileged role inside `createStoreWithSchema` so a least-privilege runtime\n * can assert the markers (a cached SELECT) and write embeddings without\n * holding `CREATE` on the schema. No-op on backends without vector support\n * (both vector contribution methods absent, or `capabilities.vector`\n * unsupported) and for graphs that declare no embedding fields. Built-in\n * backends use the batch method; the singular loop is the compatibility path.\n *\n * `onDrift: \"skip\"`: a slot already provisioned at a DIFFERENT shape (the\n * declared dimension changed since the table was created) is warned about\n * and left untouched rather than refused — boot must stay reachable so the\n * operator can run `store.reembedVectorField(kind, fieldPath)`, the\n * sanctioned recreate-and-restamp path. Until then, writes to that slot\n * fail with a typed `stale` StoreNotInitializedError.\n */\nasync function materializeVectorContributions(\n backend: GraphBackend,\n graph: GraphDef,\n): Promise<void> {\n if (backend.capabilities.vector?.supported !== true) return;\n const slots = resolveGraphVectorSlots(graph);\n const ensureVectorSlotContributions = backend.ensureVectorSlotContributions;\n if (ensureVectorSlotContributions !== undefined) {\n await ensureVectorSlotContributions(slots, { onDrift: \"skip\" });\n return;\n }\n const ensureVectorSlotContribution = backend.ensureVectorSlotContribution;\n if (ensureVectorSlotContribution === undefined) return;\n for (const slot of slots) {\n await ensureVectorSlotContribution(slot, { onDrift: \"skip\" });\n }\n}\n\n// ============================================================\n// Async Factory with Schema Management\n// ============================================================\n\n// Re-export schema manager types\nexport type {\n SchemaManagerOptions,\n SchemaValidationResult,\n} from \"../schema/manager\";\n\n/**\n * Creates a store and ensures the schema is initialized/migrated.\n *\n * This is the recommended way to create a store in production.\n * It automatically:\n * - Creates base tables on a fresh database (if the backend supports bootstrapTables)\n * - Initializes the schema on first run (version 1)\n * - Auto-migrates safe changes (additive changes)\n * - Throws MigrationError for breaking changes\n *\n * @param graph - The graph definition\n * @param backend - The database backend\n * @param options - Store and schema options\n * @returns A tuple of [store, validationResult]\n *\n * @example\n * ```typescript\n * const [store, result] = await createStoreWithSchema(graph, backend);\n *\n * if (result.status === \"initialized\") {\n * console.log(\"Schema initialized at version\", result.version);\n * } else if (result.status === \"migrated\") {\n * console.log(`Migrated from v${result.fromVersion} to v${result.toVersion}`);\n * } else if (result.status === \"pending\") {\n * console.log(`Safe changes pending at version ${result.version}`);\n * }\n * ```\n */\nexport async function createStoreWithSchema<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: HistoryStoreOptions & SchemaManagerOptions,\n): Promise<[HistoryStore<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: RecordedReadStoreOptions & SchemaManagerOptions,\n): Promise<[RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: UnboundLiveStoreOptions & SchemaManagerOptions,\n): Promise<[Store<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: (LiveStoreOptions & SchemaManagerOptions) | undefined,\n): Promise<[Store<G> | RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: (StoreOptions & SchemaManagerOptions) | undefined,\n): Promise<\n [Store<G> | HistoryStore<G> | RecordedReadStore<G>, SchemaValidationResult]\n>;\nexport async function createStoreWithSchema<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions & SchemaManagerOptions,\n): Promise<\n [Store<G> | HistoryStore<G> | RecordedReadStore<G>, SchemaValidationResult]\n> {\n const prepared = await prepareStoreWithSchema(graph, backend, options);\n return [\n new StoreImplementation(\n prepared.graph,\n backend,\n options,\n prepared.schemaMetadata,\n ),\n prepared.result,\n ];\n}\n\ntype PreparedStore<G extends GraphDef> = Readonly<{\n graph: G;\n result: SchemaValidationResult;\n schemaMetadata: StoreSchemaMetadata;\n}>;\n\nasync function prepareStoreWithSchema<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: (StoreOptions & SchemaManagerOptions) | undefined,\n): Promise<PreparedStore<G>> {\n // Fold any persisted graph extension into the graph BEFORE\n // constructing the Store. The prefetched row + parsed schema thread\n // through to ensureSchema so each Store boot pays for one DB round\n // trip and one Zod parse, not two. Additional extension kinds are\n // reachable through the registry but invisible to the type system —\n // see `mergeGraphExtension`.\n const {\n graph: merged,\n activeRow,\n storedSchema,\n } = await loadAndMergeGraphExtensionDocument(backend, graph);\n\n const result = await ensureSchemaImpl(backend, merged, {\n ...options,\n preloaded: { activeRow, storedSchema },\n });\n\n // #135/#143: this is the single durable-marker writer, and it MUST\n // run after ensureSchemaImpl so the breaking-change gate is reached\n // first — otherwise contribution DDL derived from the new code graph\n // would hit a stale table shape and mask `MigrationError`.\n await materializeRuntimeContributions(backend, merged.id);\n // Provision every embedding field's per-`(kind, field)` vector table +\n // durable marker under the privileged role, so a least-privilege runtime\n // asserts the markers (SELECT) and writes embeddings without `CREATE`.\n await materializeVectorContributions(backend, merged);\n // Bring the base-relation system indexes up to this library version.\n // Bootstrap DDL only runs on first boot, so an index shipped in a newer\n // version reaches already-initialized databases here — this is the same\n // privileged-boot step the contributions above use. `systemIndexes:\n // \"skip\"` defers to an out-of-band store.materializeSystemIndexes()\n // for deployments that must not run index builds inline at boot.\n if (options?.systemIndexes !== \"skip\") {\n await materializeSystemIndexesOnBoot(backend, merged.id, result);\n }\n\n return {\n graph: merged,\n result,\n schemaMetadata: schemaMetadataForResult(activeRow, result),\n };\n}\n\nexport async function createAdapterStoreWithSchema<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: HistoryStoreOptions & SchemaManagerOptions,\n): Promise<\n [AdapterHistoryStore<G, TNativeTransaction>, SchemaValidationResult]\n>;\nexport async function createAdapterStoreWithSchema<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: RecordedReadStoreOptions & SchemaManagerOptions,\n): Promise<\n [AdapterRecordedReadStore<G, TNativeTransaction>, SchemaValidationResult]\n>;\nexport async function createAdapterStoreWithSchema<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options?: UnboundLiveStoreOptions & SchemaManagerOptions,\n): Promise<[AdapterStore<G, TNativeTransaction>, SchemaValidationResult]>;\nexport async function createAdapterStoreWithSchema<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: (LiveStoreOptions & SchemaManagerOptions) | undefined,\n): Promise<\n [\n (\n | AdapterStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>\n ),\n SchemaValidationResult,\n ]\n>;\nexport async function createAdapterStoreWithSchema<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: (StoreOptions & SchemaManagerOptions) | undefined,\n): Promise<\n [\n (\n | AdapterStore<G, TNativeTransaction>\n | AdapterHistoryStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>\n ),\n SchemaValidationResult,\n ]\n>;\nexport async function createAdapterStoreWithSchema<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options?: StoreOptions & SchemaManagerOptions,\n): Promise<\n [\n (\n | AdapterStore<G, TNativeTransaction>\n | AdapterHistoryStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>\n ),\n SchemaValidationResult,\n ]\n> {\n const prepared = await prepareStoreWithSchema(graph, backend, options);\n return [\n asAdapterStoreSurface(\n new AdapterStoreImplementation(\n prepared.graph,\n backend,\n options,\n prepared.schemaMetadata,\n ),\n ),\n prepared.result,\n ];\n}\n\n/**\n * Boot-path system-index materialization. Lenient where the explicit\n * `store.materializeSystemIndexes()` API is strict:\n *\n * - Backends without `executeDdl` / status primitives are skipped —\n * their deployments keep the bootstrap-only behavior they had before\n * system indexes were materialized at boot, instead of failing to boot.\n * - Skipped when the schema gate did not pass (`\"breaking\"`).\n * - Individual index failures degrade to a warning: system indexes are a\n * performance concern, and a store that cannot build one must still\n * come up (the operator retries via `store.materializeSystemIndexes()`).\n */\nasync function materializeSystemIndexesOnBoot(\n backend: GraphBackend,\n graphId: string,\n result: SchemaValidationResult,\n): Promise<void> {\n if (result.status === \"breaking\") return;\n if (!backendSupportsIndexMaterialization(backend)) return;\n const schemaVersion =\n result.status === \"migrated\" ? result.toVersion : result.version;\n try {\n const { results } = await materializeSystemIndexesImpl(\n { backend: asRawBackend(backend), graphId, schemaVersion },\n {},\n );\n const failed = results.filter(\n (entryResult) => entryResult.status === \"failed\",\n );\n if (failed.length === 0) return;\n console.warn(\n `[typegraph] ${String(failed.length)} system index(es) failed to ` +\n `materialize at boot (${failed\n .map((entryResult) => entryResult.indexName)\n .join(\", \")}); the store is usable but the affected access paths ` +\n \"fall back to scans. Retry via store.materializeSystemIndexes().\",\n failed[0]?.error,\n );\n } catch (error) {\n // Leniency must hold for infrastructure throws too (status-table\n // ensure/preload/record failures, claim writes) — not only per-index\n // build failures. A store that booted on the previous version must\n // still come up after an upgrade; the operator retries explicitly.\n console.warn(\n \"[typegraph] system-index materialization failed at boot; the store \" +\n \"is usable but new system indexes were not adopted. Retry via \" +\n \"store.materializeSystemIndexes().\",\n error,\n );\n }\n}\n\n/**\n * Creates a Store after **verifying** that the database is at the same\n * schema version as the code graph — without running any DDL, bootstrap,\n * or marker writes. The runtime counterpart of `createStoreWithSchema`\n * for the deployment model in \"Database roles & least privilege\":\n *\n * - **`createStoreWithSchema(graph, backend)`** runs DDL (bootstrap,\n * safe auto-migrations, durable contribution materialization). Run it\n * once at startup under a privileged role that holds `CREATE` / DDL.\n * - **`createVerifiedStore(graph, backend)`** is the zero-DDL runtime\n * attach with a verification gate. Throws `MigrationError` when the\n * persisted schema is behind the code graph (any pending change, safe\n * or breaking), `ConfigurationError` when no schema has been\n * initialized, or `StoreNotInitializedError` when the schema is\n * current but the runtime-contribution markers are missing/stale.\n * The runtime can use a least-privilege, DML-only database role.\n * - **`createStore(graph, backend)`** is the same zero-DDL attach\n * *without* the verification gate — fastest, but schema drift goes\n * undetected until a hot-path operation trips.\n *\n * Folds any persisted graph-extension document into the supplied graph\n * before building the Store, just like `createStoreWithSchema`.\n *\n * @param graph - The graph definition\n * @param backend - The database backend\n * @param options - Optional store configuration\n * @returns A tuple of [store, validationResult] — `result.status` is\n * always `\"unchanged\"` on success\n *\n * @example\n * ```typescript\n * // Runtime — least-privilege, DML-only role. Zero DDL.\n * const [store, result] = await createVerifiedStore(graph, backend);\n * // result.status === \"unchanged\" — the privileged migrator is current.\n * ```\n *\n * @throws ConfigurationError if no schema has been initialized.\n * @throws MigrationError if the persisted schema is behind the code graph.\n * @throws StoreNotInitializedError if runtime-contribution markers are\n * missing/stale/failed for this graph on this connection.\n */\nexport async function createVerifiedStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: HistoryStoreOptions,\n): Promise<[HistoryStore<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: RecordedReadStoreOptions,\n): Promise<[RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: UnboundLiveStoreOptions,\n): Promise<[Store<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: LiveStoreOptions | undefined,\n): Promise<[Store<G> | RecordedReadStore<G>, SchemaValidationResult]>;\nexport async function createVerifiedStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options: StoreOptions | undefined,\n): Promise<\n [Store<G> | HistoryStore<G> | RecordedReadStore<G>, SchemaValidationResult]\n>;\nexport async function createVerifiedStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n options?: StoreOptions,\n): Promise<\n [Store<G> | HistoryStore<G> | RecordedReadStore<G>, SchemaValidationResult]\n> {\n const prepared = await prepareVerifiedStore(graph, backend);\n return [\n new StoreImplementation(\n prepared.graph,\n backend,\n options,\n prepared.schemaMetadata,\n ),\n prepared.result,\n ];\n}\n\nasync function prepareVerifiedStore<G extends GraphDef>(\n graph: G,\n backend: GraphBackend,\n): Promise<PreparedStore<G>> {\n const {\n graph: merged,\n activeRow,\n result,\n } = await loadAndVerifyGraph(backend, graph);\n return {\n graph: merged,\n result,\n schemaMetadata: schemaMetadataFromRow(activeRow),\n };\n}\n\nexport async function createVerifiedAdapterStore<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: HistoryStoreOptions,\n): Promise<\n [AdapterHistoryStore<G, TNativeTransaction>, SchemaValidationResult]\n>;\nexport async function createVerifiedAdapterStore<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: RecordedReadStoreOptions,\n): Promise<\n [AdapterRecordedReadStore<G, TNativeTransaction>, SchemaValidationResult]\n>;\nexport async function createVerifiedAdapterStore<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options?: UnboundLiveStoreOptions,\n): Promise<[AdapterStore<G, TNativeTransaction>, SchemaValidationResult]>;\nexport async function createVerifiedAdapterStore<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: LiveStoreOptions | undefined,\n): Promise<\n [\n (\n | AdapterStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>\n ),\n SchemaValidationResult,\n ]\n>;\nexport async function createVerifiedAdapterStore<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options: StoreOptions | undefined,\n): Promise<\n [\n (\n | AdapterStore<G, TNativeTransaction>\n | AdapterHistoryStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>\n ),\n SchemaValidationResult,\n ]\n>;\nexport async function createVerifiedAdapterStore<\n G extends GraphDef,\n TNativeTransaction,\n>(\n graph: G,\n backend: AdapterBackend<TNativeTransaction>,\n options?: StoreOptions,\n): Promise<\n [\n (\n | AdapterStore<G, TNativeTransaction>\n | AdapterHistoryStore<G, TNativeTransaction>\n | AdapterRecordedReadStore<G, TNativeTransaction>\n ),\n SchemaValidationResult,\n ]\n> {\n const prepared = await prepareVerifiedStore(graph, backend);\n return [\n asAdapterStoreSurface(\n new AdapterStoreImplementation(\n prepared.graph,\n backend,\n options,\n prepared.schemaMetadata,\n ),\n ),\n prepared.result,\n ];\n}\n"]}
|