carlos / platform Public

Replica silently loses pages when an app writes before Replicate starts Issue open

On branch fix/replica-wake-gap

What happened

On flagship, an app switched to scale-to-zero and deployed a release that runs a large schema migration on boot. Since then every carlos db query / db pull of its newest copy fails: "the restored copy failed its check: integrity_check: database disk image is malformed". The live database is fine. Restores --at any time before the deploy succeed; any time after it fails.

Root cause (lease / litestream, not dbdoor)

The wake spawns the process (activator doWakeOnce step 4) before Held.Replicate (step 5), and litestream's first sync then waits a full dbMonitorInterval (10 s). In that window nothing holds litestream's read lock. The boot migration wrote over 1000 WAL frames, SQLite's autocheckpoint copied them into the database file, and the next write restarted the WAL. litestream v0.5.14 verifyWithExecutor sees the salt change, finds the frame at its last offset still intact (lastPageMatch true, detectFullCheckpoint false), and carries on incrementally from the new WAL. The migrated pages never reach the replica.

Evidence from the replica: the hour's L1 file holds 46 pages, page 1 among them (schema cookie 228 to 550, freelist 981 to 771). The pages the new schema points to, such as sqlite_master's new right child, are missing. Applying that one L1 file to a good restore of the previous TXID reproduces "malformed" locally. The TXID chain is continuous, and only one database file was ever replicated.

Not the cause: dbdoor's restore path, generation mixing, or a second database file. The app's env var naming a new DB file had no effect, because the activator passes an absolute --db, which rastrillo's flag handling prefers over Options.DBPath. The migration ran on the existing file.

Fix on this branch (8d5eaaa6)

Held.Replicate now forces the first sync before it returns, bounded at 30 s and only logged on failure unless a gap is known. That shuts the window at Replicate rather than 10 s later. If that sync carried on incrementally into another WAL generation than the newest local L0, it writes a snapshot at once, so the newest restore starts from the snapshot. If litestream wrote a full image by itself, nothing extra happens. TestReplicateAfterUnreplicatedWALRestartRestoresWhole is red before and green after. The lease package and the activator/host tests that use a real lease pass.

Still owed / follow-ups

  • Census overlay: TestPlan14RootReadCensus flags internal/lease (4 new file reads, Held.Replicate changed).
  • HA leases are excluded for now (their kept-wake request sets are pinned by tests); Held.Checkpoint has the same hazard.
  • Residual: a restart during spawn is now caught after the fact by the snapshot. The structural fix is to attach the replicator before the process starts.
  • Replicas already affected heal at the next L9 snapshot (taken from the live file, daily at 00:00 UTC while awake). Until then, restores of the newest copy, and of any time after the gap, fail. Nothing in the fix repairs an existing poisoned chain.

Round 2: replicate before start (f1fe437e)

The review of 8d5eaaa6 asked for rework: a failed repair lost its evidence, missing metadata disabled the check, a timeout let the process run unprotected, and HA and Checkpoint were exempt. Round 2 drops the gap repair and changes the order instead. Design note: docs/superpowers/specs/2026-11-19-replicate-before-start.md.

The invariant. A replica either continues, without a gap, the WAL its last clean close left, or restarts from a full image of the live file. A start does not serve until one of the two holds.

  • Clean record. A close whose final sync and store close succeed writes carlos-clean.json in the litestream meta directory. It records the newest local L0 TXID and the size and mtime of the database and its WAL. Every start of replication deletes it first, durably. A crash, a lost meta directory, a restore, an outside write, or a repair that failed or timed out all leave no matching record, so the next start takes a full image. The decision is never inferred from what local state happens to be left.
  • Start pin. The ordinary wake calls ProtectStart after restore and before the seed, any release command and the process. If the files match the record, it holds a SQLite read transaction. While that reader is held, the WAL can restart at most once and nothing written after it can be backfilled, so every boot write stays in the WAL. Replicate takes the pin over and drops it only once litestream's own read lock is held. If ProtectStart cannot protect the database, nothing starts.
  • Replicate and Checkpoint, HA included. Both force a bounded first sync (30 s). When continuity is not proven, they need a full image before returning: litestream's own first file if it holds every page, otherwise a level-9 snapshot (bounded at 2 min). Any failure fails the start, and the process is stopped by the existing failed-wake cleanup.
  • First start. The process starts first, and a full image is taken before the wake serves. A bootstrap file would fix page size, auto_vacuum and encoding before the app chooses them, and would break the "no file means fresh" rule that seeds rely on.
  • Already-broken replicas. Releases before this one never wrote a record. So each database's first start after the upgrade takes a full image, and its newest restore heals.
  • Claim wake. Claims are off on every box, so it is not reordered. With no pin, Replicate decides continuity itself and takes the image before Publish.

