@rocicorp/zero 1.11.0-canary.4 → 1.11.0-canary.6

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.
Files changed (123) hide show
  1. package/out/replicache/src/kv/expo-sqlite/store.d.ts.map +1 -1
  2. package/out/replicache/src/kv/expo-sqlite/store.js +27 -4
  3. package/out/replicache/src/kv/expo-sqlite/store.js.map +1 -1
  4. package/out/replicache/src/kv/sqlite-store.d.ts +11 -0
  5. package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
  6. package/out/replicache/src/kv/sqlite-store.js +43 -3
  7. package/out/replicache/src/kv/sqlite-store.js.map +1 -1
  8. package/out/shared/src/error.d.ts +11 -0
  9. package/out/shared/src/error.d.ts.map +1 -1
  10. package/out/shared/src/error.js +35 -1
  11. package/out/shared/src/error.js.map +1 -1
  12. package/out/shared/src/map.d.ts +7 -2
  13. package/out/shared/src/map.d.ts.map +1 -1
  14. package/out/shared/src/map.js.map +1 -1
  15. package/out/zero/package.js +2 -2
  16. package/out/zero/package.js.map +1 -1
  17. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  18. package/out/zero-cache/src/config/normalize.js +7 -1
  19. package/out/zero-cache/src/config/normalize.js.map +1 -1
  20. package/out/zero-cache/src/config/zero-config.d.ts +9 -0
  21. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  22. package/out/zero-cache/src/config/zero-config.js +21 -0
  23. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  24. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  25. package/out/zero-cache/src/server/change-streamer.js +15 -6
  26. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  27. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  28. package/out/zero-cache/src/server/main.js +8 -1
  29. package/out/zero-cache/src/server/main.js.map +1 -1
  30. package/out/zero-cache/src/server/mutator.js +2 -0
  31. package/out/zero-cache/src/server/mutator.js.map +1 -1
  32. package/out/zero-cache/src/server/reaper.d.ts.map +1 -1
  33. package/out/zero-cache/src/server/reaper.js +2 -0
  34. package/out/zero-cache/src/server/reaper.js.map +1 -1
  35. package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
  36. package/out/zero-cache/src/server/replicator.js +2 -0
  37. package/out/zero-cache/src/server/replicator.js.map +1 -1
  38. package/out/zero-cache/src/server/runner/zero-dispatcher.d.ts.map +1 -1
  39. package/out/zero-cache/src/server/runner/zero-dispatcher.js +3 -0
  40. package/out/zero-cache/src/server/runner/zero-dispatcher.js.map +1 -1
  41. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  42. package/out/zero-cache/src/server/syncer.js +2 -0
  43. package/out/zero-cache/src/server/syncer.js.map +1 -1
  44. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +1 -1
  45. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.d.ts.map +1 -1
  46. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js +68 -8
  47. package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js.map +1 -1
  48. package/out/zero-cache/src/services/change-streamer/change-log-codec.d.ts +19 -4
  49. package/out/zero-cache/src/services/change-streamer/change-log-codec.d.ts.map +1 -1
  50. package/out/zero-cache/src/services/change-streamer/change-log-codec.js +28 -8
  51. package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
  52. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +3 -0
  53. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  54. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +3 -1
  55. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  56. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +6 -0
  57. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  58. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +86 -51
  59. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  60. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts +1 -1
  61. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
  62. package/out/zero-cache/src/services/change-streamer/schema/tables.js +4 -4
  63. package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
  64. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.d.ts +6 -1
  65. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.d.ts.map +1 -1
  66. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +27 -9
  67. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
  68. package/out/zero-cache/src/services/change-streamer/storer.d.ts +2 -2
  69. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  70. package/out/zero-cache/src/services/change-streamer/storer.js +6 -5
  71. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  72. package/out/zero-cache/src/services/litestream/litestream-checkpointer.js +50 -23
  73. package/out/zero-cache/src/services/litestream/litestream-checkpointer.js.map +1 -1
  74. package/out/zero-cache/src/services/profz.d.ts +7 -0
  75. package/out/zero-cache/src/services/profz.d.ts.map +1 -0
  76. package/out/zero-cache/src/services/profz.js +99 -0
  77. package/out/zero-cache/src/services/profz.js.map +1 -0
  78. package/out/zero-cache/src/services/replicator/change-log-stream-writer.d.ts +5 -4
  79. package/out/zero-cache/src/services/replicator/change-log-stream-writer.d.ts.map +1 -1
  80. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +20 -22
  81. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
  82. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts +6 -6
  83. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts.map +1 -1
  84. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +19 -14
  85. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  86. package/out/zero-cache/src/services/view-syncer/cvr.d.ts +17 -0
  87. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  88. package/out/zero-cache/src/services/view-syncer/cvr.js +59 -0
  89. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  90. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts +51 -0
  91. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts.map +1 -0
  92. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js +78 -0
  93. package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js.map +1 -0
  94. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  95. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +18 -6
  96. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  97. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  98. package/out/zero-cache/src/services/view-syncer/view-syncer.js +154 -6
  99. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  100. package/out/zero-cache/src/types/processes.d.ts +24 -0
  101. package/out/zero-cache/src/types/processes.d.ts.map +1 -1
  102. package/out/zero-cache/src/types/processes.js +25 -1
  103. package/out/zero-cache/src/types/processes.js.map +1 -1
  104. package/out/zero-cache/src/types/profiler.d.ts +12 -0
  105. package/out/zero-cache/src/types/profiler.d.ts.map +1 -1
  106. package/out/zero-cache/src/types/profiler.js +46 -1
  107. package/out/zero-cache/src/types/profiler.js.map +1 -1
  108. package/out/zero-client/src/client/version.js +1 -1
  109. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  110. package/out/zero-client/src/client/zero.js +12 -8
  111. package/out/zero-client/src/client/zero.js.map +1 -1
  112. package/out/zero-protocol/src/down.d.ts +27 -27
  113. package/out/zero-react/src/use-query.d.ts.map +1 -1
  114. package/out/zero-react/src/use-query.js +50 -3
  115. package/out/zero-react/src/use-query.js.map +1 -1
  116. package/out/zero-solid/src/use-query.js +1 -2
  117. package/out/zero-solid/src/use-query.js.map +1 -1
  118. package/out/zql/src/ivm/data.d.ts.map +1 -1
  119. package/out/zql/src/ivm/data.js +8 -3
  120. package/out/zql/src/ivm/data.js.map +1 -1
  121. package/out/zql/src/ivm/view-apply-change.js +6 -1
  122. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  123. package/package.json +2 -2
