@rocicorp/zero 1.11.0-canary.21 → 1.11.0-canary.23

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 (109) hide show
  1. package/out/zero/package.js +1 -1
  2. package/out/zero/package.js.map +1 -1
  3. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  4. package/out/zero-cache/src/config/normalize.js +1 -2
  5. package/out/zero-cache/src/config/normalize.js.map +1 -1
  6. package/out/zero-cache/src/config/zero-config.d.ts +0 -22
  7. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  8. package/out/zero-cache/src/config/zero-config.js +38 -42
  9. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  10. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  11. package/out/zero-cache/src/server/change-streamer.js +90 -73
  12. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  13. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.d.ts.map +1 -1
  14. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js +1 -1
  15. package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js.map +1 -1
  16. package/out/zero-cache/src/services/change-source/common/init-cleanup.d.ts +24 -0
  17. package/out/zero-cache/src/services/change-source/common/init-cleanup.d.ts.map +1 -0
  18. package/out/zero-cache/src/services/change-source/common/init-cleanup.js +44 -0
  19. package/out/zero-cache/src/services/change-source/common/init-cleanup.js.map +1 -0
  20. package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts +49 -1
  21. package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts.map +1 -1
  22. package/out/zero-cache/src/services/change-source/common/replica-restore.js.map +1 -1
  23. package/out/zero-cache/src/services/change-source/custom/change-source.d.ts +1 -1
  24. package/out/zero-cache/src/services/change-source/custom/change-source.d.ts.map +1 -1
  25. package/out/zero-cache/src/services/change-source/custom/change-source.js +7 -3
  26. package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
  27. package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts +10 -5
  28. package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts.map +1 -1
  29. package/out/zero-cache/src/services/change-source/pg/change-source-init.js +65 -21
  30. package/out/zero-cache/src/services/change-source/pg/change-source-init.js.map +1 -1
  31. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  32. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  33. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +2 -1
  34. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  35. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +3 -1
  36. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  37. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts +31 -0
  38. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts.map +1 -1
  39. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +100 -2
  40. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
  41. package/out/zero-cache/src/services/change-streamer/backfill-state-tracker.d.ts +6 -0
  42. package/out/zero-cache/src/services/change-streamer/backfill-state-tracker.d.ts.map +1 -1
  43. package/out/zero-cache/src/services/change-streamer/backfill-state-tracker.js +8 -0
  44. package/out/zero-cache/src/services/change-streamer/backfill-state-tracker.js.map +1 -1
  45. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts.map +1 -1
  46. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js +3 -16
  47. package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js.map +1 -1
  48. package/out/zero-cache/src/services/change-streamer/change-log-initializer.d.ts +17 -0
  49. package/out/zero-cache/src/services/change-streamer/change-log-initializer.d.ts.map +1 -1
  50. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +44 -1
  51. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
  52. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +7 -0
  53. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  54. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +27 -8
  55. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  56. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts +57 -0
  57. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
  58. package/out/zero-cache/src/services/change-streamer/schema/tables.js +103 -23
  59. package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
  60. package/out/zero-cache/src/services/change-streamer/storer.d.ts +86 -1
  61. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  62. package/out/zero-cache/src/services/change-streamer/storer.js +272 -77
  63. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  64. package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts +7 -5
  65. package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts.map +1 -1
  66. package/out/zero-cache/src/services/change-streamer/upstream-acker.js +9 -5
  67. package/out/zero-cache/src/services/change-streamer/upstream-acker.js.map +1 -1
  68. package/out/zero-cache/src/services/litestream/commands.d.ts +3 -11
  69. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  70. package/out/zero-cache/src/services/litestream/commands.js +29 -23
  71. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  72. package/out/zero-cache/src/services/litestream/config-v5.yml +0 -7
  73. package/out/zero-cache/src/services/profz.d.ts.map +1 -1
  74. package/out/zero-cache/src/services/profz.js +19 -1
  75. package/out/zero-cache/src/services/profz.js.map +1 -1
  76. package/out/zero-cache/src/services/replicator/replication-status.js +1 -1
  77. package/out/zero-cache/src/services/replicator/replication-status.js.map +1 -1
  78. package/out/zero-cache/src/services/view-syncer/advancement-metrics.d.ts +26 -0
  79. package/out/zero-cache/src/services/view-syncer/advancement-metrics.d.ts.map +1 -0
  80. package/out/zero-cache/src/services/view-syncer/advancement-metrics.js +26 -0
  81. package/out/zero-cache/src/services/view-syncer/advancement-metrics.js.map +1 -0
  82. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +10 -2
  83. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  84. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +102 -122
  85. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  86. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +8 -9
  87. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  88. package/out/zero-cache/src/services/view-syncer/snapshotter.js +15 -3
  89. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  90. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  91. package/out/zero-cache/src/services/view-syncer/view-syncer.js +50 -28
  92. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  93. package/out/zero-client/src/client/version.js +1 -1
  94. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  95. package/out/zero-client/src/client/zero.js +2 -1
  96. package/out/zero-client/src/client/zero.js.map +1 -1
  97. package/out/zero-react/src/use-query.js +12 -3
  98. package/out/zero-react/src/use-query.js.map +1 -1
  99. package/out/zql/src/ivm/array-view.d.ts.map +1 -1
  100. package/out/zql/src/ivm/array-view.js +21 -12
  101. package/out/zql/src/ivm/array-view.js.map +1 -1
  102. package/out/zqlite/src/db.d.ts.map +1 -1
  103. package/out/zqlite/src/db.js +34 -6
  104. package/out/zqlite/src/db.js.map +1 -1
  105. package/package.json +1 -1
  106. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts +0 -34
  107. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts.map +0 -1
  108. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js +0 -184
  109. package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"snapshotter.js","names":["#lc","#dbFile","#appID","#pageCacheSizeKib","#rowCache","#curr","#prev","#assertNotAdvanced","#reset","#permissionsTable","#syncableTables","#allTableNames","#observedTables","#prevWrites","#iterated"],"sources":["../../../../../../zero-cache/src/services/view-syncer/snapshotter.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport {stringify, type JSONValue} from '../../../../shared/src/bigint-json.ts';\nimport {getOrInsertComputed} from '../../../../shared/src/map.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport type {Row} from '../../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../../zero-types/src/schema.ts';\nimport {Database} from '../../../../zqlite/src/db.ts';\nimport {fromSQLiteTypes} from '../../../../zqlite/src/table-source.ts';\nimport type {\n LiteAndZqlSpec,\n LiteTableSpecWithKeysAndVersion,\n} from '../../db/specs.ts';\nimport {StatementRunner} from '../../db/statements.ts';\nimport {\n normalizedKeyOrder,\n type RowKey,\n type RowValue,\n} from '../../types/row-key.ts';\nimport type {AppID} from '../../types/shards.ts';\nimport {id} from '../../types/sql.ts';\nimport {\n RESET_OP,\n changeLogEntrySchema as schema,\n SET_OP,\n TRUNCATE_OP,\n} from '../replicator/schema/change-log.ts';\nimport {\n getReplicationState,\n ZERO_VERSION_COLUMN_NAME as ROW_VERSION,\n} from '../replicator/schema/replication-state.ts';\nimport type {SnapshotRowCache} from './snapshot-row-cache.ts';\n\n/**\n * A `Snapshotter` manages the progression of database snapshots for a\n * ViewSyncer.\n *\n * The Replicator and ViewSyncers operate on the same SQLite file, with the\n * Replicator being the sole writer to the database. The IVM logic in\n * ViewSyncers, however, rely on incrementally applying changes to the DB to\n * update the state of its pipelines.\n *\n * To avoid coupling the progress of the Replicator and all IVM pipelines on\n * each other, ViewSyncers operate on ephemeral forks of the database by holding\n * [concurrent](https://sqlite.org/src/doc/begin-concurrent/doc/begin_concurrent.md)\n * snapshots of the database and simulating (but ultimately rolling back)\n * mutations on these snapshots.\n *\n * Example:\n * 1. ViewSyncer takes `snapshot_a` at version `t1` of the database and\n * hydrates its pipeline(s).\n * 2. Replicator applies a new transaction to the database and notifies\n * subscribers.\n * 3. ViewSyncer takes `snapshot_b` at `t2`, and queries the `ChangeLog` at\n * that snapshot for changes since `t1`.\n * 4. ViewSyncer applies those changes to `snapshot_a` for IVM, but does not\n * commit them. (Recall that the Replicator is the sole writer to the db, so\n * the ViewSyncer never commits any writes.)\n * 5. Replicator applies the next transaction and advances the database to `t3`.\n * 6. ViewSyncer rolls back `snapshot_a` and opens `snapshot_c` at `t3`, using\n * `snapshot_b` to simulate changes from `t2` to `t3`.\n *\n * ```\n * Replicator: t1 --------------> t2 --------------> t3 --------------->\n * ViewSyncer: [snapshot_a] ----> [snapshot_b] ----> [snapshot_c]\n * ```\n *\n * Note that the Replicator (and ViewSyncers) do not wait on the progress of\n * other ViewSyncers. If a ViewSyncer is busy hydrating at `t1`, the Replicator\n * and other ViewSyncers can progress through `t2`, `t3`, etc. independently,\n * as the busy ViewSyncer simply takes its own snapshot when it is ready.\n *\n * ```\n * Replicator: t1 --------------> t2 --------------> t3 --------------->\n * ViewSyncer1: [snapshot_a] ----> [snapshot_b] ----> [snapshot_c]\n * ViewSyncer2: [.......... snapshot_a ..........] ----> [snapshot_b]\n * ```\n *\n * To minimize Database connections (and statement preparation, etc.), the\n * Snapshotter reuses the connection from the previous (rolled back)\n * snapshot when opening the new one.\n *\n * ```\n * Replicator: t1 --------------> t2 --------------> t3 --------------->\n * ViewSyncer: [snapshot_a] ----> [snapshot_b] ----> [snapshot_c]\n * (conn_1) (conn_2) (conn_1)\n * ```\n *\n * In this manner, each ViewSyncer uses two connections that continually\n * \"leapfrog\" each other to replay the timeline of changes in isolation from\n * the Replicator and other ViewSyncers.\n */\nexport class Snapshotter {\n readonly #lc: LogContext;\n readonly #dbFile: string;\n readonly #appID: string;\n readonly #pageCacheSizeKib: number | undefined;\n readonly #rowCache: SnapshotRowCache | undefined;\n #curr: Snapshot | undefined;\n #prev: Snapshot | undefined;\n\n /**\n * @param rowCache An optional worker-wide {@link SnapshotRowCache} through\n * which the row reads performed when iterating over a\n * {@link SnapshotDiff} are shared with the other Snapshotters\n * (i.e. client groups) on the worker.\n */\n constructor(\n lc: LogContext,\n dbFile: string,\n {appID}: AppID,\n pageCacheSizeKib?: number,\n rowCache?: SnapshotRowCache,\n ) {\n this.#lc = lc;\n this.#dbFile = dbFile;\n this.#appID = appID;\n this.#pageCacheSizeKib = pageCacheSizeKib;\n this.#rowCache = rowCache;\n }\n\n /**\n * Initializes the snapshot to the current head of the database. This must be\n * only be called once. The state of whether a Snapshotter has been initialized\n * can be determined by calling {@link initialized()}.\n */\n init(): this {\n assert(this.#curr === undefined, 'Already initialized');\n this.#curr = Snapshot.create(\n this.#lc,\n this.#dbFile,\n this.#appID,\n this.#pageCacheSizeKib,\n );\n this.#lc.debug?.(`Initial snapshot at version ${this.#curr.version}`);\n return this;\n }\n\n initialized(): boolean {\n return this.#curr !== undefined;\n }\n\n /** Returns the current snapshot. Asserts if {@link initialized()} is false. */\n current(): Snapshot {\n assert(this.#curr !== undefined, 'Snapshotter has not been initialized');\n return this.#curr;\n }\n\n /**\n * Advances to the head of the Database, returning a diff between the\n * previously current Snapshot and a new Snapshot at head. This is called\n * in response to a notification from a Replicator subscription. Subsequent\n * calls to {@link current()} return the new Snapshot. Note that the Snapshotter\n * must be initialized before advancing.\n *\n * The returned {@link SnapshotDiff} contains snapshots at the endpoints\n * of the database timeline. Iterating over the diff generates a sequence\n * of {@link Change}s between the two snapshots.\n *\n * Note that this sequence is not chronological; rather, the sequence is\n * ordered by `<table, row-key>`, such that a row can appear at most once\n * in the common case, or twice if its table is `TRUNCATE`'d and a new value\n * is subsequently `INSERT`'ed. This results in dropping most intermediate\n * changes to a row and bounds the amount of work needed to catch up;\n * however, as a consequence, a consistent database state is only guaranteed\n * when the sequence has been fully consumed.\n *\n * Note that Change generation relies on the state of the underlying\n * database connections, and because the connection for the previous snapshot\n * is reused to produce the next snapshot, the diff object is only valid\n * until the next call to `advance()`.\n *\n * It is okay for the caller to apply `Change`s to the `prev` snapshot\n * during the iteration (e.g. this is necessary for IVM); the remainder\n * of the iteration is not affected because a given row can appear at most\n * once in the sequence (with the exception being TRUNCATE, after which the\n * deleted rows can be re-inserted, but this will also behave correctly if\n * the changes are applied).\n *\n * Once the changes have been applied, however, a _subsequent_ iteration\n * will not produce the correct results. In order to perform multiple\n * change-applying iterations, the caller must (1) create a save point\n * on `prev` before each iteration, and (2) rollback to the save point after\n * the iteration.\n *\n * @param prevWrites How the caller writes to `prev` during the iteration,\n * which determines which `prev` reads can be shared through the\n * {@link SnapshotRowCache}. See {@link PrevWrites}.\n */\n advance(\n syncableTables: Map<string, LiteAndZqlSpec>,\n allTableNames: Set<string>,\n observedTables?: TableFilter | undefined,\n prevWrites: PrevWrites = 'uniform',\n ): SnapshotDiff {\n const {prev, curr} = this.advanceWithoutDiff();\n return new Diff(\n this.#appID,\n syncableTables,\n allTableNames,\n prev,\n curr,\n observedTables,\n this.#rowCache,\n prevWrites,\n );\n }\n\n advanceWithoutDiff() {\n assert(this.#curr !== undefined, 'Snapshotter has not been initialized');\n const next = this.#prev\n ? this.#prev.resetToHead()\n : Snapshot.create(\n this.#lc,\n this.#curr.db.db.name,\n this.#appID,\n this.#pageCacheSizeKib,\n );\n this.#prev = this.#curr;\n this.#curr = next;\n return {prev: this.#prev, curr: this.#curr};\n }\n\n /**\n * Call this to close the database connections when the Snapshotter is\n * no longer needed.\n */\n destroy() {\n this.#curr?.db.db.close();\n this.#prev?.db.db.close();\n this.#lc.debug?.('closed database connections');\n }\n}\n\nexport type Change = {\n readonly table: string;\n /**\n * If this change represents a remove the row to remove,\n * if nextValue is not null then all rows that have a unique constraint\n * violation with nextValue.\n * In both cases these rows should be removed.\n */\n readonly prevValues: Readonly<Row>[];\n readonly nextValue: Readonly<Row> | null;\n readonly rowKey: RowKey;\n};\n\nexport interface TableFilter {\n has(table: string): boolean;\n}\n\n/**\n * How the caller of {@link Snapshotter.advance()} writes the changes of a\n * {@link SnapshotDiff} to its `prev` snapshot while iterating over it.\n *\n * A `prev` read for a table with a single unique key (its primary key)\n * cannot observe earlier changes of the iteration, since a row key appears\n * once in the diff. A read for a table with other unique keys can, because\n * the rows it returns may have been displaced or edited by earlier changes.\n *\n * * `uniform`: every caller applies every change, so such a read depends on\n * the `<prev, curr>` versions of the diff, and is shared on that basis.\n * * `divergent`: callers apply different subsets of the changes (e.g. the\n * pipeline driver skips changes that no pipeline can observe), so such a\n * read depends on the caller and is not shared.\n * * `none`: the caller does not write to `prev` (e.g. IVM derivation is\n * held in memory), so every read depends solely on `prev.version`.\n */\nexport type PrevWrites = 'uniform' | 'divergent' | 'none';\n\n/**\n * Represents the difference between two database Snapshots.\n * Iterating over the object will produce a sequence of {@link Change}s\n * between the two snapshots.\n *\n * See {@link Snapshotter.advance()} for semantics and usage.\n */\nexport interface SnapshotDiff extends Iterable<Change> {\n readonly prev: {\n readonly db: StatementRunner;\n readonly version: string;\n };\n readonly curr: {\n readonly db: StatementRunner;\n readonly version: string;\n };\n\n /**\n * The number of ChangeLog entries between the snapshots. Note that this\n * may not necessarily equal the number of `Change` objects that the iteration\n * will produce, as `TRUNCATE` entries are counted as a single log entry which\n * may be expanded into many changes (i.e. row deletes).\n *\n * TODO: Determine if it is worth changing the definition to count the\n * truncated rows. This would make diff computation more expensive\n * (requiring the count to be aggregated by operation type), which\n * may not be worth it for a presumable rare operation.\n */\n readonly changes: number;\n\n /**\n * Overrides the `prevWrites` passed to {@link Snapshotter.advance()}, for a\n * caller that decides how to write to `prev` once it knows the number of\n * {@link changes}. Must be called before the diff is iterated, except to\n * switch to `divergent`, which can be done between any two changes: it\n * shares only the reads that no write to `prev` can affect.\n */\n setPrevWrites(prevWrites: PrevWrites): void;\n}\n\n/**\n * Thrown during an iteration of a {@link SnapshotDiff} when a schema\n * change or truncate is encountered, which result in aborting the\n * advancement and resetting / rehydrating the pipelines.\n */\nexport type ResetPipelinesReason =\n | 'advancement-timeout'\n | 'scalar-subquery'\n | 'schema-change'\n | 'truncation'\n | 'permissions-change';\n\nexport class ResetPipelinesSignal extends Error {\n readonly name = 'ResetPipelinesSignal';\n readonly reason: ResetPipelinesReason;\n\n constructor(msg: string, reason: ResetPipelinesReason) {\n super(msg);\n this.reason = reason;\n }\n}\n\n// Memoizes, per table spec, the SQL of the row lookups performed for each\n// change, which would otherwise be rebuilt from the table spec for every\n// read. Handing out the same string for every read of a given shape also\n// lets the SnapshotRowCache and the statement cache look it up without\n// rehashing it. Specs are recreated whenever they are recomputed, so stale\n// SQL is never served.\ntype TableReads = {\n /** `SELECT <columns> FROM <table> WHERE ` */\n readonly prefix: string;\n /** {@link Snapshot.getRow} SQL, by the NUL-joined key columns. */\n readonly byKeyColumns: Map<string, string>;\n /**\n * {@link Snapshot.getRows} SQL, by the bitmask of the table's `uniqueKeys`\n * that are queried.\n */\n readonly byUniqueKeys: Map<number, string>;\n};\n\nconst tableReads = new WeakMap<LiteTableSpecWithKeysAndVersion, TableReads>();\n\nfunction readsFor(table: LiteTableSpecWithKeysAndVersion): TableReads {\n return getOrInsertComputed(tableReads, table, () => ({\n prefix: `SELECT ${Object.keys(table.columns)\n .map(c => id(c))\n .join(',')} FROM ${id(table.name)} WHERE `,\n byKeyColumns: new Map(),\n byUniqueKeys: new Map(),\n }));\n}\n\n// The byUniqueKeys bitmask must fit in a (positive) 31-bit integer.\nconst MAX_MEMOIZED_UNIQUE_KEYS = 30;\n\n/**\n * The index that SQLite creates for the `PRIMARY KEY(\"stateVersion\", \"pos\")`\n * of `_zero.changeLog2` (the first constraint of its CREATE TABLE statement,\n * hence the `_1` suffix).\n *\n * For a `stateVersion > ?` query that reads a column outside of this index\n * (e.g. `op`) and has no ORDER BY, the query planner chooses between a range\n * search of the index and a full scan of the table based on `sqlite_stat1`.\n * Statistics recorded while the change log held only a few rows make the full\n * scan look cheaper, and they persist as the table grows to millions of rows:\n * the change log of a replication-manager's replica only receives entries\n * during column backfills, and view-syncers inherit its statistics when they\n * restore its backup. Such queries therefore pin this index with INDEXED BY,\n * which also makes them fail to prepare (rather than silently scan) if the\n * index is ever renamed.\n */\nconst CHANGE_LOG_STATE_VERSION_INDEX = 'sqlite_autoindex__zero.changeLog2_1';\n\nclass Snapshot {\n static create(\n lc: LogContext,\n dbFile: string,\n appID: string,\n pageCacheSizeKib: number | undefined,\n ) {\n const conn = new Database(lc, dbFile);\n conn.pragma('synchronous = OFF'); // Applied changes are ephemeral; COMMIT is never called.\n if (pageCacheSizeKib !== undefined) {\n conn.pragma(`cache_size = -${pageCacheSizeKib}`); // Negative = size in KiB\n }\n const [{journal_mode: mode}] = conn.pragma('journal_mode') as [\n {journal_mode: string},\n ];\n // BEGIN CONCURRENT lets the Snapshotter simulate changes on a historic\n // snapshot without taking the WAL writer lock. These private changes are\n // always rolled back; the replicator is the only committer and can use\n // BEGIN IMMEDIATE on the same WAL2 database.\n assert(\n mode === 'wal2',\n `replica db must be in wal2 mode (current: ${mode})`,\n );\n\n const db = new StatementRunner(conn);\n return new Snapshot(db, appID);\n }\n\n readonly db: StatementRunner;\n readonly #appID: string;\n readonly version: string;\n #reset = false;\n\n constructor(db: StatementRunner, appID: string) {\n db.beginConcurrent();\n // Note: The subsequent read is necessary to acquire the read lock\n // (which results in the logical creation of the snapshot). Calling\n // `BEGIN CONCURRENT` alone does not result in acquiring the read lock.\n const {stateVersion} = getReplicationState(db);\n\n this.db = db;\n this.#appID = appID;\n this.version = stateVersion;\n }\n\n numChangesSince(prevVersion: string) {\n const {count} = this.db.get(\n 'SELECT COUNT(*) AS count FROM \"_zero.changeLog2\" WHERE stateVersion > ?',\n prevVersion,\n );\n return count;\n }\n\n /**\n * Whether a table-wide RESET op (i.e. a schema change) was logged after\n * `prevVersion`. Table specs computed at or before `prevVersion` are\n * stale with respect to this snapshot if so.\n */\n schemaChangedSince(prevVersion: string): boolean {\n const row = this.db.get(\n `SELECT 1 FROM \"_zero.changeLog2\" INDEXED BY \"${CHANGE_LOG_STATE_VERSION_INDEX}\"\n WHERE stateVersion > ? AND op = ? LIMIT 1`,\n prevVersion,\n RESET_OP,\n );\n return row !== undefined;\n }\n\n /**\n * Whether any table-wide op (i.e. a RESET or TRUNCATE) was logged after\n * `prevVersion`. Iterating over a diff ending at this snapshot will\n * abort with a {@link ResetPipelinesSignal} if so.\n */\n hasTableWideOpSince(prevVersion: string): boolean {\n const row = this.db.get(\n `SELECT 1 FROM \"_zero.changeLog2\" INDEXED BY \"${CHANGE_LOG_STATE_VERSION_INDEX}\"\n WHERE stateVersion > ? AND op IN (?, ?) LIMIT 1`,\n prevVersion,\n RESET_OP,\n TRUNCATE_OP,\n );\n return row !== undefined;\n }\n\n changesSince(prevVersion: string) {\n // Note: The queried fields are constrained to only those that are relevant\n // to the snapshot diff, i.e. those defined in the changeLogEntrySchema.\n const cached = this.db.statementCache.get(\n `SELECT \"stateVersion\", \"table\", \"rowKey\", \"op\" FROM \"_zero.changeLog2\"\n WHERE \"stateVersion\" > ? ORDER BY \"stateVersion\" ASC, \"pos\" ASC`,\n );\n return {\n changes: cached.statement.iterate(prevVersion),\n cleanup: () => this.db.statementCache.return(cached),\n };\n }\n\n /**\n * Reads the row with the given `rowKey`, or `undefined` if it does not\n * exist.\n *\n * @param cache An optional {@link SnapshotRowCache} through which to\n * perform the read, along with the `tag` that identifies the\n * version(s) of the replica that the result depends on.\n */\n getRow(\n table: LiteTableSpecWithKeysAndVersion,\n rowKey: JSONValue,\n cache?: SnapshotRowCache,\n tag?: string,\n ) {\n const key = normalizedKeyOrder(rowKey as RowKey);\n const cols = Object.keys(key);\n const reads = readsFor(table);\n const sql = getOrInsertComputed(\n reads.byKeyColumns,\n cols.join('\\0'),\n () => reads.prefix + cols.map(c => `${id(c)}=?`).join(' AND '),\n );\n const args = Object.values(key);\n const read = () =>\n this.db.statementCache.use(sql, cached => {\n cached.statement.safeIntegers(true);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return cached.statement.get<any>(args);\n });\n return cache\n ? cache.getOrRead(tag ?? '', sql, 'get', args, () => {\n const row = read();\n if (row !== undefined) {\n this.#assertNotAdvanced(row);\n }\n return row;\n })\n : read();\n }\n\n /**\n * Reads the rows that conflict with `row` on any of the given unique\n * `keys` (which includes the row with the same primary key, if any).\n *\n * @param cache An optional {@link SnapshotRowCache} through which to\n * perform the read, along with the `tag` that identifies the\n * version(s) of the replica that the result depends on.\n */\n getRows(\n table: LiteTableSpecWithKeysAndVersion,\n keys: PrimaryKey[],\n row: RowValue,\n cache?: SnapshotRowCache,\n tag?: string,\n ) {\n // Filter out keys where any column is NULL. This is both correct and\n // critical for performance:\n // 1. Correctness: NULL values can't violate uniqueness (NULL != NULL in SQL)\n // 2. Performance: SQLite's MULTI-INDEX OR optimization completely fails when\n // any branch involves NULL, falling back to a full table scan. This was\n // causing slowdowns of hundreds of times on tables with nullable unique columns.\n const validKeys: PrimaryKey[] = [];\n let mask = 0;\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (\n key.every(column => row[column] !== null && row[column] !== undefined)\n ) {\n validKeys.push(key);\n mask |= 1 << i;\n }\n }\n if (validKeys.length === 0) {\n return [];\n }\n const reads = readsFor(table);\n const buildSQL = () =>\n reads.prefix +\n validKeys\n .map(key => key.map(c => `${id(c)}=?`).join(' AND '))\n .join(' OR ');\n const sql =\n keys === table.uniqueKeys && keys.length <= MAX_MEMOIZED_UNIQUE_KEYS\n ? getOrInsertComputed(reads.byUniqueKeys, mask, buildSQL)\n : buildSQL();\n const args = validKeys.flatMap(key => key.map(column => row[column]));\n const read = () =>\n this.db.statementCache.use(sql, cached => {\n cached.statement.safeIntegers(true);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return cached.statement.all<any>(args);\n });\n return cache\n ? cache.getOrRead(tag ?? '', sql, 'all', args, () => {\n const rows = read();\n for (const row of rows) {\n this.#assertNotAdvanced(row);\n }\n return rows;\n })\n : read();\n }\n\n /**\n * Rows are shared with other client groups via the SnapshotRowCache, so\n * one read from a connection that has advanced past this snapshot (i.e. a\n * {@link SnapshotDiff} used after its Snapshotter advanced) must fail\n * before it is cached, rather than be served to the valid Diffs of other\n * client groups (whose own validity checks would then fail).\n */\n #assertNotAdvanced(row: RowValue) {\n if ((row[ROW_VERSION] ?? '~') > this.version) {\n throw new InvalidDiffError(\n `Diff is no longer valid. db has advanced past ${this.version}.`,\n );\n }\n }\n\n /**\n * Whether the connection has been reset to a newer snapshot (i.e. via\n * {@link resetToHead()}), after which reads no longer reflect\n * {@link version}.\n */\n get reset(): boolean {\n return this.#reset;\n }\n\n resetToHead(): Snapshot {\n this.#reset = true;\n this.db.rollback();\n return new Snapshot(this.db, this.#appID);\n }\n}\n\nclass Diff implements SnapshotDiff {\n readonly #permissionsTable: string;\n readonly #syncableTables: Map<string, LiteAndZqlSpec>;\n readonly #allTableNames: Set<string>;\n readonly #observedTables: TableFilter | undefined;\n readonly #rowCache: SnapshotRowCache | undefined;\n #prevWrites: PrevWrites;\n #iterated = false;\n readonly prev: Snapshot;\n readonly curr: Snapshot;\n readonly changes: number;\n\n constructor(\n appID: string,\n syncableTables: Map<string, LiteAndZqlSpec>,\n allTableNames: Set<string>,\n prev: Snapshot,\n curr: Snapshot,\n observedTables?: TableFilter | undefined,\n rowCache?: SnapshotRowCache | undefined,\n prevWrites: PrevWrites = 'uniform',\n ) {\n this.#prevWrites = prevWrites;\n this.#permissionsTable = `${appID}.permissions`;\n this.#syncableTables = syncableTables;\n this.#allTableNames = allTableNames;\n this.#observedTables = observedTables;\n this.prev = prev;\n this.curr = curr;\n this.changes = curr.numChangesSince(prev.version);\n // Row values are only shared (via the cache) between Diffs that do not\n // straddle a table-wide op. This guarantees that any two Diffs that\n // encounter the same change log entry read the row from tables with\n // the same schema (and contents), since a RESET or TRUNCATE between\n // their `curr` versions would necessarily fall within the range of the\n // later Diff. (Such a Diff aborts with a ResetPipelinesSignal anyway.)\n this.#rowCache =\n rowCache && !curr.hasTableWideOpSince(prev.version)\n ? rowCache\n : undefined;\n }\n\n setPrevWrites(prevWrites: PrevWrites): void {\n assert(\n !this.#iterated || prevWrites === 'divergent',\n 'prevWrites must be set before iterating the diff',\n );\n this.#prevWrites = prevWrites;\n }\n\n [Symbol.iterator](): Iterator<Change> {\n this.#iterated = true;\n const {changes, cleanup: done} = this.curr.changesSince(this.prev.version);\n\n const cleanup = () => {\n try {\n // Allow open iterators to clean up their state.\n changes.return?.(undefined);\n } finally {\n done();\n }\n };\n\n return {\n next: () => {\n try {\n for (;;) {\n const {value, done} = changes.next();\n if (done) {\n cleanup();\n return {value, done: true};\n }\n\n const {table, rowKey, op, stateVersion} = v.parse(value, schema);\n if (op === RESET_OP) {\n // The current map of `TableSpec`s may not have the correct or complete information.\n throw new ResetPipelinesSignal(\n `schema for table ${table} has changed`,\n 'schema-change',\n );\n }\n if (op === TRUNCATE_OP) {\n // Truncates are also processed by rehydrating pipelines at current.\n throw new ResetPipelinesSignal(\n `table ${table} has been truncated`,\n 'truncation',\n );\n }\n if (\n this.#observedTables &&\n !this.#observedTables.has(table) &&\n table !== this.#permissionsTable\n ) {\n if (this.#allTableNames.has(table)) {\n continue; // skip change log entries for unobserved tables.\n }\n throw new Error(`change for unknown table ${table}`);\n }\n const specs = this.#syncableTables.get(table);\n if (!specs) {\n if (this.#allTableNames.has(table)) {\n continue; // skip change log entries for non-syncable tables.\n }\n throw new Error(`change for unknown table ${table}`);\n }\n const {tableSpec, zqlSpec} = specs;\n\n // Sanity check: All change log ops should have a stateVersion\n // greater than minRowVersion in the table metadata. This is a\n // mini-proof that the overlay does not need to be applied to\n // rows produced in incremental catchup, based on the invariant in\n // change-processor's #bumpVersions(), whereby the setting of the\n // minRowVersion is always followed by a RESET OP, meaning that\n // subsequent change-log traversal happens at a later version.\n assert(\n (tableSpec.minRowVersion ?? '') < stateVersion,\n () =>\n `unexpected change @${stateVersion} for table ${table} with ` +\n `minRowVersion ${tableSpec.minRowVersion}: ${op}(${rowKey})`,\n );\n\n assert(rowKey !== null, 'rowKey must be present for row changes');\n\n // Row reads are shared with the other client groups on the\n // worker via the SnapshotRowCache (if configured):\n //\n // * The new value of the row is read from `curr`, which is\n // never written to during the iteration, and is the version\n // of the row at `stateVersion` (as verified by\n // checkThatDiffIsValid()). It is thus identical for every\n // Diff that encounters the change log entry.\n //\n // * Previous values are read from `prev`, at `prev.version`,\n // which the caller (i.e. IVM) writes to as the iteration\n // progresses. For a table whose only unique key is its\n // primary key, no change applied before this one can affect\n // this row, so the result depends solely on `prev.version`.\n // Otherwise, the result can include rows that conflict on\n // other unique keys, which may have been added or removed by\n // preceding changes; see PrevWrites for when that can be\n // shared.\n // The first advance() after this Diff was created resets the\n // `prev` connection to head. Reads would then no longer reflect\n // `prev.version`, and cache hits would not reveal it (the cached\n // rows were read by valid Diffs), so this must be checked\n // explicitly rather than inferred from the rows' versions.\n if (this.prev.reset) {\n throw new InvalidDiffError(\n `Diff is no longer valid. prev db has advanced past ${this.prev.version}.`,\n );\n }\n\n const cache = this.#rowCache;\n const prevDependsOnWrites =\n tableSpec.uniqueKeys.length > 1 && this.#prevWrites !== 'none';\n const prevCache =\n prevDependsOnWrites && this.#prevWrites === 'divergent'\n ? undefined\n : cache;\n const prevTag = prevDependsOnWrites\n ? `p:${this.prev.version}:${this.curr.version}`\n : `p:${this.prev.version}`;\n const nextValue =\n op === SET_OP\n ? this.curr.getRow(\n tableSpec,\n rowKey,\n cache,\n `n:${stateVersion}`,\n )\n : null;\n let prevValues;\n if (nextValue) {\n prevValues = this.prev.getRows(\n tableSpec,\n tableSpec.uniqueKeys,\n nextValue,\n prevCache,\n prevTag,\n );\n } else {\n const prevValue = this.prev.getRow(\n tableSpec,\n rowKey,\n prevCache,\n prevTag,\n );\n prevValues = prevValue ? [prevValue] : [];\n }\n if (nextValue === undefined) {\n throw new Error(\n `Missing value for ${table} ${stringify(rowKey)}`,\n );\n }\n // Sanity check detects if the diff is being accessed after the Snapshots have advanced.\n this.checkThatDiffIsValid(stateVersion, op, prevValues, nextValue);\n\n if (prevValues.length === 0 && nextValue === null) {\n // Filter out no-op changes (e.g. a delete of a row that does not exist in prev).\n // TODO: Consider doing this for deep-equal values.\n continue;\n }\n\n if (\n table === this.#permissionsTable &&\n prevValues.some(\n prevValue => prevValue.permissions !== nextValue.permissions,\n )\n ) {\n throw new ResetPipelinesSignal(\n `Permissions have changed ${\n prevValues.find(\n prevValue =>\n prevValue.permissions !== nextValue.permissions,\n ).hash\n } => ${nextValue.hash}`,\n 'permissions-change',\n );\n }\n\n // Note: The raw SQLite rows may be shared with other client\n // groups via the SnapshotRowCache, so they must not be modified.\n // fromSQLiteTypes() produces new row objects.\n // TODO Can we get rid of these RowValue casts?\n return {\n value: {\n table,\n prevValues: prevValues.map(prevValue =>\n fromSQLiteTypes(zqlSpec, prevValue, table),\n ),\n nextValue: nextValue\n ? fromSQLiteTypes(zqlSpec, nextValue, table)\n : null,\n rowKey,\n } satisfies Change,\n };\n }\n } catch (e) {\n // This control flow path is not covered by the return() method (i.e. `break`).\n cleanup();\n throw e;\n }\n },\n\n return: (value: unknown) => {\n cleanup();\n return {value, done: true};\n },\n };\n }\n\n checkThatDiffIsValid(\n stateVersion: string,\n op: string,\n prevValues: RowValue[],\n nextValue: RowValue,\n ) {\n // Sanity checks to detect that the diff is not being accessed after\n // the Snapshots have advanced.\n if (stateVersion > this.curr.version) {\n throw new InvalidDiffError(\n `Diff is no longer valid. curr db has advanced past ${this.curr.version}`,\n );\n }\n if (\n prevValues.findIndex(\n prevValue => (prevValue[ROW_VERSION] ?? '~') > this.prev.version,\n ) !== -1\n ) {\n throw new InvalidDiffError(\n `Diff is no longer valid. prev db has advanced past ${this.prev.version}.`,\n );\n }\n if (op === SET_OP && nextValue[ROW_VERSION] !== stateVersion) {\n throw new InvalidDiffError(\n 'Diff is no longer valid. curr db has advanced.',\n );\n }\n }\n}\n\nexport class InvalidDiffError extends Error {\n constructor(msg: string)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W,YACP,gBAAgB,SAAS,WAAW,KAAK,IACzC;OACJ;MACF,EACF;KACF;IACF,SAAS,GAAG;KAEV,QAAQ;KACR,MAAM;IACR;GACF;GAEA,SAAS,UAAmB;IAC1B,QAAQ;IACR,OAAO;KAAC;KAAO,MAAM;IAAI;GAC3B;EACF;CACF;CAEA,qBACE,cACA,IACA,YACA,WACA;EAGA,IAAI,eAAe,KAAK,KAAK,SAC3B,MAAM,IAAI,iBACR,sDAAsD,KAAK,KAAK,SAClE;EAEF,IACE,WAAW,WACT,eAAc,UAAA,iBAA0B,OAAO,KAAK,KAAK,OAC3D,MAAM,IAEN,MAAM,IAAI,iBACR,sDAAsD,KAAK,KAAK,QAAQ,EAC1E;EAEF,IAAI,OAAA,OAAiB,UAAA,kBAA2B,cAC9C,MAAM,IAAI,iBACR,gDACF;CAEJ;AACF;AAEA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,YAAY,KAAa;EACvB,MAAM,GAAG;CACX;AACF"}
