carlos / platform Public

replicas: replicate before the app starts on every wake (#1290)

Boot writes (migrations) made before litestream started could be
checkpointed and the WAL restarted unseen, leaving replicas that restore
malformed. Wakes now pin the database and prove continuity before
anything runs, else take a confirmed full copy; any failure fails the
start. Clean-close record kept in the agent's directory.

Reviewed: Astra R1, Fable R2-R3 + census. Measure HA kept wakes on dev HA.

Squashed from fix/replica-wake-gap into main.
claude agent, operated by paul@keymail.dev cdf98181c40def06a8ebc780c2c58a04e42e0c59 parent 3f3ef7b
30 files changed, +2,022 −35
  • .amadan/code-health.tsv +4 −4
  • docs/superpowers/notes/census-proposal-replica-wake-gap-ch.md +24 −0
  • docs/superpowers/notes/census-proposal-replica-wake-gap-r3.md +29 −0
  • docs/superpowers/notes/census-proposal-replica-wake-gap.md +33 −0
  • docs/superpowers/specs/2026-11-19-replicate-before-start.md +81 −0
  • internal/activator/activator.go +9 −2
  • internal/activator/backend_exec.go +25 −1
  • internal/activator/harelease_test.go +95 −7
  • internal/activator/pendingwake_linux_test.go +12 −3
  • internal/activator/poolwithdrawal_test.go +7 −0
  • internal/activator/replicatebeforestart.go +37 −0
  • internal/activator/replicatebeforestart_test.go +73 −0
  • internal/activator/size_identical_test.go +2 −0
  • internal/host/agent.go +6 −0
  • internal/lease/checkpoint.go +18 −1
  • internal/lease/continuity.go +584 −0
  • internal/lease/continuity_round3_test.go +259 −0
  • internal/lease/continuity_test.go +335 −0
  • internal/lease/export_test.go +20 −0
  • internal/lease/fence_test.go +26 −3
  • internal/lease/gentake_test.go +7 −1
  • internal/lease/ha_continuity_test.go +147 −0
  • internal/lease/lease.go +50 −1
  • internal/lease/protect_test.go +49 −0
  • internal/lease/release.go +7 −9
  • internal/lease/release_test.go +26 −3
  • internal/provision/testdata/plan14-root-reads-chain.tsv +3 −0
  • internal/provision/testdata/plan14-root-reads-replica-wake-gap-ch.tsv +11 −0
  • internal/provision/testdata/plan14-root-reads-replica-wake-gap-r3.tsv +16 −0
  • internal/provision/testdata/plan14-root-reads-replica-wake-gap.tsv +27 −0

CI failed — run details

diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index cd9e2321a..33b6a56ab 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -2178,7 +2178,7 @@ func-lines . TestFleetAppServesThroughTheHub - 408
func-lines . runDeploy - 329
func-lines . runRoute - 519
func-lines cmd/console serve - 367
-func-lines internal/activator (*Service).doWakeOnce - 567
+func-lines internal/activator (*Service).doWakeOnce - 570 # raised: #1290 step 2c, the one call that protects the database before the seed, release commands and the process start (body in replicatebeforestart.go)
func-lines internal/analytics Prune - 343
func-lines internal/appconfig SyncExecWithCallbacks - 320
func-lines internal/console (*Server).handleAPIInstanceCreate - 769
@@ -2207,7 +2207,7 @@ func-lines internal/host plan14RequiredArtifactsRootRunner - 374
func-lines internal/host plan14TimerIntention - 315
func-lines internal/host plan14TimerIntention.func1 - 311
func-lines internal/host rootFilesSeedIsolatedWitness - 308
-func-lines internal/host runAgent - 685
+func-lines internal/host runAgent - 688 # raised: #1290 sets the agent continuity directory beside the HA obligation store, where every exec-backend store is configured
func-lines internal/host runFilesSeedPreparationWithLive - 390
func-lines internal/host runServingParkPeerNamespace - 538
func-lines internal/host testRootMigrationBootstrap - 364
@@ -2222,8 +2222,8 @@ func-lines internal/release adoptHost - 494
func-lines internal/team TestFixture - 421
file-lines . apimode.go - 4199
file-lines . apimode_test.go - 3530 # raised: fdc912b (batch 2, #1123) landed before the ratchet; tests for the system update refusals
-file-lines internal/activator activator.go - 3780 # raised: two test-only fields, the lease work counter and the lease watch stop, that tests use to end lease watches before restoring settings
-file-lines internal/activator activator_test.go - 5481
+file-lines internal/activator activator.go - 3783 # raised: #1290 step 2c, the call to protectBeforeStart (its body and interface live in replicatebeforestart.go)
+file-lines internal/activator activator_test.go - 5471
file-lines internal/console server.go - 4220 # raised: platform accounts pre-flight C1, the one line embedding platformSeams in Server
file-lines internal/host agent.go - 3214
file-lines internal/provision reconcile_test.go - 3094
diff --git a/docs/superpowers/notes/census-proposal-replica-wake-gap-ch.md b/docs/superpowers/notes/census-proposal-replica-wake-gap-ch.md
new file mode 100644
index 000000000..71d533141
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-replica-wake-gap-ch.md
@@ -0,0 +1,24 @@
+# Census approval: replica-wake-gap-ch
+
+Ruling `census-ruling-replica-wake-gap-ch`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/activator.go` `Service.doWakeOnce` | sites | -registry:DBPath, +whole:Route | Step 2c's body moved unchanged into protectBeforeStart (replicatebeforestart.go); doWakeOnce passes the whole Route it already holds and returns the error. No read added; the DBPath read moved with the body. |
+
+Envelopes re-pinned: `internal/activator`, `internal/lease`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/activator/activator.go` `Service.doWakeOnce`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: The former doWake body, not deleted logic: refresh/admit/fence/layout checks remain. Select and verify the actual staged identity before serving Acquire; use canonical mode to call doStatelessWake. Keep SQLite acquire/restore/seed/marker/replicate only in the stateful arm, with the post-acquisition selection recheck and existing cleanup proofs. Fix 3a round 1 I1/I3a: admit config directly only for stateless and mark runtime ownership refusals. Stateful Acquire/Restore precede selection and pending publication; canonical mode inspection is separate, replan precedes settlement. Fix round 2 N2/N3: retain the original route/pin projection for post-lease declaration checks; reuse the unplanned capture so a live-link repoint cannot change the selected build. Stateful capture and changed-copy errors remain start failures after Acquire/Restore. A failed preliminary verification supplies no cached mode observation. No new file path or database authority. Final review C1/R26: unprojected stateful wakes capture and materialize the live link only after Acquire and Restore. Retain original route/generation/pin stateless evidence on the context across fallback, so missing stateless evidence cannot take stateful recovery inference. Known good stateful identity skips canonical declaration lookup. Existing pre-exec verification remains. R28 final fix 2: carry whether this wake has a plan in attempt-local context; no new read here; route, generation and pin stateless projection remains intact.;rev3=census-ruling-agent-start-demo-1;basis=Reads IsDemo and demo admission/capability state; chooses local lease retention, skips seed upload and sidecar selection. Existing stop and under-lease ordering retained.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: refuse tenant starts under the existing service lock before main's demoWakeRefusal, and recheck before backend Acquire. Retain main's demo refusal and all lease, restore and serialization checks. Two added whole Route uses feed the in-memory admission predicate; no new filesystem or store read.;rev3=census-ruling-stateless-replicas-2;basis=P14: after verified storage-mode selection, before clearing the projected hint or acquiring a database lease, a set row still on the stateful branch returns ErrFenced. Reads the existing route FleetBoxes field only. Verified stateless wakes take their existing branch; legacy rows remain unchanged. No new file, registry query or bucket read. merge of origin/main 9b8b2c50: retain wake-slot and HA duty logic alongside the replica stateful-start refusal; no gate removed. merge of origin/main 6be08467: Keep main demo lease, local database and KeepLocal path; never equate replication-disabled demos with stateless generations. Merge-only body/read-site change. merge of origin/main 7920cccf: Retain main tenant admission and startOwnedLocked gates alongside the replica stateful-start refusal; whole Route passed to main admission checks, no new path or store read.;rev3=census-ruling-agent-start-demo-3;basis=Route claim seeds through seed restore/admission; do not fall back to empty boot or ordinary import behavior. Census read-site delta: +registry:SeedSource, +whole:Route.;rev3=census-ruling-region-ha-g2-fixes;basis=Bound recovery Acquire by its attempt deadline; existing acquire/restore/start ordering remains; no new read.;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): right after retainDatabase returns, attaches the write-fence watcher under a.mu (watchWriteFenceLocked, in memory). retainDatabase is called through a retainDB test seam that is nil in production. No read added; no root call; existing acquire, restore, publisher and cleanup order unchanged.;rev3=census-ruling-sr-followups;basis=#1061 Task 1, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): a refused plan now returns planRefusal(host, plan) instead of the inline fmt.Errorf, the text is unchanged, and when the planner marked the plan Installing the error also matches errBuildNotInstalled (installRefusal, in memory). Same refusal at the same point before the lease, read sites unchanged, no read, file, store, bucket or root call added;rev3=census-ruling-replica-wake-gap;basis=Step 2c: before the seed and the spawn, asks the lease to ProtectStart(rt.DBPath), the route's own database path already used by Restore and retainDatabase; a refusal gives the lease back and starts nothing. Agent code (user carlos); no root call, no new store or file read here.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/replicatebeforestart.go:Service.protectBeforeStart`: reads +registry:DBPath, +registry:Host ×2; written legacy, accepted-legacy, frozen
+- reads `internal/lease/continuity.go:Protection.pin`: -file:QueryRow ×2, +file:QueryRowContext ×2; keeps legacy, task accepted-legacy
+
+Seal: `460c6557a81afc8e5a73db79b8673a7495f84c67a0457e69a0e8443f17a265e7` → `6c3e03c493dbca78fc128355f071caa2b2d5f22674b98994cd85a0cf63d40ca8`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-replica-wake-gap-ch.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-replica-wake-gap-r3.md b/docs/superpowers/notes/census-proposal-replica-wake-gap-r3.md
new file mode 100644
index 000000000..ff7338356
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-replica-wake-gap-r3.md
@@ -0,0 +1,29 @@
+# Census approval: replica-wake-gap-r3
+
+Ruling `census-ruling-replica-wake-gap-r3`. The independent reviewer approves or rejects every change below, 3 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `runAgent` | body | unchanged (8) | Calls lease.SetContinuityDir(<data dir>/.continuity) beside the existing obligation store: the agent's own 0700 directory for clean records, outside every instance tree (#1290 round 3). No new read; failure is logged and every start then takes a full image. |
+| `internal/lease/continuity.go` `currentState` | body | unchanged (3) | The record now also names the cleaned database path (version 2); the same stats of the route database, its WAL and the replicator's own ltx/0 listing. |
+| `internal/lease/continuity.go` `startProtected` | body | unchanged (1) | A pinned start's first sync retries within firstSyncTimeout (firstSync); a full image's upload is awaited from the replica's position (awaitUploaded) under imageBudget. Same database path and replica client; no new path or input. |
+
+Envelopes re-pinned: `internal/host`, `internal/lease`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).;rev3=census-ruling-same-box-edge-fence;basis=Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added.;rev3=census-ruling-platform-mail-submission;basis=Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Task 6: also sets the ExecBackend's ManifestOf, the same staged-manifest read as TierOf (rt.App and RouteAccount(rt), hence +registry:App and +whole:Route), for the spawn-time check of decision 10, which logs and emits an event and never refuses. Agent, not root. Fable final P2-2: eb.MailSwitch is the cache's State (three-valued: on, off, unknown) in place of On; an unreadable switch is unknown, never off. No read added.;rev3=census-ruling-fleet-drain-followups;basis=P3 (#1008 T9): one call after armChangeIndex, requestBootFullPass(v, &backstopFullDue), which stores true in the existing in-memory backstopFullDue flag only when no record view is armed, so the fast loop runs its existing full pass on its first tick instead of instancesLoop a minute later; armed boxes unchanged. No read added; read sites unchanged (8); agent, not root.;rev3=census-ruling-fleet-first-reconcile-speed;basis=Startup timing log lines only: runDuties builds a step logger (newStartupLog, which reads the in-memory agent start time) and logs one line after the wait on the activator startup latch and after each existing duty before go fastConvergeLoop. One newStartupLog().at line in the edge ready hook before go tunnelLoop. No read added; read sites unchanged (8). Agent, not root.;rev3=census-ruling-ha-1192;basis=sets the group drain driver's departed hook to armedPeerDeparted (the armed departure controller's PeerDeparted: local registry identity + departure journal); no new read
+- `internal/lease/continuity.go` `currentState`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database and its -wal, and lists the replicator's own litestream meta directory's ltx/0, to compare with the clean record. Agent-owned files; read only.
+- `internal/lease/continuity.go` `startProtected`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database to tell a first start (no file) from an existing one; then litestream's own sync and, when continuity is unproven, a snapshot through the existing replica client. No new path or input.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/lease/continuity.go:imageBudget`: reads +file:Stat; written legacy, accepted-legacy, frozen
+- reads `internal/lease/continuity.go:isContinuous`: +file:Lstat; keeps legacy, task accepted-legacy
+- reads `internal/lease/continuity.go:recordClean`: +file:CreateTemp, -file:OpenFile; keeps legacy, task accepted-legacy
+
+Seal: `837b586c0aa17936bc64201245a86c3fd66c58e7f1257436b31c75ac001ac00c` → `460c6557a81afc8e5a73db79b8673a7495f84c67a0457e69a0e8443f17a265e7`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-replica-wake-gap-r3.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-replica-wake-gap.md b/docs/superpowers/notes/census-proposal-replica-wake-gap.md
new file mode 100644
index 000000000..3634cc55d
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-replica-wake-gap.md
@@ -0,0 +1,33 @@
+# Census approval: replica-wake-gap
+
+Ruling `census-ruling-replica-wake-gap`. The independent reviewer approves or rejects every change below, 9 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/lease/checkpoint.go` `Held.Checkpoint` | body | unchanged (1) | Replicate before start (#1290): decides continuity (beginContinuity) before the store opens, runs startProtected (bounded first sync; a full image when continuity is unproven) before its sync, and writes the clean record after a successful close. Same database path the caller passed; no new path, input or root decision; the agent runs it as carlos. |
+| `internal/activator/activator.go` `Service.doWakeOnce` | sites | +registry:DBPath | Step 2c: before the seed and the spawn, asks the lease to ProtectStart(rt.DBPath), the route's own database path already used by Restore and retainDatabase; a refusal gives the lease back and starts nothing. Agent code (user carlos); no root call, no new store or file read here. |
+
+Envelopes re-pinned: `internal/activator`, `internal/lease`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/lease/checkpoint.go` `Held.Checkpoint`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/activator/activator.go` `Service.doWakeOnce`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: The former doWake body, not deleted logic: refresh/admit/fence/layout checks remain. Select and verify the actual staged identity before serving Acquire; use canonical mode to call doStatelessWake. Keep SQLite acquire/restore/seed/marker/replicate only in the stateful arm, with the post-acquisition selection recheck and existing cleanup proofs. Fix 3a round 1 I1/I3a: admit config directly only for stateless and mark runtime ownership refusals. Stateful Acquire/Restore precede selection and pending publication; canonical mode inspection is separate, replan precedes settlement. Fix round 2 N2/N3: retain the original route/pin projection for post-lease declaration checks; reuse the unplanned capture so a live-link repoint cannot change the selected build. Stateful capture and changed-copy errors remain start failures after Acquire/Restore. A failed preliminary verification supplies no cached mode observation. No new file path or database authority. Final review C1/R26: unprojected stateful wakes capture and materialize the live link only after Acquire and Restore. Retain original route/generation/pin stateless evidence on the context across fallback, so missing stateless evidence cannot take stateful recovery inference. Known good stateful identity skips canonical declaration lookup. Existing pre-exec verification remains. R28 final fix 2: carry whether this wake has a plan in attempt-local context; no new read here; route, generation and pin stateless projection remains intact.;rev3=census-ruling-agent-start-demo-1;basis=Reads IsDemo and demo admission/capability state; chooses local lease retention, skips seed upload and sidecar selection. Existing stop and under-lease ordering retained.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: refuse tenant starts under the existing service lock before main's demoWakeRefusal, and recheck before backend Acquire. Retain main's demo refusal and all lease, restore and serialization checks. Two added whole Route uses feed the in-memory admission predicate; no new filesystem or store read.;rev3=census-ruling-stateless-replicas-2;basis=P14: after verified storage-mode selection, before clearing the projected hint or acquiring a database lease, a set row still on the stateful branch returns ErrFenced. Reads the existing route FleetBoxes field only. Verified stateless wakes take their existing branch; legacy rows remain unchanged. No new file, registry query or bucket read. merge of origin/main 9b8b2c50: retain wake-slot and HA duty logic alongside the replica stateful-start refusal; no gate removed. merge of origin/main 6be08467: Keep main demo lease, local database and KeepLocal path; never equate replication-disabled demos with stateless generations. Merge-only body/read-site change. merge of origin/main 7920cccf: Retain main tenant admission and startOwnedLocked gates alongside the replica stateful-start refusal; whole Route passed to main admission checks, no new path or store read.;rev3=census-ruling-agent-start-demo-3;basis=Route claim seeds through seed restore/admission; do not fall back to empty boot or ordinary import behavior. Census read-site delta: +registry:SeedSource, +whole:Route.;rev3=census-ruling-region-ha-g2-fixes;basis=Bound recovery Acquire by its attempt deadline; existing acquire/restore/start ordering remains; no new read.;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): right after retainDatabase returns, attaches the write-fence watcher under a.mu (watchWriteFenceLocked, in memory). retainDatabase is called through a retainDB test seam that is nil in production. No read added; no root call; existing acquire, restore, publisher and cleanup order unchanged.;rev3=census-ruling-sr-followups;basis=#1061 Task 1, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): a refused plan now returns planRefusal(host, plan) instead of the inline fmt.Errorf, the text is unchanged, and when the planner marked the plan Installing the error also matches errBuildNotInstalled (installRefusal, in memory). Same refusal at the same point before the lease, read sites unchanged, no read, file, store, bucket or root call added
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/lease/continuity.go:Protection.pin`: reads +file:Open, +file:QueryRow ×2, +file:Stat; written legacy, accepted-legacy, frozen
+- new `internal/lease/continuity.go:currentState`: reads +file:ReadDir, +file:Stat ×2; written legacy, accepted-legacy, frozen
+- new `internal/lease/continuity.go:firstLocalL0After`: reads +file:ReadDir; written legacy, accepted-legacy, frozen
+- new `internal/lease/continuity.go:fullImage`: reads +file:Open; written legacy, accepted-legacy, frozen
+- new `internal/lease/continuity.go:isContinuous`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+- new `internal/lease/continuity.go:newestLocalL0`: reads +file:ReadDir; written legacy, accepted-legacy, frozen
+- new `internal/lease/continuity.go:recordClean`: reads +file:OpenFile; written legacy, accepted-legacy, frozen
+- new `internal/lease/continuity.go:startProtected`: reads +file:Stat; written legacy, accepted-legacy, frozen
+- reads `internal/lease/lease.go:Held.Replicate`: +file:Stat; keeps legacy, task accepted-legacy
+
+Seal: `4568bc8acc3ee632d7637cb27ca6838c735128f4a40de21f26b7070ebb156723` → `837b586c0aa17936bc64201245a86c3fd66c58e7f1257436b31c75ac001ac00c`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-replica-wake-gap.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/specs/2026-11-19-replicate-before-start.md b/docs/superpowers/specs/2026-11-19-replicate-before-start.md
new file mode 100644
index 000000000..2922a56e0
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-19-replicate-before-start.md
@@ -0,0 +1,81 @@
+# Replicate before start
+
+Discussion #1290. Round 3: the fixes from the review of f1fe437e.
+
+## The invariant
+
+A replica either continues, without a gap, the WAL its last clean close
+left, or it restarts from an uploaded full image of the live file. A start
+does not serve until one of the two holds.
+
+Two mechanisms carry it, both in `internal/lease`:
+
+1. **The clean record.** A close whose final sync and store close succeed
+ writes a record of the newest local L0 TXID and the database and WAL
+ sizes and mtimes. The record lives in the agent's own directory
+ (`SetContinuityDir`, `<data>/.continuity`), named from the database
+ path, never in the app's tree, so the app cannot forge it. It is written
+ through `os.CreateTemp` and a rename, and trusted only if `Lstat` shows a
+ regular file. Every start (`ProtectStart`, `Replicate`, `Checkpoint`)
+ deletes it first. With no directory set, nothing is trusted.
+2. **The pin.** A SQLite read transaction, taken *before* the record is
+ compared with the files. While it is held, the WAL can restart at most
+ once and nothing written after it can be backfilled, so a process's
+ writes stay in the WAL until litestream reads them. The pin is held
+ through litestream's first sync, which takes litestream's own lock. A
+ database that cannot be pinned (no WAL or shm, not in WAL mode) is not
+ continuous.
+
+When continuity is not proven, `Replicate` returns only once a full image
+is **uploaded**: either litestream's own first file, when it holds every
+page (a first start, or a WAL that was truncated or removed), once the
+replica's position shows the replica's own monitor has uploaded it, or
+else a level-9 snapshot of the live file.
+
+## Paths
+
+- **Ordinary wake.** `ProtectStart` runs after restore and before the seed,
+ release commands and the process. A hold swap's start is such a wake. An
+ overlap successor starts while the incumbent's replicator runs.
+- **Claim wake, and any `Replicate` with no `ProtectStart` before it.**
+ `Replicate` pins first, decides under the pin, and holds the pin through
+ its first sync. A process that is already running cannot slip a write
+ between the decision and the pin. Anything it wrote earlier shows in the
+ files and forces a full image; anything later stays in the WAL. Claims are
+ off on every box, so the claim wake is not otherwise reordered.
+- **HA leases and moves (`Held.Checkpoint`).** Same rule, no exemption.
+- **Restore.** A replaced file never matches the record: a full image.
+- **Unit tenants and demos.** The box-wide litestream unit runs all the
+ time; a demo's lease is local. Neither pins.
+- **First start.** The process starts first, then a full image is uploaded
+ before the wake serves. No bootstrap file: creating the database ahead of
+ the app 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.
+
+## Failure behaviour
+
+- The first sync is bounded by `firstSyncTimeout` (30 s). On a pinned,
+ continuous start, a failure is retried with backoff inside that bound: a
+ replica listing that fails once does not fail a wake whose WAL the pin
+ holds. An unproven start is not retried; it fails the wake.
+- A full image gets 2 minutes plus the database's size at 1 MiB/s
+ (`imageBudget`), so a large database stays wakeable. Every database
+ takes one on its first wake after the upgrade.
+- Any failure fails the start. `cleanupFailedWake` stops the process and
+ gives the lease back. The person sees "replicate <host>: ..." in `carlos
+ logs --stream platform`, and the edge answers as for any failed wake. No
+ record was written, so the next wake tries the full image again.
+- litestream's init reads the replica's position, so an unreachable replica
+ fails wakes; before this change they served with replication lagging.
+ Serving read-only is not a fallback: apps migrate on boot, so a
+ "read-only" start would still write.
+- A continuous wake costs one local sync (milliseconds), plus retries only
+ while the replica is failing.
+
+## A replica that is already broken
+
+No earlier release wrote a record. So each database's first start after
+the upgrade uploads a full image, and its newest restore starts from that
+image. Poisoned L1-L3 files remain only on point-in-time paths before it,
+and they age out with snapshot retention (7 days).
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 9d55096b4..7b330bf4b 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -3200,6 +3200,12 @@ func (a *Service) doWakeOnce(ctx context.Context, e *actEntry) (*wokenInstance,
ctx = withStorageMode(ctx, rt, id, false, digest)
}
+ // 2c. Replicate before start (#1290): nothing that can write the
+ // database starts before it is protected (protectBeforeStart).
+ if err := a.protectBeforeStart(ctx, rt, lease, w); err != nil {
+ return w, err
+ }
+
// 3. First-boot seed, strictly between the restore and the spawn — so it
// runs before Start's first health probe, and a brand-new instance is born
// seeded rather than briefly serving an empty database. fresh is the
@@ -3236,8 +3242,9 @@ func (a *Service) doWakeOnce(ctx context.Context, e *actEntry) (*wokenInstance,
// 4. Spawn before replication starts: a fresh instance creates its own DB
// on boot, so waiting for the socket guarantees the file exists for
- // litestream to open. Writes that land in the gap are picked up by the
- // replica's first sync.
+ // litestream to open. Writes that land before replication are kept in
+ // the WAL by step 2c's pin, or covered by the snapshot Replicate takes
+ // when continuity was not proven.
//
// Both doors are TIMED, because this is the half an app CANNOT see.
// Backend.Start execs the binary and waits until its socket accepts, so it
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 88f0dec31..a3b59fafc 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -952,6 +952,27 @@ type execLease struct {
// take's retirement in the background (startRetirement).
replicating func(*lease.Replicator)
replicatingOnce sync.Once
+ // protected is the start protection ProtectStart took (lease
+ // ProtectStart): Replicate takes it over, and a lease given back
+ // without replicating drops it.
+ protected atomic.Pointer[lease.Protection]
+}
+
+// ProtectStart is startProtector: the database is protected (continuity
+// decided, a continuous one pinned) before anything that can write it
+// starts. An error means nothing may start.
+func (l *execLease) ProtectStart(dbPath string) error {
+ if dbPath == "" {
+ dbPath = l.defaultDB
+ }
+ p, err := lease.ProtectStart(dbPath)
+ if err != nil {
+ return err
+ }
+ if old := l.protected.Swap(p); old != nil && old != p {
+ old.Drop()
+ }
+ return nil
}
func (l *execLease) Replicate(ctx context.Context, dbPath string, syncInterval time.Duration) (Rep, error) {
@@ -1004,7 +1025,10 @@ var (
_ interface{ SyncAndWait(context.Context) error } = (*lease.Replicator)(nil)
)
-func (l *execLease) Release(ctx context.Context) error { return l.held.Release(ctx) }
+func (l *execLease) Release(ctx context.Context) error {
+ l.protected.Load().Drop()
+ return l.held.Release(ctx)
+}
// RetryRelease is releaseRetrier: the held lease's conditional retry of a
// release that failed (#292).
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go
index de97a2ea8..a566322b0 100644
--- a/internal/activator/harelease_test.go
+++ b/internal/activator/harelease_test.go
@@ -124,6 +124,9 @@ type haSvc struct {
func haService(t *testing.T, host string) *haSvc {
t.Helper()
+ // The store's background passes off (lease.SetStoreMonitorsOffForTest):
+ // they would race the request counts and the teardown below.
+ t.Cleanup(lease.SetStoreMonitorsOffForTest())
b, rt := haBackend(t, host)
h := haFixOf(b)
// A short run directory, so the unix sockets beneath it fit whatever
@@ -846,16 +849,37 @@ func TestHAWakeRequestCounts(t *testing.T) {
s := haService(t, "shop.example.com")
lock := s.lockKey()
manifest := hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host))
- wake := func() (*actEntry, []string) {
+ l0 := "PUT " + s.b.Cfg.hibernatePrefix(s.rt.Host) + "/0000/"
+ wake := func() (*actEntry, []string, []string) {
t.Helper()
n := len(s.fx.Requests())
e, err := s.wakeForTest(context.Background())
if err != nil {
t.Fatal(err)
}
- return e, s.wakePathRequests(s.fx.Requests()[n:])
+ // The wake's full image (replicate before start, #1290): an HA
+ // release truncates the WAL, so every wake starts the replica
+ // from an image and waits for its upload. Counted on its own.
+ // The store's own background passes (compactions into levels
+ // 1-8, snapshots at 9, retention's deletes) run whenever their
+ // timers fire and race the wake, so they are set aside by
+ // level; level 0 is the wake's alone.
+ var images, rest []string
+ for _, r := range s.wakeRequests(s.fx.Requests()[n:], true) {
+ switch {
+ case strings.HasPrefix(r, l0):
+ images = append(images, r)
+ case s.storeMonitorRequest(r):
+ default:
+ rest = append(rest, r)
+ }
+ }
+ return e, rest, images
+ }
+ e, reqs, images := wake()
+ if len(images) != 1 {
+ t.Fatalf("a first wake uploaded %v, want exactly one image", images)
}
- e, reqs := wake()
// A first wake: the lock's three, then the launch's publish of its
// minted secrets (Task 11): the sealed env, the sealed cutover marker
// (durability 3a) and the wake state objects, and the first manifest,
@@ -867,13 +891,13 @@ func TestHAWakeRequestCounts(t *testing.T) {
}
writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "app"})
s.stopForTest(e)
- e, reqs = wake()
- if want := []string{"GET " + lock, "PUT " + lock, "GET " + s.headKey()}; restoreCalls(s.b) != 0 || strings.Join(reqs, ",") != strings.Join(want, ",") {
- t.Fatalf("a kept wake made %v (%d restores), want %v", reqs, restoreCalls(s.b), want)
+ e, reqs, images = wake()
+ if want := []string{"GET " + lock, "PUT " + lock, "GET " + s.headKey()}; restoreCalls(s.b) != 0 || strings.Join(reqs, ",") != strings.Join(want, ",") || len(images) != 1 {
+ t.Fatalf("a kept wake made %v and uploaded %v (%d restores), want %v and exactly one image", reqs, images, restoreCalls(s.b), want)
}
s.stopForTest(e)
writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "changed after the release"}) // the keep proof fails
- e, reqs = wake()
+ e, reqs, _ = wake()
manifestReads := 0
for _, r := range reqs {
if r == "GET "+manifest {
@@ -898,12 +922,38 @@ func TestHAWakeRequestCounts(t *testing.T) {
// 2026-10-27). They are replication's requests, not the wake's, and
// counting them made the wake's budget depend on the scheduler.
func (s *haSvc) wakePathRequests(reqs []string) []string {
+ return s.wakeRequests(reqs, false)
+}
+
+// wakeRequests is wakePathRequests, keeping litestream's level 0-8 PUTs
+// when data is set.
+func (s *haSvc) wakeRequests(reqs []string, data bool) []string {
prefix := s.b.Cfg.hibernatePrefix(s.rt.Host) + "/"
var out []string
for _, r := range reqs {
if level, ok := strings.CutPrefix(r, "LIST "+prefix); ok && isReplicaLevelDir(level) {
continue
}
+ // litestream's own level 0-8 files: the full image a wake now
+ // uploads before it serves when continuity is not proven (an HA
+ // release truncates the WAL; replicate before start, #1290), and
+ // compactions the store, ready earlier, finishes inside the wake.
+ // They were the same requests a moment later. Snapshots (level 9)
+ // still count.
+ if rel, ok := strings.CutPrefix(r, "PUT "+prefix); ok && !data && replicaDataFile(rel) {
+ continue
+ }
+ // The store's own background passes (compaction reads and writes
+ // of levels 1-9, retention's deletes) run on their timers and,
+ // with the store ready inside the wake (#1290), can land in it.
+ if !data && s.storeMonitorRequest(r) {
+ continue
+ }
+ if rel, ok := strings.CutPrefix(r, "PUT "+prefix+"g-"); ok && !data {
+ if _, file, ok := strings.Cut(rel, "/"); ok && replicaDataFile(file) {
+ continue
+ }
+ }
// The same listing under a storage generation (g-N/NNNN/): the
// replicator of a generations wake writes there.
if rel, ok := strings.CutPrefix(r, "LIST "+prefix+"g-"); ok {
@@ -916,6 +966,44 @@ func (s *haSvc) wakePathRequests(reqs []string) []string {
return out
}
+// storeMonitorRequest reports whether r is the replica store's own
+// background work on this host's prefix (the root layout or a storage
+// generation): a read or write of a level
+// 1-9 file (compaction and snapshot passes), or any delete of a level file
+// (retention).
+func (s *haSvc) storeMonitorRequest(r string) bool {
+ method, key, ok := strings.Cut(r, " ")
+ if !ok {
+ return false
+ }
+ rel, ok := strings.CutPrefix(key, s.b.Cfg.hibernatePrefix(s.rt.Host)+"/")
+ if !ok {
+ return false
+ }
+ if g, ok := strings.CutPrefix(rel, "g-"); ok {
+ // The same files under a storage generation (g-N/NNNN/...).
+ if _, rel, ok = strings.Cut(g, "/"); !ok {
+ return false
+ }
+ }
+ if len(rel) <= 5 || !isReplicaLevelDir(rel[:5]) || !strings.HasSuffix(rel, ".ltx") {
+ return false
+ }
+ switch method {
+ case "DELETE":
+ return true
+ case "GET", "PUT":
+ return rel[:4] != "0000"
+ }
+ return false
+}
+
+// replicaDataFile reports whether rel is a litestream file of levels 0-8
+// ("NNNN/<min>-<max>.ltx"), not a snapshot.
+func replicaDataFile(rel string) bool {
+ return len(rel) > 5 && isReplicaLevelDir(rel[:5]) && rel[:4] <= "0008" && strings.HasSuffix(rel, ".ltx")
+}
+
// isReplicaLevelDir reports whether rel is one of litestream's level
// directories as a listing names it: four digits and a slash.
func isReplicaLevelDir(rel string) bool {
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go
index 1296234f9..04a404179 100644
--- a/internal/activator/pendingwake_linux_test.go
+++ b/internal/activator/pendingwake_linux_test.go
@@ -1610,8 +1610,13 @@ func TestFleetStopOfANeverCreatedDatabaseFinishes(t *testing.T) {
// before the wake) stays pending, the lease held and renewing.
func TestFleetStopOfAnUnsyncedDatabaseStaysPending(t *testing.T) {
r := newCheckpointRig(t, registry.PlacementTarget("pi"))
- t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
+ // The bucket refuses writes once the wake is up: a wake whose first
+ // image cannot be uploaded does not serve at all (replicate before
+ // start, #1290). The row written after it is what the bucket never
+ // receives.
e := r.wake(t)
+ t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
+ appendRow(t, r.rt.DBPath)
stopped := r.stop(e)
select {
case <-r.kept:
@@ -1853,14 +1858,18 @@ func (r *checkpointRig) assertHealedRelease(t *testing.T, rep signalRep, heal fu
// reaper releases it once the checkpoint is proven.
func TestFailedFleetWakeKeepsAnUnprovenCheckpoint(t *testing.T) {
r := newCheckpointRig(t, registry.PlacementTarget("pi"))
- heal := r.fx.FailReplicaPuts(r.prefix)
- t.Cleanup(heal)
+ // The bucket refuses writes from just after the replica started: a
+ // replica whose first image cannot be uploaded never starts at all
+ // (replicate before start, #1290).
+ heal := func() {}
+ t.Cleanup(func() { heal() })
var rep signalRep
r.a.retainDB = func(ctx context.Context, rt registry.Route, l Lease) (Rep, error) {
got, err := retainDatabase(ctx, rt, l)
if err != nil {
return got, err
}
+ heal = r.fx.FailReplicaPuts(r.prefix)
rep = signalRep{Replicator: got.(*lease.Replicator), closed: make(chan error, 8)}
appendRow(t, rt.DBPath) // the boot's write
return rep, errors.New("the wake failed after its replica started")
diff --git a/internal/activator/poolwithdrawal_test.go b/internal/activator/poolwithdrawal_test.go
index 8e5276021..12088f8bf 100644
--- a/internal/activator/poolwithdrawal_test.go
+++ b/internal/activator/poolwithdrawal_test.go
@@ -142,6 +142,13 @@ func TestPoolWithdrawalRequiresCompleteProof(t *testing.T) {
s.a.mu.Unlock()
case "failed-publication":
s.a.stopFiles(e)
+ // A change the stopped publisher never published, so the
+ // release's final files publish has a PUT to fail. Without
+ // it the test leaned on the publisher not having finished
+ // its first publish yet, which a fast box (and a wake that
+ // now does its replica work before it returns, #1290)
+ // does not give.
+ writeFiles(t, s.b, s.rt, map[string]string{"withdrawal.txt": "unpublished"})
s.fx.FailNextMatching("PUT", 403, func(k string, _ []byte) bool { return strings.Contains(k, "/files/") })
case "restart", "restart-dirty":
s = s.restart(t)
diff --git a/internal/activator/replicatebeforestart.go b/internal/activator/replicatebeforestart.go
new file mode 100644
index 000000000..177dfc7e3
--- /dev/null
+++ b/internal/activator/replicatebeforestart.go
@@ -0,0 +1,37 @@
+package activator
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// startProtector is a lease that protects its database before anything
+// that can write it starts (lease.ProtectStart; spec
+// 2026-11-19-replicate-before-start.md). A lease without it (a unit
+// tenant's, replicated by the box-wide unit; a demo's local lease) starts
+// as before.
+type startProtector interface {
+ ProtectStart(dbPath string) error
+}
+
+// protectBeforeStart is doWakeOnce's step 2c (discussion #1290): nothing
+// that can write the database (the seed, a release command, the process)
+// starts before it is protected. A database exactly as its last clean
+// close left it is pinned, so every frame the start writes stays in the
+// WAL until Replicate's litestream reads it; any other is given a full
+// image by Replicate before the wake serves. A lease that cannot protect
+// refuses the start: the lease goes back and nothing runs.
+func (a *Service) protectBeforeStart(ctx context.Context, rt registry.Route, lease Lease, w *wokenInstance) error {
+ p, ok := lease.(startProtector)
+ if !ok {
+ return nil
+ }
+ if err := p.ProtectStart(rt.DBPath); err != nil {
+ w.stopOutcome.leaseReleased = a.giveBack(ctx, rt.Host, lease)
+ return fmt.Errorf("protect %s: %w", rt.Host, err)
+ }
+ w.steps.mark(a.now(), "protect")
+ return nil
+}
diff --git a/internal/activator/replicatebeforestart_test.go b/internal/activator/replicatebeforestart_test.go
new file mode 100644
index 000000000..04c117a9e
--- /dev/null
+++ b/internal/activator/replicatebeforestart_test.go
@@ -0,0 +1,73 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// --- replicate before start (#1290) ------------------------------------------
+//
+// Nothing that can write the database starts before the lease protects it
+// (spec 2026-11-19-replicate-before-start.md): protect comes after the
+// restore and before the seed and the process.
+
+// fakeProtectErrs is what each backend's leases answer to ProtectStart.
+var fakeProtectErrs sync.Map // *fakeBackend -> error
+
+// ProtectStart is startProtector: it records "protect" in the order log
+// and answers the backend's fakeProtectErrs entry.
+func (l *fakeLease) ProtectStart(string) error {
+ if l.b == nil {
+ return nil
+ }
+ l.b.record("protect")
+ if err, ok := fakeProtectErrs.Load(l.b); ok {
+ return err.(error)
+ }
+ return nil
+}
+
+func TestWakeProtectsTheDatabaseBeforeAnythingStarts(t *testing.T) {
+ a, b, _, _ := testActivator(t, time.Minute)
+ b.restoreFresh = true
+ // Each Replicate goes into the order log too.
+ b.repWrap = func(r *fakeRep) Rep {
+ b.record("replicate")
+ return r
+ }
+ rt := testRoute("protect.example.com")
+ rt.Seed = `["seed"]`
+ release, err := a.beginRequest(context.Background(), rt)
+ if err != nil {
+ t.Fatalf("beginRequest: %v", err)
+ }
+ release()
+ ev := b.events()
+ r, p, s, st, rep := indexOf(ev, "restore"), indexOf(ev, "protect"), indexOf(ev, "seed"), indexOf(ev, "start:instance"), indexOf(ev, "replicate")
+ if r == -1 || p == -1 || s == -1 || st == -1 || rep == -1 || !(r < p && p < s && s < st && st < rep) {
+ t.Fatalf("order %v, want restore < protect < seed < start:instance < replicate", ev)
+ }
+}
+
+func TestWakeThatCannotProtectStartsNothing(t *testing.T) {
+ a, b, _, _ := testActivator(t, time.Minute)
+ fakeProtectErrs.Store(b, errors.New("pin refused"))
+ t.Cleanup(func() { fakeProtectErrs.Delete(b) })
+ rt := testRoute("unprotected.example.com")
+ if _, err := a.beginRequest(context.Background(), rt); err == nil || !strings.Contains(err.Error(), "pin refused") {
+ t.Fatalf("beginRequest: %v, want the protection's refusal", err)
+ }
+ b.mu.Lock()
+ starts, releases := b.starts, b.releases
+ b.mu.Unlock()
+ if starts != 0 {
+ t.Fatalf("%d starts after a refused protection, want 0", starts)
+ }
+ if releases != 1 {
+ t.Fatalf("%d lease releases, want 1", releases)
+ }
+}
diff --git a/internal/activator/size_identical_test.go b/internal/activator/size_identical_test.go
index 17f6aef23..b71fd5615 100644
--- a/internal/activator/size_identical_test.go
+++ b/internal/activator/size_identical_test.go
@@ -264,6 +264,7 @@ func TestNoSizeColumnSwapIsMains(t *testing.T) {
// 953b9fda: the fixture's wake, then the swap's events.
want := []string{
"restore",
+ "protect", // replicate before start (#1290)
"start:instance",
"raise:1073741824+536870912",
"startGen:" + f.staged,
@@ -290,6 +291,7 @@ func TestNoSizeColumnSwapIsMains(t *testing.T) {
// 953b9fda: the fixture's wake, then the failed swap's events.
want := []string{
"restore",
+ "protect", // replicate before start (#1290)
"start:instance",
"raise:1073741824+536870912",
"startGen:" + f.staged,
diff --git a/internal/host/agent.go b/internal/host/agent.go
index be44cabf8..e5ffcaaac 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -613,6 +613,12 @@ func runAgent(args []string, buildClaims ClaimFactory) {
if err := lease.SetObligationDir(filepath.Join(dd, ".ha-owed")); err != nil {
log.Printf("agent: region HA: obligation store: %v (every HA wake on this box refuses until it opens)", err)
}
+ // Replicate before start (#1290): clean records live in the agent's
+ // own directory, outside every instance's tree. Without it nothing
+ // is trusted and every start takes a full image.
+ if err := lease.SetContinuityDir(filepath.Join(dd, ".continuity")); err != nil {
+ log.Printf("agent: continuity records: %v (every start takes a full image)", err)
+ }
if logSink != nil { // a typed-nil in the interface would NOT be nil
eb.Logs = logSink
}
diff --git a/internal/lease/checkpoint.go b/internal/lease/checkpoint.go
index 573208fdd..b6db62284 100644
--- a/internal/lease/checkpoint.go
+++ b/internal/lease/checkpoint.go
@@ -3,6 +3,7 @@ package lease
import (
"context"
"errors"
+ "log"
"time"
)
@@ -37,15 +38,31 @@ func (h *Held) Checkpoint(ctx context.Context, dbPath string) (receipt Checkpoin
store.CompactionMonitorEnabled = false
store.L0RetentionCheckInterval = 0
store.SetRetentionEnabled(false)
+ // Replicate before start (continuity.go): a checkpoint that cannot
+ // prove the files continue the replica's last clean close snapshots
+ // before its receipt.
+ pin, continuous, err := beginContinuity(dbPath)
+ if err != nil {
+ return receipt, err
+ }
+ defer pin.Release()
openErr := store.Open(opCtx)
var syncErr error
if openErr == nil {
- syncErr = db.SyncAndWait(opCtx)
+ syncErr = startProtected(opCtx, db, continuous)
+ if syncErr == nil {
+ syncErr = db.SyncAndWait(opCtx)
+ }
}
if openErr != nil || syncErr != nil {
cancel()
}
closeErr := store.Close(opCtx)
+ if openErr == nil && syncErr == nil && closeErr == nil {
+ if rerr := recordClean(dbPath); rerr != nil {
+ log.Printf("lease: %s: clean record: %v (the next start snapshots)", dbPath, rerr)
+ }
+ }
until, healthErr := h.rn.SafeUntil()
err = errors.Join(openErr, syncErr, closeErr, healthErr, opCtx.Err())
if err != nil {
diff --git a/internal/lease/continuity.go b/internal/lease/continuity.go
new file mode 100644
index 000000000..270140b24
--- /dev/null
+++ b/internal/lease/continuity.go
@@ -0,0 +1,584 @@
+package lease
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
+)
+
+// Replicate before start (docs/superpowers/specs/2026-11-19-replicate-
+// before-start.md, discussion #1290). The invariant: a replica either
+// continues, without a gap, the WAL its last clean close left, or starts
+// from a full snapshot of the live file, and a wake does not serve until
+// one of the two is true.
+//
+// The clean record says which. A close whose final sync and store close
+// succeeded writes it. Every start of replication deletes it first, so a
+// crash, a lost meta directory, a restore, a process that wrote while
+// nothing replicated, or a repair that failed all leave no record that
+// matches, and the next start takes a full image.
+//
+// The record lives in the agent's own directory (SetContinuityDir), keyed
+// by the database path, never beside the database: the app can write
+// everything in its instance directory, and a record it could rewrite
+// would let it vouch for a gap. With no directory set, nothing is ever
+// recorded or trusted, so every start takes a full image.
+//
+// The start pin keeps a continuous database continuous across a process
+// start. While a SQLite reader is held, the WAL can restart at most once
+// and no frame written after the reader began can be backfilled, so
+// whatever the process writes stays in the WAL until litestream reads it.
+
+// metaPathOf is the replicator's litestream meta directory for dbPath (the
+// activator namespace newStore sets).
+func metaPathOf(dbPath string) string {
+ return filepath.Join(filepath.Dir(dbPath), ".activator-"+filepath.Base(dbPath)+"-litestream")
+}
+
+var continuityDir struct {
+ sync.Mutex
+ dir string
+}
+
+// SetContinuityDir is where this process keeps clean records: a directory
+// of the agent's own, outside every instance's tree. Created 0700.
+func SetContinuityDir(dir string) error {
+ if dir == "" {
+ return errors.New("lease: an empty continuity directory")
+ }
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return fmt.Errorf("lease: continuity directory: %w", err)
+ }
+ continuityDir.Lock()
+ continuityDir.dir = dir
+ continuityDir.Unlock()
+ return nil
+}
+
+// recordPath is dbPath's clean record: a name derived from the cleaned
+// absolute path, in the continuity directory. ok is false with no
+// directory set.
+func recordPath(dbPath string) (dir, path string, ok bool) {
+ continuityDir.Lock()
+ dir = continuityDir.dir
+ continuityDir.Unlock()
+ if dir == "" {
+ return "", "", false
+ }
+ abs, err := filepath.Abs(dbPath)
+ if err != nil {
+ return "", "", false
+ }
+ sum := sha256.Sum256([]byte(filepath.Clean(abs)))
+ return dir, filepath.Join(dir, hex.EncodeToString(sum[:16])+".json"), true
+}
+
+// cleanRecord is the state a clean close left: the database it is for,
+// the newest local L0 file, and the database and WAL exactly as they were.
+type cleanRecord struct {
+ V int `json:"v"`
+ DB string `json:"db"`
+ TXID uint64 `json:"txid"`
+ DBSize int64 `json:"db_size"`
+ DBMod int64 `json:"db_mtime_ns"`
+ WALSize int64 `json:"wal_size"`
+ WALMod int64 `json:"wal_mtime_ns"`
+}
+
+// currentState is the record the files would make now. ok is false when
+// the database or the local L0 history cannot be read: nothing to prove
+// continuity with.
+func currentState(dbPath string) (cleanRecord, bool) {
+ fi, err := os.Stat(dbPath)
+ if err != nil {
+ return cleanRecord{}, false
+ }
+ rec := cleanRecord{V: 2, DB: filepath.Clean(dbPath), DBSize: fi.Size(), DBMod: fi.ModTime().UnixNano(), WALSize: -1}
+ switch wi, err := os.Stat(dbPath + "-wal"); {
+ case err == nil:
+ rec.WALSize, rec.WALMod = wi.Size(), wi.ModTime().UnixNano()
+ case !errors.Is(err, os.ErrNotExist):
+ return cleanRecord{}, false
+ }
+ ents, err := os.ReadDir(filepath.Join(metaPathOf(dbPath), "ltx", "0"))
+ if err != nil {
+ return cleanRecord{}, false
+ }
+ for _, e := range ents {
+ if _, hi, err := ltx.ParseFilename(e.Name()); err == nil && uint64(hi) > rec.TXID {
+ rec.TXID = uint64(hi)
+ }
+ }
+ return rec, rec.TXID != 0
+}
+
+// isContinuous reports whether the files are exactly as a clean close left
+// them. The record must be a regular file (never a link), for this
+// database; anything unreadable is not proof.
+func isContinuous(dbPath string) bool {
+ _, path, ok := recordPath(dbPath)
+ if !ok {
+ return false
+ }
+ fi, err := os.Lstat(path)
+ if err != nil || !fi.Mode().IsRegular() {
+ return false
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return false
+ }
+ var rec cleanRecord
+ if json.Unmarshal(raw, &rec) != nil || rec.V != 2 {
+ return false
+ }
+ now, ok := currentState(dbPath)
+ return ok && now == rec
+}
+
+// recordClean writes the clean record for dbPath's files as they are now.
+// Called only after a final sync and a store close that both succeeded.
+// The temporary file is a fresh one (O_EXCL), and the rename replaces
+// whatever is at the record's name rather than following it.
+func recordClean(dbPath string) error {
+ dir, path, ok := recordPath(dbPath)
+ if !ok {
+ return nil
+ }
+ rec, ok := currentState(dbPath)
+ if !ok {
+ return nil // nothing to vouch for: the next start takes a full image
+ }
+ raw, err := json.Marshal(rec)
+ if err != nil {
+ return err
+ }
+ f, err := os.CreateTemp(dir, ".clean-*.tmp")
+ if err != nil {
+ return err
+ }
+ tmp := f.Name()
+ if _, err = f.Write(raw); err == nil {
+ err = f.Sync()
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err == nil {
+ err = os.Rename(tmp, path)
+ }
+ if err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ return syncDir(dir)
+}
+
+// clearClean deletes the clean record, durably, before replication of
+// dbPath starts.
+func clearClean(dbPath string) error {
+ dir, path, ok := recordPath(dbPath)
+ if !ok {
+ return nil
+ }
+ err := os.Remove(path)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ return nil
+ case err != nil:
+ return err
+ }
+ return syncDir(dir)
+}
+
+// Protection is one database's start: whether it was continuous, and the
+// pin that keeps it so until Replicate's litestream holds its own lock.
+type Protection struct {
+ path string
+ continuous bool
+ db *sql.DB
+ tx *sql.Tx
+}
+
+// Continuous reports whether the database was exactly as its last clean
+// close left it, and is pinned.
+func (p *Protection) Continuous() bool { return p != nil && p.continuous }
+
+// Release drops the pin. Safe on nil and more than once.
+func (p *Protection) Release() {
+ if p == nil {
+ return
+ }
+ if p.tx != nil {
+ _ = p.tx.Rollback()
+ p.tx = nil
+ }
+ if p.db != nil {
+ _ = p.db.Close()
+ p.db = nil
+ }
+}
+
+var starts = struct {
+ sync.Mutex
+ m map[string]*Protection
+}{m: map[string]*Protection{}}
+
+// ProtectStart runs before anything that can write dbPath starts. It
+// pins the database, decides continuity under the pin, and deletes the
+// clean record. Replicate (or Checkpoint) of the same path takes the pin
+// over. An error means the start must not happen.
+func ProtectStart(dbPath string) (*Protection, error) {
+ ReleaseStart(dbPath)
+ p, err := protect(dbPath)
+ if err != nil {
+ return nil, err
+ }
+ starts.Lock()
+ starts.m[dbPath] = p
+ starts.Unlock()
+ return p, nil
+}
+
+// protect pins dbPath first and only then compares the files with the
+// clean record, so a process already running cannot write between the
+// decision and the pin: anything it wrote before shows in the files, and
+// anything after stays in the WAL. A database that cannot be pinned is not
+// continuous. The record is deleted before protect returns.
+func protect(dbPath string) (*Protection, error) {
+ p := &Protection{path: dbPath}
+ pinned, err := p.pin()
+ if err != nil {
+ return nil, fmt.Errorf("lease: pin %s: %w", dbPath, err)
+ }
+ p.continuous = pinned && isContinuous(dbPath)
+ if err := clearClean(dbPath); err != nil {
+ p.Release()
+ return nil, fmt.Errorf("lease: clear the clean record of %s: %w", dbPath, err)
+ }
+ return p, nil
+}
+
+// Drop releases p if it is still the pending protection of its path (a
+// start that will not reach Replicate). A later start's protection of the
+// same path is left alone.
+func (p *Protection) Drop() {
+ if p == nil {
+ return
+ }
+ starts.Lock()
+ if starts.m[p.path] == p {
+ delete(starts.m, p.path)
+ }
+ starts.Unlock()
+ p.Release()
+}
+
+// ReleaseStart drops dbPath's pending protection, if any: a start that
+// will not reach Replicate.
+func ReleaseStart(dbPath string) {
+ takeStart(dbPath).Release()
+}
+
+func takeStart(dbPath string) *Protection {
+ starts.Lock()
+ defer starts.Unlock()
+ p := starts.m[dbPath]
+ delete(starts.m, dbPath)
+ return p
+}
+
+// pin opens a read transaction on a WAL-mode database whose WAL and
+// shared-memory files already exist (a clean close leaves both). It
+// creates nothing and changes no mode: anything else is not pinned, and
+// Replicate snapshots instead.
+func (p *Protection) pin() (bool, error) {
+ for _, f := range []string{p.path + "-wal", p.path + "-shm"} {
+ if _, err := os.Stat(f); err != nil {
+ return false, nil
+ }
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), pinTimeout)
+ defer cancel()
+ db, err := sql.Open("sqlite", "file:"+p.path+"?_pragma=busy_timeout(5000)")
+ if err != nil {
+ return false, err
+ }
+ db.SetMaxOpenConns(1)
+ var mode string
+ if err := db.QueryRowContext(ctx, `PRAGMA journal_mode`).Scan(&mode); err != nil {
+ db.Close()
+ return false, err
+ }
+ if mode != "wal" {
+ db.Close()
+ return false, nil
+ }
+ // The transaction outlives ctx: it is held until Release, so it is
+ // begun on a context that does not end.
+ tx, err := db.BeginTx(context.WithoutCancel(ctx), nil)
+ if err != nil {
+ db.Close()
+ return false, err
+ }
+ var n int
+ if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_master`).Scan(&n); err != nil {
+ _ = tx.Rollback()
+ db.Close()
+ return false, err
+ }
+ p.db, p.tx = db, tx
+ return true, nil
+}
+
+// pinTimeout bounds opening the pin: a database it cannot read within it
+// is an error, and the start does not happen.
+const pinTimeout = 30 * time.Second
+
+// beginContinuity is where Replicate and Checkpoint decide: the pin a
+// ProtectStart left, or, with none, a pin taken now (protect), held by the
+// caller through its first sync. A database that cannot be pinned is not
+// continuous. The clean record is gone either way once it returns.
+func beginContinuity(dbPath string) (*Protection, bool, error) {
+ defer continuityDecided()
+ if p := takeStart(dbPath); p != nil {
+ return p, p.continuous, nil
+ }
+ p, err := protect(dbPath)
+ if err != nil {
+ if cerr := clearClean(dbPath); cerr != nil {
+ return nil, false, fmt.Errorf("lease: clear the clean record of %s: %w", dbPath, cerr)
+ }
+ log.Printf("lease: %s: %v (the start takes a full image)", dbPath, err)
+ return nil, false, nil
+ }
+ return p, p.continuous, nil
+}
+
+// continuityDecided runs as beginContinuity returns: a test's window to
+// write the database between the decision and the replication start.
+var continuityDecided = func() {}
+
+// firstSyncTimeout bounds the forced first sync that takes litestream's
+// read lock. A full image's upload, litestream's or a snapshot, gets
+// gapSnapshotTimeout plus the time the database's size takes at
+// gapSnapshotMinRate bytes a second, so a large database stays wakeable.
+// Any of them failing fails the start.
+var (
+ firstSyncTimeout = 30 * time.Second
+ gapSnapshotTimeout = 2 * time.Minute
+ gapSnapshotMinRate int64 = 1 << 20
+ firstSyncRetryBase = 100 * time.Millisecond
+)
+
+// imageBudget is the time a full image of path's database may take.
+func imageBudget(path string) time.Duration {
+ d := gapSnapshotTimeout
+ if fi, err := os.Stat(path); err == nil && gapSnapshotMinRate > 0 {
+ d += time.Duration(float64(fi.Size()) / float64(gapSnapshotMinRate) * float64(time.Second))
+ }
+ return d
+}
+
+// firstSync is litestream's first sync, which takes its read lock and
+// reads the replica's position. A continuous, pinned start retries a
+// failure until firstSyncTimeout: a replica listing that fails once must
+// not fail a wake whose WAL the pin holds anyway. An unproven start does
+// not wait.
+func firstSync(ctx context.Context, db *litestream.DB, continuous bool) error {
+ sctx, cancel := context.WithTimeout(ctx, firstSyncTimeout)
+ defer cancel()
+ wait := firstSyncRetryBase
+ for {
+ err := db.Sync(sctx)
+ if err == nil && db.PageSize() == 0 {
+ err = errors.New("the database did not initialize")
+ }
+ if err == nil || !continuous {
+ return err
+ }
+ select {
+ case <-sctx.Done():
+ return errors.Join(err, sctx.Err())
+ case <-time.After(wait):
+ }
+ wait = min(wait*2, 2*time.Second)
+ }
+}
+
+// startProtected is the first sync of a replication start, and, when
+// continuity is not proven, the full image the replica restarts from. It
+// returns once litestream holds its read lock and the replica either
+// continues or holds that image, uploaded, or with the error that means
+// the start must not serve.
+//
+// The image is litestream's own when its first sync was a full one (a
+// first replication, or a WAL it could see was truncated or removed): the
+// replica sync that uploads it must succeed before this returns.
+// Otherwise a snapshot of the live file is written to the replica now.
+func startProtected(ctx context.Context, db *litestream.DB, continuous bool) error {
+ if _, err := os.Stat(db.Path()); errors.Is(err, os.ErrNotExist) {
+ // A first start whose process has not created its file: nothing
+ // to lose. Local state was reset, so litestream's first sync of
+ // the file is a full image.
+ return nil
+ }
+ before := newestLocalL0(db)
+ if err := firstSync(ctx, db, continuous); err != nil {
+ return fmt.Errorf("lease: first sync of %s: %w", db.Path(), err)
+ }
+ if continuous {
+ return nil
+ }
+ sctx, cancel := context.WithTimeout(ctx, imageBudget(db.Path()))
+ defer cancel()
+ if path, ok := firstLocalL0After(db, before); ok && fullImage(path) {
+ pos, err := db.Pos()
+ if err == nil {
+ err = awaitUploaded(sctx, db, pos.TXID)
+ }
+ if err != nil {
+ return fmt.Errorf("lease: upload of %s's full image: %w", db.Path(), err)
+ }
+ return nil
+ }
+ pos, err := db.Pos()
+ if err != nil {
+ return fmt.Errorf("lease: position of %s: %w", db.Path(), err)
+ }
+ info, err := writeSnapshot(sctx, db)
+ if err != nil {
+ // litestream's own snapshot monitor runs at Open and, when a
+ // snapshot is due, writes the same file at the same moment.
+ // Either copy will do if it reaches this position.
+ have, lerr := db.Replica.MaxLTXFileInfo(sctx, litestream.SnapshotLevel)
+ if lerr != nil || have.MinTXID != 1 || have.MaxTXID < pos.TXID {
+ return fmt.Errorf("lease: snapshot of %s (continuity not proven): %w", db.Path(), err)
+ }
+ info = &have
+ }
+ log.Printf("lease: %s: continuity with the last clean close not proven; snapshot 1-%s written before serving", db.Path(), info.MaxTXID)
+ return nil
+}
+
+// awaitUploaded waits until the replica's position reaches txid. Where
+// the replica's own monitor uploads (it holds the replica's lock while it
+// does), this watches rather than syncing a second time: a hung upload
+// ends at ctx, and the caller's store close cancels it.
+func awaitUploaded(ctx context.Context, db *litestream.DB, txid ltx.TXID) error {
+ if !db.Replica.MonitorEnabled {
+ // A one-shot store (a checkpoint) has no monitor to wait for:
+ // nothing else holds the replica's lock, so sync it here.
+ if err := db.Replica.Sync(ctx); err != nil {
+ return err
+ }
+ }
+ for {
+ if db.Replica.Pos().TXID >= txid {
+ return nil
+ }
+ select {
+ case <-ctx.Done():
+ return fmt.Errorf("the replica is at %s, the image at %s: %w", db.Replica.Pos().TXID, txid, ctx.Err())
+ case <-time.After(50 * time.Millisecond):
+ }
+ }
+}
+
+// newestLocalL0 is the highest TXID among the local L0 files (0: none).
+func newestLocalL0(db *litestream.DB) ltx.TXID {
+ ents, _ := os.ReadDir(db.LTXLevelDir(0))
+ var hi ltx.TXID
+ for _, e := range ents {
+ if _, max, err := ltx.ParseFilename(e.Name()); err == nil && max > hi {
+ hi = max
+ }
+ }
+ return hi
+}
+
+// firstLocalL0After is the oldest local L0 file starting after txid: the
+// first file this start's sync wrote.
+func firstLocalL0After(db *litestream.DB, txid ltx.TXID) (string, bool) {
+ ents, err := os.ReadDir(db.LTXLevelDir(0))
+ if err != nil {
+ return "", false
+ }
+ var lo, hi ltx.TXID
+ for _, e := range ents {
+ min, max, err := ltx.ParseFilename(e.Name())
+ if err != nil || min <= txid {
+ continue
+ }
+ if lo == 0 || min < lo {
+ lo, hi = min, max
+ }
+ }
+ if lo == 0 {
+ return "", false
+ }
+ return db.LTXPath(0, lo, hi), true
+}
+
+// fullImage reports whether the LTX file at path holds every page of its
+// database, 1 to its commit less SQLite's lock page: what litestream
+// writes when it snapshots. An incremental file stops being contiguous at
+// its first unchanged page, so this reads only that far. Anything
+// unreadable is not a full image.
+func fullImage(path string) bool {
+ f, err := os.Open(path)
+ if err != nil {
+ return false
+ }
+ defer f.Close()
+ dec := ltx.NewDecoder(f)
+ if err := dec.DecodeHeader(); err != nil {
+ return false
+ }
+ h := dec.Header()
+ lock := ltx.LockPgno(h.PageSize)
+ buf := make([]byte, h.PageSize)
+ want := uint32(1)
+ for {
+ if want == lock {
+ want++
+ }
+ var ph ltx.PageHeader
+ if err := dec.DecodePage(&ph, buf); err == io.EOF {
+ break
+ } else if err != nil || ph.Pgno != want {
+ return false
+ }
+ want++
+ }
+ if want == lock {
+ want++
+ }
+ return h.Commit > 0 && want > h.Commit
+}
+
+// writeSnapshot is litestream's DB.Snapshot, closing its reader on every
+// outcome (snapshotWithin says why).
+func writeSnapshot(ctx context.Context, db *litestream.DB) (*ltx.FileInfo, error) {
+ pos, rd, err := db.SnapshotReader(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if c, ok := rd.(io.Closer); ok {
+ defer c.Close()
+ }
+ return db.Replica.Client.WriteLTXFile(ctx, litestream.SnapshotLevel, 1, pos.TXID, rd)
+}
diff --git a/internal/lease/continuity_round3_test.go b/internal/lease/continuity_round3_test.go
new file mode 100644
index 000000000..76bcfaefb
--- /dev/null
+++ b/internal/lease/continuity_round3_test.go
@@ -0,0 +1,259 @@
+package lease
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
+)
+
+// Round 3 of #1290 (the review of f1fe437e).
+
+// H1: an unpinned Replicate racing a live process. The record is intact
+// and the process is open; it migrates right after the continuity
+// decision. Replicate must pin before it decides, and hold the pin
+// through its first sync.
+func TestUnpinnedReplicateRacingAProcessRestoresWhole(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := openWakeApp(t, g.path)
+ prev := continuityDecided
+ t.Cleanup(func() { continuityDecided = prev })
+ once := false
+ continuityDecided = func() {
+ if !once {
+ once = true
+ g.migrateOn(app, bigMigration)
+ }
+ }
+ if err := g.replicateAndStop(g.held(nil), app, "second wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("second wake")
+}
+
+// slowSnapshots is a store that takes delay before each level-9 write.
+type slowSnapshots struct {
+ litestream.ReplicaClient
+ delay time.Duration
+}
+
+func (c *slowSnapshots) WriteLTXFile(ctx context.Context, level int, lo, hi ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ if level == litestream.SnapshotLevel {
+ select {
+ case <-time.After(c.delay):
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+ return c.ReplicaClient.WriteLTXFile(ctx, level, lo, hi, r)
+}
+
+// H2: a full image's time is scaled to the database's size, so a large
+// database under a slow store still wakes: a fixed bound shorter than the
+// store's time would fail every retry the same way.
+func TestFullImageBudgetScalesWithDatabaseSize(t *testing.T) {
+ prevBase, prevRate := gapSnapshotTimeout, gapSnapshotMinRate
+ gapSnapshotTimeout, gapSnapshotMinRate = 50*time.Millisecond, 1<<20
+ t.Cleanup(func() { gapSnapshotTimeout, gapSnapshotMinRate = prevBase, prevRate })
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ if fi, err := os.Stat(g.path); err != nil || fi.Size() < 4<<20 {
+ t.Fatalf("the database is not large enough to need its size's time: %v %v", fi, err)
+ }
+ slow := &slowSnapshots{ReplicaClient: serialFile(g.replica), delay: 500 * time.Millisecond}
+ if err := g.replicateAndStop(g.held(slow), app, "slow store wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("slow store wake")
+}
+
+// M1: the record is written through a fresh temporary file and never
+// through a link, and a record that is a link is not trusted.
+func TestCleanRecordIgnoresPlantedSymlinks(t *testing.T) {
+ g := newGapRig(t)
+ outside := filepath.Join(t.TempDir(), "outside")
+ if err := os.WriteFile(outside, []byte("untouched"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ app := openWakeApp(t, g.path)
+ r, err := g.held(nil).Replicate(ctx, g.path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Planted while replication runs: the old in-tree temporary name.
+ meta := metaPathOf(g.path)
+ if err := os.Symlink(outside, filepath.Join(meta, "carlos-clean.json.tmp")); err != nil {
+ t.Fatal(err)
+ }
+ wakeExec(t, app, `INSERT INTO t (body) VALUES ('linked')`)
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ app.Close()
+ if err := r.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := os.ReadFile(outside); string(b) != "untouched" {
+ t.Fatalf("the record was written through a planted link: %q", b)
+ }
+ _, rec, ok := recordPath(g.path)
+ if !ok {
+ t.Fatal("no record path")
+ }
+ copyOf := filepath.Join(t.TempDir(), "copy.json")
+ raw, err := os.ReadFile(rec)
+ if err != nil {
+ t.Fatalf("no clean record after a clean close: %v", err)
+ }
+ if err := os.WriteFile(copyOf, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(rec); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(copyOf, rec); err != nil {
+ t.Fatal(err)
+ }
+ p, err := ProtectStart(g.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ReleaseStart(g.path)
+ if p.Continuous() {
+ t.Fatal("a record that is a link was trusted")
+ }
+}
+
+// M2: the app can write everything beside its database. A record it
+// rewrites there from the files' current state is not trusted.
+func TestForgedCleanRecordIsNotTrusted(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := openWakeApp(t, g.path)
+ defer app.Close() // still running: its WAL stays, so the database can be pinned
+ wakeExec(t, app, `INSERT INTO t (body) VALUES ('outside the replica')`)
+ forgeRecordBesideDB(t, g.path)
+ p, err := ProtectStart(g.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ReleaseStart(g.path)
+ if p.Continuous() {
+ t.Fatal("a record the app wrote beside its database was trusted")
+ }
+}
+
+// forgeRecordBesideDB writes, in the litestream meta directory, the record
+// the files make now, in the shape an in-tree record had.
+func forgeRecordBesideDB(t *testing.T, dbPath string) {
+ t.Helper()
+ fi, err := os.Stat(dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ walSize, walMod := int64(-1), int64(0)
+ if wi, err := os.Stat(dbPath + "-wal"); err == nil {
+ walSize, walMod = wi.Size(), wi.ModTime().UnixNano()
+ }
+ meta := metaPathOf(dbPath)
+ ents, err := os.ReadDir(filepath.Join(meta, "ltx", "0"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var txid uint64
+ for _, e := range ents {
+ if _, hi, err := ltx.ParseFilename(e.Name()); err == nil && uint64(hi) > txid {
+ txid = uint64(hi)
+ }
+ }
+ raw, _ := json.Marshal(map[string]any{"v": 1, "txid": txid, "db_size": fi.Size(), "db_mtime_ns": fi.ModTime().UnixNano(), "wal_size": walSize, "wal_mtime_ns": walMod})
+ if err := os.WriteFile(filepath.Join(meta, "carlos-clean.json"), raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// refusingUploads refuses every upload.
+type refusingUploads struct{ litestream.ReplicaClient }
+
+func (refusingUploads) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ return nil, errors.New("upload refused")
+}
+
+// M3: a full image must be uploaded before Replicate returns: on a first
+// start, and after a gap that removed the WAL (litestream's own first file
+// is then the full image).
+func TestFullImageUploadIsConfirmedBeforeServing(t *testing.T) {
+ prevBase, prevRate := gapSnapshotTimeout, gapSnapshotMinRate
+ gapSnapshotTimeout, gapSnapshotMinRate = time.Second, 1<<40
+ t.Cleanup(func() { gapSnapshotTimeout, gapSnapshotMinRate = prevBase, prevRate })
+ t.Run("first start", func(t *testing.T) {
+ g := newGapRig(t)
+ app := openWakeApp(t, g.path)
+ bad := refusingUploads{serialFile(g.replica)}
+ if err := g.replicateAndStop(g.held(bad), app, "unuploaded"); err == nil {
+ t.Fatal("Replicate returned before its first image was uploaded")
+ }
+ })
+ t.Run("gap with the WAL removed", func(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := openWakeApp(t, g.path)
+ wakeExec(t, app, `INSERT INTO t (body) VALUES ('outside the replica')`)
+ app.Close() // the last connection: SQLite checkpoints and removes the WAL
+ if _, err := os.Stat(g.path + "-wal"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the WAL is still there: %v", err)
+ }
+ app = openWakeApp(t, g.path)
+ bad := refusingUploads{serialFile(g.replica)}
+ if err := g.replicateAndStop(g.held(bad), app, "unuploaded"); err == nil {
+ t.Fatal("Replicate returned before the full image was uploaded")
+ }
+ })
+}
+
+// flakyListing fails the first n replica listings.
+type flakyListing struct {
+ litestream.ReplicaClient
+ n atomic.Int32
+}
+
+func (c *flakyListing) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ if c.n.Add(-1) >= 0 {
+ return nil, errors.New("listing failed once")
+ }
+ return c.ReplicaClient.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+// A pinned, continuous start retries a replica read that fails, within
+// firstSyncTimeout, instead of failing the wake on the first error.
+func TestPinnedReplicateRetriesATransientReplicaRead(t *testing.T) {
+ prev := firstSyncRetryBase
+ firstSyncRetryBase = 10 * time.Millisecond
+ t.Cleanup(func() { firstSyncRetryBase = prev })
+ g := newGapRig(t)
+ g.wake("first wake")
+ p, err := ProtectStart(g.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !p.Continuous() {
+ t.Fatal("not continuous after a clean close")
+ }
+ app := openWakeApp(t, g.path)
+ flaky := &flakyListing{ReplicaClient: serialFile(g.replica)}
+ flaky.n.Store(2)
+ if err := g.replicateAndStop(g.held(flaky), app, "retried"); err != nil {
+ t.Fatalf("a pinned start failed on a transient listing error: %v", err)
+ }
+}
diff --git a/internal/lease/continuity_test.go b/internal/lease/continuity_test.go
new file mode 100644
index 000000000..36afa2d97
--- /dev/null
+++ b/internal/lease/continuity_test.go
@@ -0,0 +1,335 @@
+package lease
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+)
+
+// Replicate before start (docs/superpowers/specs/2026-11-19-replicate-
+// before-start.md, discussion #1290). A wake used to start the process
+// before Replicate. A large write in that gap (a schema migration on boot)
+// trips SQLite's autocheckpoint, the next write restarts the WAL, and
+// litestream v0.5.14 carries on incrementally from the new WAL: the
+// replica lacks every migrated page and each restore after it is
+// malformed.
+
+// gapRig is one database replicated to one local replica directory across
+// several wakes.
+type gapRig struct {
+ t *testing.T
+ backend *lockStore
+ path string
+ replica string
+ rows int // rows the migration wrote
+}
+
+func newGapRig(t *testing.T) *gapRig {
+ t.Helper()
+ g := &gapRig{t: t, backend: &lockStore{}, path: filepath.Join(t.TempDir(), "app.db"), replica: t.TempDir()}
+ seedDB(t, g.path)
+ useContinuityDir(t)
+ return g
+}
+
+// useContinuityDir gives the test an agent continuity directory of its
+// own, as the agent sets one at startup.
+func useContinuityDir(t *testing.T) string {
+ t.Helper()
+ dir := t.TempDir()
+ if err := SetContinuityDir(dir); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { setContinuityDirForTest("") })
+ return dir
+}
+
+func (g *gapRig) held(client litestream.ReplicaClient) *Held {
+ g.t.Helper()
+ h := localHeld(g.t, g.backend, 10*time.Second)
+ if client == nil {
+ client = serialFile(g.replica)
+ }
+ h.replicaClient = client
+ return h
+}
+
+// wake is a clean wake and hibernation in the order the activator keeps:
+// the process runs, Replicate, a write, the process stops, then the
+// replicator closes.
+func (g *gapRig) wake(body string) {
+ g.t.Helper()
+ ctx := context.Background()
+ app := openWakeApp(g.t, g.path)
+ r, err := g.held(nil).Replicate(ctx, g.path, 0)
+ if err != nil {
+ g.t.Fatal(err)
+ }
+ wakeExec(g.t, app, `INSERT INTO t (body) VALUES ('`+body+`')`)
+ if err := r.SyncAndWait(ctx); err != nil {
+ g.t.Fatal(err)
+ }
+ app.Close()
+ if err := r.Close(ctx); err != nil {
+ g.t.Fatal(err)
+ }
+}
+
+// migrate is a process that writes while nothing replicates: a migration
+// large enough to trip the autocheckpoint, then a write that restarts the
+// WAL. It returns the process, still running.
+func (g *gapRig) migrate(rows int) *sql.DB {
+ g.t.Helper()
+ app := openWakeApp(g.t, g.path)
+ g.migrateOn(app, rows)
+ return app
+}
+
+// migrateOn is migrate in a process already running.
+func (g *gapRig) migrateOn(app *sql.DB, rows int) {
+ g.t.Helper()
+ g.rows = rows
+ wakeExec(g.t, app, `CREATE TABLE m (id INTEGER PRIMARY KEY, body TEXT)`)
+ wakeExec(g.t, app, `CREATE INDEX m_body ON m(body)`)
+ tx, err := app.Begin()
+ if err != nil {
+ g.t.Fatal(err)
+ }
+ for i := 0; i < rows; i++ {
+ if _, err := tx.Exec(`INSERT INTO m (body) VALUES (?)`, strings.Repeat(fmt.Sprint(i), 40)); err != nil {
+ g.t.Fatal(err)
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ g.t.Fatal(err)
+ }
+ wakeExec(g.t, app, `INSERT INTO t (body) VALUES ('after the migration')`)
+}
+
+// replicateAndStop finishes a wake whose process is app: Replicate on h,
+// a write, a sync, the process stops, the replicator closes.
+func (g *gapRig) replicateAndStop(h *Held, app *sql.DB, body string) error {
+ g.t.Helper()
+ ctx := context.Background()
+ r, err := h.Replicate(ctx, g.path, 0)
+ if err != nil {
+ // The failed wake's cleanup: the process stops, the lease goes back.
+ app.Close()
+ _ = h.Release(ctx)
+ return err
+ }
+ wakeExec(g.t, app, `INSERT INTO t (body) VALUES ('`+body+`')`)
+ if err := r.SyncAndWait(ctx); err != nil {
+ g.t.Fatal(err)
+ }
+ app.Close()
+ cctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ return r.Close(cctx)
+}
+
+// restoresWhole restores the newest copy and checks it holds the
+// migration and the write after it.
+func (g *gapRig) restoresWhole(last string) {
+ g.t.Helper()
+ assertRestoresWhole(g.t, g.replica, g.rows, last)
+}
+
+func assertRestoresWhole(t *testing.T, replica string, rows int, last string) {
+ t.Helper()
+ ctx := context.Background()
+ out := filepath.Join(t.TempDir(), "restored.db")
+ opt := litestream.NewRestoreOptions()
+ opt.OutputPath = out
+ if err := litestream.NewReplicaWithClient(nil, lsfile.NewReplicaClient(replica)).Restore(ctx, opt); err != nil {
+ t.Fatalf("restore: %v", err)
+ }
+ d, err := sql.Open("sqlite", "file:"+out+"?mode=ro")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ var ok string
+ if err := d.QueryRow(`PRAGMA integrity_check`).Scan(&ok); err != nil || ok != "ok" {
+ t.Fatalf("restored copy: integrity_check %q, %v", ok, err)
+ }
+ var m, n int
+ if err := d.QueryRow(`SELECT count(*) FROM m`).Scan(&m); err != nil || m != rows {
+ t.Fatalf("restored copy holds %d migrated rows (%v), want %d", m, err, rows)
+ }
+ if err := d.QueryRow(`SELECT count(*) FROM t WHERE body = ?`, last).Scan(&n); err != nil || n != 1 {
+ t.Fatalf("restored copy lacks %q: %d, %v", last, n, err)
+ }
+}
+
+// serialWrites is a local replica whose writes go one at a time. A
+// start's snapshot and the store's own first snapshot can write the same
+// file at the same moment; S3 takes each PUT whole, but litestream's file
+// client shares one temporary name, and two writers interleave in it.
+type serialWrites struct {
+ litestream.ReplicaClient
+ mu sync.Mutex
+}
+
+func (c *serialWrites) WriteLTXFile(ctx context.Context, level int, lo, hi ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.ReplicaClient.WriteLTXFile(ctx, level, lo, hi, r)
+}
+
+// serialFile is a local replica in dir with serialWrites.
+func serialFile(dir string) litestream.ReplicaClient {
+ return &serialWrites{ReplicaClient: lsfile.NewReplicaClient(dir)}
+}
+
+// bigMigration trips SQLite's 1000-frame autocheckpoint.
+const bigMigration = 20000
+
+// The process ran before Replicate (the claim wake's order, or any start
+// that took no pin): Replicate cannot prove continuity and snapshots.
+func TestReplicateAfterUnreplicatedWALRestartRestoresWhole(t *testing.T) {
+ for _, rows := range []int{50, bigMigration} {
+ t.Run(fmt.Sprint(rows), func(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(rows)
+ if err := g.replicateAndStop(g.held(nil), app, "second wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("second wake")
+ })
+ }
+}
+
+// failingSnapshots refuses level-9 writes while fail is set.
+type failingSnapshots struct {
+ litestream.ReplicaClient
+ fail atomic.Bool
+ hang atomic.Bool
+ tries atomic.Int32
+}
+
+func (c *failingSnapshots) WriteLTXFile(ctx context.Context, level int, lo, hi ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ if level == litestream.SnapshotLevel {
+ c.tries.Add(1)
+ if c.hang.Load() {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ if c.fail.Load() {
+ return nil, errors.New("snapshot refused")
+ }
+ }
+ return c.ReplicaClient.WriteLTXFile(ctx, level, lo, hi, r)
+}
+
+// Astra round 1, High 1: a repair that fails must be retried. Replicate
+// refuses (the wake does not serve), and the next Replicate repairs
+// again, however far the local state moved in between.
+func TestGapRepairFailureIsRetried(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ bad := &failingSnapshots{ReplicaClient: serialFile(g.replica)}
+ bad.fail.Store(true)
+ if err := g.replicateAndStop(g.held(bad), app, "refused wake"); err == nil {
+ t.Fatal("Replicate served across a gap whose snapshot failed")
+ }
+ // The retry: a fresh process, a working replica.
+ app = openWakeApp(t, g.path)
+ if err := g.replicateAndStop(g.held(nil), app, "retried wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("retried wake")
+}
+
+// Astra round 1, High 2: missing local metadata is not proof of
+// continuity, even with a replica that already holds history.
+func TestReplicateWithoutLocalMetadataRestoresWhole(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ meta := filepath.Join(filepath.Dir(g.path), ".activator-"+filepath.Base(g.path)+"-litestream")
+ if err := os.RemoveAll(meta); err != nil {
+ t.Fatal(err)
+ }
+ if err := g.replicateAndStop(g.held(nil), app, "second wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("second wake")
+}
+
+// Astra round 1, High 3: a repair whose upload times out fails Replicate
+// within its bound instead of leaving the process running unprotected,
+// and the next wake repairs.
+func TestGapRepairTimeoutFailsReplicateAndIsRetried(t *testing.T) {
+ prev, prevRate := gapSnapshotTimeout, gapSnapshotMinRate
+ gapSnapshotTimeout, gapSnapshotMinRate = 300*time.Millisecond, 1<<40
+ t.Cleanup(func() { gapSnapshotTimeout, gapSnapshotMinRate = prev, prevRate })
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ slow := &failingSnapshots{ReplicaClient: serialFile(g.replica)}
+ slow.hang.Store(true)
+ start := time.Now()
+ err := g.replicateAndStop(g.held(slow), app, "timed out wake")
+ if err == nil {
+ t.Fatal("Replicate returned with its repair snapshot still hanging")
+ }
+ if d := time.Since(start); d > 20*time.Second {
+ t.Fatalf("Replicate took %s on a 300 ms repair budget", d)
+ }
+ gapSnapshotTimeout, gapSnapshotMinRate = prev, prevRate // the retry gets the real budget
+ app = openWakeApp(t, g.path)
+ if err := g.replicateAndStop(g.held(nil), app, "retried wake"); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("retried wake")
+}
+
+// Astra round 1, High 4 (moves): a checkpoint across the gap snapshots.
+func TestCheckpointAcrossGapRestoresWhole(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ app := g.migrate(bigMigration)
+ defer app.Close()
+ if _, err := g.held(nil).Checkpoint(context.Background(), g.path); err != nil {
+ t.Fatal(err)
+ }
+ g.restoresWhole("after the migration")
+}
+
+// openWakeApp opens path the way an app does: its own WAL connection, with
+// SQLite's default autocheckpoint.
+func openWakeApp(t *testing.T, path string) *sql.DB {
+ t.Helper()
+ d, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ d.SetMaxOpenConns(1)
+ if err := d.Ping(); err != nil {
+ t.Fatal(err)
+ }
+ return d
+}
+
+func wakeExec(t *testing.T, d *sql.DB, q string) {
+ t.Helper()
+ if _, err := d.Exec(q); err != nil {
+ t.Fatalf("%s: %v", q, err)
+ }
+}
diff --git a/internal/lease/export_test.go b/internal/lease/export_test.go
index e9d2e62f6..69fdbe873 100644
--- a/internal/lease/export_test.go
+++ b/internal/lease/export_test.go
@@ -171,3 +171,23 @@ func SetBoxNowForTest(now func() time.Time) (restore func()) {
func NewReplicaClientForTest(bucket, prefix, region string) (litestream.ReplicaClient, error) {
return newReplicaClient(bucket, prefix, region)
}
+
+// setContinuityDirForTest sets the continuity directory without creating
+// it; "" is none.
+func setContinuityDirForTest(dir string) {
+ continuityDir.Lock()
+ continuityDir.dir = dir
+ continuityDir.Unlock()
+}
+
+// SetContinuityDirForTest is setContinuityDirForTest for the external
+// tests.
+var SetContinuityDirForTest = setContinuityDirForTest
+
+// SetImageBudgetForTest bounds a full image's upload at d, whatever the
+// database's size, for the test.
+func SetImageBudgetForTest(t interface{ Cleanup(func()) }, d time.Duration) {
+ prev, prevRate := gapSnapshotTimeout, gapSnapshotMinRate
+ gapSnapshotTimeout, gapSnapshotMinRate = d, 1<<40
+ t.Cleanup(func() { gapSnapshotTimeout, gapSnapshotMinRate = prev, prevRate })
+}
diff --git a/internal/lease/fence_test.go b/internal/lease/fence_test.go
index ed16d1536..3e37812fa 100644
--- a/internal/lease/fence_test.go
+++ b/internal/lease/fence_test.go
@@ -86,6 +86,10 @@ func (c *failingReplica) DeleteAll(ctx context.Context) error {
// finalization's calls.
type hangingReplica struct {
failingReplica
+ // open passes writes straight through while set: Replicate's first
+ // image must upload before it returns (replicate before start,
+ // #1290), so a rig opens the replica for the start and closes it after.
+ open atomic.Bool
entered chan struct{}
enterOnce sync.Once
cancelled atomic.Int32 // hung writes whose context ended
@@ -98,6 +102,15 @@ func newHangingReplica(t *testing.T) *hangingReplica {
return &hangingReplica{failingReplica: *newFailingReplica(t), entered: make(chan struct{})}
}
+// started is fencedReplicator over c, with c open for the start only.
+func (c *hangingReplica) started(t *testing.T, h *lease.Held) *fenceRig {
+ t.Helper()
+ c.open.Store(true)
+ g := fencedReplicator(t, h, c)
+ c.open.Store(false)
+ return g
+}
+
func (c *hangingReplica) rec(e string) {
c.mu.Lock()
defer c.mu.Unlock()
@@ -127,6 +140,9 @@ func (c *hangingReplica) OpenLTXFile(ctx context.Context, level int, minTXID, ma
}
func (c *hangingReplica) WriteLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ if c.open.Load() {
+ return c.failingReplica.WriteLTXFile(ctx, level, minTXID, maxTXID, r)
+ }
c.count(ctx)
c.rec("replica write")
if !lease.FinalizingForTest(ctx) {
@@ -333,7 +349,7 @@ func TestWriteFenceFiresAfterAnEarlierLoss(t *testing.T) {
fx := leasetest.NewLockFixture(t)
c := newHangingReplica(t)
h := haHeldTTL(t, fx, "instances/f", 3*time.Second)
- g := fencedReplicator(t, h, c)
+ g := c.started(t, h)
addRows(t, g.path, 3)
g.capture(t)
waitClosed(t, c.entered, 10*time.Second, "the replica upload")
@@ -418,6 +434,10 @@ func TestWriteFenceNoDatabaseNeverTrips(t *testing.T) {
t.Fatalf("WAL not frameless: %v %v", fi, err)
}
g := fencedReplicatorAt(t, haHeld(t, fx, "instances/f"), lsfile.NewReplicaClient(t.TempDir()), path)
+ // Replicate's first sync (replicate before start, #1290) writes
+ // litestream's own first frame and captures it; the rig's
+ // one-hour monitor would ship it much later, so ship it here.
+ g.syncAndWait(t)
g.steps(t, 0, 59, nil)
})
}
@@ -443,10 +463,13 @@ func TestWriteFenceUncapturedAtFirstLook(t *testing.T) {
haBox(t)
fx := leasetest.NewLockFixture(t)
c := newFailingReplica(t)
- c.down.Store(true)
path := tempDB(t)
holdOpen(t, path)
+ // The replica goes down once Replicate has started: its first sync
+ // (replicate before start, #1290) needs it, and a start that cannot
+ // reach it does not serve.
g := fencedReplicatorAt(t, haHeld(t, fx, "instances/f"), c, path)
+ c.down.Store(true)
t.Cleanup(func() { c.down.Store(false) }) // before the rig's Close
addRows(t, path, 3)
if fi, err := os.Stat(path + "-wal"); err != nil || fi.Size() <= 32 {
@@ -535,7 +558,7 @@ func TestWriteFenceReleaseKeepsItsDeadlineBehindAHungUpload(t *testing.T) {
t.Cleanup(lease.SetOwedClockForTest(func() time.Time { return now }))
fx := leasetest.NewLockFixture(t)
c := newHangingReplica(t)
- g := fencedReplicator(t, haHeld(t, fx, "instances/f"), c)
+ g := c.started(t, haHeld(t, fx, "instances/f"))
addRows(t, g.path, 5)
g.capture(t)
waitClosed(t, c.entered, 10*time.Second, "the replica upload")
diff --git a/internal/lease/gentake_test.go b/internal/lease/gentake_test.go
index 4ed765ed6..b35c00540 100644
--- a/internal/lease/gentake_test.go
+++ b/internal/lease/gentake_test.go
@@ -723,7 +723,13 @@ func TestGenerationWriterRunsRetention(t *testing.T) {
if _, ok := fx.m.Current(fx.bucket, k); ok {
t.Errorf("%s: retention's delete left it current", k)
}
- if !strings.HasPrefix(k, replicagen.Prefix(fx.loc, tk.Generation)+"0000/") {
+ // Snapshot retention may run in the same window: Replicate's
+ // first sync (replicate before start, #1290) readies the store
+ // before the snapshot level's first pass, which now runs here
+ // rather than a second later. Its deletes are inside the
+ // generation too.
+ g := replicagen.Prefix(fx.loc, tk.Generation)
+ if !strings.HasPrefix(k, g+"0000/") && !strings.HasPrefix(k, g+"0009/") {
t.Errorf("%s: L0 retention deleted outside L0", k)
}
}
diff --git a/internal/lease/ha_continuity_test.go b/internal/lease/ha_continuity_test.go
new file mode 100644
index 000000000..fbca64840
--- /dev/null
+++ b/internal/lease/ha_continuity_test.go
@@ -0,0 +1,147 @@
+package lease_test
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "io"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ leasetest "github.com/carlosframework/platform/internal/lease/locktest"
+)
+
+// Astra round 1, High 4 (HA): an HA lease's Replicate across a gap (the
+// process migrated before replication began) snapshots like any other, so
+// the newest restore is whole (discussion #1290).
+func TestHAReplicateAcrossGapRestoresWhole(t *testing.T) {
+ haBox(t)
+ fx := leasetest.NewLockFixture(t)
+ replica := t.TempDir()
+ path := tempDB(t)
+ // One client for both wakes, its writes one at a time: the start's
+ // snapshot and the store's own first snapshot can write the same file
+ // together, which S3 takes whole and litestream's file client does not.
+ client := &serialClient{ReplicaClient: lsfile.NewReplicaClient(replica)}
+
+ // A first wake under an ordinary lease, closed cleanly.
+ h, err := lease.Acquire(ctx, fx.Bucket, "instances/first", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ lease.SetReplicaClientForTest(h, client)
+ app := openApp(t, path)
+ r, err := h.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ execOn(t, app, `INSERT INTO t (body) VALUES ('first wake')`)
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ app.Close()
+ if err := r.Close(ctx); err != nil {
+ t.Fatal(err)
+ }
+
+ // The process migrates before replication starts.
+ const rows = 20000
+ app = openApp(t, path)
+ execOn(t, app, `CREATE TABLE m (id INTEGER PRIMARY KEY, body TEXT)`)
+ execOn(t, app, `CREATE INDEX m_body ON m(body)`)
+ tx, err := app.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < rows; i++ {
+ if _, err := tx.Exec(`INSERT INTO m (body) VALUES (?)`, strings.Repeat(fmt.Sprint(i), 40)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ execOn(t, app, `INSERT INTO t (body) VALUES ('after the migration')`)
+
+ // The HA wake.
+ ha, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/ha", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1"}, hafresh.Proofs{LocalEligible: func() bool { return true }}, lease.LeaseTTL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lease.SetReplicaClientForTest(ha, client)
+ hr, err := ha.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ execOn(t, app, `INSERT INTO t (body) VALUES ('ha wake')`)
+ if err := hr.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ app.Close()
+ if err := hr.ReleaseMarker(ctx, hafresh.Marker{V: 1, Clean: true}); err != nil {
+ t.Fatal(err)
+ }
+
+ out := filepath.Join(t.TempDir(), "restored.db")
+ opt := litestream.NewRestoreOptions()
+ opt.OutputPath = out
+ if err := litestream.NewReplicaWithClient(nil, lsfile.NewReplicaClient(replica)).Restore(ctx, opt); err != nil {
+ t.Fatalf("restore: %v", err)
+ }
+ d, err := sql.Open("sqlite", "file:"+out+"?mode=ro")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ var ok string
+ if err := d.QueryRow(`PRAGMA integrity_check`).Scan(&ok); err != nil || ok != "ok" {
+ t.Fatalf("restored copy: integrity_check %q, %v", ok, err)
+ }
+ var m, n int
+ if err := d.QueryRow(`SELECT count(*) FROM m`).Scan(&m); err != nil || m != rows {
+ t.Fatalf("restored copy holds %d migrated rows (%v), want %d", m, err, rows)
+ }
+ if err := d.QueryRow(`SELECT count(*) FROM t WHERE body = 'ha wake'`).Scan(&n); err != nil || n != 1 {
+ t.Fatalf("restored copy lacks the HA wake's write: %d, %v", n, err)
+ }
+}
+
+func openApp(t *testing.T, path string) *sql.DB {
+ t.Helper()
+ d, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ d.SetMaxOpenConns(1)
+ if err := d.Ping(); err != nil {
+ t.Fatal(err)
+ }
+ return d
+}
+
+func execOn(t *testing.T, d *sql.DB, q string) {
+ t.Helper()
+ if _, err := d.Exec(q); err != nil {
+ t.Fatalf("%s: %v", q, err)
+ }
+}
+
+// serialClient is a replica client whose writes go one at a time.
+type serialClient struct {
+ litestream.ReplicaClient
+ mu sync.Mutex
+}
+
+func (c *serialClient) WriteLTXFile(ctx context.Context, level int, lo, hi ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.ReplicaClient.WriteLTXFile(ctx, level, lo, hi, r)
+}
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index 6cef18bc1..1ed56bbef 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -455,11 +455,29 @@ func (h *Held) Replicate(ctx context.Context, dbPath string, syncInterval time.D
gate = newFenceGate(db.Replica.Client)
db.Replica.Client = gate
}
+ // Replicate before start (continuity.go): the pin a ProtectStart left,
+ // or the files' own state, decides whether the replica can continue.
+ pin, continuous, err := beginContinuity(dbPath)
+ if err != nil {
+ return nil, err
+ }
+ defer pin.Release()
+ if _, serr := os.Stat(dbPath); errors.Is(serr, os.ErrNotExist) {
+ // A first start: no history of this file can be continued.
+ if err := db.ResetLocalState(opCtx); err != nil {
+ return nil, err
+ }
+ }
if err := store.Open(opCtx); err != nil {
cancel()
closeErr := store.Close(opCtx)
return nil, errors.Join(fmt.Errorf("open litestream store: %w", err), closeErr)
}
+ if err := startProtected(opCtx, db, continuous); err != nil {
+ cancel()
+ closeErr := store.Close(opCtx)
+ return nil, errors.Join(err, closeErr)
+ }
if err := h.rn.Err(); err != nil {
cancel()
closeErr := store.Close(opCtx)
@@ -486,7 +504,7 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
db := litestream.NewDB(dbPath)
// Preserve the activator namespace: sharing the default metadata directory
// with another replicator corrupts shadow state even across sequential runs.
- db.SetMetaPath(filepath.Join(filepath.Dir(dbPath), ".activator-"+filepath.Base(dbPath)+"-litestream"))
+ db.SetMetaPath(metaPathOf(dbPath))
db.MonitorInterval = dbMonitorInterval
h.mu.Lock()
h.stored = true
@@ -527,6 +545,12 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
h.mu.Lock()
oneShot := h.oneShot
h.mu.Unlock()
+ if storeMonitorsOff.Load() > 0 {
+ // SetStoreMonitorsOffForTest: no background compaction, snapshot
+ // or retention pass.
+ store.CompactionMonitorEnabled = false
+ store.L0RetentionCheckInterval = 0
+ }
if oneShot {
// A checkpoint writes its L0 sync and nothing else. Each monitor
// runs one pass at store.Open, concurrently with the sync, and
@@ -780,6 +804,13 @@ func (r *Replicator) teardownAndRelease(ctx context.Context) error {
}
err := r.store.Close(ctx)
r.closeDone()
+ if err == nil {
+ // The final sync and the close succeeded: the files as they are
+ // now are what the replica holds (continuity.go).
+ if rerr := recordClean(r.db.Path()); rerr != nil {
+ log.Printf("lease: %s: clean record: %v (the next start snapshots)", r.db.Path(), rerr)
+ }
+ }
lease := r.rn.stop()
if lease != nil {
@@ -1009,6 +1040,24 @@ func SetShutdownSyncTimeoutForTest(d time.Duration) (restore func()) {
return func() { shutdownSyncTimeout.Store(prev) }
}
+// storeMonitorsOff counts the callers that turned off the background
+// passes of stores created from now on (SetStoreMonitorsOffForTest).
+var storeMonitorsOff atomic.Int32
+
+// SetStoreMonitorsOffForTest turns off the background compaction,
+// snapshot and L0 retention passes of the stores of replicators created
+// from now on, until every caller has run its restore. A test seam: with
+// the store ready inside a wake (replicate before start, #1290), those
+// passes can run while a test counts the wake's requests or tears its
+// replicator down, and litestream v0.5.14 lets a store close while its
+// own snapshot is still reading the database (a race the race detector
+// reports). Process-global, counted, so parallel callers nest.
+func SetStoreMonitorsOffForTest() (restore func()) {
+ storeMonitorsOff.Add(1)
+ var once sync.Once
+ return func() { once.Do(func() { storeMonitorsOff.Add(-1) }) }
+}
+
// Restore pulls the newest replicated state of s3://bucket/prefix into
// dbPath via litestream's restore API — the cold-wake path when the local DB
// is missing. prefix is the instance's location: the replica is the
diff --git a/internal/lease/protect_test.go b/internal/lease/protect_test.go
new file mode 100644
index 000000000..27ec08d22
--- /dev/null
+++ b/internal/lease/protect_test.go
@@ -0,0 +1,49 @@
+package lease
+
+import (
+ "testing"
+)
+
+// The start pin: taken before the process starts, it keeps every frame the
+// process writes in the WAL until Replicate's litestream reads it, so a
+// continuous database needs no snapshot even across a large migration.
+func TestProtectStartKeepsBootWritesWithoutSnapshot(t *testing.T) {
+ g := newGapRig(t)
+ g.wake("first wake")
+ p, err := ProtectStart(g.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !p.Continuous() {
+ t.Fatal("a database its clean close left untouched is not continuous")
+ }
+ app := g.migrate(bigMigration)
+ refuse := &failingSnapshots{ReplicaClient: serialFile(g.replica)}
+ refuse.fail.Store(true)
+ if err := g.replicateAndStop(g.held(refuse), app, "pinned wake"); err != nil {
+ t.Fatalf("a pinned wake needed a snapshot: %v", err)
+ }
+ g.restoresWhole("pinned wake")
+}
+
+// A database written while nothing replicated it is not continuous, and
+// neither is one with no clean record.
+func TestProtectStartRefusesContinuityAfterOutsideWrites(t *testing.T) {
+ g := newGapRig(t)
+ if p, err := ProtectStart(g.path); err != nil || p.Continuous() {
+ t.Fatalf("no clean record: continuous %v, %v", p != nil && p.Continuous(), err)
+ }
+ ReleaseStart(g.path)
+ g.wake("first wake")
+ app := openWakeApp(t, g.path)
+ wakeExec(t, app, `INSERT INTO t (body) VALUES ('outside')`)
+ app.Close()
+ p, err := ProtectStart(g.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if p.Continuous() {
+ t.Fatal("a write after the clean close counted as continuous")
+ }
+ ReleaseStart(g.path)
+}
diff --git a/internal/lease/release.go b/internal/lease/release.go
index d54cfe054..de4918b0a 100644
--- a/internal/lease/release.go
+++ b/internal/lease/release.go
@@ -5,7 +5,7 @@ import (
"context"
"errors"
"fmt"
- "io"
+ "log"
"net/http"
"time"
@@ -36,14 +36,7 @@ func (r *Replicator) snapshotWithin(ctx context.Context) (*ltx.FileInfo, error)
ctx, cancel = context.WithTimeout(ctx, time.Until(d)/2)
defer cancel()
}
- pos, rd, err := r.db.SnapshotReader(ctx)
- if err != nil {
- return nil, err
- }
- if c, ok := rd.(io.Closer); ok {
- defer c.Close()
- }
- return r.db.Replica.Client.WriteLTXFile(ctx, litestream.SnapshotLevel, 1, pos.TXID, rd)
+ return writeSnapshot(ctx, r.db)
}
// releaseWithMarker is the one HA release. lease never deletes an HA lock:
@@ -293,6 +286,11 @@ func (r *Replicator) finalize(ctx context.Context, sync, snapshot bool) (uint64,
}
}
r.closeErr = r.store.Close(ctx)
+ if sync && syncErr == nil && r.closeErr == nil {
+ if rerr := recordClean(r.db.Path()); rerr != nil {
+ log.Printf("lease: %s: clean record: %v (the next start snapshots)", r.db.Path(), rerr)
+ }
+ }
r.finishTXID = uint64(r.db.Replica.Pos().TXID)
r.finishErr = errors.Join(syncErr, r.closeErr, r.rn.Err(), r.decideFinal())
if r.snapErr == nil && snapTXID != r.finishTXID {
diff --git a/internal/lease/release_test.go b/internal/lease/release_test.go
index 51d3daf30..6e4abab78 100644
--- a/internal/lease/release_test.go
+++ b/internal/lease/release_test.go
@@ -584,19 +584,23 @@ func TestCloseProvenReleasesANeverCreatedDatabase(t *testing.T) {
func TestCloseProvenEmptyNeedsBothHalves(t *testing.T) {
// The cleanup's abandonment tries its failing final sync once.
t.Cleanup(lease.SetShutdownSyncTimeoutForTest(0))
- t.Run("database exists, bucket empty", func(t *testing.T) {
+ t.Run("database exists, bucket refuses its writes", func(t *testing.T) {
fx := leasetest.NewLockFixture(t)
prefix := "instances/unsynced.example.com"
- t.Cleanup(fx.FailReplicaPuts(prefix))
h, err := lease.Acquire(ctx, fx.Bucket, prefix, "")
if err != nil {
t.Fatal(err)
}
- r, err := h.Replicate(ctx, tempDB(t), 0)
+ path := tempDB(t)
+ // The bucket takes the start's first image (replicate before
+ // start, #1290), then refuses: the write after it cannot sync.
+ r, err := h.Replicate(ctx, path, 0)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { r.Abandon(ctx) })
+ t.Cleanup(fx.FailReplicaPuts(prefix))
+ addRows(t, path, 3)
if err := r.CloseProven(ctx); !errors.Is(err, lease.ErrCheckpointUnproven) {
t.Fatalf("CloseProven over an existing database that cannot sync = %v, want ErrCheckpointUnproven", err)
}
@@ -604,6 +608,25 @@ func TestCloseProvenEmptyNeedsBothHalves(t *testing.T) {
t.Fatal("the lease was released over an unproven checkpoint")
}
})
+ t.Run("database exists, bucket refuses the first image", func(t *testing.T) {
+ fx := leasetest.NewLockFixture(t)
+ prefix := "instances/unstarted.example.com"
+ t.Cleanup(fx.FailReplicaPuts(prefix))
+ h, err := lease.Acquire(ctx, fx.Bucket, prefix, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Replicate before start (#1290): a first image the bucket cannot
+ // receive fails the start itself, so this never reaches a close.
+ lease.SetImageBudgetForTest(t, time.Second)
+ if r, err := h.Replicate(ctx, tempDB(t), 0); err == nil {
+ r.Abandon(ctx)
+ t.Fatal("Replicate started over an existing database the bucket cannot receive")
+ }
+ if fx.LockBody(prefix) == nil {
+ t.Fatal("the lease was released over an unproven start")
+ }
+ })
t.Run("database missing, bucket holds a backup", func(t *testing.T) {
fx := leasetest.NewLockFixture(t)
prefix := "instances/backedup.example.com"
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 65ea697f1..5a1d2a9dc 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -260,3 +260,6 @@ plan14-root-reads-named-units-guard-fix.tsv aa2c0729fe761d6438d2e8b9ef4ef2c1a206
plan14-root-reads-instance-control-memory-1291.tsv 70ca25987f5a18849d7ae880e30628a47475375d6dde2409a505232d78abb872
plan14-root-reads-media-conversion.tsv 4568bc8acc3ee632d7637cb27ca6838c735128f4a40de21f26b7070ebb156723
plan14-root-reads-design-platform-accounts.tsv 4568bc8acc3ee632d7637cb27ca6838c735128f4a40de21f26b7070ebb156723
+plan14-root-reads-replica-wake-gap.tsv 837b586c0aa17936bc64201245a86c3fd66c58e7f1257436b31c75ac001ac00c
+plan14-root-reads-replica-wake-gap-r3.tsv 460c6557a81afc8e5a73db79b8673a7495f84c67a0457e69a0e8443f17a265e7
+plan14-root-reads-replica-wake-gap-ch.tsv 6c3e03c493dbca78fc128355f071caa2b2d5f22674b98994cd85a0cf63d40ca8
diff --git a/internal/provision/testdata/plan14-root-reads-replica-wake-gap-ch.tsv b/internal/provision/testdata/plan14-root-reads-replica-wake-gap-ch.tsv
new file mode 100644
index 000000000..95bb8dcb7
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-replica-wake-gap-ch.tsv
@@ -0,0 +1,11 @@
+# Census overlay replica-wake-gap-ch, written by census-propose (#369). census-ruling-replica-wake-gap-ch, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-replica-wake-gap-ch.md.
+# 0 body, 1 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 2 new dispositions: 1 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy b334f69e119ff54d8b79259a16380ce947924c65bd000a1ea692c7b79543e750 internal/activator/replicatebeforestart.go Service.protectBeforeStart legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap-ch;basis=The former step 2c, unchanged: asks the lease to ProtectStart(rt.DBPath), the route's own database path; on refusal gives the lease back (rt.Host) and starts nothing. Agent code, user carlos; no root call. registry:DBPath@201,registry:Host@274,registry:Host@328 a843def3929f1d1b8c7ad3bdf3efaac2c2372d9b4853b45e426e2b8476b242b0
+@legacy d4d1edcd15ae746fec4a45d0872c957b7f3c9adf1a1539d8099ee0ccd4ef2847 internal/lease/continuity.go Protection.pin legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Opens a SQLite read transaction on the route's database (agent, user carlos) after stat-ing its -wal and -shm, reading PRAGMA journal_mode and sqlite_master; creates nothing, changes no mode. The path is the activator's own route database path. No root involvement.;rev3=census-ruling-replica-wake-gap-ch;basis=QueryRow and Begin become QueryRowContext and BeginTx on a 30 s context (code health, db-no-context); the held transaction is begun without cancellation. Same reads of the same route database. file:Open@273,file:QueryRowContext@429,file:QueryRowContext@836,file:Stat@122 ca4ffcdadfbaf93a547c15b0f94c8618ee1b3aa50901c88634b9d1b73da96c5c
+@legacy cd9e006e3413faeb7fcc79dc50454718753b034ac7580fb0734b4590c3e2f175 internal/activator/activator.go Service.doWakeOnce legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: The former doWake body, not deleted logic: refresh/admit/fence/layout checks remain. Select and verify the actual staged identity before serving Acquire; use canonical mode to call doStatelessWake. Keep SQLite acquire/restore/seed/marker/replicate only in the stateful arm, with the post-acquisition selection recheck and existing cleanup proofs. Fix 3a round 1 I1/I3a: admit config directly only for stateless and mark runtime ownership refusals. Stateful Acquire/Restore precede selection and pending publication; canonical mode inspection is separate, replan precedes settlement. Fix round 2 N2/N3: retain the original route/pin projection for post-lease declaration checks; reuse the unplanned capture so a live-link repoint cannot change the selected build. Stateful capture and changed-copy errors remain start failures after Acquire/Restore. A failed preliminary verification supplies no cached mode observation. No new file path or database authority. Final review C1/R26: unprojected stateful wakes capture and materialize the live link only after Acquire and Restore. Retain original route/generation/pin stateless evidence on the context across fallback, so missing stateless evidence cannot take stateful recovery inference. Known good stateful identity skips canonical declaration lookup. Existing pre-exec verification remains. R28 final fix 2: carry whether this wake has a plan in attempt-local context; no new read here; route, generation and pin stateless projection remains intact.;rev3=census-ruling-agent-start-demo-1;basis=Reads IsDemo and demo admission/capability state; chooses local lease retention, skips seed upload and sidecar selection. Existing stop and under-lease ordering retained.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: refuse tenant starts under the existing service lock before main's demoWakeRefusal, and recheck before backend Acquire. Retain main's demo refusal and all lease, restore and serialization checks. Two added whole Route uses feed the in-memory admission predicate; no new filesystem or store read.;rev3=census-ruling-stateless-replicas-2;basis=P14: after verified storage-mode selection, before clearing the projected hint or acquiring a database lease, a set row still on the stateful branch returns ErrFenced. Reads the existing route FleetBoxes field only. Verified stateless wakes take their existing branch; legacy rows remain unchanged. No new file, registry query or bucket read. merge of origin/main 9b8b2c50: retain wake-slot and HA duty logic alongside the replica stateful-start refusal; no gate removed. merge of origin/main 6be08467: Keep main demo lease, local database and KeepLocal path; never equate replication-disabled demos with stateless generations. Merge-only body/read-site change. merge of origin/main 7920cccf: Retain main tenant admission and startOwnedLocked gates alongside the replica stateful-start refusal; whole Route passed to main admission checks, no new path or store read.;rev3=census-ruling-agent-start-demo-3;basis=Route claim seeds through seed restore/admission; do not fall back to empty boot or ordinary import behavior. Census read-site delta: +registry:SeedSource, +whole:Route.;rev3=census-ruling-region-ha-g2-fixes;basis=Bound recovery Acquire by its attempt deadline; existing acquire/restore/start ordering remains; no new read.;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): right after retainDatabase returns, attaches the write-fence watcher under a.mu (watchWriteFenceLocked, in memory). retainDatabase is called through a retainDB test seam that is nil in production. No read added; no root call; existing acquire, restore, publisher and cleanup order unchanged.;rev3=census-ruling-sr-followups;basis=#1061 Task 1, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): a refused plan now returns planRefusal(host, plan) instead of the inline fmt.Errorf, the text is unchanged, and when the planner marked the plan Installing the error also matches errBuildNotInstalled (installRefusal, in memory). Same refusal at the same point before the lease, read sites unchanged, no read, file, store, bucket or root call added;rev3=census-ruling-replica-wake-gap;basis=Step 2c: before the seed and the spawn, asks the lease to ProtectStart(rt.DBPath), the route's own database path already used by Restore and retainDatabase; a refusal gives the lease back and starts nothing. Agent code (user carlos); no root call, no new store or file read here.;rev3=census-ruling-replica-wake-gap-ch;basis=Step 2c's body moved unchanged into protectBeforeStart (replicatebeforestart.go); doWakeOnce passes the whole Route it already holds and returns the error. No read added; the DBPath read moved with the body. registry:DBPath@2071,registry:DBPath@2087,registry:DBPath@2214,registry:DBPath@2225,registry:FleetBoxes@12030,registry:GoodVersion@18320,registry:Host@1900,registry:Host@1975,registry:Host@2053,registry:Host@2205,registry:Host@2539,registry:Host@4556,registry:Host@6813,registry:Host@949,registry:Replication@16947,registry:Replication@17076,registry:Replication@17095,registry:Replication@17176,registry:Replication@33548,registry:Seed@22232,registry:SeedSource@35008,registry:Socket@2100,registry:Socket@2116,registry:Socket@2239,registry:Socket@2250,registry:Stateless@10090,registry:Stateless@10376,registry:Stateless@11748,registry:Stateless@12078,registry:Stateless@20729,registry:Stateless@9633,registry:Stateless@9724,whole:Route@10162,whole:Route@10321,whole:Route@10700,whole:Route@10798,whole:Route@10889,whole:Route@11021,whole:Route@11144,whole:Route@11198,whole:Route@11470,whole:Route@11646,whole:Route@11650,whole:Route@12437,whole:Route@12712,whole:Route@13030,whole:Route@142,whole:Route@14491,whole:Route@15168,whole:Route@16049,whole:Route@16927,whole:Route@17178,whole:Route@18523,whole:Route@19114,whole:Route@19279,whole:Route@1998,whole:Route@20215,whole:Route@21011,whole:Route@21286,whole:Route@21482,whole:Route@22333,whole:Route@22404,whole:Route@2434,whole:Route@2439,whole:Route@24898,whole:Route@2493,whole:Route@2499,whole:Route@2565,whole:Route@2573,whole:Route@2629,whole:Route@26756,whole:Route@27402,whole:Route@28709,whole:Route@28863,whole:Route@29362,whole:Route@29432,whole:Route@30019,whole:Route@31104,whole:Route@31535,whole:Route@31743,whole:Route@31797,whole:Route@32726,whole:Route@32911,whole:Route@333,whole:Route@33711,whole:Route@33782,whole:Route@34500,whole:Route@34549,whole:Route@34943,whole:Route@35125,whole:Route@3591,whole:Route@36377,whole:Route@36472,whole:Route@3685,whole:Route@37313,whole:Route@3752,whole:Route@4446,whole:Route@6182,whole:Route@6441,whole:Route@6703,whole:Route@6708,whole:Route@6765,whole:Route@6771,whole:Route@6840,whole:Route@6848,whole:Route@7164,whole:Route@7225,whole:Route@729,whole:Route@7323,whole:Route@8288,whole:Route@9237,whole:Route@934,whole:Route@9461,whole:Route@9525,whole:Route@9569 7a5cc22f3e9b76abb17f3d26d72b5bfd41b7f19e2c645e2288953319d9bf5d08
+internal/activator/replicatebeforestart.go Service.protectBeforeStart legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap-ch;basis=The former step 2c, unchanged: asks the lease to ProtectStart(rt.DBPath), the route's own database path; on refusal gives the lease back (rt.Host) and starts nothing. Agent code, user carlos; no root call. registry:DBPath@201,registry:Host@274,registry:Host@328 a843def3929f1d1b8c7ad3bdf3efaac2c2372d9b4853b45e426e2b8476b242b0
+internal/lease/continuity.go Protection.pin legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Opens a SQLite read transaction on the route's database (agent, user carlos) after stat-ing its -wal and -shm, reading PRAGMA journal_mode and sqlite_master; creates nothing, changes no mode. The path is the activator's own route database path. No root involvement.;rev3=census-ruling-replica-wake-gap-ch;basis=QueryRow and Begin become QueryRowContext and BeginTx on a 30 s context (code health, db-no-context); the held transaction is begun without cancellation. Same reads of the same route database. file:Open@273,file:QueryRowContext@429,file:QueryRowContext@836,file:Stat@122 ca4ffcdadfbaf93a547c15b0f94c8618ee1b3aa50901c88634b9d1b73da96c5c
+internal/activator/activator.go Service.doWakeOnce legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: The former doWake body, not deleted logic: refresh/admit/fence/layout checks remain. Select and verify the actual staged identity before serving Acquire; use canonical mode to call doStatelessWake. Keep SQLite acquire/restore/seed/marker/replicate only in the stateful arm, with the post-acquisition selection recheck and existing cleanup proofs. Fix 3a round 1 I1/I3a: admit config directly only for stateless and mark runtime ownership refusals. Stateful Acquire/Restore precede selection and pending publication; canonical mode inspection is separate, replan precedes settlement. Fix round 2 N2/N3: retain the original route/pin projection for post-lease declaration checks; reuse the unplanned capture so a live-link repoint cannot change the selected build. Stateful capture and changed-copy errors remain start failures after Acquire/Restore. A failed preliminary verification supplies no cached mode observation. No new file path or database authority. Final review C1/R26: unprojected stateful wakes capture and materialize the live link only after Acquire and Restore. Retain original route/generation/pin stateless evidence on the context across fallback, so missing stateless evidence cannot take stateful recovery inference. Known good stateful identity skips canonical declaration lookup. Existing pre-exec verification remains. R28 final fix 2: carry whether this wake has a plan in attempt-local context; no new read here; route, generation and pin stateless projection remains intact.;rev3=census-ruling-agent-start-demo-1;basis=Reads IsDemo and demo admission/capability state; chooses local lease retention, skips seed upload and sidecar selection. Existing stop and under-lease ordering retained.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: refuse tenant starts under the existing service lock before main's demoWakeRefusal, and recheck before backend Acquire. Retain main's demo refusal and all lease, restore and serialization checks. Two added whole Route uses feed the in-memory admission predicate; no new filesystem or store read.;rev3=census-ruling-stateless-replicas-2;basis=P14: after verified storage-mode selection, before clearing the projected hint or acquiring a database lease, a set row still on the stateful branch returns ErrFenced. Reads the existing route FleetBoxes field only. Verified stateless wakes take their existing branch; legacy rows remain unchanged. No new file, registry query or bucket read. merge of origin/main 9b8b2c50: retain wake-slot and HA duty logic alongside the replica stateful-start refusal; no gate removed. merge of origin/main 6be08467: Keep main demo lease, local database and KeepLocal path; never equate replication-disabled demos with stateless generations. Merge-only body/read-site change. merge of origin/main 7920cccf: Retain main tenant admission and startOwnedLocked gates alongside the replica stateful-start refusal; whole Route passed to main admission checks, no new path or store read.;rev3=census-ruling-agent-start-demo-3;basis=Route claim seeds through seed restore/admission; do not fall back to empty boot or ordinary import behavior. Census read-site delta: +registry:SeedSource, +whole:Route.;rev3=census-ruling-region-ha-g2-fixes;basis=Bound recovery Acquire by its attempt deadline; existing acquire/restore/start ordering remains; no new read.;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): right after retainDatabase returns, attaches the write-fence watcher under a.mu (watchWriteFenceLocked, in memory). retainDatabase is called through a retainDB test seam that is nil in production. No read added; no root call; existing acquire, restore, publisher and cleanup order unchanged.;rev3=census-ruling-sr-followups;basis=#1061 Task 1, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): a refused plan now returns planRefusal(host, plan) instead of the inline fmt.Errorf, the text is unchanged, and when the planner marked the plan Installing the error also matches errBuildNotInstalled (installRefusal, in memory). Same refusal at the same point before the lease, read sites unchanged, no read, file, store, bucket or root call added;rev3=census-ruling-replica-wake-gap;basis=Step 2c: before the seed and the spawn, asks the lease to ProtectStart(rt.DBPath), the route's own database path already used by Restore and retainDatabase; a refusal gives the lease back and starts nothing. Agent code (user carlos); no root call, no new store or file read here.;rev3=census-ruling-replica-wake-gap-ch;basis=Step 2c's body moved unchanged into protectBeforeStart (replicatebeforestart.go); doWakeOnce passes the whole Route it already holds and returns the error. No read added; the DBPath read moved with the body. registry:DBPath@2071,registry:DBPath@2087,registry:DBPath@2214,registry:DBPath@2225,registry:FleetBoxes@12030,registry:GoodVersion@18320,registry:Host@1900,registry:Host@1975,registry:Host@2053,registry:Host@2205,registry:Host@2539,registry:Host@4556,registry:Host@6813,registry:Host@949,registry:Replication@16947,registry:Replication@17076,registry:Replication@17095,registry:Replication@17176,registry:Replication@33548,registry:Seed@22232,registry:SeedSource@35008,registry:Socket@2100,registry:Socket@2116,registry:Socket@2239,registry:Socket@2250,registry:Stateless@10090,registry:Stateless@10376,registry:Stateless@11748,registry:Stateless@12078,registry:Stateless@20729,registry:Stateless@9633,registry:Stateless@9724,whole:Route@10162,whole:Route@10321,whole:Route@10700,whole:Route@10798,whole:Route@10889,whole:Route@11021,whole:Route@11144,whole:Route@11198,whole:Route@11470,whole:Route@11646,whole:Route@11650,whole:Route@12437,whole:Route@12712,whole:Route@13030,whole:Route@142,whole:Route@14491,whole:Route@15168,whole:Route@16049,whole:Route@16927,whole:Route@17178,whole:Route@18523,whole:Route@19114,whole:Route@19279,whole:Route@1998,whole:Route@20215,whole:Route@21011,whole:Route@21286,whole:Route@21482,whole:Route@22333,whole:Route@22404,whole:Route@2434,whole:Route@2439,whole:Route@24898,whole:Route@2493,whole:Route@2499,whole:Route@2565,whole:Route@2573,whole:Route@2629,whole:Route@26756,whole:Route@27402,whole:Route@28709,whole:Route@28863,whole:Route@29362,whole:Route@29432,whole:Route@30019,whole:Route@31104,whole:Route@31535,whole:Route@31743,whole:Route@31797,whole:Route@32726,whole:Route@32911,whole:Route@333,whole:Route@33711,whole:Route@33782,whole:Route@34500,whole:Route@34549,whole:Route@34943,whole:Route@35125,whole:Route@3591,whole:Route@36377,whole:Route@36472,whole:Route@3685,whole:Route@37313,whole:Route@3752,whole:Route@4446,whole:Route@6182,whole:Route@6441,whole:Route@6703,whole:Route@6708,whole:Route@6765,whole:Route@6771,whole:Route@6840,whole:Route@6848,whole:Route@7164,whole:Route@7225,whole:Route@729,whole:Route@7323,whole:Route@8288,whole:Route@9237,whole:Route@934,whole:Route@9461,whole:Route@9525,whole:Route@9569 7a5cc22f3e9b76abb17f3d26d72b5bfd41b7f19e2c645e2288953319d9bf5d08
+@coverage internal/activator e4d8ec4b67ca247704e54bebe5d7101350aa1a1d11cbc0a8de1c3ba1b4e09b1e
+@coverage internal/lease 4f73e2cc9043b5b8ea0c8b81543a0e3a36a4bfc073af85366858350275ace090
diff --git a/internal/provision/testdata/plan14-root-reads-replica-wake-gap-r3.tsv b/internal/provision/testdata/plan14-root-reads-replica-wake-gap-r3.tsv
new file mode 100644
index 000000000..3b475d02e
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-replica-wake-gap-r3.tsv
@@ -0,0 +1,16 @@
+# Census overlay replica-wake-gap-r3, written by census-propose (#369). census-ruling-replica-wake-gap-r3, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-replica-wake-gap-r3.md.
+# 3 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 3 new dispositions: 2 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy eabcbc9046ae89f8ae8bc17752362ac6e6ea58a0b943ff69e1bd2cbc2ed38d98 internal/lease/continuity.go currentState legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database and its -wal, and lists the replicator's own litestream meta directory's ltx/0, to compare with the clean record. Agent-owned files; read only.;rev3=census-ruling-replica-wake-gap-r3;basis=The record now also names the cleaned database path (version 2); the same stats of the route database, its WAL and the replicator's own ltx/0 listing. file:ReadDir@465,file:Stat@270,file:Stat@67 e2d00fcc291b263f51ae4c452b879795b332f37a7f91159c7f9363da3f08b0bf
+@legacy 64cfbed4d6465b58cb90131f28ed7f21f480ea5a88f3abc8cf4671ac3b078f1d internal/lease/continuity.go startProtected legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database to tell a first start (no file) from an existing one; then litestream's own sync and, when continuity is unproven, a snapshot through the existing replica client. No new path or input.;rev3=census-ruling-replica-wake-gap-r3;basis=A pinned start's first sync retries within firstSyncTimeout (firstSync); a full image's upload is awaited from the replica's position (awaitUploaded) under imageBudget. Same database path and replica client; no new path or input. file:Stat@99 7c15637c08bef2f467360d3a54ea511f5a48cc6d5ed2e8af17db07ce63ec2169
+@legacy d2c5b7cf5d60f05427f56b318d90ae88ba65b9a68ed5d965de2c526a682eae0c internal/lease/continuity.go imageBudget legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap-r3;basis=Stats the route database for its size, to scale the full image's time bound. Read only. file:Stat@86 bb36577f6a1a67aca185cea93f7b559426901b044a89f9ad5e5db6ef8abfd810
+@legacy 681ef406a6716a84ea6fcc756e6d3a131760d237f3f36aa7f7c04e2b8c3efec2 internal/lease/continuity.go isContinuous legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Reads the clean record carlos-clean.json from the replicator's own meta directory; anything unreadable is not proof of continuity (the safe answer).;rev3=census-ruling-replica-wake-gap-r3;basis=Lstat of the clean record in the agent's continuity directory (named from a hash of the database path); anything but a regular file is not trusted, then the existing read. file:Lstat@115,file:ReadFile@204 1facee361f1492bfa1c2040ca357be047475c4475b179246784e25cf23beafab
+@legacy d76b727eb17cfb8b72ae57538934294fe1d5623bcafcc04f24f4dc77f83a793f internal/lease/continuity.go recordClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Writes carlos-clean.json (0600, tmp then rename, fsync) in the replicator's own meta directory after a successful final sync and close. Agent-owned path derived from the route's database path.;rev3=census-ruling-replica-wake-gap-r3;basis=Writes the record through os.CreateTemp (O_EXCL, 0600) in the agent's continuity directory and renames it into place, replacing rather than following whatever is at the name; replaces the fixed .tmp OpenFile beside the database. file:CreateTemp@296 a09703546f176debd56b9fecce85a9a7aa7dd519736e7f825f978b351e09b022
+internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.;rev3=census-ruling-region-ha-g2-t3;basis=T3a: wire eb.Page = PageOperator beside OwnerTerminated before departures arm, so suspect-holder pages work if departure setup fails; no new read; existing nine sites and authority unchanged; pages through the existing sink. T3b: publish the same backend through an atomic pointer for the metrics observer, and clear it on return; no new external read or authority.;rev3=census-ruling-agent-start-demo-3;basis=Wire the claim activator and root snapshot client into the demo worker; pass moved readiness to status reporting. Census read-site delta: unchanged (9).;rev3=census-ruling-region-ha-g2-fixes;basis=Wire local pool evidence, live withdrawal activator, startup ingress scan and alias publication, and edge lookup; no new direct sites; new indirect record/claim reads use existing store/judge paths described in ingress helpers.;rev3=census-ruling-region-ha-g2r-fixes;basis=W3: starts the existing record-view backstop loop with a departure-inventory listener (non-blocking, coalesced signal) even without an armed RecordView; it requests the existing full pass (backstopFullDue) there. Same nine read sites; no new read or authority.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Derive one signal-time deadline with a 90-second budget; cap departure stop and startup/seed/service shutdown joins by it. No read added.;rev3=census-ruling-static-sweep-periodic;basis=in the edge-ready callback, publishes e.LargestStaticTree in staticTreeSource for the disk alert line (diskAlertFrac in the metrics loop); in-memory wiring only, no read added; read sites unchanged (9);rev3=census-ruling-edge-page-cache-1;basis=wires the exec backend's CurrentInputs into the edge cache (wireCurrentInputs) and, in the ready hook after armEdgeAssetCache (whose returned store it now keeps), calls armEdgePageCache, which does nothing unless CARLOS_PAGE_CACHE=1; read sites unchanged (9); no read added;rev3=census-ruling-gvisor-demos;basis=Capture sandbox resolution and refusal once; log errors once; gate route admission and BeforeExec before process launch. No new root read. Task 5: pass the once-captured sandbox effective mode/config error into ExecBackend, UnitBackend and the immutable Client expectation. Same startup environment/registry reads; swapArming declines gVisor before placement. Task 8: arm read-only status projection with the existing Client.SandboxStatus callback. Agent status now queries the existing root /ready endpoint; no new root authority or guest-file input. Merge2 e8a1ddde: retain main wireCurrentInputs and armEdgePageCache through the existing asset-store ready hook alongside branch once-captured sandbox mode, wake gates and root status wiring. No new direct read; main page-cache helpers retain their own census overlays.;rev3=census-ruling-region-ha-held-build;basis=wires the drain state: svc.SetDrainingSource(boxDrain.IsDraining), svc.SetPeerDrainView(e.PeerDraining), e.SetPeerDrainedHook(svc.DropHoldersNaming); in-memory only; no read added; region HA held-requests Task 5: on group members, starts the drain driver over the activator, the edge and boxDrain, and serves its root-only drain socket; no read added beyond the socket's own Branch review r1: the drain state follows the root start fence on group members (the fence reader is the existing fenceLocation.read, a root-owned fixed path); e.SetPeerUndrainedHook(svc.AllowHoldersNaming) beside the drained hook (memory only); the drain socket serves only the agent's own user. No read added.;rev3=census-ruling-security-review-mitigations;basis=Wire the cached operator flat-layout choice into the exec backend's new-resident refusal; no read source added, existing authority retained.;rev3=census-ruling-w6-ingress-drain;basis=agent (user carlos), not root. Builds the ingress drain (newIngressDrain) with arming read at ask time from os.Getenv (CARLOS_REGION_HA, CARLOS_INGRESS_TARGET_GROUPS, both from the root-owned host.env), the fixed admission and lease.CurrentSelf (existing IMDS identity); its reader is awstg.Load, the box role's credentials calling ELB DescribeTargetHealth/DescribeTargetGroupAttributes (new AWS reads, by the agent). Wires admission.closeStartsForIngressDrain, the lbhealth drain condition, ingress.setEdge, and ingress.shutdownStarted in WithShutdownStarted. The drain socket (/run/carlos/.ha-drain/drain.sock, agent-user only, existing) is now also served on a fixed box with the drain configured (was group members only), routing /v1/ingress/* to the ingress drain and the group drain verbs to 404 there. armHADepartures now takes fixtureDepartureGetenv() and MakeQueue fixtureDepartureQueue(), which in a production (non-rootrunner) build are os.Getenv and nil, as before. Read sites unchanged (9).;rev3=census-ruling-stateless-replicas-4-task1;basis=Arms the fleet-only replica swap worker next to the placement worker: same console URL and fleet token as the existing replicaCoordinatorAPI, the existing activator Service; stops and joins at shutdown. No new read site, credential or bucket reader.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: sets deployWorker.step to the rollout scheduler answer for the record permit (replicaStepOf over armedRollout), an in-memory callback; no read site, credential or bucket reader added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: the swap worker step is armedReplicaStep, the same lazy scheduler lookup as before as a named function; no read site added.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (01d6ca78, linked-deployments-slice1) starts linkLoop beside tunnelLoop; this branch keeps its replica coordinator wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 2: wires the swap worker's drive (armedReplicaDrive, the armed rollout manager's DriveReplicaRelease); no read added;rev3=census-ruling-stateless-replicas-4-merge-main2;basis=Merge of main af871da0 (v0.34.49): both sides changed it. Main (178dcfe5, member-backups-2a) moves the inline duty-view closure into armDutyView/dutyView and starts verifyAssignLoop; its sites drop by registry:Host and whole:Route x2 as main recorded them. This branch keeps its replica coordinator, swap worker and drive wiring. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-drill3;basis=drill 3 R24: makes one in-memory channel, closes it (once) inside the edge's existing shutdown-started callback after ingress.shutdownStarted, and passes it to tunnelLoop, which drains only a fleet channel name; no read added, same six sites; touches no admission, lease, ingress drain, listener or file; the agent process, no root decision;rev3=census-ruling-edge-ppv2;basis=Agent (uid carlos), not root. memwatchLoop now gets edgeProxyCounters(&demoEdge) (in-process counters, no read). The drain socket's driver is newAgentDrainSocket(ingress, e, os.Getenv), which attaches the edge trust handler only when CARLOS_INGRESS_PROXY_SOURCES in the agent's environment (from the root-owned host.env) parses to a non-empty list; the socket is served when drainSocketServed: a group member or a configured ingress drain (both as before), or a box armed for PROXY protocol (new). The socket's path and agent-user-only permissions are unchanged. Read sites unchanged (6).;rev3=census-ruling-same-box-edge-fence;basis=Agent (uid carlos), not root. One added line: armEdgeFenceStatus(ctl.EdgeFence), beside the existing armExecSandboxStatus, so the layout report can ask root's /ready for the edge fence state over the control socket client the agent already holds. No read added.;rev3=census-ruling-platform-mail-submission;basis=Task 4: sets eb.Mail = mailsubmit.SocketForwarder{} on every box, and eb.MailSwitch to a mailSwitchCache's On that opens the deploy store itself through openDeployStore, retried at most once a minute with an error line until it opens (review round 1, Task 4 P3), armed for the serial-move refresh (armedMailSwitch). Task 6: also sets the ExecBackend's ManifestOf, the same staged-manifest read as TierOf (rt.App and RouteAccount(rt), hence +registry:App and +whole:Route), for the spawn-time check of decision 10, which logs and emits an event and never refuses. Agent, not root. Fable final P2-2: eb.MailSwitch is the cache's State (three-valued: on, off, unknown) in place of On; an unreadable switch is unknown, never off. No read added.;rev3=census-ruling-fleet-drain-followups;basis=P3 (#1008 T9): one call after armChangeIndex, requestBootFullPass(v, &backstopFullDue), which stores true in the existing in-memory backstopFullDue flag only when no record view is armed, so the fast loop runs its existing full pass on its first tick instead of instancesLoop a minute later; armed boxes unchanged. No read added; read sites unchanged (8); agent, not root.;rev3=census-ruling-fleet-first-reconcile-speed;basis=Startup timing log lines only: runDuties builds a step logger (newStartupLog, which reads the in-memory agent start time) and logs one line after the wait on the activator startup latch and after each existing duty before go fastConvergeLoop. One newStartupLog().at line in the edge ready hook before go tunnelLoop. No read added; read sites unchanged (8). Agent, not root.;rev3=census-ruling-ha-1192;basis=sets the group drain driver's departed hook to armedPeerDeparted (the armed departure controller's PeerDeparted: local registry identity + departure journal); no new read;rev3=census-ruling-replica-wake-gap-r3;basis=Calls lease.SetContinuityDir(<data dir>/.continuity) beside the existing obligation store: the agent's own 0700 directory for clean records, outside every instance tree (#1290 round 3). No new read; failure is logged and every start then takes a full image. file:Exec@21990,file:Open@2191,file:Statfs@58396,registry:App@13287,registry:App@13665,whole:Route@13279,whole:Route@13657,whole:Route@51611 3ecf7db40398d0d182683c5ef54d846997b25c0f9f61bd21ce2ecce355949ed7
+internal/lease/continuity.go currentState legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database and its -wal, and lists the replicator's own litestream meta directory's ltx/0, to compare with the clean record. Agent-owned files; read only.;rev3=census-ruling-replica-wake-gap-r3;basis=The record now also names the cleaned database path (version 2); the same stats of the route database, its WAL and the replicator's own ltx/0 listing. file:ReadDir@465,file:Stat@270,file:Stat@67 e2d00fcc291b263f51ae4c452b879795b332f37a7f91159c7f9363da3f08b0bf
+internal/lease/continuity.go startProtected legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database to tell a first start (no file) from an existing one; then litestream's own sync and, when continuity is unproven, a snapshot through the existing replica client. No new path or input.;rev3=census-ruling-replica-wake-gap-r3;basis=A pinned start's first sync retries within firstSyncTimeout (firstSync); a full image's upload is awaited from the replica's position (awaitUploaded) under imageBudget. Same database path and replica client; no new path or input. file:Stat@99 7c15637c08bef2f467360d3a54ea511f5a48cc6d5ed2e8af17db07ce63ec2169
+internal/lease/continuity.go imageBudget legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap-r3;basis=Stats the route database for its size, to scale the full image's time bound. Read only. file:Stat@86 bb36577f6a1a67aca185cea93f7b559426901b044a89f9ad5e5db6ef8abfd810
+internal/lease/continuity.go isContinuous legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Reads the clean record carlos-clean.json from the replicator's own meta directory; anything unreadable is not proof of continuity (the safe answer).;rev3=census-ruling-replica-wake-gap-r3;basis=Lstat of the clean record in the agent's continuity directory (named from a hash of the database path); anything but a regular file is not trusted, then the existing read. file:Lstat@115,file:ReadFile@204 1facee361f1492bfa1c2040ca357be047475c4475b179246784e25cf23beafab
+internal/lease/continuity.go recordClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Writes carlos-clean.json (0600, tmp then rename, fsync) in the replicator's own meta directory after a successful final sync and close. Agent-owned path derived from the route's database path.;rev3=census-ruling-replica-wake-gap-r3;basis=Writes the record through os.CreateTemp (O_EXCL, 0600) in the agent's continuity directory and renames it into place, replacing rather than following whatever is at the name; replaces the fixed .tmp OpenFile beside the database. file:CreateTemp@296 a09703546f176debd56b9fecce85a9a7aa7dd519736e7f825f978b351e09b022
+@coverage internal/host 0f1b1bebdcc885cfa6d3da7b516d7be49087ce66a33715fce8b17eeaa8461c28
+@coverage internal/lease 6d2678bb0db94e6158018283d9766d62027e4157de616e083fca7fcb5337cb78
diff --git a/internal/provision/testdata/plan14-root-reads-replica-wake-gap.tsv b/internal/provision/testdata/plan14-root-reads-replica-wake-gap.tsv
new file mode 100644
index 000000000..34330e308
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-replica-wake-gap.tsv
@@ -0,0 +1,27 @@
+# Census overlay replica-wake-gap, written by census-propose (#369). census-ruling-replica-wake-gap, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-replica-wake-gap.md.
+# 1 body, 1 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 9 new dispositions: 1 reads re-frozen at their disposition with the claim, 8 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 88b9f7c7e9f19bc65301fb5b0a811710e34833e3e7bee18c41e405e7fc2dc2d1 internal/lease/checkpoint.go Held.Checkpoint legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-replica-wake-gap;basis=Replicate before start (#1290): decides continuity (beginContinuity) before the store opens, runs startProtected (bounded first sync; a full image when continuity is unproven) before its sync, and writes the clean record after a successful close. Same database path the caller passed; no new path, input or root decision; the agent runs it as carlos. file:Open@1016 337104180154a1e2f0f4d2126a4bb1b67862d8400431cc5e0b8920acced92b40
+@legacy 54e3d9197838d727d894422f43a9ee9fc5c8a9a2b003150db13d466f6ae85308 internal/lease/continuity.go Protection.pin legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Opens a SQLite read transaction on the route's database (agent, user carlos) after stat-ing its -wal and -shm, reading PRAGMA journal_mode and sqlite_master; creates nothing, changes no mode. The path is the activator's own route database path. No root involvement. file:Open@187,file:QueryRow@343,file:QueryRow@594,file:Stat@122 c4c63fc921746b07fd3d32d6f50efc7c629b859f2501c0ebd0cf722d5c2c2461
+@legacy d030b9502dda81d9cc9869bf6e9e8590484242b7146e15b9739c671d330f7b86 internal/lease/continuity.go currentState legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database and its -wal, and lists the replicator's own litestream meta directory's ltx/0, to compare with the clean record. Agent-owned files; read only. file:ReadDir@437,file:Stat@242,file:Stat@67 8e967e777f5a9d0023301075cf815bd49f5f7db3abf29de9a2b9decf57076376
+@legacy 4de020698bb10e5fc4e0a8e8bcfab93b9c441d7d4d24d7105b3c71f8ffc8ed22 internal/lease/continuity.go firstLocalL0After legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Lists the replicator's own meta directory ltx/0 to find the first file this start's sync wrote. Agent-owned; read only. file:ReadDir@88 e461881156a87217f87ed2954dafe18bcc5fead639fa64269254f8fbc7b0d92a
+@legacy a432c2653799c156dc6a4ba1d625607a9e0bb0abd9b200d695e4bce3bd249025 internal/lease/continuity.go fullImage legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Opens and decodes one local L0 file the replicator just wrote, to see whether it holds every page. Agent-owned; read only; a failed read means not a full image (the safe answer: a snapshot follows). file:Open@46 09979451df76b17e8ded6b8258ef53a6d6a42243e55663fbc03cc270c276266f
+@legacy 0751d4702f97f68e190f60b9f18b23b424ddd457c435558972eb416bc55456c5 internal/lease/continuity.go isContinuous legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Reads the clean record carlos-clean.json from the replicator's own meta directory; anything unreadable is not proof of continuity (the safe answer). file:ReadFile@53 f7daf19b564808f09f2ece439b96d6271ddc2a70f1a783380c24e4cca7fd6992
+@legacy 05f14720dc83844accd94cdc76434d73a78c18aecdb28ad1851e75784d8e4332 internal/lease/continuity.go newestLocalL0 legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Lists the replicator's own meta directory ltx/0 for the newest TXID. Agent-owned; read only. file:ReadDir@61 8c9c7aa118a38ee4c3283c03deaa0c679dd0efa9c9a4738081616fc89cbc94ca
+@legacy b0ab3c5efd4d42056748db4afa5cadf70dca9468dfd6ec98ad4d4389eec2fcaa internal/lease/continuity.go recordClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Writes carlos-clean.json (0600, tmp then rename, fsync) in the replicator's own meta directory after a successful final sync and close. Agent-owned path derived from the route's database path. file:OpenFile@302 02ef85663928f46f0ab7fbc8e215e7f5fe162184847a3cf027200d892a833e1c
+@legacy d789c24a8394c752bd37a94c117b70c685670b4c3ad3f4a016477d1d098787bd internal/lease/continuity.go startProtected legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database to tell a first start (no file) from an existing one; then litestream's own sync and, when continuity is unproven, a snapshot through the existing replica client. No new path or input. file:Stat@99 c56f5b768ffd6c8e7e03871fd0bb2901c13f3d575b50c4c06eed2c4a504aca46
+@legacy e0078a800a928855fb57533940fba37d4d95d125651872c2e201943ab4e5f6ac internal/lease/lease.go Held.Replicate legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: the Replicator it returns also carries the handle's ha flag, marker base and region, so an HA replicator releases through the marker only; the store setup, its five steps and the transfer are unchanged; the one site unchanged, no read added;rev3=census-ruling-g6-fence;basis=G6 F-C Task 2, the agent as carlos: for an HA lease at sync interval 0 only, wraps db.Replica.Client in the write fence's gate (fenceGate: cancels and refuses replica calls after the event, except the finalization's) before store.Open, and starts the fence goroutine (runFence) on db.WALPath(), the instance's own -wal; the Replicator gains done and fenced channels. The one site unchanged; no root read added; store setup, its steps and the transfer unchanged.;rev3=census-ruling-replica-wake-gap;basis=Adds beginContinuity before the store opens, a Stat of dbPath (no file: reset local litestream state so the first sync is a full image), and startProtected after Open; a failure closes the store and returns the error. Same dbPath, same replica client; no root decision. file:Open@1243,file:Stat@1041 dee32cbbd3175437275b82e6940a909914ec151fd0386064b562323a2672cbd5
+@legacy 1de971dac75880774de65d3d3fe8e33240e311352dc694ac9a5841a99c71eb84 internal/activator/activator.go Service.doWakeOnce legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: The former doWake body, not deleted logic: refresh/admit/fence/layout checks remain. Select and verify the actual staged identity before serving Acquire; use canonical mode to call doStatelessWake. Keep SQLite acquire/restore/seed/marker/replicate only in the stateful arm, with the post-acquisition selection recheck and existing cleanup proofs. Fix 3a round 1 I1/I3a: admit config directly only for stateless and mark runtime ownership refusals. Stateful Acquire/Restore precede selection and pending publication; canonical mode inspection is separate, replan precedes settlement. Fix round 2 N2/N3: retain the original route/pin projection for post-lease declaration checks; reuse the unplanned capture so a live-link repoint cannot change the selected build. Stateful capture and changed-copy errors remain start failures after Acquire/Restore. A failed preliminary verification supplies no cached mode observation. No new file path or database authority. Final review C1/R26: unprojected stateful wakes capture and materialize the live link only after Acquire and Restore. Retain original route/generation/pin stateless evidence on the context across fallback, so missing stateless evidence cannot take stateful recovery inference. Known good stateful identity skips canonical declaration lookup. Existing pre-exec verification remains. R28 final fix 2: carry whether this wake has a plan in attempt-local context; no new read here; route, generation and pin stateless projection remains intact.;rev3=census-ruling-agent-start-demo-1;basis=Reads IsDemo and demo admission/capability state; chooses local lease retention, skips seed upload and sidecar selection. Existing stop and under-lease ordering retained.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: refuse tenant starts under the existing service lock before main's demoWakeRefusal, and recheck before backend Acquire. Retain main's demo refusal and all lease, restore and serialization checks. Two added whole Route uses feed the in-memory admission predicate; no new filesystem or store read.;rev3=census-ruling-stateless-replicas-2;basis=P14: after verified storage-mode selection, before clearing the projected hint or acquiring a database lease, a set row still on the stateful branch returns ErrFenced. Reads the existing route FleetBoxes field only. Verified stateless wakes take their existing branch; legacy rows remain unchanged. No new file, registry query or bucket read. merge of origin/main 9b8b2c50: retain wake-slot and HA duty logic alongside the replica stateful-start refusal; no gate removed. merge of origin/main 6be08467: Keep main demo lease, local database and KeepLocal path; never equate replication-disabled demos with stateless generations. Merge-only body/read-site change. merge of origin/main 7920cccf: Retain main tenant admission and startOwnedLocked gates alongside the replica stateful-start refusal; whole Route passed to main admission checks, no new path or store read.;rev3=census-ruling-agent-start-demo-3;basis=Route claim seeds through seed restore/admission; do not fall back to empty boot or ordinary import behavior. Census read-site delta: +registry:SeedSource, +whole:Route.;rev3=census-ruling-region-ha-g2-fixes;basis=Bound recovery Acquire by its attempt deadline; existing acquire/restore/start ordering remains; no new read.;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): right after retainDatabase returns, attaches the write-fence watcher under a.mu (watchWriteFenceLocked, in memory). retainDatabase is called through a retainDB test seam that is nil in production. No read added; no root call; existing acquire, restore, publisher and cleanup order unchanged.;rev3=census-ruling-sr-followups;basis=#1061 Task 1, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): a refused plan now returns planRefusal(host, plan) instead of the inline fmt.Errorf, the text is unchanged, and when the planner marked the plan Installing the error also matches errBuildNotInstalled (installRefusal, in memory). Same refusal at the same point before the lease, read sites unchanged, no read, file, store, bucket or root call added;rev3=census-ruling-replica-wake-gap;basis=Step 2c: before the seed and the spawn, asks the lease to ProtectStart(rt.DBPath), the route's own database path already used by Restore and retainDatabase; a refusal gives the lease back and starts nothing. Agent code (user carlos); no root call, no new store or file read here. registry:DBPath@2071,registry:DBPath@2087,registry:DBPath@21869,registry:DBPath@2214,registry:DBPath@2225,registry:FleetBoxes@12030,registry:GoodVersion@18320,registry:Host@1900,registry:Host@1975,registry:Host@2053,registry:Host@2205,registry:Host@2539,registry:Host@4556,registry:Host@6813,registry:Host@949,registry:Replication@16947,registry:Replication@17076,registry:Replication@17095,registry:Replication@17176,registry:Replication@34070,registry:Seed@22754,registry:SeedSource@35530,registry:Socket@2100,registry:Socket@2116,registry:Socket@2239,registry:Socket@2250,registry:Stateless@10090,registry:Stateless@10376,registry:Stateless@11748,registry:Stateless@12078,registry:Stateless@20729,registry:Stateless@9633,registry:Stateless@9724,whole:Route@10162,whole:Route@10321,whole:Route@10700,whole:Route@10798,whole:Route@10889,whole:Route@11021,whole:Route@11144,whole:Route@11198,whole:Route@11470,whole:Route@11646,whole:Route@11650,whole:Route@12437,whole:Route@12712,whole:Route@13030,whole:Route@142,whole:Route@14491,whole:Route@15168,whole:Route@16049,whole:Route@16927,whole:Route@17178,whole:Route@18523,whole:Route@19114,whole:Route@19279,whole:Route@1998,whole:Route@20215,whole:Route@21011,whole:Route@21286,whole:Route@22855,whole:Route@22926,whole:Route@2434,whole:Route@2439,whole:Route@2493,whole:Route@2499,whole:Route@25420,whole:Route@2565,whole:Route@2573,whole:Route@2629,whole:Route@27278,whole:Route@27924,whole:Route@29231,whole:Route@29385,whole:Route@29884,whole:Route@29954,whole:Route@30541,whole:Route@31626,whole:Route@32057,whole:Route@32265,whole:Route@32319,whole:Route@33248,whole:Route@333,whole:Route@33433,whole:Route@34233,whole:Route@34304,whole:Route@35022,whole:Route@35071,whole:Route@35465,whole:Route@35647,whole:Route@3591,whole:Route@3685,whole:Route@36899,whole:Route@36994,whole:Route@3752,whole:Route@37835,whole:Route@4446,whole:Route@6182,whole:Route@6441,whole:Route@6703,whole:Route@6708,whole:Route@6765,whole:Route@6771,whole:Route@6840,whole:Route@6848,whole:Route@7164,whole:Route@7225,whole:Route@729,whole:Route@7323,whole:Route@8288,whole:Route@9237,whole:Route@934,whole:Route@9461,whole:Route@9525,whole:Route@9569 642bd5c0a4c68c943d51ed920045d7e29e9f968ebe93ae2d250cf616ab85a924
+internal/lease/checkpoint.go Held.Checkpoint legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-replica-wake-gap;basis=Replicate before start (#1290): decides continuity (beginContinuity) before the store opens, runs startProtected (bounded first sync; a full image when continuity is unproven) before its sync, and writes the clean record after a successful close. Same database path the caller passed; no new path, input or root decision; the agent runs it as carlos. file:Open@1016 337104180154a1e2f0f4d2126a4bb1b67862d8400431cc5e0b8920acced92b40
+internal/lease/continuity.go Protection.pin legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Opens a SQLite read transaction on the route's database (agent, user carlos) after stat-ing its -wal and -shm, reading PRAGMA journal_mode and sqlite_master; creates nothing, changes no mode. The path is the activator's own route database path. No root involvement. file:Open@187,file:QueryRow@343,file:QueryRow@594,file:Stat@122 c4c63fc921746b07fd3d32d6f50efc7c629b859f2501c0ebd0cf722d5c2c2461
+internal/lease/continuity.go currentState legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database and its -wal, and lists the replicator's own litestream meta directory's ltx/0, to compare with the clean record. Agent-owned files; read only. file:ReadDir@437,file:Stat@242,file:Stat@67 8e967e777f5a9d0023301075cf815bd49f5f7db3abf29de9a2b9decf57076376
+internal/lease/continuity.go firstLocalL0After legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Lists the replicator's own meta directory ltx/0 to find the first file this start's sync wrote. Agent-owned; read only. file:ReadDir@88 e461881156a87217f87ed2954dafe18bcc5fead639fa64269254f8fbc7b0d92a
+internal/lease/continuity.go fullImage legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Opens and decodes one local L0 file the replicator just wrote, to see whether it holds every page. Agent-owned; read only; a failed read means not a full image (the safe answer: a snapshot follows). file:Open@46 09979451df76b17e8ded6b8258ef53a6d6a42243e55663fbc03cc270c276266f
+internal/lease/continuity.go isContinuous legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Reads the clean record carlos-clean.json from the replicator's own meta directory; anything unreadable is not proof of continuity (the safe answer). file:ReadFile@53 f7daf19b564808f09f2ece439b96d6271ddc2a70f1a783380c24e4cca7fd6992
+internal/lease/continuity.go newestLocalL0 legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Lists the replicator's own meta directory ltx/0 for the newest TXID. Agent-owned; read only. file:ReadDir@61 8c9c7aa118a38ee4c3283c03deaa0c679dd0efa9c9a4738081616fc89cbc94ca
+internal/lease/continuity.go recordClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Writes carlos-clean.json (0600, tmp then rename, fsync) in the replicator's own meta directory after a successful final sync and close. Agent-owned path derived from the route's database path. file:OpenFile@302 02ef85663928f46f0ab7fbc8e215e7f5fe162184847a3cf027200d892a833e1c
+internal/lease/continuity.go startProtected legacy accepted-legacy accepted-legacy;rev3=census-ruling-replica-wake-gap;basis=Stats the route database to tell a first start (no file) from an existing one; then litestream's own sync and, when continuity is unproven, a snapshot through the existing replica client. No new path or input. file:Stat@99 c56f5b768ffd6c8e7e03871fd0bb2901c13f3d575b50c4c06eed2c4a504aca46
+internal/lease/lease.go Held.Replicate legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: the Replicator it returns also carries the handle's ha flag, marker base and region, so an HA replicator releases through the marker only; the store setup, its five steps and the transfer are unchanged; the one site unchanged, no read added;rev3=census-ruling-g6-fence;basis=G6 F-C Task 2, the agent as carlos: for an HA lease at sync interval 0 only, wraps db.Replica.Client in the write fence's gate (fenceGate: cancels and refuses replica calls after the event, except the finalization's) before store.Open, and starts the fence goroutine (runFence) on db.WALPath(), the instance's own -wal; the Replicator gains done and fenced channels. The one site unchanged; no root read added; store setup, its steps and the transfer unchanged.;rev3=census-ruling-replica-wake-gap;basis=Adds beginContinuity before the store opens, a Stat of dbPath (no file: reset local litestream state so the first sync is a full image), and startProtected after Open; a failure closes the store and returns the error. Same dbPath, same replica client; no root decision. file:Open@1243,file:Stat@1041 dee32cbbd3175437275b82e6940a909914ec151fd0386064b562323a2672cbd5
+internal/activator/activator.go Service.doWakeOnce legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: The former doWake body, not deleted logic: refresh/admit/fence/layout checks remain. Select and verify the actual staged identity before serving Acquire; use canonical mode to call doStatelessWake. Keep SQLite acquire/restore/seed/marker/replicate only in the stateful arm, with the post-acquisition selection recheck and existing cleanup proofs. Fix 3a round 1 I1/I3a: admit config directly only for stateless and mark runtime ownership refusals. Stateful Acquire/Restore precede selection and pending publication; canonical mode inspection is separate, replan precedes settlement. Fix round 2 N2/N3: retain the original route/pin projection for post-lease declaration checks; reuse the unplanned capture so a live-link repoint cannot change the selected build. Stateful capture and changed-copy errors remain start failures after Acquire/Restore. A failed preliminary verification supplies no cached mode observation. No new file path or database authority. Final review C1/R26: unprojected stateful wakes capture and materialize the live link only after Acquire and Restore. Retain original route/generation/pin stateless evidence on the context across fallback, so missing stateless evidence cannot take stateful recovery inference. Known good stateful identity skips canonical declaration lookup. Existing pre-exec verification remains. R28 final fix 2: carry whether this wake has a plan in attempt-local context; no new read here; route, generation and pin stateless projection remains intact.;rev3=census-ruling-agent-start-demo-1;basis=Reads IsDemo and demo admission/capability state; chooses local lease retention, skips seed upload and sidecar selection. Existing stop and under-lease ordering retained.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: refuse tenant starts under the existing service lock before main's demoWakeRefusal, and recheck before backend Acquire. Retain main's demo refusal and all lease, restore and serialization checks. Two added whole Route uses feed the in-memory admission predicate; no new filesystem or store read.;rev3=census-ruling-stateless-replicas-2;basis=P14: after verified storage-mode selection, before clearing the projected hint or acquiring a database lease, a set row still on the stateful branch returns ErrFenced. Reads the existing route FleetBoxes field only. Verified stateless wakes take their existing branch; legacy rows remain unchanged. No new file, registry query or bucket read. merge of origin/main 9b8b2c50: retain wake-slot and HA duty logic alongside the replica stateful-start refusal; no gate removed. merge of origin/main 6be08467: Keep main demo lease, local database and KeepLocal path; never equate replication-disabled demos with stateless generations. Merge-only body/read-site change. merge of origin/main 7920cccf: Retain main tenant admission and startOwnedLocked gates alongside the replica stateful-start refusal; whole Route passed to main admission checks, no new path or store read.;rev3=census-ruling-agent-start-demo-3;basis=Route claim seeds through seed restore/admission; do not fall back to empty boot or ordinary import behavior. Census read-site delta: +registry:SeedSource, +whole:Route.;rev3=census-ruling-region-ha-g2-fixes;basis=Bound recovery Acquire by its attempt deadline; existing acquire/restore/start ordering remains; no new read.;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): right after retainDatabase returns, attaches the write-fence watcher under a.mu (watchWriteFenceLocked, in memory). retainDatabase is called through a retainDB test seam that is nil in production. No read added; no root call; existing acquire, restore, publisher and cleanup order unchanged.;rev3=census-ruling-sr-followups;basis=#1061 Task 1, the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): a refused plan now returns planRefusal(host, plan) instead of the inline fmt.Errorf, the text is unchanged, and when the planner marked the plan Installing the error also matches errBuildNotInstalled (installRefusal, in memory). Same refusal at the same point before the lease, read sites unchanged, no read, file, store, bucket or root call added;rev3=census-ruling-replica-wake-gap;basis=Step 2c: before the seed and the spawn, asks the lease to ProtectStart(rt.DBPath), the route's own database path already used by Restore and retainDatabase; a refusal gives the lease back and starts nothing. Agent code (user carlos); no root call, no new store or file read here. registry:DBPath@2071,registry:DBPath@2087,registry:DBPath@21869,registry:DBPath@2214,registry:DBPath@2225,registry:FleetBoxes@12030,registry:GoodVersion@18320,registry:Host@1900,registry:Host@1975,registry:Host@2053,registry:Host@2205,registry:Host@2539,registry:Host@4556,registry:Host@6813,registry:Host@949,registry:Replication@16947,registry:Replication@17076,registry:Replication@17095,registry:Replication@17176,registry:Replication@34070,registry:Seed@22754,registry:SeedSource@35530,registry:Socket@2100,registry:Socket@2116,registry:Socket@2239,registry:Socket@2250,registry:Stateless@10090,registry:Stateless@10376,registry:Stateless@11748,registry:Stateless@12078,registry:Stateless@20729,registry:Stateless@9633,registry:Stateless@9724,whole:Route@10162,whole:Route@10321,whole:Route@10700,whole:Route@10798,whole:Route@10889,whole:Route@11021,whole:Route@11144,whole:Route@11198,whole:Route@11470,whole:Route@11646,whole:Route@11650,whole:Route@12437,whole:Route@12712,whole:Route@13030,whole:Route@142,whole:Route@14491,whole:Route@15168,whole:Route@16049,whole:Route@16927,whole:Route@17178,whole:Route@18523,whole:Route@19114,whole:Route@19279,whole:Route@1998,whole:Route@20215,whole:Route@21011,whole:Route@21286,whole:Route@22855,whole:Route@22926,whole:Route@2434,whole:Route@2439,whole:Route@2493,whole:Route@2499,whole:Route@25420,whole:Route@2565,whole:Route@2573,whole:Route@2629,whole:Route@27278,whole:Route@27924,whole:Route@29231,whole:Route@29385,whole:Route@29884,whole:Route@29954,whole:Route@30541,whole:Route@31626,whole:Route@32057,whole:Route@32265,whole:Route@32319,whole:Route@33248,whole:Route@333,whole:Route@33433,whole:Route@34233,whole:Route@34304,whole:Route@35022,whole:Route@35071,whole:Route@35465,whole:Route@35647,whole:Route@3591,whole:Route@3685,whole:Route@36899,whole:Route@36994,whole:Route@3752,whole:Route@37835,whole:Route@4446,whole:Route@6182,whole:Route@6441,whole:Route@6703,whole:Route@6708,whole:Route@6765,whole:Route@6771,whole:Route@6840,whole:Route@6848,whole:Route@7164,whole:Route@7225,whole:Route@729,whole:Route@7323,whole:Route@8288,whole:Route@9237,whole:Route@934,whole:Route@9461,whole:Route@9525,whole:Route@9569 642bd5c0a4c68c943d51ed920045d7e29e9f968ebe93ae2d250cf616ab85a924
+@coverage internal/activator 22a6e2f18728a2fe6d0e577d12638b742a5be22e75649b34c3ba11f1b2a3c31d
+@coverage internal/lease c61536ca0105f191666955eaa21099c74afb87ccc3836078e55003ed2290b293