@@ -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","#getSource","#createStorage","#trackRowSetSignatures","#addQueryImpl","#logQueryPipelineLifecycle","#ensureCostModelExistsIfEnabled","#advanceContext","#hydrateContext","#resolveScalarSubqueries","#warnIgnoredScalarHints","#streamer","#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 {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 transformationHash: string;\n readonly queryName?: string | undefined;\n readonly companions: readonly CompanionPipeline[];\n};\n\ntype QueryInfo = {\n readonly transformedAst: AST;\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 advanceWithoutDiff(): string {\n const {db, version} = this.#snapshotter.advanceWithoutDiff().curr;\n for (const table of this.#tables.values()) {\n table.setDB(db.db);\n }\n return 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.#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 #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 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 // 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 // Keep the companion alive even with no results — it will\n // detect a future insert that creates the row.\n companionInputs.push(input);\n return undefined;\n }\n companionRows.push({table: subqueryAST.table, row: node.row as Row});\n companionInputs.push(input);\n return (node.row[childField] as LiteralValue) ?? null;\n };\n\n const {\n ast: resolved,\n companions,\n ignoredScalarHints,\n } = resolveSimpleScalarSubqueries(ast, this.#tableSpecs, executor);\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()\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 try {\n const {\n ast: resolvedQuery,\n companionRows,\n companions: companionMeta,\n companionInputs,\n ignoredScalarHints,\n } = this.#resolveScalarSubqueries(query);\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 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 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 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 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 }\n this.#rowSetSignatures.delete(queryID);\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 );\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 let type;\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 type,\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 let source = this.#tables.get(tableName);\n if (source) {\n return source;\n }\n\n const tableSpec = mustGetTableSpec(this.#tableSpecs, tableName);\n const primaryKey = mustGetPrimaryKey(this.#primaryKeys, tableName);\n\n const {db} = this.#snapshotter.current();\n source = new TableSource(\n this.#lc,\n this.#logConfig,\n db.db,\n tableName,\n tableSpec.zqlSpec,\n primaryKey,\n () => this.#shouldYield(),\n );\n this.#tables.set(tableName, source);\n this.#lc.debug?.(`created TableSource for ${tableName}`);\n return source;\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 yield* 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 yield* 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: ${[...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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuKA,IAAM,gCAAgC;AACtC,IAAM,2CAA2C;AACjD,IAAM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AAQ,OAAO;EACxB,IAAI,SAAS,SAAS;GACpB,MAAM;GACN;EACF;EACA,MAAM;GAAC;GAAgB;GAAM;EAAI;CACnC;AACF;AAEA,SAAS,UAAU,MAAkB,KAAkB;CACrD,OAAO,OAAO,YAAY,KAAK,KAAI,QAAO,CAAC,KAAK,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC;AAClE;;;;;;AAOA,UAAiB,QACf,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,UAAiB,gBACf,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,CAAC,GAAG,MAAM,KAAK,CAAC,EAAE,KAAK,EAAE,kEAEhE;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","#getSource","#createStorage","#trackRowSetSignatures","#addQueryImpl","#logQueryPipelineLifecycle","#ensureCostModelExistsIfEnabled","#advanceContext","#hydrateContext","#resolveScalarSubqueries","#warnIgnoredScalarHints","#streamer","#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 {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 transformationHash: string;\n readonly queryName?: string | undefined;\n readonly companions: readonly CompanionPipeline[];\n};\n\ntype QueryInfo = {\n readonly transformedAst: AST;\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 advanceWithoutDiff(): string {\n const {db, version} = this.#snapshotter.advanceWithoutDiff().curr;\n for (const table of this.#tables.values()) {\n table.setDB(db.db);\n }\n return 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.#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 #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 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()\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 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 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 // 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 }\n this.#rowSetSignatures.delete(queryID);\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 );\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 let type;\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 type,\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 let source = this.#tables.get(tableName);\n if (source) {\n return source;\n }\n\n const tableSpec = mustGetTableSpec(this.#tableSpecs, tableName);\n const primaryKey = mustGetPrimaryKey(this.#primaryKeys, tableName);\n\n const {db} = this.#snapshotter.current();\n source = new TableSource(\n this.#lc,\n this.#logConfig,\n db.db,\n tableName,\n tableSpec.zqlSpec,\n primaryKey,\n () => this.#shouldYield(),\n );\n this.#tables.set(tableName, source);\n this.#lc.debug?.(`created TableSource for ${tableName}`);\n return source;\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 yield* 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 yield* 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: ${[...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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuKA,IAAM,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CAC1B,OACE,UAGE,UAAU,MAAM,mBAAmB,CAAC,GAAG,MAAM,KAAK,CAAC,EAAE,KAAK,EAAE,kEAEhE;CACA,OAAO;AACT;;;;;;;AAQA,SAAS,kBACP,GACA,GACS;CACT,OAAO,MAAM;AACf"}
@@ -1 +1 @@
1
- {"version":3,"file":"view-syncer.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/view-syncer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAcjD,OAAO,KAAK,EAAC,2BAA2B,EAAC,MAAM,yDAAyD,CAAC;AAKzG,OAAO,KAAK,EAEV,qBAAqB,EACtB,MAAM,0CAA0C,CAAC;AAElD,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,iDAAiD,CAAC;AAQ1F,OAAO,KAAK,EAEV,wBAAwB,EACzB,MAAM,6CAA6C,CAAC;AACrD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,8CAA8C,CAAC;AAGpF,OAAO,EAAkB,KAAK,IAAI,EAAC,MAAM,oBAAoB,CAAC;AAK9D,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,2BAA2B,CAAC;AACpE,OAAO,KAAK,EACV,sBAAsB,EAEvB,MAAM,yCAAyC,CAAC;AAQjD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,oCAAoC,CAAC;AAC1E,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,2BAA2B,CAAC;AAMpE,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,6BAA6B,CAAC;AAC7D,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,mBAAmB,CAAC;AAElD,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAC,YAAY,EAAC,MAAM,6BAA6B,CAAC;AACzD,OAAO,KAAK,E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,IAAI,CAAC,CAMpB;IA0BD;;;OAGG;IACH,eAAe,SAEd;CACF;AAgED;;;;;GAKG;AACH,wBAAgB,OAAO,CACrB,QAAQ,EAAE,QAAQ,EAClB,CAAC,EAAE,mBAAmB,GAAG,iBAAiB,GAAG,iBAAiB,GAC7D,OAAO,CAuBT;AAYD,qBAAa,cAAc;;IAKzB,YAAY,EAAE,EAAE,UAAU,EAEzB;IAEK,KAAK,kBAKV;IAED,oBAAoB,SAInB;IAEK,YAAY,CAAC,cAAc,CAAC,EAAE,MAAM,iBAIzC;IAOD,UAAU,WAGT;IAQD,sCAAsC;IACtC,IAAI,IAAI,MAAM,CAGb;IAED;;;OAGG;IACH,YAAY,IAAI,MAAM,CAIrB;CACF"}
@@ -28,6 +28,7 @@ import { CVRStore, ClientNotFoundError } from "./cvr-store.js";
28
28
  import { CVRConfigDrivenUpdater, CVRQueryDrivenUpdater, classifyQueriesForHydration, nextEvictionTime } from "./cvr.js";
