@rocicorp/zero 1.10.0-canary.0 → 1.10.0-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/replicache/src/db/commit.js +1 -4
- package/out/replicache/src/db/commit.js.map +1 -1
- package/out/replicache/src/db/read.d.ts +1 -0
- package/out/replicache/src/db/read.d.ts.map +1 -1
- package/out/replicache/src/db/read.js +1 -4
- package/out/replicache/src/db/read.js.map +1 -1
- package/out/replicache/src/db/write.d.ts +2 -1
- package/out/replicache/src/db/write.d.ts.map +1 -1
- package/out/replicache/src/db/write.js +4 -51
- package/out/replicache/src/db/write.js.map +1 -1
- package/out/replicache/src/persist/clients.d.ts +1 -0
- package/out/replicache/src/persist/clients.d.ts.map +1 -1
- package/out/replicache/src/persist/clients.js +4 -31
- package/out/replicache/src/persist/clients.js.map +1 -1
- package/out/replicache/src/process-env.d.ts +28 -0
- package/out/replicache/src/process-env.d.ts.map +1 -0
- package/out/replicache/src/replicache-impl.d.ts.map +1 -1
- package/out/replicache/src/replicache-impl.js.map +1 -1
- package/out/replicache/src/scan-iterator.js +2 -14
- package/out/replicache/src/scan-iterator.js.map +1 -1
- package/out/replicache/src/subscriptions.d.ts +1 -0
- package/out/replicache/src/subscriptions.d.ts.map +1 -1
- package/out/replicache/src/subscriptions.js +2 -10
- package/out/replicache/src/subscriptions.js.map +1 -1
- package/out/replicache/src/transactions.d.ts +1 -0
- package/out/replicache/src/transactions.d.ts.map +1 -1
- package/out/replicache/src/transactions.js +2 -4
- package/out/replicache/src/transactions.js.map +1 -1
- package/out/z2s/src/compiler.d.ts.map +1 -1
- package/out/z2s/src/compiler.js +1 -22
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/zero/package.js +3 -3
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/config/normalize.d.ts +1 -0
- package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
- package/out/zero-cache/src/config/normalize.js +10 -1
- package/out/zero-cache/src/config/normalize.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +52 -1
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +171 -22
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom/fetch.js +1 -1
- package/out/zero-cache/src/custom/fetch.js.map +1 -1
- package/out/zero-cache/src/db/delete-lite-db.js +2 -1
- package/out/zero-cache/src/db/delete-lite-db.js.map +1 -1
- package/out/zero-cache/src/db/migration-lite.d.ts.map +1 -1
- package/out/zero-cache/src/db/migration-lite.js +5 -2
- package/out/zero-cache/src/db/migration-lite.js.map +1 -1
- package/out/zero-cache/src/db/migration.d.ts.map +1 -1
- package/out/zero-cache/src/db/migration.js +4 -2
- package/out/zero-cache/src/db/migration.js.map +1 -1
- package/out/zero-cache/src/db/sqlite-corruption.d.ts +3 -2
- package/out/zero-cache/src/db/sqlite-corruption.d.ts.map +1 -1
- package/out/zero-cache/src/db/sqlite-corruption.js +13 -8
- package/out/zero-cache/src/db/sqlite-corruption.js.map +1 -1
- package/out/zero-cache/src/observability/metrics.d.ts +6 -1
- package/out/zero-cache/src/observability/metrics.d.ts.map +1 -1
- package/out/zero-cache/src/observability/metrics.js +20 -2
- package/out/zero-cache/src/observability/metrics.js.map +1 -1
- package/out/zero-cache/src/server/backup-watermark-poller.js +31 -0
- package/out/zero-cache/src/server/backup-watermark-poller.js.map +1 -0
- package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +91 -31
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/main.d.ts.map +1 -1
- package/out/zero-cache/src/server/main.js +6 -16
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/server/replicator.js +48 -5
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/server/runner/run-worker.js +2 -1
- package/out/zero-cache/src/server/runner/run-worker.js.map +1 -1
- package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/server/syncer.js +1 -1
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/server/worker-urls.d.ts +1 -1
- package/out/zero-cache/src/server/worker-urls.js +2 -2
- package/out/zero-cache/src/server/worker-urls.js.map +1 -1
- package/out/zero-cache/src/services/change-source/change-source.d.ts +4 -2
- package/out/zero-cache/src/services/change-source/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts +35 -0
- package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-source/common/replica-restore.js +34 -0
- package/out/zero-cache/src/services/change-source/common/replica-restore.js.map +1 -0
- package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts +2 -0
- package/out/zero-cache/src/services/change-source/common/replica-schema.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-schema.js +73 -1
- package/out/zero-cache/src/services/change-source/common/replica-schema.js.map +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.d.ts +2 -6
- package/out/zero-cache/src/services/change-source/custom/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.js +14 -5
- package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +4 -7
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +7 -7
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +82 -25
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +9 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +12 -4
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts +45 -2
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +59 -8
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts +4 -2
- package/out/zero-cache/src/services/change-source/pg/replication-slots.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js +7 -4
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts +0 -5
- package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +29 -41
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +35 -16
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +77 -7
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts +2 -1
- package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/data.js +5 -13
- package/out/zero-cache/src/services/change-source/protocol/current/data.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts +6 -3
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/schema-change-tags.d.ts +6 -0
- package/out/zero-cache/src/services/change-source/protocol/current/schema-change-tags.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/schema-change-tags.js +21 -0
- package/out/zero-cache/src/services/change-source/protocol/current/schema-change-tags.js.map +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/status.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/status.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts +5 -6
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js +32 -9
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts +15 -5
- package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-monitor.js +66 -0
- package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/broadcast.d.ts +68 -78
- package/out/zero-cache/src/services/change-streamer/broadcast.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/broadcast.js +84 -92
- package/out/zero-cache/src/services/change-streamer/broadcast.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-codec.d.ts +19 -0
- package/out/zero-cache/src/services/change-streamer/change-log-codec.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js +50 -0
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.d.ts +141 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +270 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.d.ts +19 -0
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +39 -0
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +3 -4
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +12 -17
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +69 -24
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +333 -66
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +56 -13
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/error-type-enum.d.ts +8 -0
- package/out/zero-cache/src/services/change-streamer/error-type-enum.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/forwarder.d.ts +14 -3
- package/out/zero-cache/src/services/change-streamer/forwarder.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/forwarder.js +41 -11
- package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/{litestream3-backup-monitor.d.ts → litestream3-prometheus-poller.d.ts} +19 -45
- package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/{litestream3-backup-monitor.js → litestream3-prometheus-poller.js} +57 -171
- package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/replica-poller.d.ts +15 -0
- package/out/zero-cache/src/services/change-streamer/replica-poller.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/replica-poller.js +55 -0
- package/out/zero-cache/src/services/change-streamer/replica-poller.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts +5 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.js +2 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts +14 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +86 -0
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/snapshot.d.ts +4 -1
- package/out/zero-cache/src/services/change-streamer/snapshot.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot.js +39 -14
- package/out/zero-cache/src/services/change-streamer/snapshot.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.d.ts +75 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js +261 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.d.ts +121 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +391 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.d.ts +62 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +159 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.d.ts +109 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +258 -0
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -0
- package/out/zero-cache/src/services/change-streamer/storer.d.ts +28 -12
- package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js +116 -121
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +61 -10
- package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscriber.js +101 -8
- package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts +34 -0
- package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/upstream-acker.js +86 -0
- package/out/zero-cache/src/services/change-streamer/upstream-acker.js.map +1 -0
- package/out/zero-cache/src/services/life-cycle.d.ts +1 -1
- package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
- package/out/zero-cache/src/services/life-cycle.js +4 -3
- package/out/zero-cache/src/services/life-cycle.js.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.d.ts +12 -11
- package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.js +107 -148
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/litestream/config-v5.yml +42 -0
- package/out/zero-cache/src/services/litestream/config.yml +3 -2
- package/out/zero-cache/src/services/litestream/metrics.d.ts +4 -4
- package/out/zero-cache/src/services/litestream/metrics.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/metrics.js +7 -10
- package/out/zero-cache/src/services/litestream/metrics.js.map +1 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-poller.d.ts +57 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-poller.d.ts.map +1 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-poller.js +137 -0
- package/out/zero-cache/src/services/litestream/vfs-watermark-poller.js.map +1 -0
- package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +4 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +169 -0
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-cookies.js +434 -0
- package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-db.d.ts +358 -0
- package/out/zero-cache/src/services/replicator/change-log-db.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-db.js +477 -0
- package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.d.ts +55 -0
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +150 -0
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -0
- package/out/zero-cache/src/services/replicator/change-processor.d.ts +6 -0
- package/out/zero-cache/src/services/replicator/change-processor.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +70 -25
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +19 -6
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/notifier.d.ts +0 -22
- package/out/zero-cache/src/services/replicator/notifier.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/notifier.js +7 -1
- package/out/zero-cache/src/services/replicator/notifier.js.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.d.ts +17 -2
- package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.js +9 -3
- package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/recorder.d.ts +27 -0
- package/out/zero-cache/src/services/replicator/reporter/recorder.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/recorder.js +32 -0
- package/out/zero-cache/src/services/replicator/reporter/recorder.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -1
- package/out/zero-cache/src/services/replicator/schema/backfilling.d.ts +119 -0
- package/out/zero-cache/src/services/replicator/schema/backfilling.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/schema/backfilling.js +214 -0
- package/out/zero-cache/src/services/replicator/schema/backfilling.js.map +1 -0
- package/out/zero-cache/src/services/replicator/schema/change-log.d.ts +3 -3
- package/out/zero-cache/src/services/replicator/schema/column-metadata.js +1 -1
- package/out/zero-cache/src/services/replicator/schema/column-metadata.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/replication-state.d.ts +1 -1
- package/out/zero-cache/src/services/replicator/schema/replication-state.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/replication-state.js +9 -5
- package/out/zero-cache/src/services/replicator/schema/replication-state.js.map +1 -1
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts +131 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +413 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-purger.d.ts +120 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-purger.d.ts.map +1 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-purger.js +283 -0
- package/out/zero-cache/src/services/replicator/sqlite-change-log-purger.js.map +1 -0
- package/out/zero-cache/src/services/replicator/write-worker.js +23 -12
- package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
- package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
- package/out/zero-cache/src/services/run-ast.js +2 -1
- package/out/zero-cache/src/services/run-ast.js.map +1 -1
- package/out/zero-cache/src/services/running-state.d.ts +1 -1
- package/out/zero-cache/src/services/running-state.d.ts.map +1 -1
- package/out/zero-cache/src/services/running-state.js +1 -0
- package/out/zero-cache/src/services/running-state.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/e2e-serving-lag.d.ts +53 -0
- package/out/zero-cache/src/services/view-syncer/e2e-serving-lag.d.ts.map +1 -0
- package/out/zero-cache/src/services/view-syncer/e2e-serving-lag.js +68 -0
- package/out/zero-cache/src/services/view-syncer/e2e-serving-lag.js.map +1 -0
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +18 -3
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +11 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +64 -6
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/processes.d.ts +1 -2
- package/out/zero-cache/src/types/processes.d.ts.map +1 -1
- package/out/zero-cache/src/types/processes.js +1 -25
- package/out/zero-cache/src/types/processes.js.map +1 -1
- package/out/zero-cache/src/types/streams.d.ts +21 -0
- package/out/zero-cache/src/types/streams.d.ts.map +1 -1
- package/out/zero-cache/src/types/streams.js +25 -4
- package/out/zero-cache/src/types/streams.js.map +1 -1
- package/out/zero-cache/src/types/subscription.d.ts +11 -0
- package/out/zero-cache/src/types/subscription.d.ts.map +1 -1
- package/out/zero-cache/src/types/subscription.js +27 -0
- package/out/zero-cache/src/types/subscription.js.map +1 -1
- package/out/zero-cache/src/workers/connection.d.ts +1 -0
- package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connection.js +24 -2
- package/out/zero-cache/src/workers/connection.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.d.ts +25 -0
- package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/workers/replicator.js +33 -1
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts +12 -0
- package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +75 -0
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.d.ts +6 -7
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +156 -101
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-schema/src/builder/table-builder.d.ts +23 -0
- package/out/zero-schema/src/builder/table-builder.d.ts.map +1 -1
- package/out/zero-schema/src/builder/table-builder.js +18 -0
- package/out/zero-schema/src/builder/table-builder.js.map +1 -1
- package/out/zero-server/src/custom.js +10 -3
- package/out/zero-server/src/custom.js.map +1 -1
- package/out/zero-server/src/schema.d.ts +8 -0
- package/out/zero-server/src/schema.d.ts.map +1 -1
- package/out/zero-server/src/schema.js +63 -24
- package/out/zero-server/src/schema.js.map +1 -1
- package/out/zero-types/src/schema.d.ts +11 -0
- package/out/zero-types/src/schema.d.ts.map +1 -1
- package/out/zql/src/mutate/crud.d.ts +10 -8
- package/out/zql/src/mutate/crud.d.ts.map +1 -1
- package/out/zql/src/mutate/crud.js.map +1 -1
- package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
- package/out/zql/src/query/query-delegate-base.js +5 -1
- package/out/zql/src/query/query-delegate-base.js.map +1 -1
- package/out/zql/src/query/query-impl.d.ts +2 -2
- package/out/zql/src/query/query-impl.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query.d.ts +83 -14
- package/out/zql/src/query/query.d.ts.map +1 -1
- package/out/zql/src/query/static-query.d.ts +1 -1
- package/out/zql/src/query/static-query.d.ts.map +1 -1
- package/out/zqlite/src/resolve-scalar-subqueries.d.ts +15 -0
- package/out/zqlite/src/resolve-scalar-subqueries.d.ts.map +1 -1
- package/out/zqlite/src/resolve-scalar-subqueries.js +33 -14
- package/out/zqlite/src/resolve-scalar-subqueries.js.map +1 -1
- package/package.json +3 -3
- package/out/replicache/src/db/index.js +0 -91
- package/out/replicache/src/db/index.js.map +0 -1
- package/out/replicache/src/lazy.d.ts +0 -2
- package/out/replicache/src/lazy.d.ts.map +0 -1
- package/out/replicache/src/lazy.js +0 -12
- package/out/replicache/src/lazy.js.map +0 -1
- package/out/zero-cache/src/server/backup-watermark-reader.js +0 -35
- package/out/zero-cache/src/server/backup-watermark-reader.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/litestream3-backup-monitor.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-streamer/litestream3-backup-monitor.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/replica-monitor.d.ts +0 -16
- package/out/zero-cache/src/services/change-streamer/replica-monitor.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-streamer/replica-monitor.js +0 -54
- package/out/zero-cache/src/services/change-streamer/replica-monitor.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.d.ts +0 -25
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.js +0 -159
- package/out/zero-cache/src/services/change-streamer/vfs-backup-monitor.js.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.d.ts +0 -44
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.d.ts.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.js +0 -65
- package/out/zero-cache/src/services/litestream/vfs-watermark-reader.js.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.d.ts +0 -11
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.d.ts.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.js +0 -74
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker-source.js.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.d.ts +0 -42
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.d.ts.map +0 -1
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.js +0 -117
- package/out/zero-cache/src/services/litestream/vfs-watermark-worker.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sqlite-change-log-observability.js","names":["#lc","#messageProcessing","#logCommitDuration","#transactionRows","#rollbackCounter","#invariantFailureCounter","#hashComparisonCounter","#hashUnpairedCounter","#cookieMutationCounter","#receivedHead","#sqliteHead","#rows","#estimatedBytes","#cookieRows","#sourceHasher","#invariantFailure","#sourcePos","#sourceCommitHash","#resetSourceHash","#transactionWatermark","#recordRollback","#recordUnpaired","#compareHashes","#cookieMutations","#rollbacks","#invariantFailures","#hashMatches","#hashMismatches","#hashUnpaired"],"sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"sourcesContent":["/**\n * Observability for the SQLite change log.\n *\n * Everything here now runs in the **change-streamer** process, which is where\n * the writer lives. The module stays beside the rest of the change-log code\n * under `services/replicator/` for the same reason `change-log-db.ts` and\n * `change-log-stream-writer.ts` do: moving files would obscure the topology\n * diff, and the writer's home is a property of who calls it rather than of\n * where it sits. Metric names are unchanged from 7H — only their emitting\n * process, and therefore their resource attributes, moved.\n */\n\nimport {stat} from 'node:fs/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../../shared/src/asserts.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n getOrCreateCounter,\n getOrCreateGauge,\n getOrCreateLatencyHistogram,\n getOrCreateValueHistogram,\n} from '../../observability/metrics.ts';\nimport {versionFromLexi} from '../../types/lexi-version.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {extractChangeSubstring} from '../change-streamer/change-log-codec.ts';\nimport {ChangeLogTransactionHasher} from '../change-streamer/change-log-transaction-hash.ts';\nimport {\n readCookieRowCounts,\n type CookieOpTag,\n type CookieRowCounts,\n} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n readChangeLogHead,\n readChangeLogMeta,\n type ChangeLogMeta,\n type ReconcileResult,\n} from './change-log-db.ts';\nimport type {ChangeLogStreamTransactionStats} from './change-log-stream-writer.ts';\n\n/**\n * Reports the reconciliation of the change-log database against the watermark\n * the stream connection resumes from. This runs once per stream connection, so\n * a reconnect storm is visible here as well as a restart.\n *\n * A wipe is not an error — it is how every abnormal change-log state is\n * collapsed into a correct one — but each wipe costs the retention window, so\n * every reconnecting subscriber below the head gets `too-old`. The `gap` reason\n * in particular means the log neither held the resume watermark nor could be\n * truncated to it, so a nonzero rate in steady state is an alert, not a\n * statistic.\n */\nexport function recordSQLiteChangeLogReconcile(\n lc: LogContext,\n result: ReconcileResult,\n): void {\n switch (result.action) {\n case 'truncated':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_truncated_rows',\n 'Phantom change-log rows removed at reconciliation, i.e. rows above ' +\n 'the watermark the change stream resumed from.',\n ).add(result.rows);\n break;\n case 'reseeded':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_wipes',\n 'Change-log wipes at reconciliation, by reason. Each one resets the ' +\n 'retention window, so subscribers below the head get `too-old`.',\n ).add(1, {reason: result.reason});\n break;\n case 'none':\n break;\n default:\n unreachable(result);\n }\n if (result.cookiesStale) {\n // The invariant-17 counter: after any reconcile that moved the head, the\n // log's cookie set has to be replaced with the one that belongs to the\n // resume watermark. A nonzero `truncated` series in steady state means\n // phantom truncation is happening on a shard where it should not.\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_reseed',\n 'Change-log cookie sets invalidated at reconciliation, by the ' +\n 'reconcile action that invalidated them.',\n ).add(1, {action: result.action});\n }\n lc.debug?.('SQLite change-log reconciliation', {\n sqliteChangeLogReconcile: result,\n });\n}\n\n/**\n * What the log says about itself. Nothing here reads the replica: after the\n * writer moved to the change-streamer, the replica's state version is a\n * consequence of this log rather than a fact about it.\n */\nexport type SQLiteChangeLogStartupInfo = ChangeLogMeta & {\n readonly headWatermark: string;\n};\n\nexport type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n};\n\n/**\n * Reads the meta row and the head. The head is an index-optimized `max()`, so\n * unlike {@link getSQLiteChangeLogInfo} this does not scan the log.\n *\n * Call this after reconciliation, which is the only point at which the head is\n * known to be the resume watermark.\n */\nexport function getSQLiteChangeLogStartupInfo(\n changeLog: Database,\n): SQLiteChangeLogStartupInfo {\n const meta = readChangeLogMeta(changeLog);\n const head = readChangeLogHead(changeLog);\n if (head === null) {\n throw new Error('the SQLite change log must contain its seed transaction');\n }\n return {...meta, headWatermark: head};\n}\n\n/**\n * Extends {@link getSQLiteChangeLogStartupInfo} with the retained row and\n * estimated byte totals. Computing these scans the entire change-log table, so\n * only call it when the totals are consumed, i.e. when the writer (and thus the\n * observer) is enabled.\n */\nexport function getSQLiteChangeLogInfo(\n changeLog: Database,\n): SQLiteChangeLogInfo {\n const startup = getSQLiteChangeLogStartupInfo(changeLog);\n const aggregate = changeLog\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{rows: number; estimatedBytes: number}>();\n\n return {\n ...startup,\n rows: aggregate.rows,\n estimatedBytes: aggregate.estimatedBytes,\n cookieRows: readCookieRowCounts(changeLog),\n };\n}\n\nexport function logSQLiteChangeLogStartup(\n lc: LogContext,\n file: string,\n info: SQLiteChangeLogStartupInfo,\n): void {\n lc.info?.('SQLite change-log startup', {\n sqliteChangeLog: {\n file,\n epoch: info.epoch,\n generation: info.generation,\n replicaID: info.replicaID,\n schemaVersion: info.schemaVersion,\n seedWatermark: info.seedWatermark,\n seededAtMs: info.seededAtMs,\n headWatermark: info.headWatermark,\n },\n });\n}\n\n/**\n * The on-disk footprint of a SQLite database: its main file plus its `-wal` and\n * `-wal2` sidecars, whichever exist. `-shm` is excluded — it is a\n * shared-memory index rather than retained bytes.\n *\n * A missing file counts as zero rather than warning. Which sidecars exist\n * depends on the journal mode, and the change-log database is absent entirely\n * until the writer creates it.\n */\nexport async function sqliteFileBytes(\n lc: LogContext,\n file: string,\n): Promise<number> {\n const sizes = await Promise.all(\n [file, `${file}-wal`, `${file}-wal2`].map(async path => {\n try {\n return (await stat(path)).size;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n lc.warn?.(`unable to stat ${path} for size metrics`, e);\n }\n return 0;\n }\n }),\n );\n return sizes.reduce((total, size) => total + size, 0);\n}\n\n/** What the writer reports back for a committed transaction. */\nexport type ChangeLogCommit = {\n readonly watermark: string;\n readonly stats: ChangeLogStreamTransactionStats;\n /**\n * Appending the commit row and committing the log's transaction. This is the\n * cost that sits on the forward path, once per upstream transaction.\n */\n readonly logCommitMs: number;\n};\n\nexport type SQLiteChangeLogObservabilityState = {\n readonly receivedHead: string;\n readonly sqliteHead: string;\n readonly headLag: number | undefined;\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n readonly cookieMutations: number;\n readonly rollbacks: number;\n readonly invariantFailures: number;\n readonly hashMatches: number;\n readonly hashMismatches: number;\n readonly hashUnpaired: number;\n};\n\nconst TRANSACTION_ROW_BUCKETS = [2, 3, 5, 10, 25, 50, 100, 250, 1000, 5000];\n\n/**\n * Records writer metrics in the change-streamer process. State changes only\n * after the corresponding write succeeds, except receivedHead, which advances\n * when a commit message arrives so that transient lag behind the log is\n * observable.\n */\nexport class SQLiteChangeLogObserver {\n readonly #lc: LogContext;\n readonly #messageProcessing = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.message_processing_duration',\n 'Time to write a replication message to the SQLite change log.',\n );\n // The commit that sits on the forward path. There is no second commit to\n // order against any more: the replica's belongs to a subscriber downstream of\n // this loop, so `sqlite_change_log.replica_commit_duration` and the phantom\n // window it measured are gone. A failed commit is still timed, by\n // `message_processing_duration` keyed `tag=\"commit\"`.\n readonly #logCommitDuration = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.log_commit_duration',\n 'Time to append the commit row to the SQLite change log and commit its ' +\n 'transaction. This is on the forward path: it precedes the forward of ' +\n \"that transaction's commit message.\",\n );\n readonly #transactionRows = getOrCreateValueHistogram(\n 'replica',\n 'sqlite_change_log.transaction_rows',\n {\n description: 'Rows stored per committed SQLite change-log transaction.',\n unit: '{row}',\n bucketBoundaries: TRANSACTION_ROW_BUCKETS,\n },\n );\n readonly #rollbackCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.rollbacks',\n 'SQLite change-log transactions rolled back before commit.',\n );\n readonly #invariantFailureCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.invariant_failures',\n 'Detected SQLite change-log writer invariant failures.',\n );\n readonly #hashComparisonCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_comparisons',\n 'Ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.',\n );\n readonly #hashUnpairedCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_unpaired',\n 'Committed change-log transactions without both ephemeral hashes available for comparison.',\n );\n // Near zero at steady state: cookie state only moves on schema changes.\n readonly #cookieMutationCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_mutations',\n 'Change-log cookie mutations folded from schema changes, by operation.',\n );\n\n #receivedHead: string;\n #sqliteHead: string;\n #rows: number;\n #estimatedBytes: number;\n #cookieRows: CookieRowCounts;\n #cookieMutations = 0;\n #transactionWatermark: string | undefined;\n #sourceHasher: ChangeLogTransactionHasher | undefined;\n #sourcePos = 0;\n #sourceCommitHash: string | undefined;\n #rollbacks = 0;\n #invariantFailures = 0;\n #hashMatches = 0;\n #hashMismatches = 0;\n #hashUnpaired = 0;\n\n constructor(lc: LogContext, info: SQLiteChangeLogInfo) {\n this.#lc = lc.withContext('component', 'sqlite-change-log-observer');\n // Reconciliation has just put the head at the resume watermark, which is\n // also the point the stream is about to be received from.\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.rows',\n 'Rows retained in the SQLite change log.',\n ).addCallback(result => result.observe(this.#rows));\n // Nonzero with no backfill in flight is a leaked cookie, i.e. a backfill\n // that will be re-requested forever.\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.cookie_rows',\n 'Cookie rows retained in the SQLite change log, by cookie table.',\n ).addCallback(result => {\n result.observe(this.#cookieRows.tableMetadata, {table: 'tableMetadata'});\n result.observe(this.#cookieRows.backfilling, {table: 'backfilling'});\n });\n getOrCreateGauge('replica', 'sqlite_change_log.retained_bytes', {\n description:\n 'Estimated UTF-8 payload bytes retained in the SQLite change log.',\n unit: 'By',\n }).addCallback(result => result.observe(this.#estimatedBytes));\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head',\n 'SQLite change-log head converted from its lexicographic watermark.',\n ).addCallback(result => {\n const head = watermarkValue(this.#sqliteHead);\n if (head !== undefined) {\n result.observe(head);\n }\n });\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head_lag',\n 'Distance from the latest received commit to the SQLite change-log ' +\n 'head. The log commits before the forward, so this is zero except ' +\n 'within a transaction.',\n ).addCallback(result => {\n const lag = watermarkDistance(this.#receivedHead, this.#sqliteHead);\n if (lag !== undefined) {\n result.observe(lag);\n }\n });\n }\n\n /**\n * Called as each message arrives, before it is written. Hashes the *received*\n * stream, which is compared against the hash the writer computes over what it\n * *stored*.\n */\n messageReceived(data: ChangeStreamData, json: string): void {\n const tag = data[1].tag;\n if (data[0] === 'begin') {\n if (this.#sourceHasher !== undefined) {\n this.#invariantFailure(\n 'Received change-log begin while a source hash is already open',\n {receivedWatermark: data[2].commitWatermark},\n );\n }\n const watermark = data[2].commitWatermark;\n this.#sourceHasher = new ChangeLogTransactionHasher();\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n this.#sourceHasher.add({\n watermark,\n pos: this.#sourcePos,\n tag,\n change: extractChangeSubstring(json, tag),\n precommit: null,\n });\n return;\n }\n\n if (tag === 'rollback') {\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] === 'commit') {\n this.#receivedHead = data[2].watermark;\n }\n\n const watermark = this.#transactionWatermark;\n if (this.#sourceHasher === undefined || watermark === undefined) {\n this.#invariantFailure(\n 'Received change-log message without an observed transaction',\n {tag},\n );\n return;\n }\n\n const commitWatermark =\n data[0] === 'commit' ? data[2].watermark : watermark;\n this.#sourceHasher.add({\n watermark: commitWatermark,\n pos: ++this.#sourcePos,\n tag,\n change: extractChangeSubstring(json, tag),\n precommit: data[0] === 'commit' ? watermark : null,\n });\n if (data[0] === 'commit') {\n this.#sourceCommitHash = this.#sourceHasher.digest();\n this.#sourceHasher = undefined;\n }\n }\n\n /** Called after the message has been written to the log. */\n messageProcessed(\n data: ChangeStreamData,\n commit: ChangeLogCommit | null,\n durationMs: number,\n ): void {\n const tag = data[1].tag;\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'success'});\n\n if (data[0] === 'begin') {\n if (this.#transactionWatermark !== undefined) {\n this.#invariantFailure('SQLite change-log transaction already open', {\n openWatermark: this.#transactionWatermark,\n receivedWatermark: data[2].commitWatermark,\n });\n }\n this.#transactionWatermark = data[2].commitWatermark;\n return;\n }\n\n if (tag === 'rollback') {\n this.#recordRollback('upstream');\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] !== 'commit') {\n return;\n }\n\n const watermark = data[2].watermark;\n if (commit !== null) {\n this.#logCommitDuration.recordMs(commit.logCommitMs);\n }\n if (this.#transactionWatermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit does not match the observed begin',\n {openWatermark: this.#transactionWatermark, commitWatermark: watermark},\n );\n }\n if (commit === null) {\n this.#invariantFailure(\n 'SQLite change-log commit result is missing writer statistics',\n {commitWatermark: watermark},\n );\n this.#recordUnpaired(watermark, 'missing-sqlite-hash');\n } else {\n if (commit.watermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit result has an unexpected watermark',\n {commitWatermark: watermark, resultWatermark: commit.watermark},\n );\n }\n this.#rows += commit.stats.rows;\n this.#estimatedBytes += commit.stats.estimatedBytes;\n this.#transactionRows.record(commit.stats.rows);\n this.#compareHashes(watermark, this.#sourceCommitHash, commit.stats.hash);\n }\n if (watermark < this.#sqliteHead) {\n this.#invariantFailure('SQLite change-log head regressed', {\n previousHead: this.#sqliteHead,\n commitWatermark: watermark,\n });\n }\n this.#sqliteHead = watermark;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n messageFailed(\n data: ChangeStreamData,\n error: unknown,\n durationMs: number,\n ): void {\n const tag = data[1].tag;\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'error'});\n if (data[0] === 'commit') {\n // No commit duration here: a failed commit produces no statistics, so\n // there is nothing to attribute. The attempt is timed by\n // `message_processing_duration{tag=\"commit\",outcome=\"error\"}` above.\n this.#recordUnpaired(data[2].watermark, 'sqlite-commit-failed');\n }\n if (\n error instanceof Error &&\n error.name === 'ChangeLogStreamInvariantError'\n ) {\n this.#invariantFailure(error.message);\n }\n if (this.#transactionWatermark !== undefined || data[0] === 'begin') {\n this.#recordRollback('processing-error');\n }\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n /**\n * A committed transaction folded schema changes into the cookie jar. Reported\n * separately from {@link messageProcessed} because it costs a read of the\n * cookie tables, which is only worth taking when they actually moved.\n */\n cookiesMutated(ops: readonly CookieOpTag[], rows: CookieRowCounts): void {\n for (const op of ops) {\n this.#cookieMutations++;\n this.#cookieMutationCounter.add(1, {op});\n }\n this.#cookieRows = rows;\n }\n\n /**\n * A missed truncate-above surfaces as a constraint violation on the writer's\n * plain `INSERT`, which the fail-soft policy would otherwise absorb quietly.\n * Classifying it as an invariant failure is what keeps a reconciliation bug\n * from looking like a lost cache.\n */\n invariantFailure(message: string, details?: Record<string, unknown>): void {\n this.#invariantFailure(message, details);\n }\n\n /** The source interrupted the stream mid-transaction. */\n abort(): void {\n if (this.#transactionWatermark !== undefined) {\n this.#recordRollback('source-interruption');\n this.#transactionWatermark = undefined;\n }\n this.#resetSourceHash();\n }\n\n /** Reconciliation moved the head, so the observer's totals are restated. */\n reconciled(info: SQLiteChangeLogInfo): void {\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n state(): SQLiteChangeLogObservabilityState {\n return {\n receivedHead: this.#receivedHead,\n sqliteHead: this.#sqliteHead,\n headLag: watermarkDistance(this.#receivedHead, this.#sqliteHead),\n rows: this.#rows,\n estimatedBytes: this.#estimatedBytes,\n cookieRows: this.#cookieRows,\n cookieMutations: this.#cookieMutations,\n rollbacks: this.#rollbacks,\n invariantFailures: this.#invariantFailures,\n hashMatches: this.#hashMatches,\n hashMismatches: this.#hashMismatches,\n hashUnpaired: this.#hashUnpaired,\n };\n }\n\n #recordRollback(\n reason: 'upstream' | 'processing-error' | 'source-interruption',\n ) {\n this.#rollbacks++;\n this.#rollbackCounter.add(1, {reason});\n }\n\n #invariantFailure(message: string, details?: Record<string, unknown>) {\n this.#invariantFailures++;\n this.#invariantFailureCounter.add(1);\n this.#lc.error?.(message, details);\n }\n\n #compareHashes(\n watermark: string,\n sourceHash: string | undefined,\n sqliteHash: string,\n ): void {\n if (sourceHash === undefined) {\n this.#recordUnpaired(watermark, 'missing-source-hash');\n return;\n }\n if (sourceHash === sqliteHash) {\n this.#hashMatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'match'});\n return;\n }\n this.#hashMismatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'mismatch'});\n this.#lc.error?.('SQLite change-log transaction hash mismatch', {\n sqliteChangeLogHashComparison: {\n watermark,\n sourceHash: sourceHash.slice(0, 16),\n sqliteHash: sqliteHash.slice(0, 16),\n },\n });\n }\n\n #recordUnpaired(\n watermark: string,\n reason:\n | 'missing-source-hash'\n | 'missing-sqlite-hash'\n | 'sqlite-commit-failed',\n ): void {\n this.#hashUnpaired++;\n this.#hashUnpairedCounter.add(1, {reason});\n this.#lc.warn?.('SQLite change-log transaction hash was not compared', {\n sqliteChangeLogHashComparison: {watermark, reason},\n });\n }\n\n #resetSourceHash(): void {\n this.#sourceHasher = undefined;\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n }\n}\n\nfunction watermarkValue(watermark: string): number | undefined {\n try {\n const value = Number(versionFromLexi(watermark));\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction watermarkDistance(\n receivedHead: string,\n sqliteHead: string,\n): number | undefined {\n if (receivedHead <= sqliteHead) {\n return 0;\n }\n try {\n const distance =\n versionFromLexi(receivedHead) - versionFromLexi(sqliteHead);\n const value = Number(distance);\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,+BACd,IACA,QACM;CACN,QAAQ,OAAO,QAAf;EACE,KAAK;GACH,mBACE,WACA,8CACA,kHAEF,EAAE,IAAI,OAAO,IAAI;GACjB;EACF,KAAK;GACH,mBACE,WACA,qCACA,mIAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;GAChC;EACF,KAAK,QACH;EACF,SACE,YAAY,MAAM;CACtB;CACA,IAAI,OAAO,cAKT,mBACE,WACA,mCACA,sGAEF,EAAE,IAAI,GAAG,EAAC,QAAQ,OAAO,OAAM,CAAC;CAElC,GAAG,QAAQ,oCAAoC,EAC7C,0BAA0B,OAC5B,CAAC;AACH;;;;;;;;AAwBA,SAAgB,8BACd,WAC4B;CAC5B,MAAM,OAAO,kBAAkB,SAAS;CACxC,MAAM,OAAO,kBAAkB,SAAS;CACxC,IAAI,SAAS,MACX,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;EAAC,GAAG;EAAM,eAAe;CAAI;AACtC;;;;;;;AAQA,SAAgB,uBACd,WACqB;CACrB,MAAM,UAAU,8BAA8B,SAAS;CACvD,MAAM,YAAY,UACf,QAAgB;;;gBAGL,wBAAwB;KACnC,EACA,IAA4C;CAE/C,OAAO;EACL,GAAG;EACH,MAAM,UAAU;EAChB,gBAAgB,UAAU;EAC1B,YAAY,oBAAoB,SAAS;CAC3C;AACF;AAEA,SAAgB,0BACd,IACA,MACA,MACM;CACN,GAAG,OAAO,6BAA6B,EACrC,iBAAiB;EACf;EACA,OAAO,KAAK;EACZ,YAAY,KAAK;EACjB,WAAW,KAAK;EAChB,eAAe,KAAK;EACpB,eAAe,KAAK;EACpB,YAAY,KAAK;EACjB,eAAe,KAAK;CACtB,EACF,CAAC;AACH;;;;;;;;;;AAWA,eAAsB,gBACpB,IACA,MACiB;CAajB,QAAO,MAZa,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EA,mBAAyB;EACvB,KAAKc,gBAAgB,KAAA;EACrB,KAAKE,aAAa;EAClB,KAAKC,oBAAoB,KAAA;CAC3B;AACF;AAEA,SAAS,eAAe,WAAuC;CAC7D,IAAI;EACF,MAAM,QAAQ,OAAO,gBAAgB,SAAS,CAAC;EAC/C,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF;AAEA,SAAS,kBACP,cACA,YACoB;CACpB,IAAI,gBAAgB,YAClB,OAAO;CAET,IAAI;EACF,MAAM,WACJ,gBAAgB,YAAY,IAAI,gBAAgB,UAAU;EAC5D,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deletes aged-out transactions from the change-log database, one bounded write
|
|
3
|
+
* transaction at a time.
|
|
4
|
+
*
|
|
5
|
+
* The purger is a pure function of one database: it takes the floors its caller
|
|
6
|
+
* has already gated on and narrows them, never widens them, and it reads no
|
|
7
|
+
* replication state. That is what makes it testable without a scheduler and
|
|
8
|
+
* what lets slice 9 run it from the change-streamer's stream loop, between the
|
|
9
|
+
* writer's commits, on the writer's own connection.
|
|
10
|
+
*/
|
|
11
|
+
import type { Database } from '../../../../zqlite/src/db.ts';
|
|
12
|
+
/**
|
|
13
|
+
* The eligible set, as three ANDed bounds. Only the `externalFloor` is a safety
|
|
14
|
+
* property; the other two make the log serviceable and make purge conservative.
|
|
15
|
+
*
|
|
16
|
+
* `"watermark" < @externalFloor` is deliberately strict. A follower that lost
|
|
17
|
+
* its replica restores it from S3 at watermark `W` and then asks this log for
|
|
18
|
+
* everything after `W`, which requires the `commit` row *at* `W` to still be
|
|
19
|
+
* here (`SQLITE_CHANGE_LOG_BOUNDARY_SQL`). Deleting it returns `too-old` to the
|
|
20
|
+
* very subscriber the floor exists to protect.
|
|
21
|
+
*
|
|
22
|
+
* The head cap reads `max("watermark")` from the log's own database, which
|
|
23
|
+
* keeps the purger a pure function of one file. The cap is inert in normal
|
|
24
|
+
* operation: the floor is derived from a backup of a replica that consumes this
|
|
25
|
+
* loop's output, and the log commits before that output is forwarded, so
|
|
26
|
+
* `externalFloor <= head` holds by construction. It engages only on a *stale*
|
|
27
|
+
* log — writer stopped, mode flipped to `off`, another task took over — where
|
|
28
|
+
* deleting to a floor that has run past a frozen log would empty the file. Note
|
|
29
|
+
* that head can be a phantom — committed here but not yet re-deliverable by a
|
|
30
|
+
* resumed stream — for as long as it takes the watermark the stream would
|
|
31
|
+
* resume from to advance past it. That is harmless precisely because head is
|
|
32
|
+
* never a purge candidate, and it is why the purger asserts nothing about
|
|
33
|
+
* anything outside its own file.
|
|
34
|
+
*
|
|
35
|
+
* Ordered by `("writeTimeMs", "watermark")` so it rides the partial index,
|
|
36
|
+
* which carries one entry per transaction rather than one per change. The
|
|
37
|
+
* `LIMIT` keeps a drain from re-scanning the remaining history on every batch,
|
|
38
|
+
* which would be quadratic in the number of eligible transactions and would do
|
|
39
|
+
* it inside the `BEGIN IMMEDIATE`, holding the write lock alongside the delete.
|
|
40
|
+
*
|
|
41
|
+
* Exported so the focused query-plan test covers the production query.
|
|
42
|
+
*/
|
|
43
|
+
export declare const SQLITE_CHANGE_LOG_ELIGIBLE_COMMITS_SQL = "\n SELECT \"watermark\"\n FROM \"_zero.changeLogStream\"\n WHERE \"writeTimeMs\" IS NOT NULL\n AND \"writeTimeMs\" < @retentionCutoffMs\n AND \"watermark\" < @externalFloor\n AND \"watermark\" < (SELECT max(\"watermark\") FROM \"_zero.changeLogStream\")\n ORDER BY \"writeTimeMs\", \"watermark\"\n LIMIT @limit\n";
|
|
44
|
+
/**
|
|
45
|
+
* Counts the rows at `@watermark`, capped at `@limit`. The cap is what keeps
|
|
46
|
+
* batch sizing O(budget): this runs per candidate inside the
|
|
47
|
+
* `BEGIN IMMEDIATE`, and the transaction being sized can be arbitrarily
|
|
48
|
+
* large — an uncapped count of a multi-million-row backfill would rescan
|
|
49
|
+
* every remaining row on every tear batch, holding the write lock (and the
|
|
50
|
+
* appending path behind it) for the duration, quadratically over the drain.
|
|
51
|
+
* The caller only needs to know whether the transaction fits its remaining
|
|
52
|
+
* budget, so it passes `remaining + 1` and reads a count above `remaining`
|
|
53
|
+
* as "does not fit".
|
|
54
|
+
*
|
|
55
|
+
* Exported so the focused tests cover the production query.
|
|
56
|
+
*/
|
|
57
|
+
export declare const SQLITE_CHANGE_LOG_COUNT_TRANSACTION_SQL = "\n SELECT count(*) AS \"rows\" FROM (\n SELECT 1\n FROM \"_zero.changeLogStream\"\n WHERE \"watermark\" = @watermark\n LIMIT @limit\n )\n";
|
|
58
|
+
export type PurgeBatchResult = {
|
|
59
|
+
readonly deletedRows: number;
|
|
60
|
+
/**
|
|
61
|
+
* The watermark through which whole transactions were removed. `undefined`
|
|
62
|
+
* when the batch only tore rows off the minimum transaction without
|
|
63
|
+
* completing it — in that case `deletedRows > 0` and `moreEligible` is true.
|
|
64
|
+
*/
|
|
65
|
+
readonly deletedThrough: string | undefined;
|
|
66
|
+
/** True while a tear is in progress, as well as while whole transactions remain eligible. */
|
|
67
|
+
readonly moreEligible: boolean;
|
|
68
|
+
};
|
|
69
|
+
export type PurgeBatchOptions = {
|
|
70
|
+
/**
|
|
71
|
+
* The floor the caller has already gated on subscriber ACKs and snapshot
|
|
72
|
+
* reservations — normally the confirmed S3 backup watermark. Transactions at
|
|
73
|
+
* or above it are NOT durable anywhere else: the change log is excluded from
|
|
74
|
+
* the litestream backup, so this is the boundary a follower restores to and
|
|
75
|
+
* then catches up from. Compared strictly (`<`), so the transaction *at* the
|
|
76
|
+
* floor survives as that follower's catchup boundary. The purger narrows this
|
|
77
|
+
* input and never widens it.
|
|
78
|
+
*/
|
|
79
|
+
readonly externalFloor: string;
|
|
80
|
+
/**
|
|
81
|
+
* A *minimum* retention, ANDed on top of `externalFloor` rather than an
|
|
82
|
+
* alternative to it. Which of the two binds depends on the backup interval.
|
|
83
|
+
*/
|
|
84
|
+
readonly retentionCutoffMs: number;
|
|
85
|
+
/** Starting chunk size. Not the bound — `maxDurationMs` is. */
|
|
86
|
+
readonly maxRows: number;
|
|
87
|
+
/**
|
|
88
|
+
* The statement duration target, enforced by feedback rather than by
|
|
89
|
+
* interruption: SQLite cannot yield mid-statement, so the purger measures
|
|
90
|
+
* each delete and shrinks the next batch's row budget when one overruns
|
|
91
|
+
* (see {@link SQLiteChangeLogPurger.budgetRows}) — which means the first
|
|
92
|
+
* delete after a restart, sized by `maxRows` alone, can still overrun it.
|
|
93
|
+
* The target is this consequential because purge shares the writer's
|
|
94
|
+
* connection: there is no lock to arbitrate and no `busy_timeout` to bound
|
|
95
|
+
* the wait — a long statement blocks the appending path, and the forward
|
|
96
|
+
* behind it, directly and for its full duration. That is why this is a
|
|
97
|
+
* precondition of purging from the stream loop rather than a tuning knob.
|
|
98
|
+
*/
|
|
99
|
+
readonly maxDurationMs: number;
|
|
100
|
+
};
|
|
101
|
+
export declare class SQLiteChangeLogPurger {
|
|
102
|
+
#private;
|
|
103
|
+
/**
|
|
104
|
+
* @param db a writable connection to a change log the writer has already
|
|
105
|
+
* created and reconciled — in slice 9, the writer's own connection.
|
|
106
|
+
* Statements are prepared eagerly, so a caller that may run before the
|
|
107
|
+
* log exists opens the connection lazily and treats construction failure
|
|
108
|
+
* as a skipped cycle.
|
|
109
|
+
*/
|
|
110
|
+
constructor(db: Database, now?: () => number);
|
|
111
|
+
/** The row budget the next batch would use. Exposed for tests and metrics. */
|
|
112
|
+
get budgetRows(): number | undefined;
|
|
113
|
+
/**
|
|
114
|
+
* Removes one bounded batch of aged-out history, in one `BEGIN IMMEDIATE`
|
|
115
|
+
* transaction. Callers loop while `moreEligible`, releasing whatever guards
|
|
116
|
+
* they hold between batches.
|
|
117
|
+
*/
|
|
118
|
+
purgeBatch(opts: PurgeBatchOptions): PurgeBatchResult;
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=sqlite-change-log-purger.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sqlite-change-log-purger.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-purger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,KAAK,EAAC,QAAQ,EAAY,MAAM,8BAA8B,CAAC;AAGtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,eAAO,MAAM,sCAAsC,2UASlD,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uCAAuC,4JAOnD,CAAC;AAuCF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B;;;;OAIG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5C,6FAA6F;IAC7F,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B;;;;;;;;OAQG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B;;;OAGG;IACH,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAChC,CAAC;AAWF,qBAAa,qBAAqB;;IAahC;;;;;;OAMG;gBAED,EAAE,EAAE,QAAQ,EACZ,GAAG,GAAE,MAAM,MAA0C;IAcvD,8EAA8E;IAC9E,IAAI,UAAU,IAAI,MAAM,GAAG,SAAS,CAEnC;IAED;;;;OAIG;IACH,UAAU,CAAC,IAAI,EAAE,iBAAiB,GAAG,gBAAgB;CAwMtD"}
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { assert } from "../../../../shared/src/asserts.js";
|
|
2
|
+
import { CHANGE_LOG_STREAM_TABLE } from "./change-log-db.js";
|
|
3
|
+
//#region ../zero-cache/src/services/replicator/sqlite-change-log-purger.ts
|
|
4
|
+
/**
|
|
5
|
+
* Deletes aged-out transactions from the change-log database, one bounded write
|
|
6
|
+
* transaction at a time.
|
|
7
|
+
*
|
|
8
|
+
* The purger is a pure function of one database: it takes the floors its caller
|
|
9
|
+
* has already gated on and narrows them, never widens them, and it reads no
|
|
10
|
+
* replication state. That is what makes it testable without a scheduler and
|
|
11
|
+
* what lets slice 9 run it from the change-streamer's stream loop, between the
|
|
12
|
+
* writer's commits, on the writer's own connection.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* The eligible set, as three ANDed bounds. Only the `externalFloor` is a safety
|
|
16
|
+
* property; the other two make the log serviceable and make purge conservative.
|
|
17
|
+
*
|
|
18
|
+
* `"watermark" < @externalFloor` is deliberately strict. A follower that lost
|
|
19
|
+
* its replica restores it from S3 at watermark `W` and then asks this log for
|
|
20
|
+
* everything after `W`, which requires the `commit` row *at* `W` to still be
|
|
21
|
+
* here (`SQLITE_CHANGE_LOG_BOUNDARY_SQL`). Deleting it returns `too-old` to the
|
|
22
|
+
* very subscriber the floor exists to protect.
|
|
23
|
+
*
|
|
24
|
+
* The head cap reads `max("watermark")` from the log's own database, which
|
|
25
|
+
* keeps the purger a pure function of one file. The cap is inert in normal
|
|
26
|
+
* operation: the floor is derived from a backup of a replica that consumes this
|
|
27
|
+
* loop's output, and the log commits before that output is forwarded, so
|
|
28
|
+
* `externalFloor <= head` holds by construction. It engages only on a *stale*
|
|
29
|
+
* log — writer stopped, mode flipped to `off`, another task took over — where
|
|
30
|
+
* deleting to a floor that has run past a frozen log would empty the file. Note
|
|
31
|
+
* that head can be a phantom — committed here but not yet re-deliverable by a
|
|
32
|
+
* resumed stream — for as long as it takes the watermark the stream would
|
|
33
|
+
* resume from to advance past it. That is harmless precisely because head is
|
|
34
|
+
* never a purge candidate, and it is why the purger asserts nothing about
|
|
35
|
+
* anything outside its own file.
|
|
36
|
+
*
|
|
37
|
+
* Ordered by `("writeTimeMs", "watermark")` so it rides the partial index,
|
|
38
|
+
* which carries one entry per transaction rather than one per change. The
|
|
39
|
+
* `LIMIT` keeps a drain from re-scanning the remaining history on every batch,
|
|
40
|
+
* which would be quadratic in the number of eligible transactions and would do
|
|
41
|
+
* it inside the `BEGIN IMMEDIATE`, holding the write lock alongside the delete.
|
|
42
|
+
*
|
|
43
|
+
* Exported so the focused query-plan test covers the production query.
|
|
44
|
+
*/
|
|
45
|
+
var SQLITE_CHANGE_LOG_ELIGIBLE_COMMITS_SQL = `
|
|
46
|
+
SELECT "watermark"
|
|
47
|
+
FROM "${CHANGE_LOG_STREAM_TABLE}"
|
|
48
|
+
WHERE "writeTimeMs" IS NOT NULL
|
|
49
|
+
AND "writeTimeMs" < @retentionCutoffMs
|
|
50
|
+
AND "watermark" < @externalFloor
|
|
51
|
+
AND "watermark" < (SELECT max("watermark") FROM "${CHANGE_LOG_STREAM_TABLE}")
|
|
52
|
+
ORDER BY "writeTimeMs", "watermark"
|
|
53
|
+
LIMIT @limit
|
|
54
|
+
`;
|
|
55
|
+
/**
|
|
56
|
+
* Counts the rows at `@watermark`, capped at `@limit`. The cap is what keeps
|
|
57
|
+
* batch sizing O(budget): this runs per candidate inside the
|
|
58
|
+
* `BEGIN IMMEDIATE`, and the transaction being sized can be arbitrarily
|
|
59
|
+
* large — an uncapped count of a multi-million-row backfill would rescan
|
|
60
|
+
* every remaining row on every tear batch, holding the write lock (and the
|
|
61
|
+
* appending path behind it) for the duration, quadratically over the drain.
|
|
62
|
+
* The caller only needs to know whether the transaction fits its remaining
|
|
63
|
+
* budget, so it passes `remaining + 1` and reads a count above `remaining`
|
|
64
|
+
* as "does not fit".
|
|
65
|
+
*
|
|
66
|
+
* Exported so the focused tests cover the production query.
|
|
67
|
+
*/
|
|
68
|
+
var SQLITE_CHANGE_LOG_COUNT_TRANSACTION_SQL = `
|
|
69
|
+
SELECT count(*) AS "rows" FROM (
|
|
70
|
+
SELECT 1
|
|
71
|
+
FROM "${CHANGE_LOG_STREAM_TABLE}"
|
|
72
|
+
WHERE "watermark" = @watermark
|
|
73
|
+
LIMIT @limit
|
|
74
|
+
)
|
|
75
|
+
`;
|
|
76
|
+
/**
|
|
77
|
+
* A prefix delete, so no transaction between the minimum and the head is ever
|
|
78
|
+
* split. The `<=` is correct and is not the floor comparison: `deletedThrough`
|
|
79
|
+
* is a watermark this batch already established as wholly eligible.
|
|
80
|
+
*/
|
|
81
|
+
var DELETE_THROUGH_SQL = `
|
|
82
|
+
DELETE FROM "${CHANGE_LOG_STREAM_TABLE}" WHERE "watermark" <= ?
|
|
83
|
+
`;
|
|
84
|
+
var MIN_WATERMARK_SQL = `
|
|
85
|
+
SELECT min("watermark") AS "minWatermark" FROM "${CHANGE_LOG_STREAM_TABLE}"
|
|
86
|
+
`;
|
|
87
|
+
/**
|
|
88
|
+
* The `pos` at `@offset` rows into the torn transaction, ascending. `undefined`
|
|
89
|
+
* when fewer than `@offset` rows remain, which is how the tear knows it is on
|
|
90
|
+
* its final chunk.
|
|
91
|
+
*/
|
|
92
|
+
var TEAR_BOUNDARY_SQL = `
|
|
93
|
+
SELECT "pos"
|
|
94
|
+
FROM "${CHANGE_LOG_STREAM_TABLE}"
|
|
95
|
+
WHERE "watermark" = @watermark
|
|
96
|
+
ORDER BY "pos"
|
|
97
|
+
LIMIT 1 OFFSET @offset
|
|
98
|
+
`;
|
|
99
|
+
/**
|
|
100
|
+
* A range scan on the primary key. Expressed as `"pos" < @pos` rather than
|
|
101
|
+
* `DELETE ... LIMIT n`, which is both non-portable and the wrong bound: it
|
|
102
|
+
* carries no guarantee about *which* rows it removes, and the commit row must
|
|
103
|
+
* survive until the chunk that finishes the tear.
|
|
104
|
+
*/
|
|
105
|
+
var DELETE_BELOW_POS_SQL = `
|
|
106
|
+
DELETE FROM "${CHANGE_LOG_STREAM_TABLE}"
|
|
107
|
+
WHERE "watermark" = @watermark AND "pos" < @pos
|
|
108
|
+
`;
|
|
109
|
+
var SQLiteChangeLogPurger = class {
|
|
110
|
+
#db;
|
|
111
|
+
#now;
|
|
112
|
+
#stmts;
|
|
113
|
+
/**
|
|
114
|
+
* The measured row budget, carried across batches. Row cost varies with
|
|
115
|
+
* payload size, so `maxRows` alone cannot bound a statement's duration; this
|
|
116
|
+
* shrinks when a delete overruns `maxDurationMs` and grows back when the
|
|
117
|
+
* budget — rather than the eligible set — was what limited the batch.
|
|
118
|
+
*/
|
|
119
|
+
#budgetRows;
|
|
120
|
+
/**
|
|
121
|
+
* @param db a writable connection to a change log the writer has already
|
|
122
|
+
* created and reconciled — in slice 9, the writer's own connection.
|
|
123
|
+
* Statements are prepared eagerly, so a caller that may run before the
|
|
124
|
+
* log exists opens the connection lazily and treats construction failure
|
|
125
|
+
* as a skipped cycle.
|
|
126
|
+
*/
|
|
127
|
+
constructor(db, now = performance.now.bind(performance)) {
|
|
128
|
+
this.#db = db;
|
|
129
|
+
this.#now = now;
|
|
130
|
+
this.#stmts = {
|
|
131
|
+
eligibleCommits: db.prepare(SQLITE_CHANGE_LOG_ELIGIBLE_COMMITS_SQL),
|
|
132
|
+
countTransaction: db.prepare(SQLITE_CHANGE_LOG_COUNT_TRANSACTION_SQL),
|
|
133
|
+
deleteThrough: db.prepare(DELETE_THROUGH_SQL),
|
|
134
|
+
minWatermark: db.prepare(MIN_WATERMARK_SQL),
|
|
135
|
+
tearBoundary: db.prepare(TEAR_BOUNDARY_SQL),
|
|
136
|
+
deleteBelowPos: db.prepare(DELETE_BELOW_POS_SQL)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/** The row budget the next batch would use. Exposed for tests and metrics. */
|
|
140
|
+
get budgetRows() {
|
|
141
|
+
return this.#budgetRows;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Removes one bounded batch of aged-out history, in one `BEGIN IMMEDIATE`
|
|
145
|
+
* transaction. Callers loop while `moreEligible`, releasing whatever guards
|
|
146
|
+
* they hold between batches.
|
|
147
|
+
*/
|
|
148
|
+
purgeBatch(opts) {
|
|
149
|
+
const { maxRows, maxDurationMs } = opts;
|
|
150
|
+
assert(Number.isSafeInteger(maxRows) && maxRows > 0, "change-log purge maxRows must be a positive safe integer");
|
|
151
|
+
assert(maxDurationMs > 0, "change-log purge maxDurationMs must be positive");
|
|
152
|
+
this.#db.exec("BEGIN IMMEDIATE");
|
|
153
|
+
try {
|
|
154
|
+
const result = this.#purge(opts);
|
|
155
|
+
this.#db.exec("COMMIT");
|
|
156
|
+
return result;
|
|
157
|
+
} catch (e) {
|
|
158
|
+
if (this.#db.inTransaction) this.#db.exec("ROLLBACK");
|
|
159
|
+
throw e;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
#purge(opts) {
|
|
163
|
+
const { externalFloor, retentionCutoffMs } = opts;
|
|
164
|
+
const budget = this.#budget(opts.maxRows);
|
|
165
|
+
const limit = Math.max(1, Math.ceil(budget / 2));
|
|
166
|
+
const candidates = this.#stmts.eligibleCommits.all({
|
|
167
|
+
retentionCutoffMs,
|
|
168
|
+
externalFloor,
|
|
169
|
+
limit
|
|
170
|
+
});
|
|
171
|
+
if (candidates.length === 0) return {
|
|
172
|
+
deletedRows: 0,
|
|
173
|
+
deletedThrough: void 0,
|
|
174
|
+
moreEligible: false
|
|
175
|
+
};
|
|
176
|
+
let rows = 0;
|
|
177
|
+
let deletedThrough;
|
|
178
|
+
for (const { watermark } of candidates) {
|
|
179
|
+
const remaining = budget - rows;
|
|
180
|
+
const { rows: n } = this.#stmts.countTransaction.get({
|
|
181
|
+
watermark,
|
|
182
|
+
limit: remaining + 1
|
|
183
|
+
});
|
|
184
|
+
if (n > remaining) break;
|
|
185
|
+
rows += n;
|
|
186
|
+
deletedThrough = watermark;
|
|
187
|
+
}
|
|
188
|
+
if (deletedThrough === void 0) return this.#tear(opts, budget);
|
|
189
|
+
return {
|
|
190
|
+
deletedRows: this.#timed(opts, budget, () => this.#stmts.deleteThrough.run(deletedThrough).changes),
|
|
191
|
+
deletedThrough,
|
|
192
|
+
moreEligible: this.#anyEligible(opts)
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Removes one bounded chunk of the minimum transaction, which is the only
|
|
197
|
+
* transaction that is ever torn.
|
|
198
|
+
*
|
|
199
|
+
* A single upstream transaction can be arbitrarily large — a backfill, a
|
|
200
|
+
* schema migration — and SQLite cannot yield mid-statement, so the only way
|
|
201
|
+
* to bound the lock hold is to delete it across several statements. That is
|
|
202
|
+
* unobservable given three constraints, all of which live here:
|
|
203
|
+
*
|
|
204
|
+
* 1. Only `min("watermark")` is torn, so at most one transaction is ever
|
|
205
|
+
* partial. A reader never reads *into* a transaction — `read()` starts
|
|
206
|
+
* strictly after `(fromWatermark, MAX_SAFE_INTEGER)` — so the only
|
|
207
|
+
* transaction a tear can touch is one a subscriber reads *from*, and
|
|
208
|
+
* reading from it does not read its rows.
|
|
209
|
+
* 2. Rows go ascending by `pos`, commit row last. `plan()`'s boundary check
|
|
210
|
+
* reads the *highest* `pos` at the watermark and requires it to be the
|
|
211
|
+
* `commit`; removing that row first would give a subscriber sitting
|
|
212
|
+
* exactly there a spurious `too-old`.
|
|
213
|
+
* 3. The commit row is removed by a prefix delete, which advances
|
|
214
|
+
* `min("watermark")` in the same SQLite transaction, so no state exposes
|
|
215
|
+
* the boundary as gone while the minimum still points at it. Normally that
|
|
216
|
+
* is {@link SQLiteChangeLogPurger.purgeBatch}'s ordinary whole-transaction
|
|
217
|
+
* delete, taken on the batch where what is left of the torn transaction
|
|
218
|
+
* finally fits the budget; the branch below is the same delete for the
|
|
219
|
+
* case where the minimum is not itself in the eligible set.
|
|
220
|
+
*
|
|
221
|
+
* A crash mid-tear needs no recovery state: the torn transaction is still the
|
|
222
|
+
* minimum and still eligible, so the next batch continues it. Reconciliation
|
|
223
|
+
* is unaffected — it tests the head, and a tear is at the tail.
|
|
224
|
+
*
|
|
225
|
+
* Tearing the minimum is safe even in the unusual case where it is not itself
|
|
226
|
+
* in the eligible set (a writer whose clock went backwards can put a later
|
|
227
|
+
* watermark at an earlier `writeTimeMs`). Both watermark bounds are
|
|
228
|
+
* prefix-closed — a non-empty eligible set implies `min < externalFloor` and
|
|
229
|
+
* `min < head` — and the prefix delete this batch would otherwise run removes
|
|
230
|
+
* the minimum anyway. Only the time floor, which is a minimum-retention
|
|
231
|
+
* courtesy rather than a safety property, can be crossed that way.
|
|
232
|
+
*/
|
|
233
|
+
#tear(opts, budget) {
|
|
234
|
+
const { minWatermark } = this.#stmts.minWatermark.get();
|
|
235
|
+
assert(minWatermark !== null, "change-log purge found eligible transactions in an empty log");
|
|
236
|
+
const boundary = this.#stmts.tearBoundary.get({
|
|
237
|
+
watermark: minWatermark,
|
|
238
|
+
offset: budget
|
|
239
|
+
});
|
|
240
|
+
if (boundary === void 0) return {
|
|
241
|
+
deletedRows: this.#timed(opts, budget, () => this.#stmts.deleteThrough.run(minWatermark).changes),
|
|
242
|
+
deletedThrough: minWatermark,
|
|
243
|
+
moreEligible: this.#anyEligible(opts)
|
|
244
|
+
};
|
|
245
|
+
return {
|
|
246
|
+
deletedRows: this.#timed(opts, budget, () => this.#stmts.deleteBelowPos.run({
|
|
247
|
+
watermark: minWatermark,
|
|
248
|
+
pos: boundary.pos
|
|
249
|
+
}).changes),
|
|
250
|
+
deletedThrough: void 0,
|
|
251
|
+
moreEligible: true
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
#anyEligible({ externalFloor, retentionCutoffMs }) {
|
|
255
|
+
return this.#stmts.eligibleCommits.get({
|
|
256
|
+
retentionCutoffMs,
|
|
257
|
+
externalFloor,
|
|
258
|
+
limit: 1
|
|
259
|
+
}) !== void 0;
|
|
260
|
+
}
|
|
261
|
+
#budget(maxRows) {
|
|
262
|
+
return Math.max(1, Math.min(maxRows, this.#budgetRows ?? maxRows));
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Runs a delete and feeds its measured duration back into the row budget.
|
|
266
|
+
* Growth is gated on the budget having been the binding constraint: a batch
|
|
267
|
+
* that finished quickly because only four rows were eligible is no evidence
|
|
268
|
+
* that a larger statement would stay under the target.
|
|
269
|
+
*/
|
|
270
|
+
#timed({ maxRows, maxDurationMs }, budget, run) {
|
|
271
|
+
const start = this.#now();
|
|
272
|
+
const deletedRows = run();
|
|
273
|
+
const elapsedMs = this.#now() - start;
|
|
274
|
+
if (elapsedMs > maxDurationMs) this.#budgetRows = Math.max(1, Math.floor(budget / 2));
|
|
275
|
+
else if (deletedRows >= budget && elapsedMs * 2 <= maxDurationMs) this.#budgetRows = Math.min(maxRows, budget * 2);
|
|
276
|
+
else this.#budgetRows = budget;
|
|
277
|
+
return deletedRows;
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
//#endregion
|
|
281
|
+
export { SQLiteChangeLogPurger };
|
|
282
|
+
|
|
283
|
+
//# sourceMappingURL=sqlite-change-log-purger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sqlite-change-log-purger.js","names":["#db","#now","#stmts","#budgetRows","#purge","#budget","#tear","#timed","#anyEligible"],"sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-purger.ts"],"sourcesContent":["/**\n * Deletes aged-out transactions from the change-log database, one bounded write\n * transaction at a time.\n *\n * The purger is a pure function of one database: it takes the floors its caller\n * has already gated on and narrows them, never widens them, and it reads no\n * replication state. That is what makes it testable without a scheduler and\n * what lets slice 9 run it from the change-streamer's stream loop, between the\n * writer's commits, on the writer's own connection.\n */\n\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport type {Database, Statement} from '../../../../zqlite/src/db.ts';\nimport {CHANGE_LOG_STREAM_TABLE} from './change-log-db.ts';\n\n/**\n * The eligible set, as three ANDed bounds. Only the `externalFloor` is a safety\n * property; the other two make the log serviceable and make purge conservative.\n *\n * `\"watermark\" < @externalFloor` is deliberately strict. A follower that lost\n * its replica restores it from S3 at watermark `W` and then asks this log for\n * everything after `W`, which requires the `commit` row *at* `W` to still be\n * here (`SQLITE_CHANGE_LOG_BOUNDARY_SQL`). Deleting it returns `too-old` to the\n * very subscriber the floor exists to protect.\n *\n * The head cap reads `max(\"watermark\")` from the log's own database, which\n * keeps the purger a pure function of one file. The cap is inert in normal\n * operation: the floor is derived from a backup of a replica that consumes this\n * loop's output, and the log commits before that output is forwarded, so\n * `externalFloor <= head` holds by construction. It engages only on a *stale*\n * log — writer stopped, mode flipped to `off`, another task took over — where\n * deleting to a floor that has run past a frozen log would empty the file. Note\n * that head can be a phantom — committed here but not yet re-deliverable by a\n * resumed stream — for as long as it takes the watermark the stream would\n * resume from to advance past it. That is harmless precisely because head is\n * never a purge candidate, and it is why the purger asserts nothing about\n * anything outside its own file.\n *\n * Ordered by `(\"writeTimeMs\", \"watermark\")` so it rides the partial index,\n * which carries one entry per transaction rather than one per change. The\n * `LIMIT` keeps a drain from re-scanning the remaining history on every batch,\n * which would be quadratic in the number of eligible transactions and would do\n * it inside the `BEGIN IMMEDIATE`, holding the write lock alongside the delete.\n *\n * Exported so the focused query-plan test covers the production query.\n */\nexport const SQLITE_CHANGE_LOG_ELIGIBLE_COMMITS_SQL = /*sql*/ `\n SELECT \"watermark\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"writeTimeMs\" IS NOT NULL\n AND \"writeTimeMs\" < @retentionCutoffMs\n AND \"watermark\" < @externalFloor\n AND \"watermark\" < (SELECT max(\"watermark\") FROM \"${CHANGE_LOG_STREAM_TABLE}\")\n ORDER BY \"writeTimeMs\", \"watermark\"\n LIMIT @limit\n`;\n\n/**\n * Counts the rows at `@watermark`, capped at `@limit`. The cap is what keeps\n * batch sizing O(budget): this runs per candidate inside the\n * `BEGIN IMMEDIATE`, and the transaction being sized can be arbitrarily\n * large — an uncapped count of a multi-million-row backfill would rescan\n * every remaining row on every tear batch, holding the write lock (and the\n * appending path behind it) for the duration, quadratically over the drain.\n * The caller only needs to know whether the transaction fits its remaining\n * budget, so it passes `remaining + 1` and reads a count above `remaining`\n * as \"does not fit\".\n *\n * Exported so the focused tests cover the production query.\n */\nexport const SQLITE_CHANGE_LOG_COUNT_TRANSACTION_SQL = /*sql*/ `\n SELECT count(*) AS \"rows\" FROM (\n SELECT 1\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" = @watermark\n LIMIT @limit\n )\n`;\n\n/**\n * A prefix delete, so no transaction between the minimum and the head is ever\n * split. The `<=` is correct and is not the floor comparison: `deletedThrough`\n * is a watermark this batch already established as wholly eligible.\n */\nconst DELETE_THROUGH_SQL = /*sql*/ `\n DELETE FROM \"${CHANGE_LOG_STREAM_TABLE}\" WHERE \"watermark\" <= ?\n`;\n\nconst MIN_WATERMARK_SQL = /*sql*/ `\n SELECT min(\"watermark\") AS \"minWatermark\" FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n`;\n\n/**\n * The `pos` at `@offset` rows into the torn transaction, ascending. `undefined`\n * when fewer than `@offset` rows remain, which is how the tear knows it is on\n * its final chunk.\n */\nconst TEAR_BOUNDARY_SQL = /*sql*/ `\n SELECT \"pos\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" = @watermark\n ORDER BY \"pos\"\n LIMIT 1 OFFSET @offset\n`;\n\n/**\n * A range scan on the primary key. Expressed as `\"pos\" < @pos` rather than\n * `DELETE ... LIMIT n`, which is both non-portable and the wrong bound: it\n * carries no guarantee about *which* rows it removes, and the commit row must\n * survive until the chunk that finishes the tear.\n */\nconst DELETE_BELOW_POS_SQL = /*sql*/ `\n DELETE FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n WHERE \"watermark\" = @watermark AND \"pos\" < @pos\n`;\n\nexport type PurgeBatchResult = {\n readonly deletedRows: number;\n /**\n * The watermark through which whole transactions were removed. `undefined`\n * when the batch only tore rows off the minimum transaction without\n * completing it — in that case `deletedRows > 0` and `moreEligible` is true.\n */\n readonly deletedThrough: string | undefined;\n /** True while a tear is in progress, as well as while whole transactions remain eligible. */\n readonly moreEligible: boolean;\n};\n\nexport type PurgeBatchOptions = {\n /**\n * The floor the caller has already gated on subscriber ACKs and snapshot\n * reservations — normally the confirmed S3 backup watermark. Transactions at\n * or above it are NOT durable anywhere else: the change log is excluded from\n * the litestream backup, so this is the boundary a follower restores to and\n * then catches up from. Compared strictly (`<`), so the transaction *at* the\n * floor survives as that follower's catchup boundary. The purger narrows this\n * input and never widens it.\n */\n readonly externalFloor: string;\n /**\n * A *minimum* retention, ANDed on top of `externalFloor` rather than an\n * alternative to it. Which of the two binds depends on the backup interval.\n */\n readonly retentionCutoffMs: number;\n /** Starting chunk size. Not the bound — `maxDurationMs` is. */\n readonly maxRows: number;\n /**\n * The statement duration target, enforced by feedback rather than by\n * interruption: SQLite cannot yield mid-statement, so the purger measures\n * each delete and shrinks the next batch's row budget when one overruns\n * (see {@link SQLiteChangeLogPurger.budgetRows}) — which means the first\n * delete after a restart, sized by `maxRows` alone, can still overrun it.\n * The target is this consequential because purge shares the writer's\n * connection: there is no lock to arbitrate and no `busy_timeout` to bound\n * the wait — a long statement blocks the appending path, and the forward\n * behind it, directly and for its full duration. That is why this is a\n * precondition of purging from the stream loop rather than a tuning knob.\n */\n readonly maxDurationMs: number;\n};\n\ntype Statements = {\n readonly eligibleCommits: Statement;\n readonly countTransaction: Statement;\n readonly deleteThrough: Statement;\n readonly minWatermark: Statement;\n readonly tearBoundary: Statement;\n readonly deleteBelowPos: Statement;\n};\n\nexport class SQLiteChangeLogPurger {\n readonly #db: Database;\n readonly #now: () => number;\n readonly #stmts: Statements;\n\n /**\n * The measured row budget, carried across batches. Row cost varies with\n * payload size, so `maxRows` alone cannot bound a statement's duration; this\n * shrinks when a delete overruns `maxDurationMs` and grows back when the\n * budget — rather than the eligible set — was what limited the batch.\n */\n #budgetRows: number | undefined;\n\n /**\n * @param db a writable connection to a change log the writer has already\n * created and reconciled — in slice 9, the writer's own connection.\n * Statements are prepared eagerly, so a caller that may run before the\n * log exists opens the connection lazily and treats construction failure\n * as a skipped cycle.\n */\n constructor(\n db: Database,\n now: () => number = performance.now.bind(performance),\n ) {\n this.#db = db;\n this.#now = now;\n this.#stmts = {\n eligibleCommits: db.prepare(SQLITE_CHANGE_LOG_ELIGIBLE_COMMITS_SQL),\n countTransaction: db.prepare(SQLITE_CHANGE_LOG_COUNT_TRANSACTION_SQL),\n deleteThrough: db.prepare(DELETE_THROUGH_SQL),\n minWatermark: db.prepare(MIN_WATERMARK_SQL),\n tearBoundary: db.prepare(TEAR_BOUNDARY_SQL),\n deleteBelowPos: db.prepare(DELETE_BELOW_POS_SQL),\n };\n }\n\n /** The row budget the next batch would use. Exposed for tests and metrics. */\n get budgetRows(): number | undefined {\n return this.#budgetRows;\n }\n\n /**\n * Removes one bounded batch of aged-out history, in one `BEGIN IMMEDIATE`\n * transaction. Callers loop while `moreEligible`, releasing whatever guards\n * they hold between batches.\n */\n purgeBatch(opts: PurgeBatchOptions): PurgeBatchResult {\n const {maxRows, maxDurationMs} = opts;\n assert(\n Number.isSafeInteger(maxRows) && maxRows > 0,\n 'change-log purge maxRows must be a positive safe integer',\n );\n assert(\n maxDurationMs > 0,\n 'change-log purge maxDurationMs must be positive',\n );\n\n this.#db.exec('BEGIN IMMEDIATE');\n try {\n const result = this.#purge(opts);\n this.#db.exec('COMMIT');\n return result;\n } catch (e) {\n if (this.#db.inTransaction) {\n this.#db.exec('ROLLBACK');\n }\n throw e;\n }\n }\n\n #purge(opts: PurgeBatchOptions): PurgeBatchResult {\n const {externalFloor, retentionCutoffMs} = opts;\n const budget = this.#budget(opts.maxRows);\n // Each transaction is at least a `begin` and a `commit`, so this is the\n // most candidates that can fit in the budget.\n const limit = Math.max(1, Math.ceil(budget / 2));\n const candidates = this.#stmts.eligibleCommits.all<{watermark: string}>({\n retentionCutoffMs,\n externalFloor,\n limit,\n });\n if (candidates.length === 0) {\n return {deletedRows: 0, deletedThrough: undefined, moreEligible: false};\n }\n\n // Accounted per candidate rather than per prefix, which is exact as long as\n // the candidates arrive in watermark order — they do, because the single\n // writer stamps `writeTimeMs` at commit time. A clock that went backwards\n // can put a non-candidate below `deletedThrough`, and the prefix delete\n // then removes more rows than were counted. Not a safety problem: both\n // watermark bounds are prefix-closed, only the minimum-retention courtesy\n // is crossed, and `maxRows` is the starting chunk size rather than the\n // bound — `maxDurationMs` is, and the governor measures what actually ran.\n let rows = 0;\n let deletedThrough: string | undefined;\n for (const {watermark} of candidates) {\n // The count is capped at one past the remaining budget: `n > remaining`\n // is exactly `rows + n > budget` for a fitting transaction, and a\n // too-large one stops scanning as soon as it is known not to fit.\n const remaining = budget - rows;\n const {rows: n} = this.#stmts.countTransaction.get<{rows: number}>({\n watermark,\n limit: remaining + 1,\n });\n if (n > remaining) {\n break;\n }\n rows += n;\n deletedThrough = watermark;\n }\n\n if (deletedThrough === undefined) {\n return this.#tear(opts, budget);\n }\n const deletedRows = this.#timed(\n opts,\n budget,\n () => this.#stmts.deleteThrough.run(deletedThrough).changes,\n );\n return {\n deletedRows,\n deletedThrough,\n moreEligible: this.#anyEligible(opts),\n };\n }\n\n /**\n * Removes one bounded chunk of the minimum transaction, which is the only\n * transaction that is ever torn.\n *\n * A single upstream transaction can be arbitrarily large — a backfill, a\n * schema migration — and SQLite cannot yield mid-statement, so the only way\n * to bound the lock hold is to delete it across several statements. That is\n * unobservable given three constraints, all of which live here:\n *\n * 1. Only `min(\"watermark\")` is torn, so at most one transaction is ever\n * partial. A reader never reads *into* a transaction — `read()` starts\n * strictly after `(fromWatermark, MAX_SAFE_INTEGER)` — so the only\n * transaction a tear can touch is one a subscriber reads *from*, and\n * reading from it does not read its rows.\n * 2. Rows go ascending by `pos`, commit row last. `plan()`'s boundary check\n * reads the *highest* `pos` at the watermark and requires it to be the\n * `commit`; removing that row first would give a subscriber sitting\n * exactly there a spurious `too-old`.\n * 3. The commit row is removed by a prefix delete, which advances\n * `min(\"watermark\")` in the same SQLite transaction, so no state exposes\n * the boundary as gone while the minimum still points at it. Normally that\n * is {@link SQLiteChangeLogPurger.purgeBatch}'s ordinary whole-transaction\n * delete, taken on the batch where what is left of the torn transaction\n * finally fits the budget; the branch below is the same delete for the\n * case where the minimum is not itself in the eligible set.\n *\n * A crash mid-tear needs no recovery state: the torn transaction is still the\n * minimum and still eligible, so the next batch continues it. Reconciliation\n * is unaffected — it tests the head, and a tear is at the tail.\n *\n * Tearing the minimum is safe even in the unusual case where it is not itself\n * in the eligible set (a writer whose clock went backwards can put a later\n * watermark at an earlier `writeTimeMs`). Both watermark bounds are\n * prefix-closed — a non-empty eligible set implies `min < externalFloor` and\n * `min < head` — and the prefix delete this batch would otherwise run removes\n * the minimum anyway. Only the time floor, which is a minimum-retention\n * courtesy rather than a safety property, can be crossed that way.\n */\n #tear(opts: PurgeBatchOptions, budget: number): PurgeBatchResult {\n const {minWatermark} = this.#stmts.minWatermark.get<{\n minWatermark: string | null;\n }>();\n assert(\n minWatermark !== null,\n 'change-log purge found eligible transactions in an empty log',\n );\n\n const boundary = this.#stmts.tearBoundary.get<{pos: number} | undefined>({\n watermark: minWatermark,\n offset: budget,\n });\n if (boundary === undefined) {\n // At most `budget` rows are left at the minimum, which is reachable only\n // when the minimum is not the transaction that failed to fit — i.e. when\n // it is not itself eligible. The prefix delete removes it whole and\n // advances `min(\"watermark\")`.\n const deletedRows = this.#timed(\n opts,\n budget,\n () => this.#stmts.deleteThrough.run(minWatermark).changes,\n );\n return {\n deletedRows,\n deletedThrough: minWatermark,\n moreEligible: this.#anyEligible(opts),\n };\n }\n // `boundary.pos` is the `budget`-th row by `pos`, so this removes exactly\n // `budget` rows and always makes progress. The commit row is the highest\n // `pos`, so it can only be reached by the branch above.\n const deletedRows = this.#timed(\n opts,\n budget,\n () =>\n this.#stmts.deleteBelowPos.run({\n watermark: minWatermark,\n pos: boundary.pos,\n }).changes,\n );\n return {deletedRows, deletedThrough: undefined, moreEligible: true};\n }\n\n #anyEligible({externalFloor, retentionCutoffMs}: PurgeBatchOptions): boolean {\n return (\n this.#stmts.eligibleCommits.get<{watermark: string} | undefined>({\n retentionCutoffMs,\n externalFloor,\n limit: 1,\n }) !== undefined\n );\n }\n\n #budget(maxRows: number): number {\n return Math.max(1, Math.min(maxRows, this.#budgetRows ?? maxRows));\n }\n\n /**\n * Runs a delete and feeds its measured duration back into the row budget.\n * Growth is gated on the budget having been the binding constraint: a batch\n * that finished quickly because only four rows were eligible is no evidence\n * that a larger statement would stay under the target.\n */\n #timed(\n {maxRows, maxDurationMs}: PurgeBatchOptions,\n budget: number,\n run: () => number,\n ): number {\n const start = this.#now();\n const deletedRows = run();\n const elapsedMs = this.#now() - start;\n\n if (elapsedMs > maxDurationMs) {\n this.#budgetRows = Math.max(1, Math.floor(budget / 2));\n } else if (deletedRows >= budget && elapsedMs * 2 <= maxDurationMs) {\n this.#budgetRows = Math.min(maxRows, budget * 2);\n } else {\n this.#budgetRows = budget;\n }\n return deletedRows;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,IAAa,yCAAiD;;UAEpD,wBAAwB;;;;uDAIqB,wBAAwB;;;;;;;;;;;;;;;;;AAkB/E,IAAa,0CAAkD;;;YAGnD,wBAAwB;;;;;;;;;;AAWpC,IAAM,qBAA6B;iBAClB,wBAAwB;;AAGzC,IAAM,oBAA4B;oDACkB,wBAAwB;;;;;;;AAQ5E,IAAM,oBAA4B;;UAExB,wBAAwB;;;;;;;;;;;AAYlC,IAAM,uBAA+B;iBACpB,wBAAwB;;;AA0DzC,IAAa,wBAAb,MAAmC;CACjC;CACA;CACA;;;;;;;CAQA;;;;;;;;CASA,YACE,IACA,MAAoB,YAAY,IAAI,KAAK,WAAW,GACpD;EACA,KAAKA,MAAM;EACX,KAAKC,OAAO;EACZ,KAAKC,SAAS;GACZ,iBAAiB,GAAG,QAAQ,sCAAsC;GAClE,kBAAkB,GAAG,QAAQ,uCAAuC;GACpE,eAAe,GAAG,QAAQ,kBAAkB;GAC5C,cAAc,GA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riptionState } from "./schema/replication-state.js";
|
|
|
4
4
|
import { StatementRunner } from "../../db/statements.js";
|
|
5
5
|
import { isSQLiteCorruption, logSQLiteCorruptionDiagnostics, registerSQLiteCorruptionDiagnosticTarget } from "../../db/sqlite-corruption.js";
|
|
6
6
|
import { createLogContext } from "../../server/logging.js";
|
|
7
|
+
import { deleteLiteDB } from "../../db/delete-lite-db.js";
|
|
7
8
|
import { ChangeProcessor } from "./change-processor.js";
|
|
8
9
|
import { applyPragmas, serializeError } from "./write-worker-client.js";
|
|
9
10
|
import { parentPort } from "node:worker_threads";
|
|
@@ -17,13 +18,24 @@ function createAPI() {
|
|
|
17
18
|
let mode;
|
|
18
19
|
let lc;
|
|
19
20
|
let replicaDbPath;
|
|
20
|
-
let
|
|
21
|
-
function
|
|
22
|
-
|
|
21
|
+
let unregisterCorruptionDiagnosticTargets = [];
|
|
22
|
+
function unregisterCorruptionDiagnostics() {
|
|
23
|
+
unregisterCorruptionDiagnosticTargets.forEach((unregister) => unregister());
|
|
24
|
+
unregisterCorruptionDiagnosticTargets = [];
|
|
25
|
+
}
|
|
26
|
+
function handleCorruptedDb(err) {
|
|
27
|
+
if (!lc || !replicaDbPath || !isSQLiteCorruption(err)) return;
|
|
28
|
+
logSQLiteCorruptionDiagnostics(lc, "write-worker", replicaDbPath, err);
|
|
29
|
+
try {
|
|
30
|
+
lc.warn?.(`deleting corrupted db at ${replicaDbPath}`);
|
|
31
|
+
deleteLiteDB(replicaDbPath);
|
|
32
|
+
} catch (e) {
|
|
33
|
+
lc.warn?.(`error deleting corrupted db at ${replicaDbPath}`, e);
|
|
34
|
+
}
|
|
23
35
|
}
|
|
24
36
|
function createProcessor() {
|
|
25
37
|
processor = new ChangeProcessor(must(runner), must(mode), (_lc, err) => {
|
|
26
|
-
|
|
38
|
+
handleCorruptedDb(err);
|
|
27
39
|
port.postMessage({ writeError: serializeError(err) });
|
|
28
40
|
});
|
|
29
41
|
}
|
|
@@ -31,11 +43,11 @@ function createAPI() {
|
|
|
31
43
|
init(dbPath, cpMode, pragmas, logConfig) {
|
|
32
44
|
replicaDbPath = dbPath;
|
|
33
45
|
lc = createLogContext({ log: logConfig }, "write-worker");
|
|
34
|
-
|
|
35
|
-
|
|
46
|
+
unregisterCorruptionDiagnostics();
|
|
47
|
+
unregisterCorruptionDiagnosticTargets.push(registerSQLiteCorruptionDiagnosticTarget({
|
|
36
48
|
debugName: "write-worker",
|
|
37
49
|
dbPath
|
|
38
|
-
});
|
|
50
|
+
}));
|
|
39
51
|
try {
|
|
40
52
|
db = new Database(lc, dbPath);
|
|
41
53
|
applyPragmas(db, pragmas);
|
|
@@ -43,7 +55,7 @@ function createAPI() {
|
|
|
43
55
|
mode = cpMode;
|
|
44
56
|
createProcessor();
|
|
45
57
|
} catch (e) {
|
|
46
|
-
|
|
58
|
+
handleCorruptedDb(e);
|
|
47
59
|
throw e;
|
|
48
60
|
}
|
|
49
61
|
},
|
|
@@ -51,7 +63,7 @@ function createAPI() {
|
|
|
51
63
|
try {
|
|
52
64
|
return getSubscriptionState(must(runner));
|
|
53
65
|
} catch (e) {
|
|
54
|
-
|
|
66
|
+
handleCorruptedDb(e);
|
|
55
67
|
throw e;
|
|
56
68
|
}
|
|
57
69
|
},
|
|
@@ -59,7 +71,7 @@ function createAPI() {
|
|
|
59
71
|
try {
|
|
60
72
|
return must(processor).processMessage(must(lc), downstream);
|
|
61
73
|
} catch (e) {
|
|
62
|
-
|
|
74
|
+
handleCorruptedDb(e);
|
|
63
75
|
throw e;
|
|
64
76
|
}
|
|
65
77
|
},
|
|
@@ -73,8 +85,7 @@ function createAPI() {
|
|
|
73
85
|
runner = void 0;
|
|
74
86
|
processor = void 0;
|
|
75
87
|
replicaDbPath = void 0;
|
|
76
|
-
|
|
77
|
-
unregisterCorruptionDiagnosticTarget = void 0;
|
|
88
|
+
unregisterCorruptionDiagnostics();
|
|
78
89
|
}
|
|
79
90
|
};
|
|
80
91
|
}
|