1
+ {"version":3,"file":"snapshotter.js","names":["#lc","#dbFile","#appID","#pageCacheSizeKib","#rowCache","#curr","#prev","#assertNotAdvanced","#reset","#permissionsTable","#syncableTables","#allTableNames","#observedTables","#prevWrites","#iterated"],"sources":["../../../../../../zero-cache/src/services/view-syncer/snapshotter.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport {stringify, type JSONValue} from '../../../../shared/src/bigint-json.ts';\nimport {getOrInsertComputed} from '../../../../shared/src/map.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport type {Row} from '../../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../../zero-types/src/schema.ts';\nimport {Database} from '../../../../zqlite/src/db.ts';\nimport {fromSQLiteTypes} from '../../../../zqlite/src/table-source.ts';\nimport type {\n LiteAndZqlSpec,\n LiteTableSpecWithKeysAndVersion,\n} from '../../db/specs.ts';\nimport {StatementRunner} from '../../db/statements.ts';\nimport {\n normalizedKeyOrder,\n type RowKey,\n type RowValue,\n} from '../../types/row-key.ts';\nimport type {AppID} from '../../types/shards.ts';\nimport {id} from '../../types/sql.ts';\nimport {\n RESET_OP,\n changeLogEntrySchema as schema,\n SET_OP,\n TRUNCATE_OP,\n} from '../replicator/schema/change-log.ts';\nimport {\n getReplicationState,\n ZERO_VERSION_COLUMN_NAME as ROW_VERSION,\n} from '../replicator/schema/replication-state.ts';\nimport type {SnapshotRowCache} from './snapshot-row-cache.ts';\n\n/**\n * A `Snapshotter` manages the progression of database snapshots for a\n * ViewSyncer.\n *\n * The Replicator and ViewSyncers operate on the same SQLite file, with the\n * Replicator being the sole writer to the database. The IVM logic in\n * ViewSyncers, however, rely on incrementally applying changes to the DB to\n * update the state of its pipelines.\n *\n * To avoid coupling the progress of the Replicator and all IVM pipelines on\n * each other, ViewSyncers operate on ephemeral forks of the database by holding\n * [concurrent](https://sqlite.org/src/doc/begin-concurrent/doc/begin_concurrent.md)\n * snapshots of the database and simulating (but ultimately rolling back)\n * mutations on these snapshots.\n *\n * Example:\n * 1. ViewSyncer takes `snapshot_a` at version `t1` of the database and\n * hydrates its pipeline(s).\n * 2. Replicator applies a new transaction to the database and notifies\n * subscribers.\n * 3. ViewSyncer takes `snapshot_b` at `t2`, and queries the `ChangeLog` at\n * that snapshot for changes since `t1`.\n * 4. ViewSyncer applies those changes to `snapshot_a` for IVM, but does not\n * commit them. (Recall that the Replicator is the sole writer to the db, so\n * the ViewSyncer never commits any writes.)\n * 5. Replicator applies the next transaction and advances the database to `t3`.\n * 6. ViewSyncer rolls back `snapshot_a` and opens `snapshot_c` at `t3`, using\n * `snapshot_b` to simulate changes from `t2` to `t3`.\n *\n * ```\n * Replicator: t1 --------------> t2 --------------> t3 --------------->\n * ViewSyncer: [snapshot_a] ----> [snapshot_b] ----> [snapshot_c]\n * ```\n *\n * Note that the Replicator (and ViewSyncers) do not wait on the progress of\n * other ViewSyncers. If a ViewSyncer is busy hydrating at `t1`, the Replicator\n * and other ViewSyncers can progress through `t2`, `t3`, etc. independently,\n * as the busy ViewSyncer simply takes its own snapshot when it is ready.\n *\n * ```\n * Replicator: t1 --------------> t2 --------------> t3 --------------->\n * ViewSyncer1: [snapshot_a] ----> [snapshot_b] ----> [snapshot_c]\n * ViewSyncer2: [.......... snapshot_a ..........] ----> [snapshot_b]\n * ```\n *\n * To minimize Database connections (and statement preparation, etc.), the\n * Snapshotter reuses the connection from the previous (rolled back)\n * snapshot when opening the new one.\n *\n * ```\n * Replicator: t1 --------------> t2 --------------> t3 --------------->\n * ViewSyncer: [snapshot_a] ----> [snapshot_b] ----> [snapshot_c]\n * (conn_1) (conn_2) (conn_1)\n * ```\n *\n * In this manner, each ViewSyncer uses two connections that continually\n * \"leapfrog\" each other to replay the timeline of changes in isolation from\n * the Replicator and other ViewSyncers.\n */\nexport class Snapshotter {\n readonly #lc: LogContext;\n readonly #dbFile: string;\n readonly #appID: string;\n readonly #pageCacheSizeKib: number | undefined;\n readonly #rowCache: SnapshotRowCache | undefined;\n #curr: Snapshot | undefined;\n #prev: Snapshot | undefined;\n\n /**\n * @param rowCache An optional worker-wide {@link SnapshotRowCache} through\n * which the row reads performed when iterating over a\n * {@link SnapshotDiff} are shared with the other Snapshotters\n * (i.e. client groups) on the worker.\n */\n constructor(\n lc: LogContext,\n dbFile: string,\n {appID}: AppID,\n pageCacheSizeKib?: number,\n rowCache?: SnapshotRowCache,\n ) {\n this.#lc = lc;\n this.#dbFile = dbFile;\n this.#appID = appID;\n this.#pageCacheSizeKib = pageCacheSizeKib;\n this.#rowCache = rowCache;\n }\n\n /**\n * Initializes the snapshot to the current head of the database. This must be\n * only be called once. The state of whether a Snapshotter has been initialized\n * can be determined by calling {@link initialized()}.\n */\n init(): this {\n assert(this.#curr === undefined, 'Already initialized');\n this.#curr = Snapshot.create(\n this.#lc,\n this.#dbFile,\n this.#appID,\n this.#pageCacheSizeKib,\n );\n this.#lc.debug?.(`Initial snapshot at version ${this.#curr.version}`);\n return this;\n }\n\n initialized(): boolean {\n return this.#curr !== undefined;\n }\n\n /** Returns the current snapshot. Asserts if {@link initialized()} is false. */\n current(): Snapshot {\n assert(this.#curr !== undefined, 'Snapshotter has not been initialized');\n return this.#curr;\n }\n\n /**\n * Advances to the head of the Database, returning a diff between the\n * previously current Snapshot and a new Snapshot at head. This is called\n * in response to a notification from a Replicator subscription. Subsequent\n * calls to {@link current()} return the new Snapshot. Note that the Snapshotter\n * must be initialized before advancing.\n *\n * The returned {@link SnapshotDiff} contains snapshots at the endpoints\n * of the database timeline. Iterating over the diff generates a sequence\n * of {@link Change}s between the two snapshots.\n *\n * Note that this sequence is not chronological; rather, the sequence is\n * ordered by `<table, row-key>`, such that a row can appear at most once\n * in the common case, or twice if its table is `TRUNCATE`'d and a new value\n * is subsequently `INSERT`'ed. This results in dropping most intermediate\n * changes to a row and bounds the amount of work needed to catch up;\n * however, as a consequence, a consistent database state is only guaranteed\n * when the sequence has been fully consumed.\n *\n * Note that Change generation relies on the state of the underlying\n * database connections, and because the connection for the previous snapshot\n * is reused to produce the next snapshot, the diff object is only valid\n * until the next call to `advance()`.\n *\n * It is okay for the caller to apply `Change`s to the `prev` snapshot\n * during the iteration (e.g. this is necessary for IVM); the remainder\n * of the iteration is not affected because a given row can appear at most\n * once in the sequence (with the exception being TRUNCATE, after which the\n * deleted rows can be re-inserted, but this will also behave correctly if\n * the changes are applied).\n *\n * Once the changes have been applied, however, a _subsequent_ iteration\n * will not produce the correct results. In order to perform multiple\n * change-applying iterations, the caller must (1) create a save point\n * on `prev` before each iteration, and (2) rollback to the save point after\n * the iteration.\n *\n * @param prevWrites How the caller writes to `prev` during the iteration,\n * which determines which `prev` reads can be shared through the\n * {@link SnapshotRowCache}. See {@link PrevWrites}.\n */\n advance(\n syncableTables: Map<string, LiteAndZqlSpec>,\n allTableNames: Set<string>,\n observedTables?: TableFilter | undefined,\n prevWrites: PrevWrites = 'uniform',\n ): SnapshotDiff {\n const {prev, curr} = this.advanceWithoutDiff();\n return new Diff(\n this.#appID,\n syncableTables,\n allTableNames,\n prev,\n curr,\n observedTables,\n this.#rowCache,\n prevWrites,\n );\n }\n\n advanceWithoutDiff() {\n assert(this.#curr !== undefined, 'Snapshotter has not been initialized');\n const next = this.#prev\n ? this.#prev.resetToHead()\n : Snapshot.create(\n this.#lc,\n this.#curr.db.db.name,\n this.#appID,\n this.#pageCacheSizeKib,\n );\n this.#prev = this.#curr;\n this.#curr = next;\n return {prev: this.#prev, curr: this.#curr};\n }\n\n /**\n * Call this to close the database connections when the Snapshotter is\n * no longer needed.\n */\n destroy() {\n this.#curr?.db.db.close();\n this.#prev?.db.db.close();\n this.#lc.debug?.('closed database connections');\n }\n}\n\nexport type Change = {\n readonly table: string;\n /**\n * If this change represents a remove the row to remove,\n * if nextValue is not null then all rows that have a unique constraint\n * violation with nextValue.\n * In both cases these rows should be removed.\n */\n readonly prevValues: Readonly<Row>[];\n readonly nextValue: Readonly<Row> | null;\n readonly rowKey: RowKey;\n};\n\nexport interface TableFilter {\n has(table: string): boolean;\n}\n\n/**\n * How the caller of {@link Snapshotter.advance()} writes the changes of a\n * {@link SnapshotDiff} to its `prev` snapshot while iterating over it.\n *\n * A `prev` read for a table with a single unique key (its primary key)\n * cannot observe earlier changes of the iteration, since a row key appears\n * once in the diff. A read for a table with other unique keys can, because\n * the rows it returns may have been displaced or edited by earlier changes.\n *\n * * `uniform`: every caller applies every change, so such a read depends on\n * the `<prev, curr>` versions of the diff, and is shared on that basis.\n * * `divergent`: callers apply different subsets of the changes (e.g. the\n * pipeline driver skips changes that no pipeline can observe), so such a\n * read depends on the caller and is not shared.\n * * `none`: the caller does not write to `prev` (e.g. IVM derivation is\n * held in memory), so every read depends solely on `prev.version`.\n */\nexport type PrevWrites = 'uniform' | 'divergent' | 'none';\n\n/**\n * Represents the difference between two database Snapshots.\n * Iterating over the object will produce a sequence of {@link Change}s\n * between the two snapshots.\n *\n * See {@link Snapshotter.advance()} for semantics and usage.\n */\nexport interface SnapshotDiff extends Iterable<Change> {\n readonly prev: {\n readonly db: StatementRunner;\n readonly version: string;\n };\n readonly curr: {\n readonly db: StatementRunner;\n readonly version: string;\n };\n\n /**\n * The raw number of ChangeLog entries between the snapshots, before filtering\n * out unobserved/non-syncable tables or no-op changes. Progress against this\n * total must use {@link changesScanned}, rather than the number of yielded\n * changes. Table-wide operations abort iteration and reset the pipelines.\n */\n readonly changes: number;\n\n /** The number of raw ChangeLog entries read so far, including skipped entries. */\n readonly changesScanned: number;\n\n /** The scanned entries omitted because their table is unobserved/non-syncable or the change is a no-op. */\n readonly changesSkipped: number;\n\n /**\n * Overrides the `prevWrites` passed to {@link Snapshotter.advance()}, for a\n * caller that decides how to write to `prev` once it knows the number of\n * {@link changes}. Must be called before the diff is iterated, except to\n * switch to `divergent`, which can be done between any two changes: it\n * shares only the reads that no write to `prev` can affect.\n */\n setPrevWrites(prevWrites: PrevWrites): void;\n}\n\n/**\n * Thrown during an iteration of a {@link SnapshotDiff} when a schema\n * change or truncate is encountered, which result in aborting the\n * advancement and resetting / rehydrating the pipelines.\n */\nexport type ResetPipelinesReason =\n | 'advancement-timeout'\n | 'scalar-subquery'\n | 'schema-change'\n | 'truncation'\n | 'permissions-change';\n\nexport class ResetPipelinesSignal extends Error {\n readonly name = 'ResetPipelinesSignal';\n readonly reason: ResetPipelinesReason;\n\n constructor(msg: string, reason: ResetPipelinesReason) {\n super(msg);\n this.reason = reason;\n }\n}\n\n// Memoizes, per table spec, the SQL of the row lookups performed for each\n// change, which would otherwise be rebuilt from the table spec for every\n// read. Handing out the same string for every read of a given shape also\n// lets the SnapshotRowCache and the statement cache look it up without\n// rehashing it. Specs are recreated whenever they are recomputed, so stale\n// SQL is never served.\ntype TableReads = {\n /** `SELECT <columns> FROM <table> WHERE ` */\n readonly prefix: string;\n /** {@link Snapshot.getRow} SQL, by the NUL-joined key columns. */\n readonly byKeyColumns: Map<string, string>;\n /**\n * {@link Snapshot.getRows} SQL, by the bitmask of the table's `uniqueKeys`\n * that are queried.\n */\n readonly byUniqueKeys: Map<number, string>;\n};\n\nconst tableReads = new WeakMap<LiteTableSpecWithKeysAndVersion, TableReads>();\n\nfunction readsFor(table: LiteTableSpecWithKeysAndVersion): TableReads {\n return getOrInsertComputed(tableReads, table, () => ({\n prefix: `SELECT ${Object.keys(table.columns)\n .map(c => id(c))\n .join(',')} FROM ${id(table.name)} WHERE `,\n byKeyColumns: new Map(),\n byUniqueKeys: new Map(),\n }));\n}\n\n// The byUniqueKeys bitmask must fit in a (positive) 31-bit integer.\nconst MAX_MEMOIZED_UNIQUE_KEYS = 30;\n\n/**\n * The index that SQLite creates for the `PRIMARY KEY(\"stateVersion\", \"pos\")`\n * of `_zero.changeLog2` (the first constraint of its CREATE TABLE statement,\n * hence the `_1` suffix).\n *\n * For a `stateVersion > ?` query that reads a column outside of this index\n * (e.g. `op`) and has no ORDER BY, the query planner chooses between a range\n * search of the index and a full scan of the table based on `sqlite_stat1`.\n * Statistics recorded while the change log held only a few rows make the full\n * scan look cheaper, and they persist as the table grows to millions of rows:\n * the change log of a replication-manager's replica only receives entries\n * during column backfills, and view-syncers inherit its statistics when they\n * restore its backup. Such queries therefore pin this index with INDEXED BY,\n * which also makes them fail to prepare (rather than silently scan) if the\n * index is ever renamed.\n */\nconst CHANGE_LOG_STATE_VERSION_INDEX = 'sqlite_autoindex__zero.changeLog2_1';\n\nclass Snapshot {\n static create(\n lc: LogContext,\n dbFile: string,\n appID: string,\n pageCacheSizeKib: number | undefined,\n ) {\n const conn = new Database(lc, dbFile);\n conn.pragma('synchronous = OFF'); // Applied changes are ephemeral; COMMIT is never called.\n if (pageCacheSizeKib !== undefined) {\n conn.pragma(`cache_size = -${pageCacheSizeKib}`); // Negative = size in KiB\n }\n const [{journal_mode: mode}] = conn.pragma('journal_mode') as [\n {journal_mode: string},\n ];\n // BEGIN CONCURRENT lets the Snapshotter simulate changes on a historic\n // snapshot without taking the WAL writer lock. These private changes are\n // always rolled back; the replicator is the only committer and can use\n // BEGIN IMMEDIATE on the same WAL2 database.\n assert(\n mode === 'wal2',\n `replica db must be in wal2 mode (current: ${mode})`,\n );\n\n const db = new StatementRunner(conn);\n return new Snapshot(db, appID);\n }\n\n readonly db: StatementRunner;\n readonly #appID: string;\n readonly version: string;\n #reset = false;\n\n constructor(db: StatementRunner, appID: string) {\n db.beginConcurrent();\n // Note: The subsequent read is necessary to acquire the read lock\n // (which results in the logical creation of the snapshot). Calling\n // `BEGIN CONCURRENT` alone does not result in acquiring the read lock.\n const {stateVersion} = getReplicationState(db);\n\n this.db = db;\n this.#appID = appID;\n this.version = stateVersion;\n }\n\n numChangesSince(prevVersion: string) {\n const {count} = this.db.get(\n 'SELECT COUNT(*) AS count FROM \"_zero.changeLog2\" WHERE stateVersion > ?',\n prevVersion,\n );\n return count;\n }\n\n /**\n * Whether a table-wide RESET op (i.e. a schema change) was logged after\n * `prevVersion`. Table specs computed at or before `prevVersion` are\n * stale with respect to this snapshot if so.\n */\n schemaChangedSince(prevVersion: string): boolean {\n const row = this.db.get(\n `SELECT 1 FROM \"_zero.changeLog2\" INDEXED BY \"${CHANGE_LOG_STATE_VERSION_INDEX}\"\n WHERE stateVersion > ? AND op = ? LIMIT 1`,\n prevVersion,\n RESET_OP,\n );\n return row !== undefined;\n }\n\n /**\n * Whether any table-wide op (i.e. a RESET or TRUNCATE) was logged after\n * `prevVersion`. Iterating over a diff ending at this snapshot will\n * abort with a {@link ResetPipelinesSignal} if so.\n */\n hasTableWideOpSince(prevVersion: string): boolean {\n const row = this.db.get(\n `SELECT 1 FROM \"_zero.changeLog2\" INDEXED BY \"${CHANGE_LOG_STATE_VERSION_INDEX}\"\n WHERE stateVersion > ? AND op IN (?, ?) LIMIT 1`,\n prevVersion,\n RESET_OP,\n TRUNCATE_OP,\n );\n return row !== undefined;\n }\n\n changesSince(prevVersion: string) {\n // Note: The queried fields are constrained to only those that are relevant\n // to the snapshot diff, i.e. those defined in the changeLogEntrySchema.\n const cached = this.db.statementCache.get(\n `SELECT \"stateVersion\", \"table\", \"rowKey\", \"op\" FROM \"_zero.changeLog2\"\n WHERE \"stateVersion\" > ? ORDER BY \"stateVersion\" ASC, \"pos\" ASC`,\n );\n return {\n changes: cached.statement.iterate(prevVersion),\n cleanup: () => this.db.statementCache.return(cached),\n };\n }\n\n /**\n * Reads the row with the given `rowKey`, or `undefined` if it does not\n * exist.\n *\n * @param cache An optional {@link SnapshotRowCache} through which to\n * perform the read, along with the `tag` that identifies the\n * version(s) of the replica that the result depends on.\n */\n getRow(\n table: LiteTableSpecWithKeysAndVersion,\n rowKey: JSONValue,\n cache?: SnapshotRowCache,\n tag?: string,\n ) {\n const key = normalizedKeyOrder(rowKey as RowKey);\n const cols = Object.keys(key);\n const reads = readsFor(table);\n const sql = getOrInsertComputed(\n reads.byKeyColumns,\n cols.join('\\0'),\n () => reads.prefix + cols.map(c => `${id(c)}=?`).join(' AND '),\n );\n const args = Object.values(key);\n const read = () =>\n this.db.statementCache.use(sql, cached => {\n cached.statement.safeIntegers(true);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return cached.statement.get<any>(args);\n });\n return cache\n ? cache.getOrRead(tag ?? '', sql, 'get', args, () => {\n const row = read();\n if (row !== undefined) {\n this.#assertNotAdvanced(row);\n }\n return row;\n })\n : read();\n }\n\n /**\n * Reads the rows that conflict with `row` on any of the given unique\n * `keys` (which includes the row with the same primary key, if any).\n *\n * @param cache An optional {@link SnapshotRowCache} through which to\n * perform the read, along with the `tag` that identifies the\n * version(s) of the replica that the result depends on.\n */\n getRows(\n table: LiteTableSpecWithKeysAndVersion,\n keys: PrimaryKey[],\n row: RowValue,\n cache?: SnapshotRowCache,\n tag?: string,\n ) {\n // Filter out keys where any column is NULL. This is both correct and\n // critical for performance:\n // 1. Correctness: NULL values can't violate uniqueness (NULL != NULL in SQL)\n // 2. Performance: SQLite's MULTI-INDEX OR optimization completely fails when\n // any branch involves NULL, falling back to a full table scan. This was\n // causing slowdowns of hundreds of times on tables with nullable unique columns.\n const validKeys: PrimaryKey[] = [];\n let mask = 0;\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (\n key.every(column => row[column] !== null && row[column] !== undefined)\n ) {\n validKeys.push(key);\n mask |= 1 << i;\n }\n }\n if (validKeys.length === 0) {\n return [];\n }\n const reads = readsFor(table);\n const buildSQL = () =>\n reads.prefix +\n validKeys\n .map(key => key.map(c => `${id(c)}=?`).join(' AND '))\n .join(' OR ');\n const sql =\n keys === table.uniqueKeys && keys.length <= MAX_MEMOIZED_UNIQUE_KEYS\n ? getOrInsertComputed(reads.byUniqueKeys, mask, buildSQL)\n : buildSQL();\n const args = validKeys.flatMap(key => key.map(column => row[column]));\n const read = () =>\n this.db.statementCache.use(sql, cached => {\n cached.statement.safeIntegers(true);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return cached.statement.all<any>(args);\n });\n return cache\n ? cache.getOrRead(tag ?? '', sql, 'all', args, () => {\n const rows = read();\n for (const row of rows) {\n this.#assertNotAdvanced(row);\n }\n return rows;\n })\n : read();\n }\n\n /**\n * Rows are shared with other client groups via the SnapshotRowCache, so\n * one read from a connection that has advanced past this snapshot (i.e. a\n * {@link SnapshotDiff} used after its Snapshotter advanced) must fail\n * before it is cached, rather than be served to the valid Diffs of other\n * client groups (whose own validity checks would then fail).\n */\n #assertNotAdvanced(row: RowValue) {\n if ((row[ROW_VERSION] ?? '~') > this.version) {\n throw new InvalidDiffError(\n `Diff is no longer valid. db has advanced past ${this.version}.`,\n );\n }\n }\n\n /**\n * Whether the connection has been reset to a newer snapshot (i.e. via\n * {@link resetToHead()}), after which reads no longer reflect\n * {@link version}.\n */\n get reset(): boolean {\n return this.#reset;\n }\n\n resetToHead(): Snapshot {\n this.#reset = true;\n this.db.rollback();\n return new Snapshot(this.db, this.#appID);\n }\n}\n\nclass Diff implements SnapshotDiff {\n readonly #permissionsTable: string;\n readonly #syncableTables: Map<string, LiteAndZqlSpec>;\n readonly #allTableNames: Set<string>;\n readonly #observedTables: TableFilter | undefined;\n readonly #rowCache: SnapshotRowCache | undefined;\n #prevWrites: PrevWrites;\n #iterated = false;\n readonly prev: Snapshot;\n readonly curr: Snapshot;\n readonly changes: number;\n changesScanned = 0;\n changesSkipped = 0;\n\n constructor(\n appID: string,\n syncableTables: Map<string, LiteAndZqlSpec>,\n allTableNames: Set<string>,\n prev: Snapshot,\n curr: Snapshot,\n observedTables?: TableFilter | undefined,\n rowCache?: SnapshotRowCache | undefined,\n prevWrites: PrevWrites = 'uniform',\n ) {\n this.#prevWrites = prevWrites;\n this.#permissionsTable = `${appID}.permissions`;\n this.#syncableTables = syncableTables;\n this.#allTableNames = allTableNames;\n this.#observedTables = observedTables;\n this.prev = prev;\n this.curr = curr;\n this.changes = curr.numChangesSince(prev.version);\n // Row values are only shared (via the cache) between Diffs that do not\n // straddle a table-wide op. This guarantees that any two Diffs that\n // encounter the same change log entry read the row from tables with\n // the same schema (and contents), since a RESET or TRUNCATE between\n // their `curr` versions would necessarily fall within the range of the\n // later Diff. (Such a Diff aborts with a ResetPipelinesSignal anyway.)\n this.#rowCache =\n rowCache && !curr.hasTableWideOpSince(prev.version)\n ? rowCache\n : undefined;\n }\n\n setPrevWrites(prevWrites: PrevWrites): void {\n assert(\n !this.#iterated || prevWrites === 'divergent',\n 'prevWrites must be set before iterating the diff',\n );\n this.#prevWrites = prevWrites;\n }\n\n [Symbol.iterator](): Iterator<Change> {\n this.#iterated = true;\n const {changes, cleanup: done} = this.curr.changesSince(this.prev.version);\n\n const cleanup = () => {\n try {\n // Allow open iterators to clean up their state.\n changes.return?.(undefined);\n } finally {\n done();\n }\n };\n\n return {\n next: () => {\n try {\n for (;;) {\n const {value, done} = changes.next();\n if (done) {\n cleanup();\n return {value, done: true};\n }\n\n this.changesScanned++;\n const {table, rowKey, op, stateVersion} = v.parse(value, schema);\n if (op === RESET_OP) {\n // The current map of `TableSpec`s may not have the correct or complete information.\n throw new ResetPipelinesSignal(\n `schema for table ${table} has changed`,\n 'schema-change',\n );\n }\n if (op === TRUNCATE_OP) {\n // Truncates are also processed by rehydrating pipelines at current.\n throw new ResetPipelinesSignal(\n `table ${table} has been truncated`,\n 'truncation',\n );\n }\n if (\n this.#observedTables &&\n !this.#observedTables.has(table) &&\n table !== this.#permissionsTable\n ) {\n if (this.#allTableNames.has(table)) {\n this.changesSkipped++;\n continue; // skip change log entries for unobserved tables.\n }\n throw new Error(`change for unknown table ${table}`);\n }\n const specs = this.#syncableTables.get(table);\n if (!specs) {\n if (this.#allTableNames.has(table)) {\n this.changesSkipped++;\n continue; // skip change log entries for non-syncable tables.\n }\n throw new Error(`change for unknown table ${table}`);\n }\n const {tableSpec, zqlSpec} = specs;\n\n // Sanity check: All change log ops should have a stateVersion\n // greater than minRowVersion in the table metadata. This is a\n // mini-proof that the overlay does not need to be applied to\n // rows produced in incremental catchup, based on the invariant in\n // change-processor's #bumpVersions(), whereby the setting of the\n // minRowVersion is always followed by a RESET OP, meaning that\n // subsequent change-log traversal happens at a later version.\n assert(\n (tableSpec.minRowVersion ?? '') < stateVersion,\n () =>\n `unexpected change @${stateVersion} for table ${table} with ` +\n `minRowVersion ${tableSpec.minRowVersion}: ${op}(${rowKey})`,\n );\n\n assert(rowKey !== null, 'rowKey must be present for row changes');\n\n // Row reads are shared with the other client groups on the\n // worker via the SnapshotRowCache (if configured):\n //\n // * The new value of the row is read from `curr`, which is\n // never written to during the iteration, and is the version\n // of the row at `stateVersion` (as verified by\n // checkThatDiffIsValid()). It is thus identical for every\n // Diff that encounters the change log entry.\n //\n // * Previous values are read from `prev`, at `prev.version`,\n // which the caller (i.e. IVM) writes to as the iteration\n // progresses. For a table whose only unique key is its\n // primary key, no change applied before this one can affect\n // this row, so the result depends solely on `prev.version`.\n // Otherwise, the result can include rows that conflict on\n // other unique keys, which may have been added or removed by\n // preceding changes; see PrevWrites for when that can be\n // shared.\n // The first advance() after this Diff was created resets the\n // `prev` connection to head. Reads would then no longer reflect\n // `prev.version`, and cache hits would not reveal it (the cached\n // rows were read by valid Diffs), so this must be checked\n // explicitly rather than inferred from the rows' versions.\n if (this.prev.reset) {\n throw new InvalidDiffError(\n `Diff is no longer valid. prev db has advanced past ${this.prev.version}.`,\n );\n }\n\n const cache = this.#rowCache;\n const prevDependsOnWrites =\n tableSpec.uniqueKeys.length > 1 && this.#prevWrites !== 'none';\n const prevCache =\n prevDependsOnWrites && this.#prevWrites === 'divergent'\n ? undefined\n : cache;\n const prevTag = prevDependsOnWrites\n ? `p:${this.prev.version}:${this.curr.version}`\n : `p:${this.prev.version}`;\n const nextValue =\n op === SET_OP\n ? this.curr.getRow(\n tableSpec,\n rowKey,\n cache,\n `n:${stateVersion}`,\n )\n : null;\n let prevValues;\n if (nextValue) {\n prevValues = this.prev.getRows(\n tableSpec,\n tableSpec.uniqueKeys,\n nextValue,\n prevCache,\n prevTag,\n );\n } else {\n const prevValue = this.prev.getRow(\n tableSpec,\n rowKey,\n prevCache,\n prevTag,\n );\n prevValues = prevValue ? [prevValue] : [];\n }\n if (nextValue === undefined) {\n throw new Error(\n `Missing value for ${table} ${stringify(rowKey)}`,\n );\n }\n // Sanity check detects if the diff is being accessed after the Snapshots have advanced.\n this.checkThatDiffIsValid(stateVersion, op, prevValues, nextValue);\n\n if (prevValues.length === 0 && nextValue === null) {\n // Filter out no-op changes (e.g. a delete of a row that does not exist in prev).\n // TODO: Consider doing this for deep-equal values.\n this.changesSkipped++;\n continue;\n }\n\n if (\n table === this.#permissionsTable &&\n prevValues.some(\n prevValue => prevValue.permissions !== nextValue.permissions,\n )\n ) {\n throw new ResetPipelinesSignal(\n `Permissions have changed ${\n prevValues.find(\n prevValue =>\n prevValue.permissions !== nextValue.permissions,\n ).hash\n } => ${nextValue.hash}`,\n 'permissions-change',\n );\n }\n\n // Note: The raw SQLite rows may be shared with other client\n // groups via the SnapshotRowCache, so they must not be modified.\n // fromSQLiteTypes() produces new row objects.\n // TODO Can we get rid of these RowValue casts?\n return {\n value: {\n table,\n prevValues: prevValues.map(prevValue =>\n fromSQLiteTypes(zqlSpec, prevValue, table),\n ),\n nextValue: nextValue\n ? fromSQLiteTypes(zqlSpec, nextValue, table)\n : null,\n rowKey,\n } satisfies Change,\n };\n }\n } catch (e) {\n // This control flow path is not covered by the return() method (i.e. `break`).\n cleanup();\n throw e;\n }\n },\n\n return: (value: unknown) => {\n cleanup();\n return {value, done: true};\n },\n };\n }\n\n checkThatDiffIsValid(\n stateVersion: string,\n op: string,\n prevValues: RowValue[],\n nextValue: RowValue,\n ) {\n // Sanity checks to detect that the diff is not being accessed after\n // the Snapshots have advanced.\n if (stateVersion > this.curr.version) {\n throw new InvalidDiffError(\n `Diff is no longer valid. curr db has advanced past ${this.curr.version}`,\n );\n }\n if (\n prevValues.findIndex(\n prevValue => (prevValue[ROW_VERSION] ?? '~') > this.prev.version,\n ) !== -1\n ) {\n throw new InvalidDiffError(\n `Diff is no longer valid. prev db has advanced past ${this.prev.version}.`,\n );\n }\n if (op === SET_OP && nextValue[ROW_VERSION] !== stateVersion) {\n throw new InvalidDiffError(\n 'Diff is no longer valid. curr db has advanced.',\n );\n }\n }\n}\n\nexport class InvalidDiffError extends Error {\n constructor(msg: string) {\n super(msg);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;;;;;;;CAQA,YACE,IACA,QACA,EAAC,SACD,kBACA,UACA;EACA,KAAKA,MAAM;EACX,KAAKC,UAAU;EACf,KAAKC,SAAS;EACd,KAAKC,oBAAoB;EACzB,KAAKC,YAAY;CACnB;;;;;;CAOA,OAAa;EACX,OAAO,KAAKC,UAAU,KAAA,GAAW,qBAAqB;EACtD,KAAKA,QAAQ,SAAS,OACpB,KAAKL,KACL,KAAKC,SACL,KAAKC,QACL,KAAKC,iBACP;EACA,KAAKH,IAAI,QAAQ,+BAA+B,KAAKK,MAAM,SAAS;EACpE,OAAO;CACT;CAEA,cAA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AAC,CAMpB;IAsCD;;;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"}
@@ -26,6 +26,7 @@ import { ttlClockAsNumber, ttlClockFromNumber } from "./ttl-clock.js";
26
26
  import { EMPTY_CVR_VERSION, cmpVersions, versionFromString, versionString, versionToCookie } from "./schema/types.js";
27
27
  import { ProtocolErrorWithLevel, getLogLevel, wrapWithProtocolError } from "../../types/error-with-level.js";
28
28
  import { isAuthErrorBody } from "../../auth/auth.js";
29
+ import { AdvancementMetrics } from "./advancement-metrics.js";
29
30
  import { ClientHandler, startPoke } from "./client-handler.js";
30
31
  import { tracer } from "./tracer.js";
31
32
  import { CVRStore, ClientNotFoundError } from "./cvr-store.js";
@@ -144,6 +145,7 @@ var ViewSyncerService = class {
144
145
  description: "Observations of sync.e2e_serving_lag that came out negative and were clamped to zero. Non-zero means the upstream database clock is running ahead of this pod by more than the entire pipeline latency, so sync.e2e_serving_lag is biased low and reads healthier than reality. See replication.upstream_clock_skew for the magnitude.",
145
146
  unit: "{observation}"
146
147
  });