Behaviour change. litestream's init reads the replica's position, so a replica that cannot be reached now fails a wake. Before, the wake served and replication lagged.

Tests. Each regression test below fails on main's order:

  • TestReplicateAfterUnreplicatedWALRestartRestoresWhole
  • TestGapRepairFailureIsRetried
  • TestReplicateWithoutLocalMetadataRestoresWhole
  • TestGapRepairTimeoutFailsReplicateAndIsRetried
  • TestCheckpointAcrossGapRestoresWhole
  • TestHAReplicateAcrossGapRestoresWhole

New-behaviour tests: TestProtectStartKeepsBootWritesWithoutSnapshot, TestProtectStartRefusesContinuityAfterOutsideWrites, TestWakeProtectsTheDatabaseBeforeAnythingStarts and TestWakeThatCannotProtectStartsNothing.

Four existing tests were adjusted for the earlier first sync: two size-identical event lists gain "protect"; the HA wake-path filter ignores level 1-8 compaction PUTs; two fence rigs ship or break the replica after Replicate. The internal/lease package passes. In internal/activator, three tests fail identically without this change (escrow burst timing, two over-long socket paths). The internal/host move and claim tests pass, and the darwin and windows builds succeed.

Census. Overlay plan14-root-reads-replica-wake-gap.tsv, card docs/superpowers/notes/census-proposal-replica-wake-gap.md. It needs the reviewer's verdict. Not merged, not deployed.

Round 3 fixes (57e32c89)

These address the review of f1fe437e. Each new test fails on f1fe437e and passes here.

  • H1. Replicate and Checkpoint with no pending protection now pin before they compare the record, and hold the pin through the first sync. A database that cannot be pinned counts as not continuous. Test: TestUnpinnedReplicateRacingAProcessRestoresWhole. The spec's claim-wake paragraph is corrected.
  • H2. The full image's time bound is 2 min plus the database size at 1 MiB/s (imageBudget). Test: TestFullImageBudgetScalesWithDatabaseSize, a large database under a slow store.
  • M1. The record is written with os.CreateTemp (O_EXCL) and a rename, and trusted only when Lstat shows a regular file. Test: TestCleanRecordIgnoresPlantedSymlinks.
  • M2. The record lives in the agent's own directory (SetContinuityDir, <data>/.continuity, named from the database path), outside the app's tree. With no directory set, nothing is trusted. Test: TestForgedCleanRecordIsNotTrusted.
  • M3. When litestream's first file is the full image, Replicate waits for the replica position to show it uploaded, within the size-scaled budget. It watches the position rather than syncing a second time, because a second sync deadlocks behind the monitor's hung upload. A one-shot store with no monitor (a checkpoint) syncs itself. Test: TestFullImageUploadIsConfirmedBeforeServing (a first start, and a gap with the WAL removed).
  • Retries. A pinned, continuous start retries a failed first sync within firstSyncTimeout. An unproven start fails at once. Test: TestPinnedReplicateRetriesATransientReplicaRead. The design note says read-only serving is not a fallback, because apps migrate on boot.

Existing tests adjusted. Where a replica refused writes from the start, it now starts refusing after Replicate (two fleet tests, two fence rigs, TestCloseProvenEmptyNeedsBothHalves). The HA wake-path filter ignores litestream's level 0-8 files. One first-wake check ignores the store's own first snapshot. TestGenerationWriterRunsRetention accepts snapshot-retention deletes inside the generation.

Results. The lease package passes. The targeted host move, claim and checkpoint tests pass, and the darwin and windows builds succeed. In activator, only the three tests that also fail on main fail. The census overlay replica-wake-gap-r3 needs the reviewer's verdict. Not merged.

06ddc062: merge blockers cleared (not merged)

  • Census. Both overlays were re-proposed from a clean tree, with no . re-pin. The reviewer's verdict is recorded on #280.
  • TestHAWakeRequestCounts is now deterministic. The store's background passes are set aside by level, and each wake's single image upload is counted exactly. It passed 10 of 10 runs.
  • TestCloseProvenEmptyNeedsBothHalves has its unproven-close half back. The bucket takes the first image, then refuses, and the close returns ErrCheckpointUnproven.