29
29
  import { E2EServingLagTracker } from "./e2e-serving-lag.js";
30
30
  import { HydrationBudget } from "./hydration-budget.js";
31
+ import { HydrationCircuitBreaker } from "./hydration-circuit-breaker.js";
31
32
  import { handleInspect } from "./inspect-handler.js";
32
33
  import { QueryCoveringIndex } from "./query-covering.js";
33
34
  import { resolver } from "@rocicorp/resolver";
@@ -62,6 +63,7 @@ var ViewSyncerService = class {
62
63
  #drainCoordinator;
63
64
  #keepaliveMs;
64
65
  #slowHydrateThreshold;
66
+ #hydrationCircuitBreaker;
65
67
  #lastConnectTime = Date.now();
66
68
  /**
67
69
  * The TTL clock is used to determine the time at which queries are considered
@@ -181,7 +183,15 @@ var ViewSyncerService = class {
181
183
  ]
182
184
  });
183
185
  #queryEvictions = getOrCreateCounter("sync", "query_evictions", {
184
- description: "Number of inactive queries evicted, grouped by reason.",
186
+ description: "Number of queries evicted from the CVR ahead of their removal by the client, grouped by reason. Inactive queries are evicted by ttl and hydration-budget; hydration-timeout and hydration-circuit-breaker evict active queries as well.",
187
+ unit: "{query}"
188
+ });
189
+ #hydrationTimeouts = getOrCreateCounter("sync", "hydration_timeouts", {
190
+ description: "Number of query hydrations aborted for exceeding the query hydration timeout.",
191
+ unit: "{query}"
192
+ });
193
+ #hydrationCircuitBreakerRejections = getOrCreateCounter("sync", "hydration_circuit_breaker_rejections", {
194
+ description: "Number of queries rejected without hydration because their hydration circuit breaker was open.",
185
195
  unit: "{query}"
186
196
  });
187
197
  #inspectorDelegate;
@@ -203,6 +213,7 @@ var ViewSyncerService = class {
203
213
  this.#cvrStore = new CVRStore(lc, cvrDb, shard, taskID, clientGroupID, () => this.#stateChanges.cancel());
204
214
  this.#setTimeout = setTimeoutFn;
205
215
  this.#now = now;
216
+ this.#hydrationCircuitBreaker = new HydrationCircuitBreaker(config.viewSyncerQueryHydrationTimeoutMs ?? 0, void 0, now);
206
217
  this.#runPriorityOp = runPriorityOp;
207
218
  this.keepalive();
208
219
  }
@@ -795,6 +806,10 @@ var ViewSyncerService = class {
795
806
  for (const { id: queryID, transformationHash, transformedAst } of transformedQueries) {
796
807
  const query = cvr.queries[queryID];
797
808
  const queryName = query.type === "custom" ? query.name : void 0;
809
+ if (query.type !== "internal" && this.#hydrationCircuitBreaker.isOpen(transformationHash)) {
810
+ lc.info?.(`skipping hydration of ${queryID}: hydration circuit breaker open`);
811
+ continue;
812
+ }
798
813
  const covered = queryCoveringIndex ? this.#findQueryCoverageShadowHit(queryCoveringIndex, queryID, transformationHash, transformedAst, queryName) : void 0;
799
814
  totalHydratedQueries++;
800
815
  if (covered) {
@@ -803,15 +818,30 @@ var ViewSyncerService = class {
803
818
  }
804
819
  const timer = new TimeSliceTimer(lc);
805
820
  let count = 0;
821
+ let timedOut = false;
806
822
  await startAsyncSpan(tracer, "vs.#hydrateUnchangedQueries.addQuery", async (span) => {
807
823
  span.setAttribute("queryHash", queryID);
808
824
  span.setAttribute("transformationHash", transformationHash);
809
825
  span.setAttribute("table", transformedAst.table);
810
826
  if (queryName !== void 0) span.setAttribute("queryName", queryName);
811
- for (const change of this.#pipelines.addQuery(transformationHash, queryID, transformedAst, await timer.start(), queryName, "unchanged-query-rehydrate")) if (change === "yield") await timer.yieldProcess("yield in hydrateUnchangedQueries");
812
- else count++;
827
+ for (const change of this.#pipelines.addQuery(transformationHash, queryID, transformedAst, await timer.start(), queryName, "unchanged-query-rehydrate")) if (change === "yield") {
828
+ if (query.type !== "internal" && this.#hydrationCircuitBreaker.exceeded(timer.totalElapsed())) {
829
+ timedOut = true;
830
+ await timer.yieldProcess("yield in hydrateUnchangedQueries");
831
+ break;
832
+ }
833
+ await timer.yieldProcess("yield in hydrateUnchangedQueries");
834
+ } else count++;
813
835
  });
814
836
  const elapsed = timer.totalElapsed();
837
+ if (timedOut) {
838
+ this.#recordHydrationTimeout(lc, {
839
+ id: queryID,
840
+ transformationHash,
841
+ name: queryName
842
+ }, elapsed, count);
843
+ continue;
844
+ }
815
845
  hydrationPassStats.activeHydratedQueries++;
816
846
  this.#hydrations.add(1);
817
847
  this.#hydrationTime.recordMs(elapsed);
@@ -1000,7 +1030,17 @@ var ViewSyncerService = class {
1000
1030
  const queriesToTransform = [...required, ...optionalToHydrate];
1001
1031
  transformOtherQueries(queriesToTransform);
1002
1032
  await transformCustomQueries(queriesToTransform.filter((query) => query.type === "custom" && shouldTransformCustomQuery(query)));
1003
- const removeQueriesQueryIds = new Set([...naturallyExpiredQueryIDs, ...erroredQueryIDs]);
1033
+ const circuitBrokenQueries = transformedQueries.filter(({ id, origQuery, transformed }) => origQuery.type !== "internal" && this.#pipelines.queries().get(id)?.transformationHash !== transformed.transformationHash && this.#hydrationCircuitBreaker.isOpen(transformed.transformationHash)).map(({ id, origQuery, transformed }) => ({
1034
+ id,
1035
+ transformationHash: transformed.transformationHash,
1036
+ name: origQuery.type === "custom" ? origQuery.name : void 0
1037
+ }));
1038
+ if (circuitBrokenQueries.length > 0) this.#rejectCircuitBrokenQueries(lc, cvr, circuitBrokenQueries);
1039
+ const removeQueriesQueryIds = new Set([
1040
+ ...naturallyExpiredQueryIDs,
1041
+ ...erroredQueryIDs,
1042
+ ...circuitBrokenQueries.map(({ id }) => id)
1043
+ ]);
1004
1044
  const addQueries = transformedQueries.map(({ id, origQuery, transformed }) => ({
1005
1045
  id,
1006
1046
  ast: transformed.transformedAst,
@@ -1011,7 +1051,7 @@ var ViewSyncerService = class {
1011
1051
  addQueries.sort((a, b) => must(hydrationOrder.get(a.id)) - must(hydrationOrder.get(b.id)));
1012
1052
  const requiredAddQueries = addQueries.filter((query) => requiredQueryIDs.has(query.id));
1013
1053
  const optionalAddQueries = addQueries.filter((query) => !requiredQueryIDs.has(query.id));
1014
- lc.info?.(`syncQueryPipelineSet: ${cvrQueryEntires.length} CVR queries, ${transformedCustomQueryCount} custom re-transformed, ${erroredQueryIDs.length} errored, ${removeQueriesQueryIds.size} to remove, ${addQueries.length} to add`);
1054
+ lc.info?.(`syncQueryPipelineSet: ${cvrQueryEntires.length} CVR queries, ${transformedCustomQueryCount} custom re-transformed, ${erroredQueryIDs.length} errored, ${circuitBrokenQueries.length} circuit-broken, ${removeQueriesQueryIds.size} to remove, ${addQueries.length} to add`);
1015
1055
  for (const q of addQueries) {
1016
1056
  const orig = cvr.queries[q.id];
1017
1057
  lc.debug?.("ViewSyncer adding query", q.ast, "transformed from", orig.type === "custom" ? orig.name : orig.ast);
@@ -1050,6 +1090,79 @@ var ViewSyncerService = class {
1050
1090
  record.count++;
1051
1091
  if (record.count >= THRASH_THRESHOLD) this.#lc.warn?.(`Query thrashing detected for query ${queryID}. ${record.count} replacements in 60s. This may indicate clients with different auth contexts connecting to the same client group.`);
1052
1092
  }
1093
+ /**
1094
+ * Records that hydrating `query` was aborted for exceeding the query
1095
+ * hydration timeout, and opens its circuit breaker.
1096
+ */
1097
+ #recordHydrationTimeout(lc, query, elapsedMs, rowCount) {
1098
+ this.#hydrationCircuitBreaker.trip(query.transformationHash);
1099
+ this.#hydrationTimeouts.add(1);
1100
+ lc.warn?.("Query hydration aborted for exceeding the hydration timeout", {
1101
+ clientGroupID: this.id,
1102
+ queryHash: query.id,
1103
+ transformationHash: query.transformationHash,
1104
+ ...query.name !== void 0 && { queryName: query.name },
1105
+ hydrationTimeoutMs: this.#hydrationCircuitBreaker.timeoutMs,
1106
+ hydrationElapsedMs: elapsedMs,
1107
+ ...rowCount !== void 0 && { hydrationRowCount: rowCount },
1108
+ circuitBreakerOpenMs: this.#hydrationCircuitBreaker.openMs
1109
+ });
1110
+ }
1111
+ /** Records that `query` was rejected without hydration by its open breaker. */
1112
+ #recordCircuitBreakerRejection(lc, query) {
1113
+ this.#hydrationCircuitBreakerRejections.add(1);
1114
+ lc.warn?.("Query rejected by its open hydration circuit breaker", {
1115
+ clientGroupID: this.id,
1116
+ queryHash: query.id,
1117
+ transformationHash: query.transformationHash,
1118
+ ...query.name !== void 0 && { queryName: query.name },
1119
+ hydrationTimeoutMs: this.#hydrationCircuitBreaker.timeoutMs,
1120
+ circuitBreakerOpenMs: this.#hydrationCircuitBreaker.openMs
1121
+ });
1122
+ }
1123
+ /**
1124
+ * Handles queries whose hydration circuit breaker is open: they are counted,
1125
+ * logged, and errored to the affected clients. The caller removes them from
1126
+ * the CVR.
1127
+ */
1128
+ #rejectCircuitBrokenQueries(lc, cvr, queries) {
1129
+ for (const query of queries) this.#recordCircuitBreakerRejection(lc, query);
1130
+ this.#queryEvictions.add(queries.length, { reason: "hydration-circuit-breaker" });
1131
+ this.#sendHydrationTimeoutErrors(cvr, queries);
1132
+ }
1133
+ /**
1134
+ * Sends a per-query error to every client that desires one of `queries`.
1135
+ * The error goes out as a `transformError` application error, which every
1136
+ * client understands as "this query errored" without affecting the
1137
+ * connection or the client's other queries.
1138
+ */
1139
+ #sendHydrationTimeoutErrors(cvr, queries) {
1140
+ const timeoutMs = this.#hydrationCircuitBreaker.timeoutMs;
1141
+ const errorsByClient = /* @__PURE__ */ new Map();
1142
+ for (const { id, name } of queries) {
1143
+ const query = cvr.queries[id];
1144
+ if (query === void 0 || query.type === "internal") continue;
1145
+ const error = {
1146
+ error: "app",
1147
+ id,
1148
+ name: name ?? (query.type === "custom" ? query.name : "legacy"),
1149
+ message: `Query hydration exceeded the ${timeoutMs}ms limit (ZERO_VIEW_SYNCER_QUERY_HYDRATION_TIMEOUT_MS) and was aborted`,
1150
+ details: {
1151
+ kind: "HydrationTimeout",
1152
+ timeoutMs
1153
+ }
1154
+ };
1155
+ for (const clientID of Object.keys(query.clientState)) {
1156
+ let errors = errorsByClient.get(clientID);
1157
+ if (!errors) {
1158
+ errors = [];
1159
+ errorsByClient.set(clientID, errors);
1160
+ }
1161
+ errors.push(error);
1162
+ }
1163
+ }
1164
+ for (const [clientID, errors] of errorsByClient) this.#clients.get(clientID)?.sendQueryTransformApplicationErrors(errors);
1165
+ }
1053
1166
  #recordHydrationBudgetExhaustion(lc, hydrationBudget, activeHydratedQueries, inactiveHydratedQueries, inactiveEvictedQueryIDs) {