148
+ #advancementMetrics = new AdvancementMetrics();
147
149
  #transactionAdvanceTime = getOrCreateLatencyHistogram("sync", "advance-time", "Time to advance all queries for a given client group after applying a new transaction to the replica.");
148
150
  #queryTransformations = getOrCreateCounter("sync", "query.transformations", "Number of query transformations performed");
149
151
  #queryTransformationTime = getOrCreateLatencyHistogram("sync", "query.transformation-time", "Time to transform custom queries via API server.");
@@ -1635,37 +1637,57 @@ var ViewSyncerService = class {
1635
1637
  assert(this.#pipelines.initialized(), "pipelines must be initialized (advancePipelines");
1636
1638
  const start = performance.now();
1637
1639
  const timer = new TimeSliceTimer(lc);
1638
- let pokers;
1639
- let updater;
1640
- let version;
1641
- let numChanges = 0;
1640
+ let outcome = { outcome: "error" };
1641
+ let setupTimeMs;
1642
1642
  try {
1643
- const advancement = this.#pipelines.advance(timer);
1644
- version = advancement.version;
1645
- numChanges = advancement.numChanges;
1646
- lc = lc.withContext("newVersion", version);
1647
- updater = new CVRQueryDrivenUpdater(this.#cvrStore, cvr, version, this.#pipelines.replicaVersion, (queryID) => this.#pipelines.rowSetSignature(queryID));
1648
- pokers = startPoke(lc, this.#getClients(cvr.version), updater.updatedVersion());
1649
- lc.debug?.(`applying ${numChanges} to advance to ${version}`);
1650
- await this.#processChanges(lc, await timer.start(), advancement.changes, updater, pokers);
1651
- } catch (e) {
1652
- if (e instanceof ResetPipelinesSignal) {
1653
- await pokers?.cancel();
1654
- this.#cvrStore.discardPending();
1655
- return e;
1643
+ let pokers;
1644
+ let updater;
1645
+ let version;
1646
+ let numChanges = 0;
1647
+ try {
1648
+ const advancement = this.#pipelines.advance(timer);
1649
+ version = advancement.version;
1650
+ numChanges = advancement.numChanges;
1651
+ lc = lc.withContext("newVersion", version);
1652
+ updater = new CVRQueryDrivenUpdater(this.#cvrStore, cvr, version, this.#pipelines.replicaVersion, (queryID) => this.#pipelines.rowSetSignature(queryID));
1653
+ pokers = startPoke(lc, this.#getClients(cvr.version), updater.updatedVersion());
1654
+ lc.debug?.(`applying ${numChanges} to advance to ${version}`);
1655
+ setupTimeMs = performance.now() - start;
1656
+ await this.#processChanges(lc, await timer.start(), advancement.changes, updater, pokers);
1657
+ } catch (e) {
1658
+ setupTimeMs ??= performance.now() - start;
1659
+ if (e instanceof ResetPipelinesSignal) {
1660
+ await pokers?.cancel();
1661
+ this.#cvrStore.discardPending();
1662
+ outcome = {
1663
+ outcome: "reset",
1664
+ reason: e.reason
1665
+ };
1666
+ return e;
1667
+ }
1668
+ throw e;
1656
1669
  }
1657
- throw e;
1670
+ assert(updater && pokers && version !== void 0, "advancement state missing");
1671
+ this.#cvr = await this.#flushPoked(lc, updater, pokers);
1672
+ const finalVersion = this.#cvr.version;
1673
+ await startAsyncSpan(tracer, "vs.#advancePipelines.pokeEnd", () => pokers.end(finalVersion));
1674
+ this.#markVersionServed(version);
1675
+ const wallTime = performance.now() - start;
1676
+ const totalProcessTime = timer.totalElapsed();
1677
+ lc.debug?.(`finished processing advancement of ${numChanges} changes ((process: ${totalProcessTime} ms, wall: ${wallTime} ms))`);
1678
+ this.#transactionAdvanceTime.recordMs(totalProcessTime);
1679
+ outcome = { outcome: "success" };
1680
+ return "success";
1681
+ } finally {
1682
+ const setupMs = must(setupTimeMs);
1683
+ const processingTimeMs = setupMs + timer.totalElapsed();
1684
+ const wallTimeMs = performance.now() - start;
1685
+ this.#advancementMetrics.record({
1686
+ processingTimeMs,
1687
+ setupTimeMs: setupMs,
1688
+ wallTimeMs
1689
+ }, outcome);
1658
1690
  }
1659
- assert(updater && pokers && version !== void 0, "advancement state missing");
1660
- this.#cvr = await this.#flushPoked(lc, updater, pokers);
1661
- const finalVersion = this.#cvr.version;
1662
- await startAsyncSpan(tracer, "vs.#advancePipelines.pokeEnd", () => pokers.end(finalVersion));
1663
- this.#markVersionServed(version);
1664
- const wallTime = performance.now() - start;
1665
- const totalProcessTime = timer.totalElapsed();
1666
- lc.debug?.(`finished processing advancement of ${numChanges} changes ((process: ${totalProcessTime} ms, wall: ${wallTime} ms))`);
1667
- this.#transactionAdvanceTime.recordMs(totalProcessTime);
1668
- return "success";
1669
1691
  });
1670
1692
  }
1671
1693
  async inspect(selector, msg) {