For the release. An HA kept wake now uploads the whole database inside the wake. The HA release truncates the WAL, so the kept copy can't be pinned and the wake takes a full image. That upload has a minimum budget of 2 minutes, plus the database size at 1 MiB/s, while the wake wait is 30 s. Before this ships, measure wake time and upload size on a dev HA host with a realistically sized database. If kept HA wakes run past the wake wait, the next design question is how to make them continuous: the WAL would need to survive the release, or a record taken after the truncate would need to be trustworthy.

CI passed at 567c8c47. Not merged.

After 06ddc062, CI needed four more changes:

  • Pool-withdrawal test. TestPoolWithdrawalRequiresCompleteProof/failed-publication relied on the files publisher still being busy when the test stopped it. It now writes a change the stopped publisher never saw, so the release always has a publish to fail.
  • Local-replica writes are serialised in the continuity tests. The start's snapshot and the store's own first snapshot can write the same file together. S3 takes each PUT whole, but litestream's file client shares one temporary name between writers.
  • Code health. pin now passes a context to its database calls, and step 2c moved into protectBeforeStart. Three line-count records are raised with reasons.
  • Race step. HA activator tests turn the store's background passes off (lease.SetStoreMonitorsOffForTest). litestream v0.5.14 can close a store while its own snapshot goroutine is still reading the database. The store is now ready inside the wake, so that pass overlapped test teardown.

For the release:

  • The litestream race above exists in production too, outside tests. A replicator closing within moments of an Open-time or daily snapshot would hit it. It is rare, but it should be tracked.
  • Measure the HA kept wake's full-image upload against the 30 s wake wait on a dev HA host, as noted above.

The census overlay replica-wake-gap-ch still needs a reviewer verdict (see #280).

Release coordination (platform-79): I plan to cut v0.40.3 from main after the v0.40.2 flagship window on #421 closes, and roll it to dev only: canary, one stable promote, dev console, the IE group with the verb. Paul approved this for domains Plan 2a, and platform-fd agreed.

cdf98181 (replicate before start on every wake) is on main and would ride it. It is live on the wake path with no flag.

This memory says the release is owed with Paul's GO, after measuring the HA kept-wake full upload on a dev HA host first. Questions for the owner of this thread:

  1. Is a dev-only v0.40.3 the right place for that measurement, or do you want cdf98181 left out of v0.40.3?
  2. Which witness should the dev roll run? I'll watch wakecheck and the IE probe, and carry the #1291 memory witness on the IE members.

I'll wait for an answer here before cutting.

Paul's decision (2026-11-20): roll it all to dev. cdf98181 rides v0.40.3, which is cut at main 69b44f53. A release session is cutting it now and will roll dev only.

The replicate-before-start measurement is part of that roll's witnesses. On the IE HA moves and at least one kept wake of an HA host on dev, it records:

  • the time from wake to app start;
  • whether the wake used the pin with a continuity proof or a confirmed full copy;
  • the bytes uploaded for a full copy;
  • the .continuity record.

wakecheck gets a PRAGMA integrity_check after the roll. Results go on #421 with the lock release. Flagship waits for Paul's separate GO.

v0.40.3 is on dev (09:31Z): replicate-before-start measured. The full report is on #421; the parts for this thread:

  • Full copy (first wake after the upgrade, and hosts taken in a move): wakecheck 1.31 MB, replicate step 142 ms, wake 702 ms. held-1 / held-2: 4.2 / 6.3 MB, replicate step 343 / 470 ms, wake 1.76 / 1.80 s.
  • Kept wake (pin + continuity proof, nothing uploaded): wakecheck replicate step 174 ms, wake 740 ms. held-1 / held-2: replicate step 360 / 424 ms, wake 900 / 877 ms.
  • Integrity: PRAGMA integrity_check on wakecheck returned ok. Its row count matches the live counter.

Two costs for the owner of this thread to weigh before flagship:

  1. A move never proves continuity, because the .continuity record stays on the old box. So every move uploads two full copies per host: the drain snapshot from the old box and the new box's full copy.
  2. Kept HA wakes are about 300 ms slower than on v0.40.2: 877-900 ms now against 572-609 ms. The replicate step went from 5-8 ms to 360-424 ms.