1054
1167
  const elapsedMs = hydrationBudget.exhaustedAtMs;
1055
1168
  if (elapsedMs === void 0) return;
@@ -1106,6 +1219,9 @@ var ViewSyncerService = class {
1106
1219
  let firstCoveredQuery;
1107
1220
  const hydratedQueryIDs = [];
1108
1221
  const budgetEvictedQueryIDs = [];
1222
+ const timedOutQueries = [];
1223
+ const rejectedQueries = [];
1224
+ const circuitBreaker = this.#hydrationCircuitBreaker;
1109
1225
  const self = this;
1110
1226
  await yieldProcess(lc);
1111
1227
  function* hydrateQueries(queries, optional, slowHydrateThreshold) {
@@ -1118,15 +1234,34 @@ var ViewSyncerService = class {
1118
1234
  let queryLC = lc.withContext("hash", q.id).withContext("queryHash", q.id).withContext("transformationHash", q.transformationHash);
1119
1235
  if (q.name !== void 0) queryLC = queryLC.withContext("queryName", q.name);
1120
1236
  queryLC.debug?.(`adding pipeline for query`, q.ast);
1237
+ const breakable = cvr.queries[q.id]?.type !== "internal";
1238
+ if (breakable && circuitBreaker.isOpen(q.transformationHash)) {
1239
+ rejectedQueries.push(q);
1240
+ self.#recordCircuitBreakerRejection(queryLC, q);
1241
+ continue;
1242
+ }
1121
1243
  const covered = queryCoveringIndex ? self.#findQueryCoverageShadowHit(queryCoveringIndex, q.id, q.transformationHash, q.ast, q.name) : void 0;
1122
1244
  totalHydratedQueries++;
1123
1245
  if (covered) {
1124
1246
  coveredHydratedQueries++;
1125
1247
  firstCoveredQuery ??= covered;
1126
1248
  }
1127
- yield* pipelines.addQuery(q.transformationHash, q.id, q.ast, timer.startWithoutYielding(), q.name, "query-set-sync");
1249
+ let timedOut = false;
1250
+ for (const change of pipelines.addQuery(q.transformationHash, q.id, q.ast, timer.startWithoutYielding(), q.name, "query-set-sync")) {
1251
+ if (change === "yield" && breakable && circuitBreaker.exceeded(timer.totalElapsed())) {
1252
+ timedOut = true;
1253
+ yield change;
1254
+ break;
1255
+ }
1256
+ yield change;
1257
+ }
1128
1258
  const elapsed = timer.stop();
1129
1259
  totalProcessTime += elapsed;
1260
+ if (timedOut) {
1261
+ timedOutQueries.push(q);
1262
+ self.#recordHydrationTimeout(queryLC, q, elapsed);
1263
+ continue;
1264
+ }
1130
1265
  hydratedQueryIDs.push(q.id);
1131
1266
  if (optional) hydrationPassStats.inactiveHydratedQueries++;
1132
1267
  else hydrationPassStats.activeHydratedQueries++;
@@ -1152,6 +1287,19 @@ var ViewSyncerService = class {
1152
1287
  yield* hydrateQueries(optionalQueries, true, slowHydrateThreshold);
1153
1288
  }
1154
1289
  await this.#processChanges(lc, timer, generateRowChanges(this.#slowHydrateThreshold), updater, pokers);
1290
+ const abortedQueries = [...timedOutQueries, ...rejectedQueries];
1291
+ if (abortedQueries.length > 0) {
1292
+ const abortedQueryIDs = abortedQueries.map(({ id }) => id);
1293
+ for (const patch of await updater.abortExecutedQueries(lc, abortedQueryIDs)) await pokers.addPatch(patch);
1294
+ for (const queryID of abortedQueryIDs) {
1295
+ this.#pipelines.removeQuery(queryID);
1296
+ this.#inspectorDelegate.removeQuery(queryID);
1297
+ this.#queryReplacements.delete(queryID);
1298
+ }
1299
+ if (timedOutQueries.length > 0) this.#queryEvictions.add(timedOutQueries.length, { reason: "hydration-timeout" });
1300
+ if (rejectedQueries.length > 0) this.#queryEvictions.add(rejectedQueries.length, { reason: "hydration-circuit-breaker" });
1301
+ this.#sendHydrationTimeoutErrors(cvr, abortedQueries);
1302
+ }
1155
1303
  for (const patch of updater.removeTrackedQueries(budgetEvictedQueryIDs)) await pokers.addPatch(patch);
1156
1304
  for (const queryID of budgetEvictedQueryIDs) {
1157
1305
  this.#pipelines.removeQuery(queryID);