@rocicorp/zero 1.11.0-canary.11 → 1.11.0-canary.13
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/out/analyze-query/src/analyze-cli.js +2 -2
- package/out/analyze-query/src/analyze-cli.js.map +1 -1
- package/out/shared/src/ring-buffer.d.ts +2 -0
- package/out/shared/src/ring-buffer.d.ts.map +1 -1
- package/out/shared/src/ring-buffer.js +4 -0
- package/out/shared/src/ring-buffer.js.map +1 -1
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/server/replicator.js +26 -13
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/backfill-manager.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js +169 -19
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js.map +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.js +2 -2
- package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +45 -6
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +118 -33
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +2 -2
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +10 -17
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.js +15 -4
- package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-message.d.ts +92 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-message.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-message.js +42 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-message.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot.d.ts +7 -89
- package/out/zero-cache/src/services/change-streamer/snapshot.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot.js +26 -98
- package/out/zero-cache/src/services/change-streamer/snapshot.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscribe.d.ts +358 -0
- package/out/zero-cache/src/services/change-streamer/subscribe.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/subscribe.js +68 -0
- package/out/zero-cache/src/services/change-streamer/subscribe.js.map +1 -0
- package/out/zero-cache/src/services/litestream/commands.d.ts +2 -3
- package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.js +3 -2
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +12 -1
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +2 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +13 -7
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.d.ts +2 -1
- package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.js +2 -2
- package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/client-handler.d.ts +19 -2
- package/out/zero-cache/src/services/view-syncer/client-handler.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/client-handler.js +8 -1
- package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts +19 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js +34 -11
- package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts +6 -2
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.js +9 -5
- package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +44 -11
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +21 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.js +14 -6
- package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +28 -4
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/streams.d.ts +33 -7
- package/out/zero-cache/src/types/streams.d.ts.map +1 -1
- package/out/zero-cache/src/types/streams.js +93 -50
- package/out/zero-cache/src/types/streams.js.map +1 -1
- package/out/zero-cache/src/types/subscription.d.ts +11 -0
- package/out/zero-cache/src/types/subscription.d.ts.map +1 -1
- package/out/zero-cache/src/types/subscription.js +56 -35
- package/out/zero-cache/src/types/subscription.js.map +1 -1
- package/out/zero-cache/src/types/ws.js +1 -31
- package/out/zero-cache/src/types/ws.js.map +1 -1
- package/out/zero-cache/src/workers/connection.js +3 -3
- package/out/zero-cache/src/workers/connection.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +2 -2
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +5 -5
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-protocol/src/inspect-down.d.ts +81 -81
- package/out/zql/src/builder/builder.d.ts.map +1 -1
- package/out/zql/src/builder/builder.js +6 -4
- package/out/zql/src/builder/builder.js.map +1 -1
- package/out/zql/src/ivm/cap.d.ts +2 -1
- package/out/zql/src/ivm/cap.d.ts.map +1 -1
- package/out/zql/src/ivm/cap.js +3 -0
- package/out/zql/src/ivm/cap.js.map +1 -1
- package/out/zql/src/ivm/exists.d.ts +2 -0
- package/out/zql/src/ivm/exists.d.ts.map +1 -1
- package/out/zql/src/ivm/exists.js +3 -0
- package/out/zql/src/ivm/exists.js.map +1 -1
- package/out/zql/src/ivm/fan-in.d.ts +5 -1
- package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
- package/out/zql/src/ivm/fan-in.js +7 -0
- package/out/zql/src/ivm/fan-in.js.map +1 -1
- package/out/zql/src/ivm/fan-out.d.ts +3 -0
- package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
- package/out/zql/src/ivm/fan-out.js +4 -0
- package/out/zql/src/ivm/fan-out.js.map +1 -1
- package/out/zql/src/ivm/filter-operators.d.ts +2 -0
- package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
- package/out/zql/src/ivm/filter-operators.js +9 -0
- package/out/zql/src/ivm/filter-operators.js.map +1 -1
- package/out/zql/src/ivm/filter.d.ts +4 -1
- package/out/zql/src/ivm/filter.d.ts.map +1 -1
- package/out/zql/src/ivm/filter.js +3 -0
- package/out/zql/src/ivm/filter.js.map +1 -1
- package/out/zql/src/ivm/flipped-join.d.ts +4 -3
- package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
- package/out/zql/src/ivm/flipped-join.js +73 -22
- package/out/zql/src/ivm/flipped-join.js.map +1 -1
- package/out/zql/src/ivm/join-utils.d.ts +24 -7
- package/out/zql/src/ivm/join-utils.d.ts.map +1 -1
- package/out/zql/src/ivm/join-utils.js +87 -4
- package/out/zql/src/ivm/join-utils.js.map +1 -1
- package/out/zql/src/ivm/join.d.ts +4 -4
- package/out/zql/src/ivm/join.d.ts.map +1 -1
- package/out/zql/src/ivm/join.js +55 -64
- package/out/zql/src/ivm/join.js.map +1 -1
- package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.js +33 -23
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/out/zql/src/ivm/operator.d.ts +39 -10
- package/out/zql/src/ivm/operator.d.ts.map +1 -1
- package/out/zql/src/ivm/operator.js +9 -4
- package/out/zql/src/ivm/operator.js.map +1 -1
- package/out/zql/src/ivm/push-accumulated.d.ts +6 -1
- package/out/zql/src/ivm/push-accumulated.d.ts.map +1 -1
- package/out/zql/src/ivm/push-accumulated.js +47 -2
- package/out/zql/src/ivm/push-accumulated.js.map +1 -1
- package/out/zql/src/ivm/skip.d.ts +2 -1
- package/out/zql/src/ivm/skip.d.ts.map +1 -1
- package/out/zql/src/ivm/skip.js +3 -0
- package/out/zql/src/ivm/skip.js.map +1 -1
- package/out/zql/src/ivm/take-gate.d.ts +24 -2
- package/out/zql/src/ivm/take-gate.d.ts.map +1 -1
- package/out/zql/src/ivm/take-gate.js +26 -1
- package/out/zql/src/ivm/take-gate.js.map +1 -1
- package/out/zql/src/ivm/take.d.ts +2 -1
- package/out/zql/src/ivm/take.d.ts.map +1 -1
- package/out/zql/src/ivm/take.js +59 -40
- package/out/zql/src/ivm/take.js.map +1 -1
- package/out/zql/src/ivm/union-fan-in.d.ts +3 -0
- package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
- package/out/zql/src/ivm/union-fan-in.js +56 -5
- package/out/zql/src/ivm/union-fan-in.js.map +1 -1
- package/out/zql/src/ivm/union-fan-out.d.ts +2 -1
- package/out/zql/src/ivm/union-fan-out.d.ts.map +1 -1
- package/out/zql/src/ivm/union-fan-out.js +5 -0
- package/out/zql/src/ivm/union-fan-out.js.map +1 -1
- package/out/zql/src/query/measure-push-operator.d.ts +2 -1
- package/out/zql/src/query/measure-push-operator.d.ts.map +1 -1
- package/out/zql/src/query/measure-push-operator.js +7 -0
- package/out/zql/src/query/measure-push-operator.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline-driver.js","names":["#tables","#pipelines","#rowSetSignatures","#lc","#snapshotter","#storage","#shardID","#logConfig","#config","#tableSpecs","#allTableNames","#costModels","#yieldThresholdMs","#advanceTime","#conflictRowsDeleted","#inspectorDelegate","#initAndResetCommon","#destroyPipeline","#primaryKeys","#replicaVersion","#permissions","#disableCorrelatedPredicatePushdown","#getSource","#createStorage","#trackRowSetSignatures","#addQueryImpl","#logQueryPipelineLifecycle","#ensureCostModelExistsIfEnabled","#advanceContext","#hydrateContext","#resolveScalarSubqueries","#warnIgnoredScalarHints","#streamer","#pruneUnusedTables","#advance","#shouldAdvanceYieldMaybeAbortAdvance","#push","#shouldYield","#throwSlowCurrentChangeReset","#throwProjectedAdvancementReset","#startAccumulating","#stopAccumulating","#logQueryFailure","#changes","#streamChanges","#streamNodes","#input","#queryHash","#transformationHash","#queryName","#output"],"sources":["../../../../../../zero-cache/src/services/view-syncer/pipeline-driver.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert, unreachable} from '../../../../shared/src/asserts.ts';\nimport {deepEqual, type JSONValue} from '../../../../shared/src/json.ts';\nimport {getOrInsertComputed} from '../../../../shared/src/map.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {randInt} from '../../../../shared/src/rand.ts';\nimport type {AST, LiteralValue} from '../../../../zero-protocol/src/ast.ts';\nimport type {ClientSchema} from '../../../../zero-protocol/src/client-schema.ts';\nimport type {Row} from '../../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../../zero-protocol/src/primary-key.ts';\nimport {buildPipeline} from '../../../../zql/src/builder/builder.ts';\nimport {\n Debug,\n runtimeDebugFlags,\n} from '../../../../zql/src/builder/debug-delegate.ts';\nimport {ChangeIndex} from '../../../../zql/src/ivm/change-index.ts';\nimport {ChangeType} from '../../../../zql/src/ivm/change-type.ts';\nimport type {Change} from '../../../../zql/src/ivm/change.ts';\nimport type {Node} from '../../../../zql/src/ivm/data.ts';\nimport {\n skipYields,\n throwOutput,\n type FetchRequest,\n type Input,\n type Output,\n type Storage,\n} from '../../../../zql/src/ivm/operator.ts';\nimport type {SourceSchema} from '../../../../zql/src/ivm/schema.ts';\nimport {\n type Source,\n type SourceChange,\n type SourceInput,\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../../zql/src/ivm/source.ts';\nimport type {ConnectionCostModel} from '../../../../zql/src/planner/planner-connection.ts';\nimport {MeasurePushOperator} from '../../../../zql/src/query/measure-push-operator.ts';\nimport type {ClientGroupStorage} from '../../../../zqlite/src/database-storage.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n resolveSimpleScalarSubqueries,\n type CompanionSubquery,\n type IgnoredScalarHint,\n} from '../../../../zqlite/src/resolve-scalar-subqueries.ts';\nimport {createSQLiteCostModel} from '../../../../zqlite/src/sqlite-cost-model.ts';\nimport {TableSource} from '../../../../zqlite/src/table-source.ts';\nimport {\n reloadPermissionsIfChanged,\n type LoadedPermissions,\n} from '../../auth/load-permissions.ts';\nimport type {LogConfig, ZeroConfig} from '../../config/zero-config.ts';\nimport {computeZqlSpecs, mustGetTableSpec} from '../../db/lite-tables.ts';\nimport type {LiteAndZqlSpec, LiteTableSpec} from '../../db/specs.ts';\nimport {\n getOrCreateCounter,\n getOrCreateLatencyHistogram,\n} from '../../observability/metrics.ts';\nimport type {InspectorDelegate} from '../../server/inspector-delegate.ts';\nimport {type RowKey} from '../../types/row-key.ts';\nimport {type ShardID} from '../../types/shards.ts';\nimport {\n getSubscriptionState,\n ZERO_VERSION_COLUMN_NAME,\n} from '../replicator/schema/replication-state.ts';\nimport {checkClientSchema} from './client-schema.ts';\nimport {rowIDSignatureUnit} from './row-set-signature.ts';\nimport type {Snapshotter} from './snapshotter.ts';\nimport {ResetPipelinesSignal, type SnapshotDiff} from './snapshotter.ts';\n\ntype RowOp<Op extends Omit<ChangeType, ChangeType.CHILD>> = {\n readonly type: Op;\n readonly queryID: string;\n readonly table: string;\n readonly rowKey: Row;\n readonly row: Row;\n};\n\nexport type RowAdd = RowOp<ChangeType.ADD>;\n\nexport type RowRemove = RowOp<ChangeType.REMOVE>;\n\nexport type RowEdit = RowOp<ChangeType.EDIT>;\n\nexport type RowChange = RowAdd | RowRemove | RowEdit;\n\ntype CompanionPipeline = {\n readonly input: Input;\n readonly childField: string;\n readonly resolvedValue: LiteralValue | null | undefined;\n};\n\ntype Pipeline = {\n readonly input: Input;\n readonly hydrationTimeMs: number;\n readonly hydrationRowCount: number;\n readonly hydrationReason: PipelineHydrationReason;\n readonly pipelineRunID: string;\n readonly pipelineReadyAtMs: number;\n readonly transformedAst: AST;\n readonly originalAst: AST;\n readonly transformationHash: string;\n readonly queryName?: string | undefined;\n readonly companions: readonly CompanionPipeline[];\n};\n\nexport type QueryInfo = {\n readonly transformedAst: AST;\n readonly originalAst?: AST | undefined;\n readonly transformationHash: string;\n readonly queryName?: string | undefined;\n};\n\ntype QueryLogInfo = {\n readonly queryHash: string;\n readonly transformationHash: string;\n readonly queryName?: string | undefined;\n};\n\ntype QueryPipelineLifecycleEvent =\n | 'query-pipeline-hydrate-start'\n | 'query-pipeline-hydrate-finish'\n | 'query-pipeline-hydrate-failed'\n | 'query-pipeline-hydrate-aborted'\n | 'query-pipeline-stop';\n\nexport type PipelineHydrationReason =\n | 'query-set-sync'\n | 'unchanged-query-rehydrate';\n\ntype PipelineStopReason =\n | 'replace-query'\n | 'remove-query'\n | 'reset'\n | 'destroy';\n\ntype QueryPipelineLifecycleLog = {\n readonly zeroEvent: QueryPipelineLifecycleEvent;\n readonly pipelineRunID: string;\n readonly queryHash: string;\n readonly transformationHash: string;\n readonly queryName?: string | undefined;\n readonly hydrationReason?: PipelineHydrationReason | undefined;\n readonly stopReason?: PipelineStopReason | undefined;\n readonly hydrationTimeMs?: number | undefined;\n readonly hydrationRowCount?: number | undefined;\n readonly pipelineLifetimeMs?: number | undefined;\n};\n\ntype AdvanceContext = {\n readonly timer: Timer;\n readonly totalHydrationTimeMs: number;\n readonly numChanges: number;\n currentChangeStartMs: number | undefined;\n pos: number;\n};\n\ntype HydrateContext = {\n readonly timer: Timer;\n};\n\nexport type Timer = {\n elapsedLap: () => number;\n totalElapsed: () => number;\n};\n\n/**\n * No matter how fast hydration is, advancement is given at least this long to\n * complete before doing a pipeline reset.\n */\nconst MIN_ADVANCEMENT_TIME_LIMIT_MS = 50;\nconst MIN_PROJECTED_ADVANCEMENT_SAMPLE_CHANGES = 8;\nconst PROJECTED_ADVANCEMENT_SAMPLE_FRACTION = 0.25;\nconst MAX_PROJECTED_ADVANCEMENT_SAMPLE_CHANGES = 50;\nconst MIN_PROJECTED_ADVANCEMENT_SAMPLE_MS = 5;\nconst MIN_PROJECTED_ADVANCEMENT_CHANGES = 16;\nconst PROJECTED_ADVANCEMENT_RESET_MULTIPLIER = 1.5;\nconst LATE_ADVANCEMENT_FINISH_PROGRESS = 0.8;\n\nfunction randomID() {\n return randInt(1, Number.MAX_SAFE_INTEGER).toString(36);\n}\n\nfunction projectedAdvancementTimeMs(\n elapsedMs: number,\n processedChanges: number,\n numChanges: number,\n): number | undefined {\n if (processedChanges <= 0 || numChanges <= 0) {\n return undefined;\n }\n return (elapsedMs / processedChanges) * numChanges;\n}\n\nfunction advancementResetTimeLimitMs(totalHydrationTimeMs: number): number {\n return Math.max(totalHydrationTimeMs, 1);\n}\n\nfunction minProjectedAdvancementSampleChanges(numChanges: number): number {\n return Math.max(\n MIN_PROJECTED_ADVANCEMENT_SAMPLE_CHANGES,\n Math.min(\n MAX_PROJECTED_ADVANCEMENT_SAMPLE_CHANGES,\n Math.ceil(numChanges * PROJECTED_ADVANCEMENT_SAMPLE_FRACTION),\n ),\n );\n}\n\nfunction shouldResetProjectedAdvancement(\n elapsedMs: number,\n projectedTotalTimeMs: number | undefined,\n processedChanges: number,\n numChanges: number,\n totalHydrationTimeMs: number,\n): boolean {\n if (\n projectedTotalTimeMs === undefined ||\n numChanges < MIN_PROJECTED_ADVANCEMENT_CHANGES ||\n processedChanges < minProjectedAdvancementSampleChanges(numChanges) ||\n elapsedMs < MIN_PROJECTED_ADVANCEMENT_SAMPLE_MS\n ) {\n return false;\n }\n\n return (\n projectedTotalTimeMs >\n advancementResetTimeLimitMs(totalHydrationTimeMs) *\n PROJECTED_ADVANCEMENT_RESET_MULTIPLIER\n );\n}\n\nfunction shouldFinishLateAdvancement(\n processedChanges: number,\n numChanges: number,\n): boolean {\n return (\n numChanges > 0 &&\n processedChanges / numChanges >= LATE_ADVANCEMENT_FINISH_PROGRESS\n );\n}\n\nfunction shouldResetSlowCurrentChange(\n currentChangeElapsedMs: number,\n totalHydrationTimeMs: number,\n): boolean {\n return (\n currentChangeElapsedMs > MIN_ADVANCEMENT_TIME_LIMIT_MS &&\n currentChangeElapsedMs > advancementResetTimeLimitMs(totalHydrationTimeMs)\n );\n}\n\n/**\n * Manages the state of IVM pipelines for a given ViewSyncer (i.e. client group).\n */\nexport class PipelineDriver {\n readonly #tables = new Map<string, TableSource>();\n // Query id to pipeline\n readonly #pipelines = new Map<string, Pipeline>();\n /**\n * XOR signature of the set of rows currently attached to each active\n * query, maintained as RowChanges are yielded from {@link addQuery} and\n * {@link advance}. ADDs / REMOVEs XOR the row's unit in (XOR is\n * self-inverse, so one op serves both directions); EDITs are no-ops.\n * Hydration implicitly reseeds from `0n` because {@link addQuery} calls\n * {@link removeQuery} first, which deletes the entry.\n */\n readonly #rowSetSignatures = new Map<string, bigint>();\n\n readonly #lc: LogContext;\n readonly #snapshotter: Snapshotter;\n readonly #storage: ClientGroupStorage;\n readonly #shardID: ShardID;\n readonly #logConfig: LogConfig;\n readonly #config: ZeroConfig | undefined;\n readonly #tableSpecs = new Map<string, LiteAndZqlSpec>();\n readonly #allTableNames = new Set<string>();\n readonly #costModels: WeakMap<Database, ConnectionCostModel> | undefined;\n readonly #yieldThresholdMs: () => number;\n #streamer: Streamer | null = null;\n #hydrateContext: HydrateContext | null = null;\n #advanceContext: AdvanceContext | null = null;\n #replicaVersion: string | null = null;\n #primaryKeys: Map<string, PrimaryKey> | null = null;\n #permissions: LoadedPermissions | null = null;\n\n readonly #advanceTime = getOrCreateLatencyHistogram(\n 'sync',\n 'ivm.advance-time',\n 'Time to advance all queries for a given client group in response to a single change.',\n );\n\n readonly #conflictRowsDeleted = getOrCreateCounter(\n 'sync',\n 'ivm.conflict-rows-deleted',\n 'Number of rows deleted because they conflicted with added row',\n );\n\n readonly #inspectorDelegate: InspectorDelegate;\n\n constructor(\n lc: LogContext,\n logConfig: LogConfig,\n snapshotter: Snapshotter,\n shardID: ShardID,\n storage: ClientGroupStorage,\n clientGroupID: string,\n inspectorDelegate: InspectorDelegate,\n yieldThresholdMs: () => number,\n enablePlanner?: boolean,\n config?: ZeroConfig,\n ) {\n this.#lc = lc.withContext('clientGroupID', clientGroupID);\n this.#snapshotter = snapshotter;\n this.#storage = storage;\n this.#shardID = shardID;\n this.#logConfig = logConfig;\n this.#config = config;\n this.#inspectorDelegate = inspectorDelegate;\n this.#costModels = enablePlanner ? new WeakMap() : undefined;\n this.#yieldThresholdMs = yieldThresholdMs;\n }\n\n /**\n * Initializes the PipelineDriver to the current head of the database.\n * Queries can then be added (i.e. hydrated) with {@link addQuery()}.\n *\n * Must only be called once.\n */\n init(clientSchema: ClientSchema) {\n assert(!this.#snapshotter.initialized(), 'Already initialized');\n this.#snapshotter.init();\n this.#initAndResetCommon(clientSchema);\n }\n\n /**\n * @returns Whether the PipelineDriver has been initialized.\n */\n initialized(): boolean {\n return this.#snapshotter.initialized();\n }\n\n /**\n * Clears the current pipelines and TableSources, returning the PipelineDriver\n * to its initial state. This should be called in response to a schema change,\n * as TableSources need to be recomputed.\n */\n reset(clientSchema: ClientSchema) {\n for (const [queryID, pipeline] of this.#pipelines) {\n this.#pipelines.delete(queryID);\n this.#destroyPipeline(queryID, pipeline, 'reset');\n }\n this.#tables.clear();\n this.#allTableNames.clear();\n this.#rowSetSignatures.clear();\n this.#initAndResetCommon(clientSchema);\n }\n\n #initAndResetCommon(clientSchema: ClientSchema) {\n const {db} = this.#snapshotter.current();\n const fullTables = new Map<string, LiteTableSpec>();\n computeZqlSpecs(\n this.#lc,\n db.db,\n {includeBackfillingColumns: false},\n this.#tableSpecs,\n fullTables,\n );\n checkClientSchema(\n this.#shardID,\n clientSchema,\n this.#tableSpecs,\n fullTables,\n );\n this.#allTableNames.clear();\n for (const table of fullTables.keys()) {\n this.#allTableNames.add(table);\n }\n const primaryKeys = this.#primaryKeys ?? new Map<string, PrimaryKey>();\n this.#primaryKeys = primaryKeys;\n primaryKeys.clear();\n for (const [table, spec] of this.#tableSpecs.entries()) {\n primaryKeys.set(table, spec.tableSpec.primaryKey);\n }\n buildPrimaryKeys(clientSchema, primaryKeys);\n const {replicaVersion} = getSubscriptionState(db);\n this.#replicaVersion = replicaVersion;\n }\n\n /** @returns The replica version. The PipelineDriver must have been initialized. */\n get replicaVersion(): string {\n return must(this.#replicaVersion, 'Not yet initialized');\n }\n\n /**\n * Returns the current version of the database. This will reflect the\n * latest version change when calling {@link advance()} once the\n * iteration has begun.\n */\n currentVersion(): string {\n assert(this.initialized(), 'Not yet initialized');\n return this.#snapshotter.current().version;\n }\n\n /**\n * Returns the current upstream {app}.permissions, or `null` if none are defined.\n */\n currentPermissions(): LoadedPermissions | null {\n assert(this.initialized(), 'Not yet initialized');\n const res = reloadPermissionsIfChanged(\n this.#lc,\n this.#snapshotter.current().db,\n this.#shardID.appID,\n this.#permissions,\n this.#config,\n );\n if (res.changed) {\n this.#permissions = res.permissions;\n this.#lc.debug?.(\n 'Reloaded permissions',\n JSON.stringify(this.#permissions),\n );\n }\n return this.#permissions;\n }\n\n /**\n * Advances the snapshot to the head of the database without diffing the\n * change log, in preparation for hydrating queries at head.\n *\n * Throws a {@link ResetPipelinesSignal} if the change log records a\n * schema change since the previous snapshot. The table specs (and any\n * TableSources built from them) were computed at or before that snapshot\n * and are stale with respect to the new head, so the caller must\n * {@link reset()} before hydrating. ({@link advance()} detects this when\n * the diff encounters the RESET op; this path skips the diff and so must\n * check explicitly.)\n */\n advanceWithoutDiff(): string {\n const {prev, curr} = this.#snapshotter.advanceWithoutDiff();\n if (curr.schemaChangedSince(prev.version)) {\n throw new ResetPipelinesSignal(\n `schema changed between ${prev.version} and ${curr.version}`,\n 'schema-change',\n );\n }\n for (const table of this.#tables.values()) {\n table.setDB(curr.db.db);\n }\n return curr.version;\n }\n\n #ensureCostModelExistsIfEnabled(db: Database) {\n let existing = this.#costModels?.get(db);\n if (existing) {\n return existing;\n }\n if (this.#costModels) {\n const costModel = createSQLiteCostModel(db, this.#tableSpecs);\n this.#costModels.set(db, costModel);\n return costModel;\n }\n return undefined;\n }\n\n /**\n * Clears storage used for the pipelines. Call this when the\n * PipelineDriver will no longer be used.\n */\n destroy() {\n for (const [queryID, pipeline] of this.#pipelines) {\n this.#pipelines.delete(queryID);\n this.#destroyPipeline(queryID, pipeline, 'destroy');\n }\n this.#tables.clear();\n this.#rowSetSignatures.clear();\n this.#storage.destroy();\n this.#snapshotter.destroy();\n }\n\n /** @return Map from query ID to PipelineInfo for all added queries. */\n queries(): ReadonlyMap<string, QueryInfo> {\n return this.#pipelines;\n }\n\n totalHydrationTimeMs(): number {\n let total = 0;\n for (const pipeline of this.#pipelines.values()) {\n total += pipeline.hydrationTimeMs;\n }\n return total;\n }\n\n #logQueryPipelineLifecycle({\n zeroEvent,\n pipelineRunID,\n queryHash,\n transformationHash,\n queryName,\n hydrationReason,\n stopReason,\n hydrationTimeMs,\n hydrationRowCount,\n pipelineLifetimeMs,\n }: QueryPipelineLifecycleLog): void {\n let lc = this.#lc\n .withContext('zeroEvent', zeroEvent)\n .withContext('pipelineRunID', pipelineRunID)\n .withContext('queryHash', queryHash)\n .withContext('transformationHash', transformationHash);\n if (queryName !== undefined) {\n lc = lc.withContext('queryName', queryName);\n }\n if (hydrationReason !== undefined) {\n lc = lc.withContext('hydrationReason', hydrationReason);\n }\n if (stopReason !== undefined) {\n lc = lc.withContext('stopReason', stopReason);\n }\n if (hydrationTimeMs !== undefined) {\n lc = lc.withContext('hydrationTimeMs', hydrationTimeMs);\n }\n if (hydrationRowCount !== undefined) {\n lc = lc.withContext('hydrationRowCount', hydrationRowCount);\n }\n if (pipelineLifetimeMs !== undefined) {\n lc = lc.withContext('pipelineLifetimeMs', pipelineLifetimeMs);\n }\n lc.info?.('query pipeline lifecycle');\n }\n\n /**\n * A `{scalar: true}` that cannot be honored degrades silently to a plain\n * EXISTS, so the author gets none of the plan they asked for and no signal\n * that they didn't. Say so, with the unique keys that were actually\n * available — the client schema knows only primary keys, so this is the only\n * place the advice can be correct.\n */\n #warnIgnoredScalarHints(queryID: string, hints: IgnoredScalarHint[]): void {\n for (const {table, uniqueKeys} of hints) {\n const keys = uniqueKeys.map(k => `(${k.join(', ')})`).join(', ');\n this.#lc.warn?.(\n `Ignoring {scalar: true} on the \"${table}\" subquery of query ` +\n `${queryID}: it does not constrain every column of any unique key ` +\n `${keys.length > 0 ? `[${keys}]` : '(none on this table)'} to a ` +\n `literal with \"=\", so it is not provably limited to one row. ` +\n `The gate runs as a plain EXISTS.`,\n );\n }\n }\n\n #disableCorrelatedPredicatePushdown(): boolean {\n return this.#config?.enableCorrelatedPredicatePushdown === false;\n }\n\n #resolveScalarSubqueries(ast: AST): {\n ast: AST;\n companionRows: {table: string; row: Row}[];\n companions: CompanionSubquery[];\n companionInputs: Input[];\n ignoredScalarHints: IgnoredScalarHint[];\n } {\n const companionRows: {table: string; row: Row}[] = [];\n const companionInputs: Input[] = [];\n\n const executor = (\n subqueryAST: AST,\n childField: string,\n ): LiteralValue | null | undefined => {\n const input = buildPipeline(\n subqueryAST,\n {\n disableCorrelatedPredicatePushdown:\n this.#disableCorrelatedPredicatePushdown(),\n getSource: name => this.#getSource(name),\n createStorage: () => this.#createStorage(),\n decorateSourceInput: (input: SourceInput): Input => input,\n decorateInput: input => input,\n addEdge() {},\n decorateFilterInput: input => input,\n },\n 'scalar-subquery',\n );\n // Tracked before it is fetched so that a failure in this or a later\n // subquery can tear it down below. A companion with no result is kept\n // alive too: it detects a future insert that creates the row.\n companionInputs.push(input);\n // Consume the full stream rather than using first() to avoid\n // triggering early return on Take's #initialFetch assertion.\n // The subquery AST already has limit: 1, so at most one row is produced.\n let node: Node | undefined;\n for (const n of skipYields(input.fetch({}))) {\n node ??= n;\n }\n if (!node) {\n return undefined;\n }\n companionRows.push({table: subqueryAST.table, row: node.row as Row});\n return (node.row[childField] as LiteralValue) ?? null;\n };\n\n let resolved: AST;\n let companions: CompanionSubquery[];\n let ignoredScalarHints: IgnoredScalarHint[];\n try {\n ({\n ast: resolved,\n companions,\n ignoredScalarHints,\n } = resolveSimpleScalarSubqueries(ast, this.#tableSpecs, executor));\n } catch (e) {\n for (const input of companionInputs) {\n input.destroy();\n }\n throw e;\n }\n return {\n ast: resolved,\n companionRows,\n companions,\n companionInputs,\n ignoredScalarHints,\n };\n }\n\n /**\n * Adds a pipeline for the query. The method will hydrate the query using the\n * driver's current snapshot of the database and return a stream of results.\n * Henceforth, updates to the query will be returned when the driver is\n * {@link advance}d. The query and its pipeline can be removed with\n * {@link removeQuery()}.\n *\n * If a query with the same queryID is already added, the existing pipeline\n * will be removed and destroyed before adding the new pipeline.\n *\n * @param timer The caller-controlled {@link Timer} used to determine the\n * final hydration time. (The caller may pause and resume the timer\n * when yielding the thread for time-slicing).\n * @return The rows from the initial hydration of the query.\n */\n addQuery(\n transformationHash: string,\n queryID: string,\n query: AST,\n timer: Timer,\n queryName?: string,\n hydrationReason: PipelineHydrationReason = 'query-set-sync',\n ): Iterable<RowChange | 'yield'> {\n return this.#trackRowSetSignatures(\n this.#addQueryImpl(\n transformationHash,\n queryID,\n query,\n timer,\n queryName,\n hydrationReason,\n ),\n );\n }\n\n *#addQueryImpl(\n transformationHash: string,\n queryID: string,\n query: AST,\n timer: Timer,\n queryName?: string,\n hydrationReason: PipelineHydrationReason = 'query-set-sync',\n ): Iterable<RowChange | 'yield'> {\n assert(\n this.initialized(),\n 'Pipeline driver must be initialized before adding queries',\n );\n this.removeQuery(queryID, 'replace-query');\n const pipelineRunID = randomID();\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-hydrate-start',\n pipelineRunID,\n queryHash: queryID,\n transformationHash,\n queryName,\n hydrationReason,\n });\n const debugDelegate = runtimeDebugFlags.trackRowsVended\n ? new Debug(true)\n : undefined;\n\n const costModel = this.#ensureCostModelExistsIfEnabled(\n this.#snapshotter.current().db.db,\n );\n\n assert(\n this.#advanceContext === null,\n 'Cannot hydrate while advance is in progress',\n );\n this.#hydrateContext = {\n timer,\n };\n let hydrationFinished = false;\n let hydrationFailed = false;\n let hydrationRowCount = 0;\n // The inputs built so far, held outside the try so that a hydration that\n // does not finish (aborted by the consumer or failed) can tear them down.\n // Only a finished hydration hands them over to #pipelines.\n let builtInputs: Input[] = [];\n try {\n const {\n ast: resolvedQuery,\n companionRows,\n companions: companionMeta,\n companionInputs,\n ignoredScalarHints,\n } = this.#resolveScalarSubqueries(query);\n builtInputs = [...companionInputs];\n\n this.#warnIgnoredScalarHints(queryID, ignoredScalarHints);\n\n const input = buildPipeline(\n resolvedQuery,\n {\n debug: debugDelegate,\n enableNotExists: true, // Server-side can handle NOT EXISTS\n disableCorrelatedPredicatePushdown:\n this.#disableCorrelatedPredicatePushdown(),\n enablePlannerAwarePushdown:\n this.#config?.enablePlannerAwarePushdown !== false,\n getSource: name => this.#getSource(name),\n createStorage: () => this.#createStorage(),\n decorateSourceInput: (input: SourceInput, _queryID: string): Input =>\n new MeasurePushOperator(\n new QueryFailureLoggingOperator(\n this.#lc,\n input,\n queryID,\n transformationHash,\n queryName,\n ),\n queryID,\n this.#inspectorDelegate,\n 'query-update-server',\n ),\n decorateInput: input => input,\n addEdge() {},\n decorateFilterInput: input => input,\n },\n queryID,\n costModel,\n );\n builtInputs.push(input);\n const schema = input.getSchema();\n input.setOutput({\n push: change => {\n const streamer = this.#streamer;\n assert(streamer, 'must #startAccumulating() before pushing changes');\n streamer.accumulate(queryID, schema, [change]);\n return [];\n },\n });\n\n for (const change of hydrateInternal(\n input,\n queryID,\n must(this.#primaryKeys),\n this.#tableSpecs,\n )) {\n if (change !== 'yield') {\n hydrationRowCount++;\n }\n yield change;\n }\n\n for (const {table, row} of companionRows) {\n const primaryKey = mustGetPrimaryKey(this.#primaryKeys, table);\n hydrationRowCount++;\n yield {\n type: ChangeType.ADD,\n queryID,\n table,\n rowKey: getRowKey(primaryKey, row),\n row,\n } as RowChange;\n }\n\n const hydrationTimeMs = timer.totalElapsed();\n if (runtimeDebugFlags.trackRowCountsVended) {\n if (hydrationTimeMs > this.#logConfig.slowHydrateThreshold) {\n let totalRowsConsidered = 0;\n const lc = this.#lc\n .withContext('queryID', queryID)\n .withContext('hydrationTimeMs', hydrationTimeMs);\n for (const tableName of this.#tables.keys()) {\n const entries = Object.entries(\n debugDelegate?.getVendedRowCounts()[tableName] ?? {},\n );\n totalRowsConsidered += entries.reduce(\n (acc, entry) => acc + entry[1],\n 0,\n );\n lc.info?.(tableName + ' VENDED: ', entries);\n }\n lc.info?.(`Total rows considered: ${totalRowsConsidered}`);\n }\n }\n debugDelegate?.reset();\n\n // Set up live companion pipelines for reactive scalar subquery monitoring.\n const liveCompanions: CompanionPipeline[] = [];\n for (let i = 0; i < companionMeta.length; i++) {\n const meta = companionMeta[i];\n const companionInput = companionInputs[i];\n const companionSchema = companionInput.getSchema();\n const {childField, resolvedValue} = meta;\n companionInput.setOutput({\n push: (change: Change) => {\n let newValue: LiteralValue | null | undefined;\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n case ChangeType.EDIT:\n newValue =\n (change[ChangeIndex.NODE].row[childField] as LiteralValue) ??\n null;\n break;\n case ChangeType.REMOVE:\n newValue = undefined;\n break;\n case ChangeType.CHILD:\n return [];\n }\n if (!scalarValuesEqual(newValue, resolvedValue)) {\n throw new ResetPipelinesSignal(\n `Scalar subquery value changed for ${meta.ast.table}: ` +\n `${String(resolvedValue)} -> ${String(newValue)}`,\n 'scalar-subquery',\n );\n }\n const streamer = this.#streamer;\n assert(\n streamer,\n 'must #startAccumulating() before pushing changes',\n );\n streamer.accumulate(queryID, companionSchema, [change]);\n return [];\n },\n });\n liveCompanions.push({input: companionInput, childField, resolvedValue});\n }\n\n // Note: This hydrationTime is a wall-clock overestimate, as it does\n // not take time slicing into account. The view-syncer resets this\n // to a more precise processing-time measurement with setHydrationTime().\n const pipelineReadyAtMs = Date.now();\n this.#pipelines.set(queryID, {\n input,\n hydrationTimeMs,\n hydrationRowCount,\n hydrationReason,\n pipelineRunID,\n pipelineReadyAtMs,\n transformedAst: resolvedQuery,\n originalAst: query,\n transformationHash,\n ...(queryName !== undefined && {queryName}),\n companions: liveCompanions,\n });\n hydrationFinished = true;\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-hydrate-finish',\n pipelineRunID,\n queryHash: queryID,\n transformationHash,\n queryName,\n hydrationReason,\n hydrationTimeMs,\n hydrationRowCount,\n });\n } catch (e) {\n hydrationFailed = true;\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-hydrate-failed',\n pipelineRunID,\n queryHash: queryID,\n transformationHash,\n queryName,\n hydrationReason,\n hydrationTimeMs: timer.totalElapsed(),\n hydrationRowCount,\n });\n logQueryFailure(\n this.#lc,\n {queryHash: queryID, transformationHash, queryName},\n 'query hydration failed',\n e,\n );\n throw e;\n } finally {\n if (!hydrationFinished && !hydrationFailed) {\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-hydrate-aborted',\n pipelineRunID,\n queryHash: queryID,\n transformationHash,\n queryName,\n hydrationReason,\n hydrationTimeMs: timer.totalElapsed(),\n hydrationRowCount,\n });\n }\n if (!hydrationFinished) {\n for (const input of builtInputs) {\n input.destroy();\n }\n this.#pruneUnusedTables();\n // Rows may already have been yielded through #trackRowSetSignatures,\n // and rowSetSignature() must not report a signature for a query\n // without an active pipeline.\n this.#rowSetSignatures.delete(queryID);\n }\n this.#hydrateContext = null;\n }\n }\n\n /**\n * Removes the pipeline for the query. This is a no-op if the query\n * was not added.\n */\n removeQuery(\n queryID: string,\n stopReason: PipelineStopReason = 'remove-query',\n ) {\n const pipeline = this.#pipelines.get(queryID);\n if (pipeline) {\n this.#pipelines.delete(queryID);\n this.#destroyPipeline(queryID, pipeline, stopReason);\n this.#pruneUnusedTables();\n }\n this.#rowSetSignatures.delete(queryID);\n }\n\n #pruneUnusedTables() {\n for (const [table, source] of this.#tables.entries()) {\n if (!source.hasConnections()) {\n this.#tables.delete(table);\n }\n }\n }\n\n #destroyPipeline(\n queryID: string,\n pipeline: Pipeline,\n stopReason: PipelineStopReason,\n ): void {\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-stop',\n pipelineRunID: pipeline.pipelineRunID,\n queryHash: queryID,\n transformationHash: pipeline.transformationHash,\n queryName: pipeline.queryName,\n hydrationReason: pipeline.hydrationReason,\n stopReason,\n hydrationTimeMs: pipeline.hydrationTimeMs,\n hydrationRowCount: pipeline.hydrationRowCount,\n pipelineLifetimeMs: Date.now() - pipeline.pipelineReadyAtMs,\n });\n pipeline.input.destroy();\n for (const companion of pipeline.companions) {\n companion.input.destroy();\n }\n }\n\n /**\n * Current XOR signature of the row-set attached to `queryID`, or\n * `undefined` if no pipeline for the query is currently active.\n * Maintained incrementally by {@link addQuery} and {@link advance}.\n */\n rowSetSignature(queryID: string): bigint | undefined {\n return this.#rowSetSignatures.get(queryID);\n }\n\n /**\n * Wraps an iterable of RowChanges, XORing each row's unit hash into the\n * query's signature (ADDs and REMOVEs share the same op; EDITs are no-ops).\n * Used to intercept the yield streams from {@link addQuery} and\n * {@link advance}.\n */\n *#trackRowSetSignatures(\n changes: Iterable<RowChange | 'yield'>,\n ): Iterable<RowChange | 'yield'> {\n for (const change of changes) {\n if (change !== 'yield' && change.type !== ChangeType.EDIT) {\n const cur = this.#rowSetSignatures.get(change.queryID) ?? 0n;\n const unit = rowIDSignatureUnit({\n schema: '',\n table: change.table,\n rowKey: change.rowKey as RowKey,\n });\n this.#rowSetSignatures.set(change.queryID, cur ^ unit);\n }\n yield change;\n }\n }\n\n /**\n * Returns the value of the row with the given primary key `pk`,\n * or `undefined` if there is no such row. The pipeline must have been\n * initialized.\n */\n getRow(table: string, pk: RowKey): Row | undefined {\n assert(this.initialized(), 'Not yet initialized');\n const source = must(this.#tables.get(table));\n return source.getRow(pk as Row);\n }\n\n /**\n * Advances to the new head of the database.\n *\n * @param timer The caller-controlled {@link Timer} that will be used to\n * measure the progress of the advancement and abort with a\n * {@link ResetPipelinesSignal} if it is estimated to take longer\n * than a hydration.\n * @return The resulting row changes for all added queries. Note that the\n * `changes` must be iterated over in their entirety in order to\n * advance the database snapshot.\n */\n advance(timer: Timer): {\n version: string;\n numChanges: number;\n changes: Iterable<RowChange | 'yield'>;\n } {\n assert(\n this.initialized(),\n 'Pipeline driver must be initialized before advancing',\n );\n const diff = this.#snapshotter.advance(\n this.#tableSpecs,\n this.#allTableNames,\n this.#tables,\n );\n const {prev, curr, changes} = diff;\n this.#lc.debug?.(\n `advance ${prev.version} => ${curr.version}: ${changes} changes`,\n );\n\n return {\n version: curr.version,\n numChanges: changes,\n changes: this.#trackRowSetSignatures(this.#advance(diff, timer, changes)),\n };\n }\n\n *#advance(\n diff: SnapshotDiff,\n timer: Timer,\n numChanges: number,\n ): Iterable<RowChange | 'yield'> {\n assert(\n this.#hydrateContext === null,\n 'Cannot advance while hydration is in progress',\n );\n const totalHydrationTimeMs = this.totalHydrationTimeMs();\n this.#advanceContext = {\n timer,\n totalHydrationTimeMs,\n numChanges,\n currentChangeStartMs: undefined,\n pos: 0,\n };\n this.#lc.debug?.(\n `starting pipeline advancement of ${numChanges} changes with an ` +\n `advancement time limited based on total hydration time of ` +\n `${totalHydrationTimeMs} ms.`,\n );\n try {\n for (const {table, prevValues, nextValue} of diff) {\n // Advance progress is checked each time a row is fetched\n // from a TableSource during push processing, but some pushes\n // don't read any rows. Check progress here before processing\n // the next change.\n if (this.#shouldAdvanceYieldMaybeAbortAdvance()) {\n yield 'yield';\n }\n const start = timer.totalElapsed();\n const advanceContext = must(this.#advanceContext);\n advanceContext.currentChangeStartMs = start;\n\n try {\n try {\n const tableSource = this.#tables.get(table);\n if (!tableSource) {\n // no pipelines read from this table, so no need to process the change\n continue;\n }\n const primaryKey = mustGetPrimaryKey(this.#primaryKeys, table);\n let editOldRow: Row | undefined = undefined;\n for (const prevValue of prevValues) {\n if (\n nextValue &&\n deepEqual(\n getRowKey(primaryKey, prevValue as Row) as JSONValue,\n getRowKey(primaryKey, nextValue as Row) as JSONValue,\n )\n ) {\n editOldRow = prevValue;\n } else {\n if (nextValue) {\n this.#conflictRowsDeleted.add(1);\n }\n yield* this.#push(\n tableSource,\n makeSourceChangeRemove(prevValue as Row),\n );\n }\n }\n if (nextValue) {\n if (editOldRow) {\n yield* this.#push(\n tableSource,\n makeSourceChangeEdit(nextValue as Row, editOldRow),\n );\n } else {\n yield* this.#push(\n tableSource,\n makeSourceChangeAdd(nextValue as Row),\n );\n }\n }\n } finally {\n advanceContext.pos++;\n }\n\n this.#shouldAdvanceYieldMaybeAbortAdvance(false);\n } finally {\n advanceContext.currentChangeStartMs = undefined;\n }\n\n const elapsed = timer.totalElapsed() - start;\n this.#advanceTime.recordMs(elapsed, {\n table,\n });\n }\n\n // Set the new snapshot on all TableSources.\n const {curr} = diff;\n for (const table of this.#tables.values()) {\n table.setDB(curr.db.db);\n }\n this.#ensureCostModelExistsIfEnabled(curr.db.db);\n this.#lc.debug?.(`Advanced to ${curr.version}`);\n } finally {\n this.#advanceContext = null;\n }\n }\n\n /** Implements `BuilderDelegate.getSource()` */\n #getSource(tableName: string): Source {\n return getOrInsertComputed(this.#tables, tableName, tableName => {\n const tableSpec = mustGetTableSpec(this.#tableSpecs, tableName);\n const primaryKey = mustGetPrimaryKey(this.#primaryKeys, tableName);\n\n const {db} = this.#snapshotter.current();\n const source = new TableSource(\n this.#lc,\n this.#logConfig,\n db.db,\n tableName,\n tableSpec.zqlSpec,\n primaryKey,\n () => this.#shouldYield(),\n // Pipelines only read tables through their connections, and the\n // sources are moved to the next snapshot after every advancement.\n {skipUnobservableChanges: true},\n );\n this.#lc.debug?.(`created TableSource for ${tableName}`);\n return source;\n });\n }\n\n #shouldYield(): boolean {\n if (this.#hydrateContext) {\n return this.#hydrateContext.timer.elapsedLap() > this.#yieldThresholdMs();\n }\n if (this.#advanceContext) {\n return this.#shouldAdvanceYieldMaybeAbortAdvance();\n }\n throw new Error('shouldYield called outside of hydration or advancement');\n }\n\n /**\n * Cancel advancement processing when either the whole batch projects to be\n * more expensive than hydration, or the current source change alone exceeds\n * the hydration budget. The late-finish exception only applies to batch-level\n * checks; a single pathological push always resets.\n */\n #shouldAdvanceYieldMaybeAbortAdvance(checkYield = true): boolean {\n const {\n currentChangeStartMs,\n pos,\n numChanges,\n timer: advanceTimer,\n totalHydrationTimeMs,\n } = must(this.#advanceContext);\n const elapsed = advanceTimer.totalElapsed();\n const currentChangeElapsedMs =\n currentChangeStartMs === undefined\n ? undefined\n : elapsed - currentChangeStartMs;\n if (\n currentChangeElapsedMs !== undefined &&\n shouldResetSlowCurrentChange(currentChangeElapsedMs, totalHydrationTimeMs)\n ) {\n this.#throwSlowCurrentChangeReset(\n pos,\n numChanges,\n elapsed,\n currentChangeElapsedMs,\n totalHydrationTimeMs,\n );\n }\n const projectedTotalTimeMs = projectedAdvancementTimeMs(\n elapsed,\n pos,\n numChanges,\n );\n const shouldFinish = shouldFinishLateAdvancement(pos, numChanges);\n if (\n !shouldFinish &&\n shouldResetProjectedAdvancement(\n elapsed,\n projectedTotalTimeMs,\n pos,\n numChanges,\n totalHydrationTimeMs,\n )\n ) {\n this.#throwProjectedAdvancementReset(\n pos,\n numChanges,\n elapsed,\n projectedTotalTimeMs,\n totalHydrationTimeMs,\n );\n }\n if (\n !shouldFinish &&\n elapsed > MIN_ADVANCEMENT_TIME_LIMIT_MS &&\n (elapsed > totalHydrationTimeMs ||\n (elapsed > totalHydrationTimeMs / 2 && pos <= numChanges / 2))\n ) {\n throw new ResetPipelinesSignal(\n `Advancement exceeded timeout at ${pos} of ${numChanges} changes ` +\n `after ${elapsed} ms. Advancement time limited based on total ` +\n `hydration time of ${totalHydrationTimeMs} ms.`,\n 'advancement-timeout',\n );\n }\n return checkYield && advanceTimer.elapsedLap() > this.#yieldThresholdMs();\n }\n\n #throwSlowCurrentChangeReset(\n pos: number,\n numChanges: number,\n elapsed: number,\n currentChangeElapsedMs: number,\n totalHydrationTimeMs: number,\n ): never {\n throw new ResetPipelinesSignal(\n `Advancement exceeded timeout processing current change at ${pos} of ` +\n `${numChanges} changes after ${currentChangeElapsedMs} ms ` +\n `(${elapsed} ms total). Advancement time limited based on total ` +\n `hydration time of ${totalHydrationTimeMs} ms.`,\n 'advancement-timeout',\n );\n }\n\n #throwProjectedAdvancementReset(\n pos: number,\n numChanges: number,\n elapsed: number,\n projectedTotalTimeMs: number | undefined,\n totalHydrationTimeMs: number,\n ): never {\n const projection =\n projectedTotalTimeMs === undefined\n ? ''\n : ` Projected total advancement time is ${projectedTotalTimeMs} ms.`;\n throw new ResetPipelinesSignal(\n `Advancement projected to exceed hydration time at ${pos} of ` +\n `${numChanges} changes after ${elapsed} ms.` +\n projection +\n ` Advancement time limited based on total hydration time of ` +\n `${totalHydrationTimeMs} ms.`,\n 'advancement-timeout',\n );\n }\n\n /** Implements `BuilderDelegate.createStorage()` */\n #createStorage(): Storage {\n return this.#storage.createStorage();\n }\n\n *#push(\n source: TableSource,\n change: SourceChange,\n ): Iterable<RowChange | 'yield'> {\n this.#startAccumulating();\n try {\n for (const val of source.genPush(change)) {\n if (val === 'yield') {\n yield 'yield';\n }\n for (const changeOrYield of this.#stopAccumulating().stream()) {\n yield changeOrYield;\n }\n this.#startAccumulating();\n }\n } finally {\n if (this.#streamer !== null) {\n this.#stopAccumulating();\n }\n }\n }\n\n #startAccumulating() {\n assert(this.#streamer === null, 'Streamer already started');\n this.#streamer = new Streamer(\n must(this.#primaryKeys),\n this.#tableSpecs,\n (queryID, error) =>\n this.#logQueryFailure(queryID, 'query pipeline failed', error),\n );\n }\n\n #stopAccumulating(): Streamer {\n const streamer = this.#streamer;\n assert(streamer, 'Streamer not started');\n this.#streamer = null;\n return streamer;\n }\n\n #logQueryFailure(queryID: string, message: string, error: unknown): void {\n const pipeline = this.#pipelines.get(queryID);\n const queryInfo = pipeline\n ? {\n queryHash: queryID,\n transformationHash: pipeline.transformationHash,\n queryName: pipeline.queryName,\n }\n : undefined;\n logQueryFailure(this.#lc, queryInfo, message, error);\n }\n}\n\nclass Streamer {\n readonly #primaryKeys: Map<string, PrimaryKey>;\n readonly #tableSpecs: Map<string, LiteAndZqlSpec>;\n readonly #logQueryFailure:\n | ((queryID: string, error: unknown) => void)\n | undefined;\n\n constructor(\n primaryKeys: Map<string, PrimaryKey>,\n tableSpecs: Map<string, LiteAndZqlSpec>,\n logQueryFailure?: (queryID: string, error: unknown) => void,\n ) {\n this.#primaryKeys = primaryKeys;\n this.#tableSpecs = tableSpecs;\n this.#logQueryFailure = logQueryFailure;\n }\n\n readonly #changes: [\n queryID: string,\n schema: SourceSchema,\n changes: Iterable<Change | 'yield'>,\n ][] = [];\n\n accumulate(\n queryID: string,\n schema: SourceSchema,\n changes: Iterable<Change | 'yield'>,\n ): this {\n this.#changes.push([queryID, schema, changes]);\n return this;\n }\n\n *stream(): Iterable<RowChange | 'yield'> {\n for (const [queryID, schema, changes] of this.#changes) {\n try {\n yield* this.#streamChanges(queryID, schema, changes);\n } catch (e) {\n this.#logQueryFailure?.(queryID, e);\n throw e;\n }\n }\n }\n\n *#streamChanges(\n queryID: string,\n schema: SourceSchema,\n changes: Iterable<Change | 'yield'>,\n ): Iterable<RowChange | 'yield'> {\n // We do not sync rows gathered by the permissions\n // system to the client.\n if (schema.system === 'permissions') {\n return;\n }\n\n for (const change of changes) {\n if (change === 'yield') {\n yield change;\n continue;\n }\n const type = change[ChangeIndex.TYPE];\n switch (type) {\n case ChangeType.REMOVE:\n case ChangeType.ADD: {\n yield* this.#streamNodes(queryID, schema, type, () => [\n change[ChangeIndex.NODE],\n ]);\n break;\n }\n\n case ChangeType.CHILD: {\n const child = change[ChangeIndex.CHILD_DATA];\n const childSchema = must(\n schema.relationships[child.relationshipName],\n );\n\n yield* this.#streamChanges(queryID, childSchema, [child.change]);\n break;\n }\n case ChangeType.EDIT:\n yield* this.#streamNodes(queryID, schema, type, () => [\n {row: change[ChangeIndex.NODE].row, relationships: {}},\n ]);\n break;\n default:\n unreachable(change[ChangeIndex.TYPE]);\n }\n }\n }\n\n *#streamNodes(\n queryID: string,\n schema: SourceSchema,\n op: ChangeType.ADD | ChangeType.REMOVE | ChangeType.EDIT,\n nodes: () => Iterable<Node | 'yield'>,\n ): Iterable<RowChange | 'yield'> {\n const {tableName: table, system} = schema;\n\n const primaryKey = must(this.#primaryKeys.get(table));\n const spec = must(this.#tableSpecs.get(table)).tableSpec;\n\n // We do not sync rows gathered by the permissions\n // system to the client.\n if (system === 'permissions') {\n return;\n }\n\n for (const node of nodes()) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n const {relationships} = node;\n let {row} = node;\n const rowKey = getRowKey(primaryKey, row);\n if (op !== ChangeType.REMOVE) {\n const rowVersion = row[ZERO_VERSION_COLUMN_NAME];\n if (\n typeof rowVersion === 'string' &&\n rowVersion < (spec.minRowVersion ?? '00')\n ) {\n row = {...row, [ZERO_VERSION_COLUMN_NAME]: spec.minRowVersion};\n }\n }\n\n yield {\n type: op,\n queryID,\n table,\n rowKey,\n row: op === ChangeType.REMOVE ? undefined : row,\n } as RowChange;\n\n for (const [relationship, children] of Object.entries(relationships)) {\n const childSchema = must(schema.relationships[relationship]);\n yield* this.#streamNodes(queryID, childSchema, op, children);\n }\n }\n }\n}\n\nclass QueryFailureLoggingOperator implements Input, Output {\n readonly #lc: LogContext;\n readonly #input: Input;\n readonly #queryHash: string;\n readonly #transformationHash: string;\n readonly #queryName: string | undefined;\n #output: Output = throwOutput;\n\n constructor(\n lc: LogContext,\n input: Input,\n queryHash: string,\n transformationHash: string,\n queryName?: string,\n ) {\n this.#lc = lc;\n this.#input = input;\n this.#queryHash = queryHash;\n this.#transformationHash = transformationHash;\n this.#queryName = queryName;\n input.setOutput(this);\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n fetch(req: FetchRequest): Iterable<Node | 'yield'> {\n return this.#input.fetch(req);\n }\n\n *push(change: Change): Iterable<'yield'> {\n try {\n yield* this.#output.push(change, this);\n } catch (e) {\n logQueryFailure(\n this.#lc,\n {\n queryHash: this.#queryHash,\n transformationHash: this.#transformationHash,\n queryName: this.#queryName,\n },\n 'query pipeline failed',\n e,\n );\n throw e;\n }\n }\n}\n\nfunction logQueryFailure(\n lc: LogContext,\n queryInfo: QueryLogInfo | undefined,\n message: string,\n error: unknown,\n): void {\n if (error instanceof ResetPipelinesSignal) {\n return;\n }\n let queryLC = lc;\n if (queryInfo) {\n queryLC = queryLC\n .withContext('queryHash', queryInfo.queryHash)\n .withContext('transformationHash', queryInfo.transformationHash);\n if (queryInfo.queryName !== undefined) {\n queryLC = queryLC.withContext('queryName', queryInfo.queryName);\n }\n }\n queryLC.error?.(message, error);\n}\n\nfunction* toAdds(nodes: Iterable<Node | 'yield'>): Iterable<Change | 'yield'> {\n for (const node of nodes) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n yield [ChangeType.ADD, node, null];\n }\n}\n\nfunction getRowKey(cols: PrimaryKey, row: Row): RowKey {\n return Object.fromEntries(cols.map(col => [col, must(row[col])]));\n}\n\n/**\n * Core hydration logic used by {@link PipelineDriver#addQuery}, extracted to a\n * function for reuse by the analyze-query RPC path so that analysis hydrates\n * queries the same way the view-syncer does in production.\n */\nexport function hydrate(\n input: Input,\n hash: string,\n clientSchema: ClientSchema,\n tableSpecs: Map<string, LiteAndZqlSpec>,\n): Iterable<RowChange | 'yield'> {\n const res = input.fetch({});\n const streamer = new Streamer(\n buildPrimaryKeys(clientSchema),\n tableSpecs,\n ).accumulate(hash, input.getSchema(), toAdds(res));\n return streamer.stream();\n}\n\nexport function hydrateInternal(\n input: Input,\n hash: string,\n primaryKeys: Map<string, PrimaryKey>,\n tableSpecs: Map<string, LiteAndZqlSpec>,\n): Iterable<RowChange | 'yield'> {\n const res = input.fetch({});\n const streamer = new Streamer(primaryKeys, tableSpecs).accumulate(\n hash,\n input.getSchema(),\n toAdds(res),\n );\n return streamer.stream();\n}\n\nfunction buildPrimaryKeys(\n clientSchema: ClientSchema,\n primaryKeys: Map<string, PrimaryKey> = new Map<string, PrimaryKey>(),\n) {\n for (const [tableName, {primaryKey}] of Object.entries(clientSchema.tables)) {\n primaryKeys.set(tableName, primaryKey as unknown as PrimaryKey);\n }\n return primaryKeys;\n}\n\nfunction mustGetPrimaryKey(\n primaryKeys: Map<string, PrimaryKey> | null,\n table: string,\n): PrimaryKey {\n const pKeys = must(primaryKeys, 'primaryKey map must be non-null');\n\n const rv = pKeys.get(table);\n assert(\n rv,\n () =>\n // oxlint-disable-next-line e18e/prefer-array-to-sorted\n `table '${table}' is not one of: ${JSON.stringify([...pKeys.keys()].sort())}. ` +\n `Check the spelling and ensure that the table has a primary key.`,\n );\n return rv;\n}\n\n/**\n * Compares two scalar subquery resolved values for equality.\n * Unlike `valuesEqual` in data.ts (which treats null != null for join\n * semantics), this uses identity semantics: undefined === undefined\n * (no row matched), null === null (row matched but field was NULL).\n */\nfunction scalarValuesEqual(\n a: LiteralValue | null | undefined,\n b: LiteralValue | null | undefined,\n): boolean {\n return a === b;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0KA,IAAM,gCAAgC;AACtC,IAAM,2CAA2C;AACjD,IAAM,wCAAwC;AAC9C,IAAM,2CAA2C;AACjD,IAAM,sCAAsC;AAC5C,IAAM,oCAAoC;AAC1C,IAAM,yCAAyC;AAC/C,IAAM,mCAAmC;AAEzC,SAAS,WAAW;CAClB,OAAO,QAAQ,GAAG,OAAO,gBAAgB,EAAE,SAAS,EAAE;AACxD;AAEA,SAAS,2BACP,WACA,kBACA,YACoB;CACpB,IAAI,oBAAoB,KAAK,cAAc,GACzC;CAEF,OAAQ,YAAY,mBAAoB;AAC1C;AAEA,SAAS,4BAA4B,sBAAsC;CACzE,OAAO,KAAK,IAAI,sBAAsB,CAAC;AACzC;AAEA,SAAS,qCAAqC,YAA4B;CACxE,OAAO,KAAK,IACV,0CACA,KAAK,IACH,0CACA,KAAK,KAAK,aAAa,qCAAqC,CAC9D,CACF;AACF;AAEA,SAAS,gCACP,WACA,sBACA,kBACA,YACA,sBACS;CACT,IACE,yBAAyB,KAAA,KACzB,aAAa,qCACb,mBAAmB,qCAAqC,UAAU,KAClE,YAAY,qCAEZ,OAAO;CAGT,OACE,uBACA,4BAA4B,oBAAoB,IAC9C;AAEN;AAEA,SAAS,4BACP,kBACA,YACS;CACT,OACE,aAAa,KACb,mBAAmB,cAAc;AAErC;AAEA,SAAS,6BACP,wBACA,sBACS;CACT,OACE,yBAAyB,iCACzB,yBAAyB,4BAA4B,oBAAoB;AAE7E;;;;AAKA,IAAa,iBAAb,MAA4B;CAC1B,0BAAmB,IAAI,IAAyB;CAEhD,6BAAsB,IAAI,IAAsB;;;;;;;;;CAShD,oCAA6B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AAC,KAAK,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;AAClE;;;;;;AAOA,SAAgB,QACd,OACA,MACA,cACA,YAC+B;CAC/B,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC;CAK1B,OAJiB,IAAI,SACnB,iBAAiB,YAAY,GAC7B,UACF,EAAE,WAAW,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,CACzC,EAAS,OAAO;AACzB;AAEA,SAAgB,gBACd,OACA,MACA,aACA,YAC+B;CAC/B,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC;CAM1B,OALiB,IAAI,SAAS,aAAa,UAAU,EAAE,WACrD,MACA,MAAM,UAAU,GAChB,OAAO,GAAG,CAEL,EAAS,OAAO;AACzB;AAEA,SAAS,iBACP,cACA,8BAAuC,IAAI,IAAwB,GACnE;CACA,KAAK,MAAM,CAAC,WAAW,EAAC,iBAAgB,OAAO,QAAQ,aAAa,MAAM,GACxE,YAAY,IAAI,WAAW,UAAmC;CAEhE,OAAO;AACT;AAEA,SAAS,kBACP,aACA,OACY;CACZ,MAAM,QAAQ,KAAK,aAAa,iCAAiC;CAEjE,MAAM,KAAK,MAAM,IAAI,KAAK;CAC1B,OACE,UAGE,UAAU,MAAM,mBAAmB,KAAK,UAAU,CAAC,GAAG,MAAM,KAAK,CAAC,EAAE,KAAK,CAAC,EAAE,kEAEhF;CACA,OAAO;AACT;;;;;;;AAQA,SAAS,kBACP,GACA,GACS;CACT,OAAO,MAAM;AACf"}
|
|
1
|
+
{"version":3,"file":"pipeline-driver.js","names":["#tables","#pipelines","#rowSetSignatures","#lc","#snapshotter","#storage","#shardID","#logConfig","#config","#tableSpecs","#allTableNames","#costModels","#yieldThresholdMs","#advanceTime","#conflictRowsDeleted","#inspectorDelegate","#initAndResetCommon","#destroyPipeline","#primaryKeys","#replicaVersion","#permissions","#disableCorrelatedPredicatePushdown","#getSource","#createStorage","#trackRowSetSignatures","#addQueryImpl","#logQueryPipelineLifecycle","#ensureCostModelExistsIfEnabled","#advanceContext","#hydrateContext","#resolveScalarSubqueries","#warnIgnoredScalarHints","#streamPushed","#pruneUnusedTables","#advance","#shouldAdvanceYieldMaybeAbortAdvance","#push","#shouldYield","#throwSlowCurrentChangeReset","#throwProjectedAdvancementReset","#startAccumulating","#stopAccumulating","#streamer","#logQueryFailure","#changes","#rowChanges","#streamChanges","#streamNodes","#input","#queryHash","#transformationHash","#queryName","#output"],"sources":["../../../../../../zero-cache/src/services/view-syncer/pipeline-driver.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert, unreachable} from '../../../../shared/src/asserts.ts';\nimport {deepEqual, type JSONValue} from '../../../../shared/src/json.ts';\nimport {getOrInsertComputed} from '../../../../shared/src/map.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {randInt} from '../../../../shared/src/rand.ts';\nimport type {AST, LiteralValue} from '../../../../zero-protocol/src/ast.ts';\nimport type {ClientSchema} from '../../../../zero-protocol/src/client-schema.ts';\nimport type {Row} from '../../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../../zero-protocol/src/primary-key.ts';\nimport {buildPipeline} from '../../../../zql/src/builder/builder.ts';\nimport {\n Debug,\n runtimeDebugFlags,\n} from '../../../../zql/src/builder/debug-delegate.ts';\nimport {ChangeIndex} from '../../../../zql/src/ivm/change-index.ts';\nimport {ChangeType} from '../../../../zql/src/ivm/change-type.ts';\nimport type {Change} from '../../../../zql/src/ivm/change.ts';\nimport type {Node} from '../../../../zql/src/ivm/data.ts';\nimport {\n skipYields,\n throwOutput,\n type FetchRequest,\n type Input,\n type InputBase,\n type Output,\n type Storage,\n} from '../../../../zql/src/ivm/operator.ts';\nimport type {SourceSchema} from '../../../../zql/src/ivm/schema.ts';\nimport {\n type Source,\n type SourceChange,\n type SourceInput,\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../../zql/src/ivm/source.ts';\nimport type {Stream} from '../../../../zql/src/ivm/stream.ts';\nimport type {ConnectionCostModel} from '../../../../zql/src/planner/planner-connection.ts';\nimport {MeasurePushOperator} from '../../../../zql/src/query/measure-push-operator.ts';\nimport type {ClientGroupStorage} from '../../../../zqlite/src/database-storage.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n resolveSimpleScalarSubqueries,\n type CompanionSubquery,\n type IgnoredScalarHint,\n} from '../../../../zqlite/src/resolve-scalar-subqueries.ts';\nimport {createSQLiteCostModel} from '../../../../zqlite/src/sqlite-cost-model.ts';\nimport {TableSource} from '../../../../zqlite/src/table-source.ts';\nimport {\n reloadPermissionsIfChanged,\n type LoadedPermissions,\n} from '../../auth/load-permissions.ts';\nimport type {LogConfig, ZeroConfig} from '../../config/zero-config.ts';\nimport {computeZqlSpecs, mustGetTableSpec} from '../../db/lite-tables.ts';\nimport type {LiteAndZqlSpec, LiteTableSpec} from '../../db/specs.ts';\nimport {\n getOrCreateCounter,\n getOrCreateLatencyHistogram,\n} from '../../observability/metrics.ts';\nimport type {InspectorDelegate} from '../../server/inspector-delegate.ts';\nimport {type RowKey} from '../../types/row-key.ts';\nimport {type ShardID} from '../../types/shards.ts';\nimport {\n getSubscriptionState,\n ZERO_VERSION_COLUMN_NAME,\n} from '../replicator/schema/replication-state.ts';\nimport {checkClientSchema} from './client-schema.ts';\nimport {rowIDSignatureUnit} from './row-set-signature.ts';\nimport type {Snapshotter} from './snapshotter.ts';\nimport {ResetPipelinesSignal, type SnapshotDiff} from './snapshotter.ts';\n\ntype RowOp<Op extends Omit<ChangeType, ChangeType.CHILD>> = {\n readonly type: Op;\n readonly queryID: string;\n readonly table: string;\n readonly rowKey: Row;\n readonly row: Row;\n};\n\nexport type RowAdd = RowOp<ChangeType.ADD>;\n\nexport type RowRemove = RowOp<ChangeType.REMOVE>;\n\nexport type RowEdit = RowOp<ChangeType.EDIT>;\n\nexport type RowChange = RowAdd | RowRemove | RowEdit;\n\ntype CompanionPipeline = {\n readonly input: Input;\n readonly childField: string;\n readonly resolvedValue: LiteralValue | null | undefined;\n};\n\ntype Pipeline = {\n readonly input: Input;\n readonly hydrationTimeMs: number;\n readonly hydrationRowCount: number;\n readonly hydrationReason: PipelineHydrationReason;\n readonly pipelineRunID: string;\n readonly pipelineReadyAtMs: number;\n readonly transformedAst: AST;\n readonly originalAst: AST;\n readonly transformationHash: string;\n readonly queryName?: string | undefined;\n readonly companions: readonly CompanionPipeline[];\n};\n\nexport type QueryInfo = {\n readonly transformedAst: AST;\n readonly originalAst?: AST | undefined;\n readonly transformationHash: string;\n readonly queryName?: string | undefined;\n};\n\ntype QueryLogInfo = {\n readonly queryHash: string;\n readonly transformationHash: string;\n readonly queryName?: string | undefined;\n};\n\ntype QueryPipelineLifecycleEvent =\n | 'query-pipeline-hydrate-start'\n | 'query-pipeline-hydrate-finish'\n | 'query-pipeline-hydrate-failed'\n | 'query-pipeline-hydrate-aborted'\n | 'query-pipeline-stop';\n\nexport type PipelineHydrationReason =\n | 'query-set-sync'\n | 'unchanged-query-rehydrate';\n\ntype PipelineStopReason =\n | 'replace-query'\n | 'remove-query'\n | 'reset'\n | 'destroy';\n\ntype QueryPipelineLifecycleLog = {\n readonly zeroEvent: QueryPipelineLifecycleEvent;\n readonly pipelineRunID: string;\n readonly queryHash: string;\n readonly transformationHash: string;\n readonly queryName?: string | undefined;\n readonly hydrationReason?: PipelineHydrationReason | undefined;\n readonly stopReason?: PipelineStopReason | undefined;\n readonly hydrationTimeMs?: number | undefined;\n readonly hydrationRowCount?: number | undefined;\n readonly pipelineLifetimeMs?: number | undefined;\n};\n\ntype AdvanceContext = {\n readonly timer: Timer;\n readonly totalHydrationTimeMs: number;\n readonly numChanges: number;\n currentChangeStartMs: number | undefined;\n pos: number;\n};\n\ntype HydrateContext = {\n readonly timer: Timer;\n};\n\nexport type Timer = {\n elapsedLap: () => number;\n totalElapsed: () => number;\n};\n\n/**\n * No matter how fast hydration is, advancement is given at least this long to\n * complete before doing a pipeline reset.\n */\nconst MIN_ADVANCEMENT_TIME_LIMIT_MS = 50;\nconst MIN_PROJECTED_ADVANCEMENT_SAMPLE_CHANGES = 8;\nconst PROJECTED_ADVANCEMENT_SAMPLE_FRACTION = 0.25;\nconst MAX_PROJECTED_ADVANCEMENT_SAMPLE_CHANGES = 50;\nconst MIN_PROJECTED_ADVANCEMENT_SAMPLE_MS = 5;\nconst MIN_PROJECTED_ADVANCEMENT_CHANGES = 16;\nconst PROJECTED_ADVANCEMENT_RESET_MULTIPLIER = 1.5;\nconst LATE_ADVANCEMENT_FINISH_PROGRESS = 0.8;\n\nfunction randomID() {\n return randInt(1, Number.MAX_SAFE_INTEGER).toString(36);\n}\n\nfunction projectedAdvancementTimeMs(\n elapsedMs: number,\n processedChanges: number,\n numChanges: number,\n): number | undefined {\n if (processedChanges <= 0 || numChanges <= 0) {\n return undefined;\n }\n return (elapsedMs / processedChanges) * numChanges;\n}\n\nfunction advancementResetTimeLimitMs(totalHydrationTimeMs: number): number {\n return Math.max(totalHydrationTimeMs, 1);\n}\n\nfunction minProjectedAdvancementSampleChanges(numChanges: number): number {\n return Math.max(\n MIN_PROJECTED_ADVANCEMENT_SAMPLE_CHANGES,\n Math.min(\n MAX_PROJECTED_ADVANCEMENT_SAMPLE_CHANGES,\n Math.ceil(numChanges * PROJECTED_ADVANCEMENT_SAMPLE_FRACTION),\n ),\n );\n}\n\nfunction shouldResetProjectedAdvancement(\n elapsedMs: number,\n projectedTotalTimeMs: number | undefined,\n processedChanges: number,\n numChanges: number,\n totalHydrationTimeMs: number,\n): boolean {\n if (\n projectedTotalTimeMs === undefined ||\n numChanges < MIN_PROJECTED_ADVANCEMENT_CHANGES ||\n processedChanges < minProjectedAdvancementSampleChanges(numChanges) ||\n elapsedMs < MIN_PROJECTED_ADVANCEMENT_SAMPLE_MS\n ) {\n return false;\n }\n\n return (\n projectedTotalTimeMs >\n advancementResetTimeLimitMs(totalHydrationTimeMs) *\n PROJECTED_ADVANCEMENT_RESET_MULTIPLIER\n );\n}\n\nfunction shouldFinishLateAdvancement(\n processedChanges: number,\n numChanges: number,\n): boolean {\n return (\n numChanges > 0 &&\n processedChanges / numChanges >= LATE_ADVANCEMENT_FINISH_PROGRESS\n );\n}\n\nfunction shouldResetSlowCurrentChange(\n currentChangeElapsedMs: number,\n totalHydrationTimeMs: number,\n): boolean {\n return (\n currentChangeElapsedMs > MIN_ADVANCEMENT_TIME_LIMIT_MS &&\n currentChangeElapsedMs > advancementResetTimeLimitMs(totalHydrationTimeMs)\n );\n}\n\n/**\n * Manages the state of IVM pipelines for a given ViewSyncer (i.e. client group).\n */\nexport class PipelineDriver {\n readonly #tables = new Map<string, TableSource>();\n // Query id to pipeline\n readonly #pipelines = new Map<string, Pipeline>();\n /**\n * XOR signature of the set of rows currently attached to each active\n * query, maintained as RowChanges are yielded from {@link addQuery} and\n * {@link advance}. ADDs / REMOVEs XOR the row's unit in (XOR is\n * self-inverse, so one op serves both directions); EDITs are no-ops.\n * Hydration implicitly reseeds from `0n` because {@link addQuery} calls\n * {@link removeQuery} first, which deletes the entry.\n */\n readonly #rowSetSignatures = new Map<string, bigint>();\n\n readonly #lc: LogContext;\n readonly #snapshotter: Snapshotter;\n readonly #storage: ClientGroupStorage;\n readonly #shardID: ShardID;\n readonly #logConfig: LogConfig;\n readonly #config: ZeroConfig | undefined;\n readonly #tableSpecs = new Map<string, LiteAndZqlSpec>();\n readonly #allTableNames = new Set<string>();\n readonly #costModels: WeakMap<Database, ConnectionCostModel> | undefined;\n readonly #yieldThresholdMs: () => number;\n #streamer: Streamer | null = null;\n #hydrateContext: HydrateContext | null = null;\n #advanceContext: AdvanceContext | null = null;\n #replicaVersion: string | null = null;\n #primaryKeys: Map<string, PrimaryKey> | null = null;\n #permissions: LoadedPermissions | null = null;\n\n readonly #advanceTime = getOrCreateLatencyHistogram(\n 'sync',\n 'ivm.advance-time',\n 'Time to advance all queries for a given client group in response to a single change.',\n );\n\n readonly #conflictRowsDeleted = getOrCreateCounter(\n 'sync',\n 'ivm.conflict-rows-deleted',\n 'Number of rows deleted because they conflicted with added row',\n );\n\n readonly #inspectorDelegate: InspectorDelegate;\n\n constructor(\n lc: LogContext,\n logConfig: LogConfig,\n snapshotter: Snapshotter,\n shardID: ShardID,\n storage: ClientGroupStorage,\n clientGroupID: string,\n inspectorDelegate: InspectorDelegate,\n yieldThresholdMs: () => number,\n enablePlanner?: boolean,\n config?: ZeroConfig,\n ) {\n this.#lc = lc.withContext('clientGroupID', clientGroupID);\n this.#snapshotter = snapshotter;\n this.#storage = storage;\n this.#shardID = shardID;\n this.#logConfig = logConfig;\n this.#config = config;\n this.#inspectorDelegate = inspectorDelegate;\n this.#costModels = enablePlanner ? new WeakMap() : undefined;\n this.#yieldThresholdMs = yieldThresholdMs;\n }\n\n /**\n * Initializes the PipelineDriver to the current head of the database.\n * Queries can then be added (i.e. hydrated) with {@link addQuery()}.\n *\n * Must only be called once.\n */\n init(clientSchema: ClientSchema) {\n assert(!this.#snapshotter.initialized(), 'Already initialized');\n this.#snapshotter.init();\n this.#initAndResetCommon(clientSchema);\n }\n\n /**\n * @returns Whether the PipelineDriver has been initialized.\n */\n initialized(): boolean {\n return this.#snapshotter.initialized();\n }\n\n /**\n * Clears the current pipelines and TableSources, returning the PipelineDriver\n * to its initial state. This should be called in response to a schema change,\n * as TableSources need to be recomputed.\n */\n reset(clientSchema: ClientSchema) {\n for (const [queryID, pipeline] of this.#pipelines) {\n this.#pipelines.delete(queryID);\n this.#destroyPipeline(queryID, pipeline, 'reset');\n }\n this.#tables.clear();\n this.#allTableNames.clear();\n this.#rowSetSignatures.clear();\n this.#initAndResetCommon(clientSchema);\n }\n\n #initAndResetCommon(clientSchema: ClientSchema) {\n const {db} = this.#snapshotter.current();\n const fullTables = new Map<string, LiteTableSpec>();\n computeZqlSpecs(\n this.#lc,\n db.db,\n {includeBackfillingColumns: false},\n this.#tableSpecs,\n fullTables,\n );\n checkClientSchema(\n this.#shardID,\n clientSchema,\n this.#tableSpecs,\n fullTables,\n );\n this.#allTableNames.clear();\n for (const table of fullTables.keys()) {\n this.#allTableNames.add(table);\n }\n const primaryKeys = this.#primaryKeys ?? new Map<string, PrimaryKey>();\n this.#primaryKeys = primaryKeys;\n primaryKeys.clear();\n for (const [table, spec] of this.#tableSpecs.entries()) {\n primaryKeys.set(table, spec.tableSpec.primaryKey);\n }\n buildPrimaryKeys(clientSchema, primaryKeys);\n const {replicaVersion} = getSubscriptionState(db);\n this.#replicaVersion = replicaVersion;\n }\n\n /** @returns The replica version. The PipelineDriver must have been initialized. */\n get replicaVersion(): string {\n return must(this.#replicaVersion, 'Not yet initialized');\n }\n\n /**\n * Returns the current version of the database. This will reflect the\n * latest version change when calling {@link advance()} once the\n * iteration has begun.\n */\n currentVersion(): string {\n assert(this.initialized(), 'Not yet initialized');\n return this.#snapshotter.current().version;\n }\n\n /**\n * Returns the current upstream {app}.permissions, or `null` if none are defined.\n */\n currentPermissions(): LoadedPermissions | null {\n assert(this.initialized(), 'Not yet initialized');\n const res = reloadPermissionsIfChanged(\n this.#lc,\n this.#snapshotter.current().db,\n this.#shardID.appID,\n this.#permissions,\n this.#config,\n );\n if (res.changed) {\n this.#permissions = res.permissions;\n this.#lc.debug?.(\n 'Reloaded permissions',\n JSON.stringify(this.#permissions),\n );\n }\n return this.#permissions;\n }\n\n /**\n * Advances the snapshot to the head of the database without diffing the\n * change log, in preparation for hydrating queries at head.\n *\n * Throws a {@link ResetPipelinesSignal} if the change log records a\n * schema change since the previous snapshot. The table specs (and any\n * TableSources built from them) were computed at or before that snapshot\n * and are stale with respect to the new head, so the caller must\n * {@link reset()} before hydrating. ({@link advance()} detects this when\n * the diff encounters the RESET op; this path skips the diff and so must\n * check explicitly.)\n */\n advanceWithoutDiff(): string {\n const {prev, curr} = this.#snapshotter.advanceWithoutDiff();\n if (curr.schemaChangedSince(prev.version)) {\n throw new ResetPipelinesSignal(\n `schema changed between ${prev.version} and ${curr.version}`,\n 'schema-change',\n );\n }\n for (const table of this.#tables.values()) {\n table.setDB(curr.db.db);\n }\n return curr.version;\n }\n\n #ensureCostModelExistsIfEnabled(db: Database) {\n let existing = this.#costModels?.get(db);\n if (existing) {\n return existing;\n }\n if (this.#costModels) {\n const costModel = createSQLiteCostModel(db, this.#tableSpecs);\n this.#costModels.set(db, costModel);\n return costModel;\n }\n return undefined;\n }\n\n /**\n * Clears storage used for the pipelines. Call this when the\n * PipelineDriver will no longer be used.\n */\n destroy() {\n for (const [queryID, pipeline] of this.#pipelines) {\n this.#pipelines.delete(queryID);\n this.#destroyPipeline(queryID, pipeline, 'destroy');\n }\n this.#tables.clear();\n this.#rowSetSignatures.clear();\n this.#storage.destroy();\n this.#snapshotter.destroy();\n }\n\n /** @return Map from query ID to PipelineInfo for all added queries. */\n queries(): ReadonlyMap<string, QueryInfo> {\n return this.#pipelines;\n }\n\n totalHydrationTimeMs(): number {\n let total = 0;\n for (const pipeline of this.#pipelines.values()) {\n total += pipeline.hydrationTimeMs;\n }\n return total;\n }\n\n #logQueryPipelineLifecycle({\n zeroEvent,\n pipelineRunID,\n queryHash,\n transformationHash,\n queryName,\n hydrationReason,\n stopReason,\n hydrationTimeMs,\n hydrationRowCount,\n pipelineLifetimeMs,\n }: QueryPipelineLifecycleLog): void {\n let lc = this.#lc\n .withContext('zeroEvent', zeroEvent)\n .withContext('pipelineRunID', pipelineRunID)\n .withContext('queryHash', queryHash)\n .withContext('transformationHash', transformationHash);\n if (queryName !== undefined) {\n lc = lc.withContext('queryName', queryName);\n }\n if (hydrationReason !== undefined) {\n lc = lc.withContext('hydrationReason', hydrationReason);\n }\n if (stopReason !== undefined) {\n lc = lc.withContext('stopReason', stopReason);\n }\n if (hydrationTimeMs !== undefined) {\n lc = lc.withContext('hydrationTimeMs', hydrationTimeMs);\n }\n if (hydrationRowCount !== undefined) {\n lc = lc.withContext('hydrationRowCount', hydrationRowCount);\n }\n if (pipelineLifetimeMs !== undefined) {\n lc = lc.withContext('pipelineLifetimeMs', pipelineLifetimeMs);\n }\n lc.info?.('query pipeline lifecycle');\n }\n\n /**\n * A `{scalar: true}` that cannot be honored degrades silently to a plain\n * EXISTS, so the author gets none of the plan they asked for and no signal\n * that they didn't. Say so, with the unique keys that were actually\n * available — the client schema knows only primary keys, so this is the only\n * place the advice can be correct.\n */\n #warnIgnoredScalarHints(queryID: string, hints: IgnoredScalarHint[]): void {\n for (const {table, uniqueKeys} of hints) {\n const keys = uniqueKeys.map(k => `(${k.join(', ')})`).join(', ');\n this.#lc.warn?.(\n `Ignoring {scalar: true} on the \"${table}\" subquery of query ` +\n `${queryID}: it does not constrain every column of any unique key ` +\n `${keys.length > 0 ? `[${keys}]` : '(none on this table)'} to a ` +\n `literal with \"=\", so it is not provably limited to one row. ` +\n `The gate runs as a plain EXISTS.`,\n );\n }\n }\n\n #disableCorrelatedPredicatePushdown(): boolean {\n return this.#config?.enableCorrelatedPredicatePushdown === false;\n }\n\n #resolveScalarSubqueries(ast: AST): {\n ast: AST;\n companionRows: {table: string; row: Row}[];\n companions: CompanionSubquery[];\n companionInputs: Input[];\n ignoredScalarHints: IgnoredScalarHint[];\n } {\n const companionRows: {table: string; row: Row}[] = [];\n const companionInputs: Input[] = [];\n\n const executor = (\n subqueryAST: AST,\n childField: string,\n ): LiteralValue | null | undefined => {\n const input = buildPipeline(\n subqueryAST,\n {\n disableCorrelatedPredicatePushdown:\n this.#disableCorrelatedPredicatePushdown(),\n getSource: name => this.#getSource(name),\n createStorage: () => this.#createStorage(),\n decorateSourceInput: (input: SourceInput): Input => input,\n decorateInput: input => input,\n addEdge() {},\n decorateFilterInput: input => input,\n },\n 'scalar-subquery',\n );\n // Tracked before it is fetched so that a failure in this or a later\n // subquery can tear it down below. A companion with no result is kept\n // alive too: it detects a future insert that creates the row.\n companionInputs.push(input);\n // Consume the full stream rather than using first() to avoid\n // triggering early return on Take's #initialFetch assertion.\n // The subquery AST already has limit: 1, so at most one row is produced.\n let node: Node | undefined;\n for (const n of skipYields(input.fetch({}))) {\n node ??= n;\n }\n if (!node) {\n return undefined;\n }\n companionRows.push({table: subqueryAST.table, row: node.row as Row});\n return (node.row[childField] as LiteralValue) ?? null;\n };\n\n let resolved: AST;\n let companions: CompanionSubquery[];\n let ignoredScalarHints: IgnoredScalarHint[];\n try {\n ({\n ast: resolved,\n companions,\n ignoredScalarHints,\n } = resolveSimpleScalarSubqueries(ast, this.#tableSpecs, executor));\n } catch (e) {\n for (const input of companionInputs) {\n input.destroy();\n }\n throw e;\n }\n return {\n ast: resolved,\n companionRows,\n companions,\n companionInputs,\n ignoredScalarHints,\n };\n }\n\n /**\n * Adds a pipeline for the query. The method will hydrate the query using the\n * driver's current snapshot of the database and return a stream of results.\n * Henceforth, updates to the query will be returned when the driver is\n * {@link advance}d. The query and its pipeline can be removed with\n * {@link removeQuery()}.\n *\n * If a query with the same queryID is already added, the existing pipeline\n * will be removed and destroyed before adding the new pipeline.\n *\n * @param timer The caller-controlled {@link Timer} used to determine the\n * final hydration time. (The caller may pause and resume the timer\n * when yielding the thread for time-slicing).\n * @return The rows from the initial hydration of the query.\n */\n addQuery(\n transformationHash: string,\n queryID: string,\n query: AST,\n timer: Timer,\n queryName?: string,\n hydrationReason: PipelineHydrationReason = 'query-set-sync',\n ): Iterable<RowChange | 'yield'> {\n return this.#trackRowSetSignatures(\n this.#addQueryImpl(\n transformationHash,\n queryID,\n query,\n timer,\n queryName,\n hydrationReason,\n ),\n );\n }\n\n *#addQueryImpl(\n transformationHash: string,\n queryID: string,\n query: AST,\n timer: Timer,\n queryName?: string,\n hydrationReason: PipelineHydrationReason = 'query-set-sync',\n ): Iterable<RowChange | 'yield'> {\n assert(\n this.initialized(),\n 'Pipeline driver must be initialized before adding queries',\n );\n this.removeQuery(queryID, 'replace-query');\n const pipelineRunID = randomID();\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-hydrate-start',\n pipelineRunID,\n queryHash: queryID,\n transformationHash,\n queryName,\n hydrationReason,\n });\n const debugDelegate = runtimeDebugFlags.trackRowsVended\n ? new Debug(true)\n : undefined;\n\n const costModel = this.#ensureCostModelExistsIfEnabled(\n this.#snapshotter.current().db.db,\n );\n\n assert(\n this.#advanceContext === null,\n 'Cannot hydrate while advance is in progress',\n );\n this.#hydrateContext = {\n timer,\n };\n let hydrationFinished = false;\n let hydrationFailed = false;\n let hydrationRowCount = 0;\n // The inputs built so far, held outside the try so that a hydration that\n // does not finish (aborted by the consumer or failed) can tear them down.\n // Only a finished hydration hands them over to #pipelines.\n let builtInputs: Input[] = [];\n try {\n const {\n ast: resolvedQuery,\n companionRows,\n companions: companionMeta,\n companionInputs,\n ignoredScalarHints,\n } = this.#resolveScalarSubqueries(query);\n builtInputs = [...companionInputs];\n\n this.#warnIgnoredScalarHints(queryID, ignoredScalarHints);\n\n const input = buildPipeline(\n resolvedQuery,\n {\n debug: debugDelegate,\n enableNotExists: true, // Server-side can handle NOT EXISTS\n disableCorrelatedPredicatePushdown:\n this.#disableCorrelatedPredicatePushdown(),\n enablePlannerAwarePushdown:\n this.#config?.enablePlannerAwarePushdown !== false,\n getSource: name => this.#getSource(name),\n createStorage: () => this.#createStorage(),\n decorateSourceInput: (input: SourceInput, _queryID: string): Input =>\n new MeasurePushOperator(\n new QueryFailureLoggingOperator(\n this.#lc,\n input,\n queryID,\n transformationHash,\n queryName,\n ),\n queryID,\n this.#inspectorDelegate,\n 'query-update-server',\n ),\n decorateInput: input => input,\n addEdge() {},\n decorateFilterInput: input => input,\n },\n queryID,\n costModel,\n );\n builtInputs.push(input);\n const schema = input.getSchema();\n input.setOutput({\n push: change => this.#streamPushed(queryID, schema, change),\n });\n\n for (const change of hydrateInternal(\n input,\n queryID,\n must(this.#primaryKeys),\n this.#tableSpecs,\n )) {\n if (change !== 'yield') {\n hydrationRowCount++;\n }\n yield change;\n }\n\n for (const {table, row} of companionRows) {\n const primaryKey = mustGetPrimaryKey(this.#primaryKeys, table);\n hydrationRowCount++;\n yield {\n type: ChangeType.ADD,\n queryID,\n table,\n rowKey: getRowKey(primaryKey, row),\n row,\n } as RowChange;\n }\n\n const hydrationTimeMs = timer.totalElapsed();\n if (runtimeDebugFlags.trackRowCountsVended) {\n if (hydrationTimeMs > this.#logConfig.slowHydrateThreshold) {\n let totalRowsConsidered = 0;\n const lc = this.#lc\n .withContext('queryID', queryID)\n .withContext('hydrationTimeMs', hydrationTimeMs);\n for (const tableName of this.#tables.keys()) {\n const entries = Object.entries(\n debugDelegate?.getVendedRowCounts()[tableName] ?? {},\n );\n totalRowsConsidered += entries.reduce(\n (acc, entry) => acc + entry[1],\n 0,\n );\n lc.info?.(tableName + ' VENDED: ', entries);\n }\n lc.info?.(`Total rows considered: ${totalRowsConsidered}`);\n }\n }\n debugDelegate?.reset();\n\n // Set up live companion pipelines for reactive scalar subquery monitoring.\n const liveCompanions: CompanionPipeline[] = [];\n for (let i = 0; i < companionMeta.length; i++) {\n const meta = companionMeta[i];\n const companionInput = companionInputs[i];\n const companionSchema = companionInput.getSchema();\n const {childField, resolvedValue} = meta;\n companionInput.setOutput({\n push: (change: Change) => {\n let newValue: LiteralValue | null | undefined;\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n case ChangeType.EDIT:\n newValue =\n (change[ChangeIndex.NODE].row[childField] as LiteralValue) ??\n null;\n break;\n case ChangeType.REMOVE:\n newValue = undefined;\n break;\n case ChangeType.CHILD:\n return [];\n }\n if (!scalarValuesEqual(newValue, resolvedValue)) {\n throw new ResetPipelinesSignal(\n `Scalar subquery value changed for ${meta.ast.table}: ` +\n `${String(resolvedValue)} -> ${String(newValue)}`,\n 'scalar-subquery',\n );\n }\n return this.#streamPushed(queryID, companionSchema, change);\n },\n });\n liveCompanions.push({input: companionInput, childField, resolvedValue});\n }\n\n // Note: This hydrationTime is a wall-clock overestimate, as it does\n // not take time slicing into account. The view-syncer resets this\n // to a more precise processing-time measurement with setHydrationTime().\n const pipelineReadyAtMs = Date.now();\n this.#pipelines.set(queryID, {\n input,\n hydrationTimeMs,\n hydrationRowCount,\n hydrationReason,\n pipelineRunID,\n pipelineReadyAtMs,\n transformedAst: resolvedQuery,\n originalAst: query,\n transformationHash,\n ...(queryName !== undefined && {queryName}),\n companions: liveCompanions,\n });\n hydrationFinished = true;\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-hydrate-finish',\n pipelineRunID,\n queryHash: queryID,\n transformationHash,\n queryName,\n hydrationReason,\n hydrationTimeMs,\n hydrationRowCount,\n });\n } catch (e) {\n hydrationFailed = true;\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-hydrate-failed',\n pipelineRunID,\n queryHash: queryID,\n transformationHash,\n queryName,\n hydrationReason,\n hydrationTimeMs: timer.totalElapsed(),\n hydrationRowCount,\n });\n logQueryFailure(\n this.#lc,\n {queryHash: queryID, transformationHash, queryName},\n 'query hydration failed',\n e,\n );\n throw e;\n } finally {\n if (!hydrationFinished && !hydrationFailed) {\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-hydrate-aborted',\n pipelineRunID,\n queryHash: queryID,\n transformationHash,\n queryName,\n hydrationReason,\n hydrationTimeMs: timer.totalElapsed(),\n hydrationRowCount,\n });\n }\n if (!hydrationFinished) {\n for (const input of builtInputs) {\n input.destroy();\n }\n this.#pruneUnusedTables();\n // Rows may already have been yielded through #trackRowSetSignatures,\n // and rowSetSignature() must not report a signature for a query\n // without an active pipeline.\n this.#rowSetSignatures.delete(queryID);\n }\n this.#hydrateContext = null;\n }\n }\n\n /**\n * Removes the pipeline for the query. This is a no-op if the query\n * was not added.\n */\n removeQuery(\n queryID: string,\n stopReason: PipelineStopReason = 'remove-query',\n ) {\n const pipeline = this.#pipelines.get(queryID);\n if (pipeline) {\n this.#pipelines.delete(queryID);\n this.#destroyPipeline(queryID, pipeline, stopReason);\n this.#pruneUnusedTables();\n }\n this.#rowSetSignatures.delete(queryID);\n }\n\n #pruneUnusedTables() {\n for (const [table, source] of this.#tables.entries()) {\n if (!source.hasConnections()) {\n this.#tables.delete(table);\n }\n }\n }\n\n #destroyPipeline(\n queryID: string,\n pipeline: Pipeline,\n stopReason: PipelineStopReason,\n ): void {\n this.#logQueryPipelineLifecycle({\n zeroEvent: 'query-pipeline-stop',\n pipelineRunID: pipeline.pipelineRunID,\n queryHash: queryID,\n transformationHash: pipeline.transformationHash,\n queryName: pipeline.queryName,\n hydrationReason: pipeline.hydrationReason,\n stopReason,\n hydrationTimeMs: pipeline.hydrationTimeMs,\n hydrationRowCount: pipeline.hydrationRowCount,\n pipelineLifetimeMs: Date.now() - pipeline.pipelineReadyAtMs,\n });\n pipeline.input.destroy();\n for (const companion of pipeline.companions) {\n companion.input.destroy();\n }\n }\n\n /**\n * Current XOR signature of the row-set attached to `queryID`, or\n * `undefined` if no pipeline for the query is currently active.\n * Maintained incrementally by {@link addQuery} and {@link advance}.\n */\n rowSetSignature(queryID: string): bigint | undefined {\n return this.#rowSetSignatures.get(queryID);\n }\n\n /**\n * Wraps an iterable of RowChanges, XORing each row's unit hash into the\n * query's signature (ADDs and REMOVEs share the same op; EDITs are no-ops).\n * Used to intercept the yield streams from {@link addQuery} and\n * {@link advance}.\n */\n *#trackRowSetSignatures(\n changes: Iterable<RowChange | 'yield'>,\n ): Iterable<RowChange | 'yield'> {\n for (const change of changes) {\n if (change !== 'yield' && change.type !== ChangeType.EDIT) {\n const cur = this.#rowSetSignatures.get(change.queryID) ?? 0n;\n const unit = rowIDSignatureUnit({\n schema: '',\n table: change.table,\n rowKey: change.rowKey as RowKey,\n });\n this.#rowSetSignatures.set(change.queryID, cur ^ unit);\n }\n yield change;\n }\n }\n\n /**\n * Returns the value of the row with the given primary key `pk`,\n * or `undefined` if there is no such row. The pipeline must have been\n * initialized.\n */\n getRow(table: string, pk: RowKey): Row | undefined {\n assert(this.initialized(), 'Not yet initialized');\n const source = must(this.#tables.get(table));\n return source.getRow(pk as Row);\n }\n\n /**\n * Advances to the new head of the database.\n *\n * @param timer The caller-controlled {@link Timer} that will be used to\n * measure the progress of the advancement and abort with a\n * {@link ResetPipelinesSignal} if it is estimated to take longer\n * than a hydration.\n * @return The resulting row changes for all added queries. Note that the\n * `changes` must be iterated over in their entirety in order to\n * advance the database snapshot.\n */\n advance(timer: Timer): {\n version: string;\n numChanges: number;\n changes: Iterable<RowChange | 'yield'>;\n } {\n assert(\n this.initialized(),\n 'Pipeline driver must be initialized before advancing',\n );\n const diff = this.#snapshotter.advance(\n this.#tableSpecs,\n this.#allTableNames,\n this.#tables,\n // Sources skip changes that none of this client group's pipelines can\n // observe, so a `prev` they write to diverges from other groups'.\n 'divergent',\n );\n const {prev, curr, changes} = diff;\n this.#lc.debug?.(\n `advance ${prev.version} => ${curr.version}: ${changes} changes`,\n );\n\n return {\n version: curr.version,\n numChanges: changes,\n changes: this.#trackRowSetSignatures(this.#advance(diff, timer, changes)),\n };\n }\n\n *#advance(\n diff: SnapshotDiff,\n timer: Timer,\n numChanges: number,\n ): Iterable<RowChange | 'yield'> {\n assert(\n this.#hydrateContext === null,\n 'Cannot advance while hydration is in progress',\n );\n const totalHydrationTimeMs = this.totalHydrationTimeMs();\n this.#advanceContext = {\n timer,\n totalHydrationTimeMs,\n numChanges,\n currentChangeStartMs: undefined,\n pos: 0,\n };\n this.#lc.debug?.(\n `starting pipeline advancement of ${numChanges} changes with an ` +\n `advancement time limited based on total hydration time of ` +\n `${totalHydrationTimeMs} ms.`,\n );\n try {\n for (const {table, prevValues, nextValue} of diff) {\n // Advance progress is checked each time a row is fetched\n // from a TableSource during push processing, but some pushes\n // don't read any rows. Check progress here before processing\n // the next change.\n if (this.#shouldAdvanceYieldMaybeAbortAdvance()) {\n yield 'yield';\n }\n const start = timer.totalElapsed();\n const advanceContext = must(this.#advanceContext);\n advanceContext.currentChangeStartMs = start;\n\n try {\n try {\n const tableSource = this.#tables.get(table);\n if (!tableSource) {\n // no pipelines read from this table, so no need to process the change\n continue;\n }\n const primaryKey = mustGetPrimaryKey(this.#primaryKeys, table);\n let editOldRow: Row | undefined = undefined;\n for (const prevValue of prevValues) {\n if (\n nextValue &&\n deepEqual(\n getRowKey(primaryKey, prevValue as Row) as JSONValue,\n getRowKey(primaryKey, nextValue as Row) as JSONValue,\n )\n ) {\n editOldRow = prevValue;\n } else {\n if (nextValue) {\n this.#conflictRowsDeleted.add(1);\n }\n yield* this.#push(\n tableSource,\n makeSourceChangeRemove(prevValue as Row),\n );\n }\n }\n if (nextValue) {\n if (editOldRow) {\n yield* this.#push(\n tableSource,\n makeSourceChangeEdit(nextValue as Row, editOldRow),\n );\n } else {\n yield* this.#push(\n tableSource,\n makeSourceChangeAdd(nextValue as Row),\n );\n }\n }\n } finally {\n advanceContext.pos++;\n }\n\n this.#shouldAdvanceYieldMaybeAbortAdvance(false);\n } finally {\n advanceContext.currentChangeStartMs = undefined;\n }\n\n const elapsed = timer.totalElapsed() - start;\n this.#advanceTime.recordMs(elapsed, {\n table,\n });\n }\n\n // Set the new snapshot on all TableSources.\n const {curr} = diff;\n for (const table of this.#tables.values()) {\n table.setDB(curr.db.db);\n }\n this.#ensureCostModelExistsIfEnabled(curr.db.db);\n this.#lc.debug?.(`Advanced to ${curr.version}`);\n } finally {\n this.#advanceContext = null;\n }\n }\n\n /** Implements `BuilderDelegate.getSource()` */\n #getSource(tableName: string): Source {\n return getOrInsertComputed(this.#tables, tableName, tableName => {\n const tableSpec = mustGetTableSpec(this.#tableSpecs, tableName);\n const primaryKey = mustGetPrimaryKey(this.#primaryKeys, tableName);\n\n const {db} = this.#snapshotter.current();\n const source = new TableSource(\n this.#lc,\n this.#logConfig,\n db.db,\n tableName,\n tableSpec.zqlSpec,\n primaryKey,\n () => this.#shouldYield(),\n // Pipelines only read tables through their connections, and the\n // sources are moved to the next snapshot after every advancement.\n {skipUnobservableChanges: true},\n );\n this.#lc.debug?.(`created TableSource for ${tableName}`);\n return source;\n });\n }\n\n #shouldYield(): boolean {\n if (this.#hydrateContext) {\n return this.#hydrateContext.timer.elapsedLap() > this.#yieldThresholdMs();\n }\n if (this.#advanceContext) {\n return this.#shouldAdvanceYieldMaybeAbortAdvance();\n }\n throw new Error('shouldYield called outside of hydration or advancement');\n }\n\n /**\n * Cancel advancement processing when either the whole batch projects to be\n * more expensive than hydration, or the current source change alone exceeds\n * the hydration budget. The late-finish exception only applies to batch-level\n * checks; a single pathological push always resets.\n */\n #shouldAdvanceYieldMaybeAbortAdvance(checkYield = true): boolean {\n const {\n currentChangeStartMs,\n pos,\n numChanges,\n timer: advanceTimer,\n totalHydrationTimeMs,\n } = must(this.#advanceContext);\n const elapsed = advanceTimer.totalElapsed();\n const currentChangeElapsedMs =\n currentChangeStartMs === undefined\n ? undefined\n : elapsed - currentChangeStartMs;\n if (\n currentChangeElapsedMs !== undefined &&\n shouldResetSlowCurrentChange(currentChangeElapsedMs, totalHydrationTimeMs)\n ) {\n this.#throwSlowCurrentChangeReset(\n pos,\n numChanges,\n elapsed,\n currentChangeElapsedMs,\n totalHydrationTimeMs,\n );\n }\n const projectedTotalTimeMs = projectedAdvancementTimeMs(\n elapsed,\n pos,\n numChanges,\n );\n const shouldFinish = shouldFinishLateAdvancement(pos, numChanges);\n if (\n !shouldFinish &&\n shouldResetProjectedAdvancement(\n elapsed,\n projectedTotalTimeMs,\n pos,\n numChanges,\n totalHydrationTimeMs,\n )\n ) {\n this.#throwProjectedAdvancementReset(\n pos,\n numChanges,\n elapsed,\n projectedTotalTimeMs,\n totalHydrationTimeMs,\n );\n }\n if (\n !shouldFinish &&\n elapsed > MIN_ADVANCEMENT_TIME_LIMIT_MS &&\n (elapsed > totalHydrationTimeMs ||\n (elapsed > totalHydrationTimeMs / 2 && pos <= numChanges / 2))\n ) {\n throw new ResetPipelinesSignal(\n `Advancement exceeded timeout at ${pos} of ${numChanges} changes ` +\n `after ${elapsed} ms. Advancement time limited based on total ` +\n `hydration time of ${totalHydrationTimeMs} ms.`,\n 'advancement-timeout',\n );\n }\n return checkYield && advanceTimer.elapsedLap() > this.#yieldThresholdMs();\n }\n\n #throwSlowCurrentChangeReset(\n pos: number,\n numChanges: number,\n elapsed: number,\n currentChangeElapsedMs: number,\n totalHydrationTimeMs: number,\n ): never {\n throw new ResetPipelinesSignal(\n `Advancement exceeded timeout processing current change at ${pos} of ` +\n `${numChanges} changes after ${currentChangeElapsedMs} ms ` +\n `(${elapsed} ms total). Advancement time limited based on total ` +\n `hydration time of ${totalHydrationTimeMs} ms.`,\n 'advancement-timeout',\n );\n }\n\n #throwProjectedAdvancementReset(\n pos: number,\n numChanges: number,\n elapsed: number,\n projectedTotalTimeMs: number | undefined,\n totalHydrationTimeMs: number,\n ): never {\n const projection =\n projectedTotalTimeMs === undefined\n ? ''\n : ` Projected total advancement time is ${projectedTotalTimeMs} ms.`;\n throw new ResetPipelinesSignal(\n `Advancement projected to exceed hydration time at ${pos} of ` +\n `${numChanges} changes after ${elapsed} ms.` +\n projection +\n ` Advancement time limited based on total hydration time of ` +\n `${totalHydrationTimeMs} ms.`,\n 'advancement-timeout',\n );\n }\n\n /** Implements `BuilderDelegate.createStorage()` */\n #createStorage(): Storage {\n return this.#storage.createStorage();\n }\n\n *#push(\n source: TableSource,\n change: SourceChange,\n ): Iterable<RowChange | 'yield'> {\n this.#startAccumulating();\n try {\n for (const val of source.genPush(change)) {\n if (val === 'yield') {\n yield 'yield';\n }\n for (const changeOrYield of this.#stopAccumulating().stream()) {\n yield changeOrYield;\n }\n this.#startAccumulating();\n }\n } finally {\n if (this.#streamer !== null) {\n this.#stopAccumulating();\n }\n }\n }\n\n /**\n * Converts a change pushed out of a query pipeline into row changes during\n * the push. The relationships of a pushed node are lazy, and operators such\n * as Join compute them from the state of the push in progress: while a child\n * change is pushed to each matching parent in turn, parents not yet pushed\n * must not see it. Read after the push has moved on to the next parent, or\n * after it has finished, a node's relationships show the later state, and\n * rows that are also pushed separately are counted twice.\n */\n *#streamPushed(\n queryID: string,\n schema: SourceSchema,\n change: Change,\n ): Stream<'yield'> {\n const streamer = this.#streamer;\n assert(streamer, 'must #startAccumulating() before pushing changes');\n for (const rowChange of streamer.streamChange(queryID, schema, change)) {\n if (rowChange === 'yield') {\n yield rowChange;\n continue;\n }\n // #push replaces the streamer after each 'yield', so add to the\n // current one.\n must(this.#streamer).add(rowChange);\n }\n }\n\n #startAccumulating() {\n assert(this.#streamer === null, 'Streamer already started');\n this.#streamer = new Streamer(\n must(this.#primaryKeys),\n this.#tableSpecs,\n (queryID, error) =>\n this.#logQueryFailure(queryID, 'query pipeline failed', error),\n );\n }\n\n #stopAccumulating(): Streamer {\n const streamer = this.#streamer;\n assert(streamer, 'Streamer not started');\n this.#streamer = null;\n return streamer;\n }\n\n #logQueryFailure(queryID: string, message: string, error: unknown): void {\n const pipeline = this.#pipelines.get(queryID);\n const queryInfo = pipeline\n ? {\n queryHash: queryID,\n transformationHash: pipeline.transformationHash,\n queryName: pipeline.queryName,\n }\n : undefined;\n logQueryFailure(this.#lc, queryInfo, message, error);\n }\n}\n\nclass Streamer {\n readonly #primaryKeys: Map<string, PrimaryKey>;\n readonly #tableSpecs: Map<string, LiteAndZqlSpec>;\n readonly #logQueryFailure:\n | ((queryID: string, error: unknown) => void)\n | undefined;\n\n constructor(\n primaryKeys: Map<string, PrimaryKey>,\n tableSpecs: Map<string, LiteAndZqlSpec>,\n logQueryFailure?: (queryID: string, error: unknown) => void,\n ) {\n this.#primaryKeys = primaryKeys;\n this.#tableSpecs = tableSpecs;\n this.#logQueryFailure = logQueryFailure;\n }\n\n readonly #changes: [\n queryID: string,\n schema: SourceSchema,\n changes: Iterable<Change | 'yield'>,\n ][] = [];\n\n /** Row changes that were already produced by {@link streamChange}. */\n readonly #rowChanges: RowChange[] = [];\n\n add(rowChange: RowChange) {\n this.#rowChanges.push(rowChange);\n }\n\n streamChange(\n queryID: string,\n schema: SourceSchema,\n change: Change,\n ): Iterable<RowChange | 'yield'> {\n return this.#streamChanges(queryID, schema, [change]);\n }\n\n accumulate(\n queryID: string,\n schema: SourceSchema,\n changes: Iterable<Change | 'yield'>,\n ): this {\n this.#changes.push([queryID, schema, changes]);\n return this;\n }\n\n *stream(): Iterable<RowChange | 'yield'> {\n yield* this.#rowChanges;\n for (const [queryID, schema, changes] of this.#changes) {\n try {\n yield* this.#streamChanges(queryID, schema, changes);\n } catch (e) {\n this.#logQueryFailure?.(queryID, e);\n throw e;\n }\n }\n }\n\n *#streamChanges(\n queryID: string,\n schema: SourceSchema,\n changes: Iterable<Change | 'yield'>,\n ): Iterable<RowChange | 'yield'> {\n // We do not sync rows gathered by the permissions\n // system to the client.\n if (schema.system === 'permissions') {\n return;\n }\n\n for (const change of changes) {\n if (change === 'yield') {\n yield change;\n continue;\n }\n const type = change[ChangeIndex.TYPE];\n switch (type) {\n case ChangeType.REMOVE:\n case ChangeType.ADD: {\n yield* this.#streamNodes(queryID, schema, type, () => [\n change[ChangeIndex.NODE],\n ]);\n break;\n }\n\n case ChangeType.CHILD: {\n const child = change[ChangeIndex.CHILD_DATA];\n const childSchema = must(\n schema.relationships[child.relationshipName],\n );\n\n yield* this.#streamChanges(queryID, childSchema, [child.change]);\n break;\n }\n case ChangeType.EDIT:\n yield* this.#streamNodes(queryID, schema, type, () => [\n {row: change[ChangeIndex.NODE].row, relationships: {}},\n ]);\n break;\n default:\n unreachable(change[ChangeIndex.TYPE]);\n }\n }\n }\n\n *#streamNodes(\n queryID: string,\n schema: SourceSchema,\n op: ChangeType.ADD | ChangeType.REMOVE | ChangeType.EDIT,\n nodes: () => Iterable<Node | 'yield'>,\n ): Iterable<RowChange | 'yield'> {\n const {tableName: table, system} = schema;\n\n const primaryKey = must(this.#primaryKeys.get(table));\n const spec = must(this.#tableSpecs.get(table)).tableSpec;\n\n // We do not sync rows gathered by the permissions\n // system to the client.\n if (system === 'permissions') {\n return;\n }\n\n for (const node of nodes()) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n const {relationships} = node;\n let {row} = node;\n const rowKey = getRowKey(primaryKey, row);\n if (op !== ChangeType.REMOVE) {\n const rowVersion = row[ZERO_VERSION_COLUMN_NAME];\n if (\n typeof rowVersion === 'string' &&\n rowVersion < (spec.minRowVersion ?? '00')\n ) {\n row = {...row, [ZERO_VERSION_COLUMN_NAME]: spec.minRowVersion};\n }\n }\n\n yield {\n type: op,\n queryID,\n table,\n rowKey,\n row: op === ChangeType.REMOVE ? undefined : row,\n } as RowChange;\n\n for (const [relationship, children] of Object.entries(relationships)) {\n const childSchema = must(schema.relationships[relationship]);\n yield* this.#streamNodes(queryID, childSchema, op, children);\n }\n }\n }\n}\n\nclass QueryFailureLoggingOperator implements Input, Output {\n readonly #lc: LogContext;\n readonly #input: Input;\n readonly #queryHash: string;\n readonly #transformationHash: string;\n readonly #queryName: string | undefined;\n #output: Output = throwOutput;\n\n constructor(\n lc: LogContext,\n input: Input,\n queryHash: string,\n transformationHash: string,\n queryName?: string,\n ) {\n this.#lc = lc;\n this.#input = input;\n this.#queryHash = queryHash;\n this.#transformationHash = transformationHash;\n this.#queryName = queryName;\n input.setOutput(this);\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n fetch(req: FetchRequest): Iterable<Node | 'yield'> {\n return this.#input.fetch(req);\n }\n\n *push(change: Change): Iterable<'yield'> {\n try {\n yield* this.#output.push(change, this);\n } catch (e) {\n logQueryFailure(\n this.#lc,\n {\n queryHash: this.#queryHash,\n transformationHash: this.#transformationHash,\n queryName: this.#queryName,\n },\n 'query pipeline failed',\n e,\n );\n throw e;\n }\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n try {\n yield* this.#output.reconcile(this);\n } catch (e) {\n logQueryFailure(\n this.#lc,\n {\n queryHash: this.#queryHash,\n transformationHash: this.#transformationHash,\n queryName: this.#queryName,\n },\n 'query pipeline failed during reconcile',\n e,\n );\n throw e;\n }\n }\n }\n}\n\nfunction logQueryFailure(\n lc: LogContext,\n queryInfo: QueryLogInfo | undefined,\n message: string,\n error: unknown,\n): void {\n if (error instanceof ResetPipelinesSignal) {\n return;\n }\n let queryLC = lc;\n if (queryInfo) {\n queryLC = queryLC\n .withContext('queryHash', queryInfo.queryHash)\n .withContext('transformationHash', queryInfo.transformationHash);\n if (queryInfo.queryName !== undefined) {\n queryLC = queryLC.withContext('queryName', queryInfo.queryName);\n }\n }\n queryLC.error?.(message, error);\n}\n\nfunction* toAdds(nodes: Iterable<Node | 'yield'>): Iterable<Change | 'yield'> {\n for (const node of nodes) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n yield [ChangeType.ADD, node, null];\n }\n}\n\nfunction getRowKey(cols: PrimaryKey, row: Row): RowKey {\n return Object.fromEntries(cols.map(col => [col, must(row[col])]));\n}\n\n/**\n * Core hydration logic used by {@link PipelineDriver#addQuery}, extracted to a\n * function for reuse by the analyze-query RPC path so that analysis hydrates\n * queries the same way the view-syncer does in production.\n */\nexport function hydrate(\n input: Input,\n hash: string,\n clientSchema: ClientSchema,\n tableSpecs: Map<string, LiteAndZqlSpec>,\n): Iterable<RowChange | 'yield'> {\n const res = input.fetch({});\n const streamer = new Streamer(\n buildPrimaryKeys(clientSchema),\n tableSpecs,\n ).accumulate(hash, input.getSchema(), toAdds(res));\n return streamer.stream();\n}\n\nexport function hydrateInternal(\n input: Input,\n hash: string,\n primaryKeys: Map<string, PrimaryKey>,\n tableSpecs: Map<string, LiteAndZqlSpec>,\n): Iterable<RowChange | 'yield'> {\n const res = input.fetch({});\n const streamer = new Streamer(primaryKeys, tableSpecs).accumulate(\n hash,\n input.getSchema(),\n toAdds(res),\n );\n return streamer.stream();\n}\n\nfunction buildPrimaryKeys(\n clientSchema: ClientSchema,\n primaryKeys: Map<string, PrimaryKey> = new Map<string, PrimaryKey>(),\n) {\n for (const [tableName, {primaryKey}] of Object.entries(clientSchema.tables)) {\n primaryKeys.set(tableName, primaryKey as unknown as PrimaryKey);\n }\n return primaryKeys;\n}\n\nfunction mustGetPrimaryKey(\n primaryKeys: Map<string, PrimaryKey> | null,\n table: string,\n): PrimaryKey {\n const pKeys = must(primaryKeys, 'primaryKey map must be non-null');\n\n const rv = pKeys.get(table);\n assert(\n rv,\n () =>\n // oxlint-disable-next-line e18e/prefer-array-to-sorted\n `table '${table}' is not one of: ${JSON.stringify([...pKeys.keys()].sort())}. ` +\n `Check the spelling and ensure that the table has a primary key.`,\n );\n return rv;\n}\n\n/**\n * Compares two scalar subquery resolved values for equality.\n * Unlike `valuesEqual` in data.ts (which treats null != null for join\n * semantics), this uses identity semantics: undefined === undefined\n * (no row matched), null === null (row matched but field was NULL).\n */\nfunction scalarValuesEqual(\n a: LiteralValue | null | undefined,\n b: LiteralValue | null | undefined,\n): boolean {\n return a === b;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4KA,IAAM,gCAAgC;AACtC,IAAM,2CAA2C;AACjD,IAAM,wCAAwC;AAC9C,IAAM,2CAA2C;AACjD,IAAM,sCAAsC;AAC5C,IAAM,oCAAoC;AAC1C,IAAM,yCAAyC;AAC/C,IAAM,mCAAmC;AAEzC,SAAS,WAAW;CAClB,OAAO,QAAQ,GAAG,OAAO,gBAAgB,EAAE,SAAS,EAAE;AACxD;AAEA,SAAS,2BACP,WACA,kBACA,YACoB;CACpB,IAAI,oBAAoB,KAAK,cAAc,GACzC;CAEF,OAAQ,YAAY,mBAAoB;AAC1C;AAEA,SAAS,4BAA4B,sBAAsC;CACzE,OAAO,KAAK,IAAI,sBAAsB,CAAC;AACzC;AAEA,SAAS,qCAAqC,YAA4B;CACxE,OAAO,KAAK,IACV,0CACA,KAAK,IACH,0CACA,KAAK,KAAK,aAAa,qCAAqC,CAC9D,CACF;AACF;AAEA,SAAS,gCACP,WACA,sBACA,kBACA,YACA,sBACS;CACT,IACE,yBAAyB,KAAA,KACzB,aAAa,qCACb,mBAAmB,qCAAqC,UAAU,KAClE,YAAY,qCAEZ,OAAO;CAGT,OACE,uBACA,4BAA4B,oBAAoB,IAC9C;AAEN;AAEA,SAAS,4BACP,kBACA,YACS;CACT,OACE,aAAa,KACb,mBAAmB,cAAc;AAErC;AAEA,SAAS,6BACP,wBACA,sBACS;CACT,OACE,yBAAyB,iCACzB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,iBAAgB,OAAO,QAAQ,aAAa,MAAM,GACxE,YAAY,IAAI,WAAW,UAAmC;CAEhE,OAAO;AACT;AAEA,SAAS,kBACP,aACA,OACY;CACZ,MAAM,QAAQ,KAAK,aAAa,iCAAiC;CAEjE,MAAM,KAAK,MAAM,IAAI,KAAK;CAC1B,OACE,UAGE,UAAU,MAAM,mBAAmB,KAAK,UAAU,CAAC,GAAG,MAAM,KAAK,CAAC,EAAE,KAAK,CAAC,EAAE,kEAEhF;CACA,OAAO;AACT;;;;;;;AAQA,SAAS,kBACP,GACA,GACS;CACT,OAAO,MAAM;AACf"}
|
|
@@ -120,8 +120,12 @@ export declare class Snapshotter {
|
|
|
120
120
|
* change-applying iterations, the caller must (1) create a save point
|
|
121
121
|
* on `prev` before each iteration, and (2) rollback to the save point after
|
|
122
122
|
* the iteration.
|
|
123
|
+
*
|
|
124
|
+
* @param prevWrites How the caller writes to `prev` during the iteration,
|
|
125
|
+
* which determines which `prev` reads can be shared through the
|
|
126
|
+
* {@link SnapshotRowCache}. See {@link PrevWrites}.
|
|
123
127
|
*/
|
|
124
|
-
advance(syncableTables: Map<string, LiteAndZqlSpec>, allTableNames: Set<string>, observedTables?: TableFilter | undefined): SnapshotDiff;
|
|
128
|
+
advance(syncableTables: Map<string, LiteAndZqlSpec>, allTableNames: Set<string>, observedTables?: TableFilter | undefined, prevWrites?: PrevWrites): SnapshotDiff;
|
|
125
129
|
advanceWithoutDiff(): {
|
|
126
130
|
prev: Snapshot;
|
|
127
131
|
curr: Snapshot;
|
|
@@ -147,6 +151,22 @@ export type Change = {
|
|
|
147
151
|
export interface TableFilter {
|
|
148
152
|
has(table: string): boolean;
|
|
149
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* How the caller of {@link Snapshotter.advance()} writes the changes of a
|
|
156
|
+
* {@link SnapshotDiff} to its `prev` snapshot while iterating over it.
|
|
157
|
+
*
|
|
158
|
+
* A `prev` read for a table with a single unique key (its primary key)
|
|
159
|
+
* cannot observe earlier changes of the iteration, since a row key appears
|
|
160
|
+
* once in the diff. A read for a table with other unique keys can, because
|
|
161
|
+
* the rows it returns may have been displaced or edited by earlier changes.
|
|
162
|
+
*
|
|
163
|
+
* * `uniform`: every caller applies every change, so such a read depends on
|
|
164
|
+
* the `<prev, curr>` versions of the diff, and is shared on that basis.
|
|
165
|
+
* * `divergent`: callers apply different subsets of the changes (e.g. the
|
|
166
|
+
* pipeline driver skips changes that no pipeline can observe), so such a
|
|
167
|
+
* read depends on the caller and is not shared.
|
|
168
|
+
*/
|
|
169
|
+
export type PrevWrites = 'uniform' | 'divergent';
|
|
150
170
|
/**
|
|
151
171
|
* Represents the difference between two database Snapshots.
|
|
152
172
|
* Iterating over the object will produce a sequence of {@link Change}s
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshotter.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/snapshotter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,EAAY,KAAK,SAAS,EAAC,MAAM,uCAAuC,CAAC;AAGhF,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,uCAAuC,CAAC;AAC/D,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,sCAAsC,CAAC;AAGrE,OAAO,KAAK,EACV,cAAc,EACd,+BAA+B,EAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAC,eAAe,EAAC,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,QAAQ,EACd,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,uBAAuB,CAAC;AAYjD,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,qBAAa,WAAW;;IAStB;;;;;OAKG;IACH,YACE,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,EAAC,KAAK,EAAC,EAAE,KAAK,EACd,gBAAgB,CAAC,EAAE,MAAM,EACzB,QAAQ,CAAC,EAAE,gBAAgB,EAO5B;IAED;;;;OAIG;IACH,IAAI,IAAI,IAAI,CAUX;IAED,WAAW,IAAI,OAAO,CAErB;IAED,+EAA+E;IAC/E,OAAO,IAAI,QAAQ,CAGlB;IAED
|
|
1
|
+
{"version":3,"file":"snapshotter.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/snapshotter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,EAAY,KAAK,SAAS,EAAC,MAAM,uCAAuC,CAAC;AAGhF,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,uCAAuC,CAAC;AAC/D,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,sCAAsC,CAAC;AAGrE,OAAO,KAAK,EACV,cAAc,EACd,+BAA+B,EAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAC,eAAe,EAAC,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,QAAQ,EACd,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,uBAAuB,CAAC;AAYjD,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AAE9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,qBAAa,WAAW;;IAStB;;;;;OAKG;IACH,YACE,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,EAAC,KAAK,EAAC,EAAE,KAAK,EACd,gBAAgB,CAAC,EAAE,MAAM,EACzB,QAAQ,CAAC,EAAE,gBAAgB,EAO5B;IAED;;;;OAIG;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,EAAE,MAAM,SAgDb;IAiBD;;;;OAIG;IACH,IAAI,KAAK,IAAI,OAAO,CAEnB;IAED,WAAW,IAAI,QAAQ,CAItB;CACF;AAgRD,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,YAAY,GAAG,EAAE,MAAM,EAEtB;CACF"}
|
|
@@ -146,10 +146,14 @@ var Snapshotter = class {
|
|
|
146
146
|
* change-applying iterations, the caller must (1) create a save point
|
|
147
147
|
* on `prev` before each iteration, and (2) rollback to the save point after
|
|
148
148
|
* the iteration.
|
|
149
|
+
*
|
|
150
|
+
* @param prevWrites How the caller writes to `prev` during the iteration,
|
|
151
|
+
* which determines which `prev` reads can be shared through the
|
|
152
|
+
* {@link SnapshotRowCache}. See {@link PrevWrites}.
|
|
149
153
|
*/
|
|
150
|
-
advance(syncableTables, allTableNames, observedTables) {
|
|
154
|
+
advance(syncableTables, allTableNames, observedTables, prevWrites = "uniform") {
|
|
151
155
|
const { prev, curr } = this.advanceWithoutDiff();
|
|
152
|
-
return new Diff(this.#appID, syncableTables, allTableNames, prev, curr, observedTables, this.#rowCache);
|
|
156
|
+
return new Diff(this.#appID, syncableTables, allTableNames, prev, curr, observedTables, this.#rowCache, prevWrites);
|
|
153
157
|
}
|
|
154
158
|
advanceWithoutDiff() {
|
|
155
159
|
assert(this.#curr !== void 0, "Snapshotter has not been initialized");
|
|
@@ -323,10 +327,12 @@ var Diff = class {
|
|
|
323
327
|
#allTableNames;
|
|
324
328
|
#observedTables;
|
|
325
329
|
#rowCache;
|
|
330
|
+
#prevWrites;
|
|
326
331
|
prev;
|
|
327
332
|
curr;
|
|
328
333
|
changes;
|
|
329
|
-
constructor(appID, syncableTables, allTableNames, prev, curr, observedTables, rowCache) {
|
|
334
|
+
constructor(appID, syncableTables, allTableNames, prev, curr, observedTables, rowCache, prevWrites = "uniform") {
|
|
335
|
+
this.#prevWrites = prevWrites;
|
|
330
336
|
this.#permissionsTable = `${appID}.permissions`;
|
|
331
337
|
this.#syncableTables = syncableTables;
|
|
332
338
|
this.#allTableNames = allTableNames;
|
|
@@ -374,12 +380,14 @@ var Diff = class {
|
|
|
374
380
|
assert(rowKey !== null, "rowKey must be present for row changes");
|
|
375
381
|
if (this.prev.reset) throw new InvalidDiffError(`Diff is no longer valid. prev db has advanced past ${this.prev.version}.`);
|
|
376
382
|
const cache = this.#rowCache;
|
|
377
|
-
const
|
|
383
|
+
const prevDependsOnWrites = tableSpec.uniqueKeys.length > 1;
|
|
384
|
+
const prevCache = prevDependsOnWrites && this.#prevWrites === "divergent" ? void 0 : cache;
|
|
385
|
+
const prevTag = prevDependsOnWrites ? `p:${this.prev.version}:${this.curr.version}` : `p:${this.prev.version}`;
|
|
378
386
|
const nextValue = op === "s" ? this.curr.getRow(tableSpec, rowKey, cache, `n:${stateVersion}`) : null;
|
|
379
387
|
let prevValues;
|
|
380
|
-
if (nextValue) prevValues = this.prev.getRows(tableSpec, tableSpec.uniqueKeys, nextValue,
|
|
388
|
+
if (nextValue) prevValues = this.prev.getRows(tableSpec, tableSpec.uniqueKeys, nextValue, prevCache, prevTag);
|
|
381
389
|
else {
|
|
382
|
-
const prevValue = this.prev.getRow(tableSpec, rowKey,
|
|
390
|
+
const prevValue = this.prev.getRow(tableSpec, rowKey, prevCache, prevTag);
|
|
383
391
|
prevValues = prevValue ? [prevValue] : [];
|
|
384
392
|
}
|
|
385
393
|
if (nextValue === void 0) throw new Error(`Missing value for ${table} ${stringify(rowKey)}`);
|