carlos / platform Public

feat: enforce replica rollout permissions at launch

Stateless replicas Plan 4 Task 2 (#511): every launch of a copy of an
assigned instance honours the record's release result and this box's
swap permit.

- replicas.Deploy gains Allows, TargetAllowed, Baseline and Want. A box
  runs the target only after its release passed and it completed its
  switch, holds the permit, or the deploy is done; otherwise it runs
  the baseline. The writer now records Previous (the LastGood an
  attempt began with) and owns it.
- The activator's final exec gate asks Allows of the fresh record for
  every set-row start. prepareStateless takes a set row's baseline
  from the record, never local committedGood (D4), and never begins a
  release for a build the row does not name. Swap refuses holds and
  not-yet-permitted targets before raising or spawning. ConvergeAdopted
  and the sweep's drift cycle never cycle a copy.
- ReplicaSwap runs the permitted overlap as a settled canary behind the
  tenant start gates (W6, the §25 fence) and reports Proven only after
  the switch, worker handover and the old generation's stop proof. A
  switched copy asked again re-proves without a second swap.
- The rollout scheduler holds a set row's adoption while the target's
  release runs or waits for this box's permit, runs the permitted step
  through its slot, intent and failure book, and plans wakes from the
  record. A new build waits while another copy's step is open.
- The swap worker acknowledges only the step's proven answer; no
  answer, no ACK, so no next permit. An open switch now refuses a new
  begin with SR-4-C31 instead of an unknown release result.
- Provisional copy SR-4-C43..C45, pending Paul's copy review. Census
  proposal stateless-replicas-4-task2 and the record-write census layer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c98180b1a55dd7fc5a105cdc10ba9712f10f4bce parent c4357c1
28 files changed, +2,009 −37
  • docs/superpowers/notes/census-proposal-stateless-replicas-4-task2.md +40 −0
  • docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md +3 −0
  • internal/activator/activator.go +13 −0
  • internal/activator/replica_reconcile_wake_test.go +7 −2
  • internal/activator/replicadeploy.go +199 −0
  • internal/activator/replicadeploy_test.go +378 −0
  • internal/activator/stateless.go +30 −4
  • internal/activator/stateless_assignment_test.go +9 −3
  • internal/activator/statelessrelease.go +8 −0
  • internal/activator/swap.go +20 −0
  • internal/host/agent.go +6 −6
  • internal/host/replica_deploy_e2e_test.go +358 −0
  • internal/host/replicadeploy.go +68 −12
  • internal/host/replicadeploy_test.go +7 −1
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/replicadeploy.go +13 −5
  • internal/provision/replicadeploy_test.go +40 −0
  • internal/provision/stateless_replicas_4_task2_census_test.go +37 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task2.tsv +36 −0
  • internal/replicas/deploy.go +49 −0
  • internal/replicas/deploy_test.go +64 −0
  • internal/rollout/manager.go +9 −0
  • internal/rollout/queue.go +38 −2
  • internal/rollout/replicas.go +197 −0
  • internal/rollout/replicas_test.go +331 −0
  • internal/rollout/scheduler.go +9 −0
  • internal/rollout/wakeplan.go +38 −1

CI failed — run details

Intent

Human

<task-notification> <task-id>a9f821e38ebce5680</task-id> <tool-use-id>toolu_01JDeFAULbAQLpMubs34Ng1P</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a9f821e38ebce5680.output</output-file> <status>completed</status> <summary>Agent "Implement Plan 4 Task 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS - **Commit:** `c4357c11 fix: refuse a retry replay when unreached instances changed`, local only, on top of `6f212320`. - **Tests:** - All 28 Task 1 tests pass, including the 2 new ones this round. The targeted console, provision and root runs, the D11 HA guards, vet, gofmt and all three cross-builds pass. - All 3 mutations this round were caught. - **#2 fix:** a request that already reached a record counts as a replay. A replay is refused whole, writing nothing, if any record it hasn't reached carries intent or an attempt from another request, or is now on a different build. The refusal uses new copy row SR-4-C42 and returns 409 from the promote API. Records it already armed are left alone; there is no snapshot and no reconcile path. - **Tests added:** - The reviewer's exact case: r1 arms A and fails on B, r2 retries B, B2 fails, and replaying r1 is refused with no writes. Covered in provision and through the promote API. - The changed-target case: a new build starts on B without a retry, and replaying r1 is refused with no writes. - **Census:** record-write census unchanged. The root-read card shows only `internal/provision` re-pinned; the proposal is `stateless-replicas-4-task1-fix3`, and the #280 verdict is yours. - **Concerns:** - A replay is recognised only while some record still carries the request's key. If every record it reached has since moved to a new build, the replay is treated as a fresh request, which is harmless: nothing on the old build is selected, and the console refuses to renew a version the channel no longer names. - SR-4-C39 to C42 are pending Paul's copy review. - `git commit` warned again about the stale `packed-refs.lock` that is not mine; the commit landed and the tree is clean. - **Report:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-4/.superpowers/sdd/2026-11-01-stateless-replicas-4-deploy-and-drill/task-1-report.md` ("Fix round 3" is appended)</result> <usage><subagent_tokens>660299</subagent_tokens><tool_uses>10</tool_uses><duration_ms>598999</duration_ms></usage> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="09cca118-043b-44a3-94aa-a983228e744d" message-id="ff020fe2-ccbc-4a19-b0e5-dc6235d9aea3"> Hello from the session Paul asked to take #892 (stateless replicas at production scale) to merged code. I&apos;m a subagent of the Tito session (paseo 09cca118). Before I start, I&apos;d like to agree the boundary with you, since #892 builds on your #511 Plan 4. What I plan to do, and not do: 1. I won&apos;t touch stateless-replicas-4, or any file Plan 4 lists, until Plan 4 merges (stopping rule 4: one design in flight per area, never review against unmerged work). 2. Meanwhile I write #892&apos;s design on its own docs-only branch (design-stateless-replicas-scale), against main, as an addendum to the 11-01 stateless replicas spec. Its plans that touch replicas, placement, the activator&apos;s stateless/rootfs release path or the console&apos;s replica doors wait for Plan 4 to merge. 3. Direction I&apos;m leaning to (tell me if you see a problem): keep Paul&apos;s 5.4 rule (one copy per box, a copy grows to fit its box). Production scale comes from big copies, not many: copies = boxes (3), web as Puma cluster mode and Sidekiq as several processes inside each copy, with the copy&apos;s limit split per process inside it (web&apos;s share vs each worker&apos;s), not separate worker instances. The rejected alternative is a worker-only instance, which would need a cross-instance release order (release runs once per instance, so two instances of one app would run migrations twice and concurrently). 4. Plan 4 Task 4 (fleet tiers 6g+, FleetMemoryBudget, overlap reservation), which R17 deferred out of v0.35.0: I propose #892 adopts it as its size slice, built after Plan 4 merges, on Plan 4&apos;s floor and its reviewed task text. Do you agree, or do you want to keep Task 4 on #511? Questions: a. When do you expect Plan 4 (Tasks 2, 3, F11, 5) to merge? Roughly is fine. b. Anything independent of Plan 4 that you know of that I could build now without overlapping you? My candidate: a per-copy environment value giving the process its memory limit (for example so Puma can derive WEB_CONCURRENCY from the copy&apos;s size), if nothing in Plan 4 touches rootfsenv.go. c. Any objection to the direction in point 3? A short reply here is enough. I&apos;ll post the agreed boundary on #892. </paseo-system>

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/3488194.sock" from-name="amadan-13" from-mode="bypass"> amadan-13 (the amadan session), heads-up: carlos/platform's CI is on hosted CI (32 vCPU) for the next hour or so while I measure it. Paul approved moving platform off the shared fleet box. Pushes in this window run on hosted, and the first one starts with a cold cache. If a run fails for a reason that looks environmental (missing tool, timeout, browser), tell me rather than working around it. Undo is `amadan ci hosted carlos/platform off`. </cross-session-message>

Attributed to this commit: 44.2 g CO₂e (5,540,837 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-replicas-4, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-4-task2.md b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task2.md
new file mode 100644
index 000000000..6b0756d44
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task2.md
@@ -0,0 +1,40 @@
+# Census approval: stateless-replicas-4-task2
+
+Ruling `census-ruling-stateless-replicas-4-task2`. The independent reviewer approves or rejects every change below, 10 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` `type Service` | body | unchanged (0) | Task 2: one field, replicaPolicies (host to the newest observed replica deploy and this box label, under mu), set only by SetReplicaDeploy; declaration only, no read. |
+| `internal/activator/statelessrelease.go` `Service.prepareStatelessRelease` | body | unchanged (17) | Task 2: refuses with provision.ErrReplicaSwitchOpen (SR-4-C31) before term acquisition when the observed record already has an unresolved copy-switch permit, instead of a begin the writer refuses and that read as an unknown result. Refusal only; same calls, no read added. |
+| `internal/host/agent.go` `runAgent` | body | unchanged (9) | 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. |
+| `internal/rollout/scheduler.go` `scheduler.execute` | sites | +registry:Host, +whole:Route | Task 2: a dispatch marked Replica (this box permitted step) calls Manager.replicaStep, which calls activator ReplicaSwap, instead of Swap, and emits the swapping event only when the step moves; the added Host and whole Route reads are the same registry row this unit already reads (rt). Agent, not root. |
+| `internal/rollout/wakeplan.go` `Manager.planRow` | sites | +whole:Route | Task 2: a set row with a noted deploy is planned by decideReplicaWake from the record deploy (Want) instead of decideWake; the added whole Route read passes the row already read to replicaWant. Agent, not root. |
+
+Envelopes re-pinned: `internal/activator`, `internal/host`, `internal/provision`, `internal/replicas`, `internal/rollout`.
+
+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` `type Service`: authority, task B,C,D,F,J4. Basis: rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.;rev3=census-ruling-wake-storm-cap;basis=the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Add the B2 DutyStore interface field and process-local duty view, suppression and invalidation state. No read added. B2 adds the verified-successor identity callback; no read in the declaration. B3b adds a nonblocking departure-suspicion callback, invoked only after an accepted holder-forward failure and after cache locks release; it cannot authorize a take.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: immutable callbacks installed before Start for tenant admission, local start permission, fixed route exemptions and shutdown closure; nil callbacks preserve switch-off behavior; no new reads. Fix R1: add an immutable startup-phase callback for response copy, set before service startup. No new read or execution authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Add in-memory HA loss state and pool withdrawal jobs; no new read.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 1: one new field, drain (drainSources: two atomic func pointers for this box's and peers' drain state); no read added. region HA held-requests Task 2: one new field, moves (moveTable: per-host move state, hold counts and admission tickets in memory, under mu); no read added;rev3=census-ruling-held-move-speed;basis=the agent as carlos: one new field, moveStreams (per-host in-memory set of edge.StreamEnd for requests in flight, own mutex), for the move's early stream cut; actEntry gains drainRelease (bool, under a.mu), set by DrainStop; declarations only, no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: two fields, wakeFailMu and wakeFailLogged (per-host in-memory note of the last journalled wake failure); declaration only, no read;rev3=census-ruling-w6-ingress-drain;basis=new field TenantStartsClosed func() bool; when it answers true tenantStartRefusal refuses every start, exempt routes included. Wired only by fixedAdmission.bind to the ingress drain's closed flag. Struct field only; no read added.
+- `internal/activator/statelessrelease.go` `Service.prepareStatelessRelease`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-replicas-4-task1;basis=The former PrepareStatelessRelease body. R9: adopts the record's attempt for this lifetime and target in every phase before any coordination; otherwise acquires the term first and only then selects the ID (R1); a begin carries RetryOf only when consuming a durable retry. Same calls (ObserveReplicaRelease, coordinator, escrow initializer, actEntry, runReleaseAdmitted); same gates, proof and SafeUntil checks; no new store read or writer.
+- `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.
+- `internal/rollout/scheduler.go` `scheduler.execute`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route
+- `internal/rollout/wakeplan.go` `Manager.planRow`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry each selection read by the existing planner on its WakePlan so wake uses that same canonical verdict/digest, including selected fallbacks.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/activator.go:Service.ConvergeAdopted`: reads +registry:FleetBoxes, +whole:Route; written legacy, accepted-legacy, frozen
+- new `internal/activator/replicadeploy.go:Service.ReplicaSwap`: reads +registry:FleetBoxes, +whole:Route ×3; written legacy, accepted-legacy, frozen
+- new `internal/activator/replicadeploy.go:Service.replicaPolicyAllows`: reads +registry:Host, +registry:ReplicaIncarnation; written legacy, accepted-legacy, frozen
+- new `internal/activator/replicadeploy.go:Service.replicaSettle`: reads +whole:Route ×2; written legacy, accepted-legacy, frozen
+- new `internal/rollout/replicas.go:Manager.replicaWant`: reads +registry:FleetBoxes, +registry:Host, +registry:ReplicaIncarnation; written legacy, accepted-legacy, frozen
+- new `internal/rollout/wakeplan.go:decideReplicaWake`: reads +registry:App, +registry:GoodDemand, +registry:GoodDigest, +registry:GoodVersion ×2, +registry:Version ×2, +whole:Route ×5; written legacy, accepted-legacy, frozen
+- reads `internal/activator/activator.go:Service.sweepOnce`: +registry:FleetBoxes, +whole:Route; keeps legacy, task accepted-legacy
+- reads `internal/activator/stateless.go:Service.prepareStateless`: +registry:FleetBoxes, +registry:Version, +whole:Route ×2; keeps legacy, task accepted-legacy
+- reads `internal/activator/stateless.go:Service.statelessFinalRecord`: +registry:FleetBoxes; keeps legacy, task accepted-legacy
+- reads `internal/activator/swap.go:Service.Swap`: +registry:FleetBoxes, +whole:Route; keeps legacy, task accepted-legacy
+
+Seal: `3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5` → `40c909a853a761733e9f837d4c8336bc91e174125cad65ac412f71141978be19`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
index 769c441ec..20d1c6323 100644
--- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
+++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
@@ -114,3 +114,6 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| SR-4-C40 | cli.go | this app runs stateless replicas, so retry it through the console: carlos instances retry <host>, or carlos promote --retry while logged in to the console | pending (added by Plan 4 Task 1 fix round 1 for the direct-bucket retry refusal; awaiting Paul's copy review) |
| SR-4-C41 | internal/provision/replicadeploy.go | an instance record could not be read, so nothing was retried. try again | pending (added by Plan 4 Task 1 fix round 2 for retries that fail closed on unreadable records; awaiting Paul's copy review) |
| SR-4-C42 | internal/provision/replicadeploy.go | the instances changed since this retry was requested, so nothing was retried. run the retry again | pending (added by Plan 4 Task 1 fix round 3 for a refused replay of a retry request; awaiting Paul's copy review) |
+| SR-4-C43 | internal/activator/replicadeploy.go | this copy keeps its current build until its turn to switch | pending (added by Plan 4 Task 2 for a copy refused a build its deploy has not yet permitted on its box; awaiting Paul's copy review) |
+| SR-4-C44 | internal/activator/replicadeploy.go | copies above 1 switch builds with an overlap swap, so this release's hold swap was refused. the current build keeps serving | pending (added by Plan 4 Task 2 for a hold demand or hold policy on a replicated instance; awaiting Paul's copy review) |
+| SR-4-C45 | internal/rollout/replicas.go | this copy waits for a release to pass before it starts | pending (added by Plan 4 Task 2 for a copy's wake when its record names no build that passed a release; awaiting Paul's copy review) |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index d332d4f96..31e83c68b 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1297,6 +1297,9 @@ type Service struct {
ReplicaDeployID func(replicas.Identity, replicas.Build, *replicas.Deploy) (string, error)
ObserveReplicaRelease func(context.Context, registry.Route) (replicas.Identity, replicas.Build, *replicas.Deploy, error)
replicaReleaseLocks sync.Map
+ // replicaPolicies is each set row's newest observed deploy
+ // (SetReplicaDeploy), guarded by mu. It refuses early; it grants nothing.
+ replicaPolicies map[string]replicaPolicy
// Startup gates admission while the agent recovers installations. Set before publication.
Startup <-chan struct{}
@@ -3939,6 +3942,11 @@ func (a *Service) ConvergeAdopted(host, ver string) bool {
if e == nil || e.worker || e.probeHeld || e.state != actAwake || a.fences[host] != 0 {
return false
}
+ // A copy of an assigned instance moves only by its permitted step
+ // (replicadeploy.go): a repointed link alone never cycles it.
+ if e.route.FleetBoxes != "" {
+ return false
+ }
if ver == "" || e.spawnVersion == "" || e.spawnVersion == ver {
return false
}
@@ -5749,6 +5757,11 @@ func (a *Service) sweepOnce() {
go a.OnDrift(host)
cycle = false
}
+ if cycle && e.route.FleetBoxes != "" {
+ // A copy of an assigned instance moves only by its permitted
+ // step (replicadeploy.go), never by this stop-then-wake cycle.
+ cycle = false
+ }
if cycle && a.convergeBudget > 0 {
// An always-on worker converges as one MOVE, not as a cycle: the
// cycle's second half is "something wakes it back up", and a
diff --git a/internal/activator/replica_reconcile_wake_test.go b/internal/activator/replica_reconcile_wake_test.go
index 3088fea8b..51c43578e 100644
--- a/internal/activator/replica_reconcile_wake_test.go
+++ b/internal/activator/replica_reconcile_wake_test.go
@@ -129,6 +129,11 @@ func TestReplicaReconcileMemberWakeVerifiesGeneration(t *testing.T) {
if err := reg.SetInstancePaths(rt.Host, rt.DBPath, rt.Socket, rt.DBPath, filepath.Join(t.TempDir(), "app.sock")); err != nil {
t.Fatal(err)
}
+ // The pointer installed the build the wake boots (Task 2: a copy
+ // never releases a build its row does not name).
+ if err := reg.SetVersions(rt.Host, r.next.Version, ""); err != nil {
+ t.Fatal(err)
+ }
rt, err = reg.Get(rec.Host)
if err != nil || rt == nil {
t.Fatalf("route paths: %v", err)
@@ -147,13 +152,13 @@ func TestReplicaReconcileMemberWakeVerifiesGeneration(t *testing.T) {
if !ok {
return RecordFacts{}, ErrFenced
}
- current.ReplicaDeploy = coordinator.snapshot()
+ current.ReplicaDeploy = permittedDeploy(coordinator.snapshot())
return RecordFactsOf(current)
}
r.a.Fleet = FleetWake{Mode: FleetWakeCheck, Fleet: "pi", Label: "a", Record: func(ctx context.Context, rt registry.Route) (*provision.Record, error) {
current, err := provision.GetRecord(ctx, store, rt.Account, rt.App, rt.Host)
if err == nil {
- current.ReplicaDeploy = coordinator.snapshot()
+ current.ReplicaDeploy = permittedDeploy(coordinator.snapshot())
}
return current, err
}}
diff --git a/internal/activator/replicadeploy.go b/internal/activator/replicadeploy.go
new file mode 100644
index 000000000..76d803432
--- /dev/null
+++ b/internal/activator/replicadeploy.go
@@ -0,0 +1,199 @@
+// replicadeploy.go is the box side of a replicated deploy (stateless
+// replicas Plan 4, Task 2): which build a copy of an assigned instance (a
+// set row, rt.FleetBoxes != "") may start, and the permitted overlap step
+// whose proven outcome is the only thing a box acknowledges.
+//
+// The launch rule is replicas.(*Deploy).Allows, always asked of the record:
+//
+// - statelessFinalRecord, the final exec gate, asks it of the record it
+// reads fresh at every stateless exec: a planned or cold wake, its
+// fallback, a hold's pinned wake, an overlap successor and a restart all
+// end there, so no set row's generation starts without it.
+// - prepareStateless takes a set row's baseline from the record's deploy,
+// never from the box's local good build (ruling D4), and never begins a
+// release for a build the pointer does not name.
+// - Swap refuses a hold early, and refuses a target the observed policy
+// (SetReplicaDeploy) does not allow, so a waiting copy raises no parent
+// and spawns nothing. The policy is an observation, never a grant: the
+// exec gate decides.
+//
+// ReplicaSwap is the permitted step. Its order of proof, which the ACK
+// waits on (the host's swap worker sends it only for a Proven result):
+//
+// 1. the permit is this box's, unresolved and not halted, for this build;
+// 2. the release is an overlap: a hold is refused before anything runs;
+// 3. the tenant start gates (W6 TenantStartsClosed, the §25 retained start
+// fence) admit a start: a refused start answers nothing;
+// 4. the successor passes GET / and the normal settle window (Canary);
+// 5. it is switched in, the workers are handed over and the retiring
+// generation's stop is proven: replicaStepProven.
+//
+// A step that ends anywhere short of 5 leaves the permit open. Asking
+// again after the box already switched (a lost reply, an agent restart)
+// re-proves 4 and 5 on the running generation and never swaps twice.
+package activator
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// replicaRefusal is a set row's launch refusal. It is ErrFenced to the
+// classifiers (verdictOf, classifyStep), so nothing of the build ran and
+// nothing is recorded as the build's failure.
+type replicaRefusal struct{ msg string }
+
+func (e replicaRefusal) Error() string { return e.msg }
+func (e replicaRefusal) Is(target error) bool { return target == ErrFenced }
+
+var (
+ // errReplicaTurn: the record does not allow this copy the build yet.
+ // copy SR-4-C43 (provisional)
+ errReplicaTurn error = replicaRefusal{"this copy keeps its current build until its turn to switch"}
+ // errReplicaHold: copies switch builds only by overlap.
+ // copy SR-4-C44 (provisional)
+ errReplicaHold error = replicaRefusal{"copies above 1 switch builds with an overlap swap, so this release's hold swap was refused. the current build keeps serving"}
+)
+
+// replicaPolicy is the newest deploy the swap worker observed for a set
+// row, and this box's label.
+type replicaPolicy struct {
+ deploy replicas.Deploy
+ box string
+}
+
+// SetReplicaDeploy records the deploy observed on host's record for box,
+// this box: an observed policy update that lets Swap refuse early. It is
+// not a grant and substitutes for no launch gate. An empty deploy forgets
+// the host. An older revision of the same attempt never replaces a newer.
+func (a *Service) SetReplicaDeploy(host string, deploy replicas.Deploy, box string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if deploy.ID == "" || box == "" {
+ delete(a.replicaPolicies, host)
+ return
+ }
+ if cur, ok := a.replicaPolicies[host]; ok && cur.deploy.ID == deploy.ID && cur.deploy.Incarnation == deploy.Incarnation && cur.deploy.Revision > deploy.Revision {
+ return
+ }
+ if a.replicaPolicies == nil {
+ a.replicaPolicies = make(map[string]replicaPolicy)
+ }
+ a.replicaPolicies[host] = replicaPolicy{deploy: deploy.Clone(), box: box}
+}
+
+// replicaPolicyAllows is Allows over the observed policy for rt's lifetime
+// and the build with canonical digest, on this box.
+func (a *Service) replicaPolicyAllows(rt registry.Route, digest string) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ p, ok := a.replicaPolicies[rt.Host]
+ return ok && p.box != "" && p.box == a.Fleet.Label && p.deploy.Allows(p.box, rt.ReplicaIncarnation, digest)
+}
+
+// replicaSwapRefusal refuses, before anything runs, an attempt a set row
+// can never take: a stateful build, or anything but an overlap (a hold
+// demand, an app hold policy, a foreign layout that would run as a hold).
+func (a *Service) replicaSwapRefusal(at Attempt, stateless bool) error {
+ if !stateless {
+ return ErrFenced
+ }
+ if at.Mode != ModeOverlap || at.Demand == release.DemandHold || a.foreignRow(at.Host) {
+ return errReplicaHold
+ }
+ return nil
+}
+
+// ReplicaSwap runs this box's permitted step of deploy: the overlap swap of
+// at onto the deploy's target, under the existing overlap (never stop then
+// start). Only a result with Proven set may be acknowledged; see the file
+// comment for what it proves and in which order. box is this box's label.
+func (a *Service) ReplicaSwap(ctx context.Context, at Attempt, deploy replicas.Deploy, box string, newest func(string) uint64) SwapResult {
+ a.SetReplicaDeploy(at.Host, deploy, box)
+ // 1. The permit.
+ if box == "" || box != a.Fleet.Label || deploy.Phase != "released" || deploy.Swap.Halted || deploy.Swap.ActiveBox != box || at.Build != deploy.Target.Version {
+ return abandon(errReplicaTurn)
+ }
+ // 2. Overlap only.
+ if at.Mode != ModeOverlap || at.Demand == release.DemandHold || a.foreignRow(at.Host) {
+ return abandon(errReplicaHold)
+ }
+ // 3. The start gates.
+ a.mu.Lock()
+ e := a.entries[at.Host]
+ var route registry.Route
+ if e != nil {
+ route = e.route
+ }
+ a.mu.Unlock()
+ if e == nil {
+ return abandon(errSwapNotAwake)
+ }
+ if route.FleetBoxes == "" {
+ return abandon(ErrFenced)
+ }
+ if err := a.tenantStartRefusal(route); err != nil {
+ return abandon(err)
+ }
+ // 4 and 5 for a step that already switched: prove it, swap nothing.
+ if cur, ok := a.Current(at.Host); ok && cur.Build == at.Build && cur.Digest == at.Digest {
+ return a.replicaSettle(ctx, at.Host, cur)
+ }
+ // 4 and 5: the overlap, as a canary (the settle window), then the proof.
+ at.Canary = true
+ res := a.Swap(ctx, at, newest)
+ if res.Outcome == SwapDone {
+ res.Proven = a.replicaStepProven(at.Host, res.Gen)
+ if !res.Proven && res.Reason == "" {
+ res.Reason = "the switch is not yet proven; the step stays open"
+ }
+ }
+ return res
+}
+
+// replicaSettle re-proves a step whose switch already happened: g, host's
+// current generation, answers GET / and stays up through the settle
+// window, and nothing older is left. Anything short of that abandons, and
+// the permit stays open.
+func (a *Service) replicaSettle(ctx context.Context, host string, g Gen) SwapResult {
+ a.mu.Lock()
+ e := a.entries[host]
+ if e == nil || e.state != actAwake || e.gen.N != g.N || e.proc == nil {
+ a.mu.Unlock()
+ return abandon(errSwapNotAwake)
+ }
+ rt, proc := e.route, e.proc
+ a.mu.Unlock()
+ if err := a.genHealthy(ctx, rt, g); err != nil {
+ return abandon(fmt.Errorf("health: %w", err))
+ }
+ if observeSettle(ctx, proc, swapSettle) != settleOK {
+ return abandon(errSwapStopped)
+ }
+ res := SwapResult{Outcome: SwapDone, Gen: g, Proven: a.replicaStepProven(host, g)}
+ if !res.Proven {
+ res.Reason = "the switch is not yet proven; the step stays open"
+ }
+ return res
+}
+
+// replicaStepProven is the step's last proof: g is host's current, live,
+// awake generation; no other generation is left in the operation set (a
+// retiring one whose stop was not proven stays there until the sweep proves
+// it); and no worker of another generation, stray included, is left.
+func (a *Service) replicaStepProven(host string, g Gen) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[host]
+ if e == nil || e.state != actAwake || e.gen.N != g.N || e.proc == nil || e.proc.Exited() {
+ return false
+ }
+ if len(e.ops.members) != 0 {
+ return false
+ }
+ return len(workerNamesWhereLocked(e, func(gen uint64) bool { return gen != g.N })) == 0
+}
diff --git a/internal/activator/replicadeploy_test.go b/internal/activator/replicadeploy_test.go
new file mode 100644
index 000000000..2fa7a4838
--- /dev/null
+++ b/internal/activator/replicadeploy_test.go
@@ -0,0 +1,378 @@
+package activator
+
+import (
+ "context"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// replicaSetRig is box label's copy of acme/shop, a set row assigned to
+// boxes a and b, over wakeRelRig. The pointer installed v2; v1 is the build
+// the record last passed, and v0 is a stale local good build the record
+// never passed. The record's deploy lives in store, so the release path and
+// the final exec gate read the same evidence.
+type replicaSetRig struct {
+ *wakeRelRig
+ store *replicaReleaseStore
+ inc string
+ label string
+ stale release.StagedIdentity
+}
+
+var (
+ replicaGood = replicas.Build{Version: "v1", Digest: "canonical-v1"}
+ replicaTarget = replicas.Build{Version: "v2", Digest: "canonical-v2"}
+)
+
+func newReplicaSetRig(t *testing.T, label string, state func(inc string) *replicas.Deploy) *replicaSetRig {
+ t.Helper()
+ r := newWakeRelRig(t)
+ store := wireStatelessRig(r)
+ rec := provision.Record{Schema: 1, Host: r.rt.Host, Account: r.rt.Account, App: r.rt.App, Channel: r.rt.Channel, Environment: r.rt.Environment, Runtime: r.rt.Runtime, Region: "fleet/pi", CreatedAt: time.Unix(1, 0), Hibernate: new(bool), ReplicaAssignment: &replicas.Assignment{Desired: 2, Revision: 1, Boxes: []string{"a", "b"}}}
+ inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.rt.Region = rec.Region
+ r.rt.FleetBoxes = `["a","b"]`
+ r.rt.Copies = 2
+ r.rt.ReplicaRevision = 1
+ r.rt.ReplicaIncarnation = inc
+ r.rt.Stateless = true
+ r.rt.Version = "v2"
+ stale := stagedID(t, t.TempDir(), "v0")
+ r.routes.set(r.rt)
+ r.b.procs["v2"] = map[string]release.Process{release.ProcessWeb: {Command: []string{"serve"}}}
+ r.a.StorageDeclaration = func(_ context.Context, _ registry.Route, id release.StagedIdentity) (bool, string, error) {
+ return true, "canonical-" + id.Version, nil
+ }
+ record := func() provision.Record {
+ current := rec
+ current.ReplicaDeploy = store.snapshot()
+ return current
+ }
+ r.a.Fleet = FleetWake{Mode: FleetWakeCheck, Fleet: "pi", Label: label, Record: func(context.Context, registry.Route) (*provision.Record, error) {
+ current := record()
+ return &current, nil
+ }}
+ r.a.cfg.ReplicaRecord = func(registry.Route) (RecordFacts, error) { return RecordFactsOf(record()) }
+ r.a.cfg.Record = func(_ context.Context, rt registry.Route) (RecordFacts, error) { return r.a.cfg.ReplicaRecord(rt) }
+ if d := state(inc); d != nil {
+ store.d = d
+ r.a.SetReplicaDeploy(r.rt.Host, *d, label)
+ }
+ return &replicaSetRig{wakeRelRig: r, store: store, inc: inc, label: label, stale: stale}
+}
+
+// replicaAttempt is deploy-v2 in phase with swap, as the writer leaves it:
+// it began from v1, and a passed release made v2 its LastGood.
+func replicaAttempt(phase string, swap replicas.Swap) func(string) *replicas.Deploy {
+ return func(inc string) *replicas.Deploy {
+ d := &replicas.Deploy{ID: "deploy-v2", Incarnation: inc, Target: replicaTarget, Previous: replicaGood, LastGood: replicaGood, Phase: phase, Term: "term", Revision: 5, Swap: swap}
+ if replicas.ReleasePassed(phase) {
+ d.LastGood = replicaTarget
+ }
+ return d
+ }
+}
+
+// The release states a box b may meet. In every one but permitted and done,
+// b may not start v2.
+var replicaStates = []struct {
+ name string
+ state func(string) *replicas.Deploy
+ target bool // b may run v2
+ good bool // b may run v1
+}{
+ {"absent", func(string) *replicas.Deploy { return nil }, false, false},
+ {"failed", replicaAttempt("failed", replicas.Swap{}), false, true},
+ {"unknown", replicaAttempt("unknown", replicas.Swap{}), false, true},
+ {"waiting", replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, ActiveBox: "a", Permit: 4}), false, true},
+ {"halted", replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, Halted: true}), false, true},
+ {"permitted", replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5}), true, true},
+ {"done", replicaAttempt("done", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a", "b"}}), true, true},
+}
+
+func (r *replicaSetRig) started(build string) bool {
+ return slices.Contains(r.b.events(), "start:"+build)
+}
+
+// awake wakes the copy on v1, the record's baseline, for the paths that
+// begin from a running copy.
+func (r *replicaSetRig) awake(t *testing.T) {
+ t.Helper()
+ r.setPlan(WakePlan{Boot: r.good, Mode: ModeOverlap, Token: 1})
+ if err := waitErr(t, r.wake(r.a)); err != nil {
+ t.Fatalf("baseline wake: %v", err)
+ }
+ if g, ok := r.a.Current(r.rt.Host); !ok || g.Build != "v1" {
+ t.Fatalf("not awake on v1: %+v %v", g, ok)
+ }
+}
+
+func (r *replicaSetRig) attempt(cause Cause, mode SwapMode) Attempt {
+ return Attempt{Host: r.rt.Host, Cause: cause, Build: "v2", StagedPath: r.next.StagedPath, Digest: r.next.Digest, Mode: mode, SchedRev: 1}
+}
+
+func newestOne(string) uint64 { return 1 }
+
+// permittedDeploy is d with its passed release taken through to done, as
+// the coordinator's ordered swaps would leave it: for the tests of other
+// gates whose copy must be allowed its target (Task 2).
+func permittedDeploy(d *replicas.Deploy) *replicas.Deploy {
+ if d != nil && d.Phase == "released" {
+ d.Phase = "done"
+ }
+ return d
+}
+
+// TestReplicaWakeAndAdoptCannotBypassRelease (Task 2): every launch path of
+// a set row onto the target asks the record's release result and this box's
+// permit, and a set row's baseline comes from the record, never from local
+// good-build state (D4). Paths: the planned first wake (a cold wake, or the
+// wake after a box returns), its fallback, F10 recovery onto a local good
+// build, an overlap swap, a restart, a hold swap (with its pinned wake), and
+// ConvergeAdopted. States: absent, failed, unknown, released while waiting
+// for the permit, halted, and the two that allow the target.
+func TestReplicaWakeAndAdoptCannotBypassRelease(t *testing.T) {
+ for _, st := range replicaStates {
+ t.Run(st.name, func(t *testing.T) {
+ t.Run("planned first wake", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", st.state)
+ r.setPlan(WakePlan{Boot: r.next, Mode: ModeOverlap, FirstWake: true, Fallback: &r.good, Token: 1})
+ err := waitErr(t, r.wake(r.a))
+ if r.started("v2") != st.target {
+ t.Fatalf("v2 started=%t, want %t (wake: %v; events %v)", r.started("v2"), st.target, err, r.b.events())
+ }
+ if !st.target && r.started("v1") {
+ t.Fatalf("the fallback started without a failed start of v2: %v", r.b.events())
+ }
+ })
+ t.Run("baseline wake", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", st.state)
+ r.setPlan(WakePlan{Boot: r.good, Mode: ModeOverlap, Token: 1})
+ err := waitErr(t, r.wake(r.a))
+ if r.started("v1") != st.good {
+ t.Fatalf("v1 started=%t, want %t (wake: %v)", r.started("v1"), st.good, err)
+ }
+ })
+ t.Run("local good recovery", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", st.state)
+ r.rt.GoodVersion, r.rt.GoodDigest = r.stale.Version, r.stale.Digest
+ r.routes.set(r.rt)
+ before := r.store.snapshot()
+ r.setPlan(WakePlan{Boot: r.stale, Mode: ModeOverlap, Token: 1})
+ waitErr(t, r.wake(r.a))
+ if r.started("v0") {
+ t.Fatalf("a set row booted its local good build: %v", r.b.events())
+ }
+ // No copy begins a release attempt for a build its row does
+ // not name.
+ if after := r.store.snapshot(); (before == nil) != (after == nil) || (after != nil && after.ID != before.ID) {
+ t.Fatalf("the recovery began a release attempt: %+v", after)
+ }
+ })
+ if !st.good {
+ return
+ }
+ t.Run("overlap swap", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", st.state)
+ r.awake(t)
+ res := r.a.Swap(context.Background(), r.attempt(CauseRelease, ModeOverlap), newestOne)
+ if (res.Outcome == SwapDone) != st.target || r.started("v2") != st.target {
+ t.Fatalf("swap %+v, v2 started=%t; want %t", res, r.started("v2"), st.target)
+ }
+ if len(r.b.releaseStarts()) != 0 {
+ t.Fatalf("a copy ran a release: %v", r.b.releaseStarts())
+ }
+ // A copy waiting for its permit is refused before the parent
+ // raise and the spawn, not only at the exec gate.
+ if (st.name == "waiting" || st.name == "halted") && res.Err != errReplicaTurn {
+ t.Fatalf("waiting copy refused late: %+v", res)
+ }
+ })
+ t.Run("restart", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", st.state)
+ r.awake(t)
+ res := r.a.Swap(context.Background(), r.attempt(CauseRestart, ModeOverlap), newestOne)
+ if !st.target && (res.Outcome == SwapDone || r.started("v2")) {
+ t.Fatalf("restart moved onto v2: %+v", res)
+ }
+ })
+ t.Run("hold swap", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", st.state)
+ r.awake(t)
+ res := r.a.Swap(context.Background(), r.attempt(CauseRelease, ModeHold), newestOne)
+ if res.Outcome != SwapAbandoned || r.started("v2") {
+ t.Fatalf("a set row hold-swapped: %+v", res)
+ }
+ if g, ok := r.a.Current(r.rt.Host); !ok || g.Build != "v1" {
+ t.Fatal("the hold refusal stopped the serving copy")
+ }
+ })
+ t.Run("converge adopted", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", st.state)
+ r.awake(t)
+ r.a.liveVer = func(string) (string, error) { return "v2", nil }
+ if r.a.ConvergeAdopted(r.rt.Host, "v2") {
+ t.Fatal("repointing the live link cycled a copy")
+ }
+ if g, ok := r.a.Current(r.rt.Host); !ok || g.Build != "v1" {
+ t.Fatal("the copy stopped")
+ }
+ })
+ })
+ }
+}
+
+// TestReplicaReturnsAfterDeploy (Task 2, D4): box b was down for the whole
+// deploy and returns with stale local state (good build v1, a stale v0 on
+// its row). Its wake cold-starts the committed target from the record: no
+// release runs, and exactly one generation is left running. A row with no
+// assignment keeps F10's local recovery.
+func TestReplicaReturnsAfterDeploy(t *testing.T) {
+ r := newReplicaSetRig(t, "b", replicaAttempt("done", replicas.Swap{Order: []string{"a"}, Completed: []string{"a"}}))
+ r.setPlan(WakePlan{Boot: r.next, Mode: ModeOverlap, FirstWake: true, Fallback: &r.good, Token: 1})
+ if err := waitErr(t, r.wake(r.a)); err != nil {
+ t.Fatal(err)
+ }
+ // Current hides a first wake under its observation; the entry is read.
+ r.a.mu.Lock()
+ g := r.a.entries[r.rt.Host].gen
+ r.a.mu.Unlock()
+ returnedVersion, targetVersion := g.Build, replicaTarget.Version
+ extraReleaseRuns := len(r.b.releaseStarts())
+ staleProcesses := 0
+ for _, started := range r.b.started() {
+ if p := r.b.procOf(started.N); started.N != g.N && p != nil && !p.Exited() {
+ staleProcesses++
+ }
+ }
+ // TestReplicaReturnsAfterDeploy
+ if returnedVersion != targetVersion || extraReleaseRuns != 0 || staleProcesses != 0 {
+ t.Fatalf("returning copy did not join committed target: returned %s, releases %d, stale %d; events %v", returnedVersion, extraReleaseRuns, staleProcesses, r.b.events())
+ }
+ if d := r.store.snapshot(); d.ID != "deploy-v2" || d.Revision != 5 {
+ t.Fatalf("the return wrote the record: %+v", d)
+ }
+
+ // No assignment: F10's local committed good build still recovers a
+ // failed release (the record names no baseline for such a row).
+ plain := newWakeRelRig(t)
+ store := wireStatelessRig(plain)
+ plain.rt.Version, plain.rt.Stateless = "v2", true
+ plain.routes.set(plain.rt)
+ plain.b.procs["v2"] = map[string]release.Process{release.ProcessWeb: {Command: []string{"serve"}}}
+ inc, _ := provision.Incarnation(plain.rt.Account, plain.rt.App, plain.rt.Host, time.Unix(1, 0))
+ store.d = &replicas.Deploy{ID: "deploy-v2", Incarnation: inc, Target: replicas.Build{Version: "v2", Digest: "canonical"}, Phase: "failed", Term: "term", Revision: 3}
+ plain.setPlan(WakePlan{Boot: plain.good, Mode: ModeOverlap, Token: 1})
+ if err := waitErr(t, plain.wake(plain.a)); err != nil {
+ t.Fatalf("F10 recovery without an assignment: %v", err)
+ }
+ if g, ok := plain.a.Current(plain.rt.Host); !ok || g.Build != "v1" {
+ t.Fatalf("F10 recovery: %+v", g)
+ }
+}
+
+// TestReplicaSwapAcksOnlyAfterProof (Task 2): ReplicaSwap runs the permitted
+// overlap with its settle window and reports Proven, the only result a box
+// may acknowledge, once the new generation is current and every earlier
+// generation and worker is proven stopped. An unproven stop keeps the step
+// outstanding; asking again proves it without a second swap. A start gate
+// that is closed, a hold, or a box without the permit swaps nothing. An
+// admission ticket left open across the swap does not hold it up (R8).
+func TestReplicaSwapAcksOnlyAfterProof(t *testing.T) {
+ prev := swapSettle
+ swapSettle = 20 * time.Millisecond
+ t.Cleanup(func() { swapSettle = prev })
+ permitted := replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5})
+ ctx := context.Background()
+
+ t.Run("proven", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", permitted)
+ r.awake(t)
+ old, _ := r.a.Current(r.rt.Host)
+ // A request admitted before the swap, still open (R8): no ticket is
+ // awaited by a replica swap.
+ r.a.MoveState(r.rt, edge.MoveAsk{})
+ res := r.a.ReplicaSwap(ctx, r.attempt(CauseRelease, ModeOverlap), *r.store.snapshot(), "b", newestOne)
+ if res.Outcome != SwapDone || !res.Proven || res.Gen.Build != "v2" {
+ t.Fatalf("permitted swap: %+v", res)
+ }
+ if p := r.b.procOf(old.N); p == nil || !p.Exited() {
+ t.Fatal("proven before the old generation stopped")
+ }
+ if len(r.b.releaseStarts()) != 0 {
+ t.Fatal("the copy ran a release")
+ }
+ })
+ t.Run("unproven stop", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", permitted)
+ r.awake(t)
+ old, _ := r.a.Current(r.rt.Host)
+ p := r.b.procOf(old.N)
+ p.mu.Lock()
+ p.stuck = true
+ p.mu.Unlock()
+ t.Cleanup(p.exit) // a failed assertion must not leave Shutdown waiting on it
+ res := r.a.ReplicaSwap(ctx, r.attempt(CauseRelease, ModeOverlap), *r.store.snapshot(), "b", newestOne)
+ if res.Outcome != SwapDone || res.Proven {
+ t.Fatalf("an unproven stop was acknowledgeable: %+v", res)
+ }
+ starts := len(r.b.started())
+ p.exit()
+ waitFor(t, "the sweep's stop proof", func() bool {
+ r.a.sweepOnce()
+ res = r.a.ReplicaSwap(ctx, r.attempt(CauseRelease, ModeOverlap), *r.store.snapshot(), "b", newestOne)
+ return res.Proven
+ })
+ if res.Outcome != SwapDone || len(r.b.started()) != starts {
+ t.Fatalf("the proof swapped again: %+v, starts %d -> %d", res, starts, len(r.b.started()))
+ }
+ })
+ t.Run("successor fails", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", permitted)
+ r.awake(t)
+ r.a.genHealth = func(_ context.Context, g Gen) error {
+ if g.Build == "v2" {
+ return context.DeadlineExceeded
+ }
+ return nil
+ }
+ res := r.a.ReplicaSwap(ctx, r.attempt(CauseRelease, ModeOverlap), *r.store.snapshot(), "b", newestOne)
+ if res.Outcome != SwapFailed || res.Proven {
+ t.Fatalf("failed successor: %+v", res)
+ }
+ if g, ok := r.a.Current(r.rt.Host); !ok || g.Build != "v1" {
+ t.Fatal("the incumbent stopped serving")
+ }
+ })
+ for _, tc := range []struct {
+ name string
+ state func(string) *replicas.Deploy
+ edit func(*replicaSetRig, *Attempt)
+ }{
+ {"start gate closed", permitted, func(r *replicaSetRig, _ *Attempt) { r.a.TenantStartsClosed = func() bool { return true } }},
+ {"hold demand", permitted, func(_ *replicaSetRig, at *Attempt) { at.Mode = ModeHold }},
+ {"another box's permit", replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, ActiveBox: "a", Permit: 4}), func(*replicaSetRig, *Attempt) {}},
+ {"halted permit", replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5, Halted: true}), func(*replicaSetRig, *Attempt) {}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", tc.state)
+ r.awake(t)
+ at := r.attempt(CauseRelease, ModeOverlap)
+ tc.edit(r, &at)
+ res := r.a.ReplicaSwap(ctx, at, *r.store.snapshot(), "b", newestOne)
+ if res.Outcome != SwapAbandoned || res.Proven || r.started("v2") {
+ t.Fatalf("%s: %+v", tc.name, res)
+ }
+ })
+ }
+}
diff --git a/internal/activator/stateless.go b/internal/activator/stateless.go
index 3a4a2bc67..ad68ed20b 100644
--- a/internal/activator/stateless.go
+++ b/internal/activator/stateless.go
@@ -319,7 +319,18 @@ func (a *Service) statelessFinalRecord(ctx context.Context, rt registry.Route) e
if facts.Identity != identity || facts.ID != identity.Incarnation {
return ErrFenced
}
- if prepared, ok := ctx.Value(statelessPreparedKey{}).(*statelessPreparation); ok {
+ prepared, ok := ctx.Value(statelessPreparedKey{}).(*statelessPreparation)
+ if rt.FleetBoxes != "" {
+ // A copy of an assigned instance: the record read now decides every
+ // build, the target and the baseline alike (replicadeploy.go). Its
+ // target also needs the attempt this launch prepared.
+ if !ok || !facts.ReplicaDeploy.Allows(a.Fleet.Label, identity.Incarnation, prepared.digest) {
+ return errReplicaTurn
+ }
+ if d := facts.ReplicaDeploy; !prepared.baseline && (d.ID != prepared.deployID || d.Target != (replicas.Build{Version: prepared.id.Version, Digest: prepared.digest})) {
+ return ErrFenced
+ }
+ } else if ok {
if prepared.recovery {
good, err := a.committedGood(rt)
if err != nil || good.Version != prepared.id.Version || good.Digest != prepared.id.Digest {
@@ -386,9 +397,21 @@ func (a *Service) prepareStateless(ctx context.Context, rt registry.Route, id re
return ctx, err
}
observation, _ := observed.Value(replicaObservationKey{}).(replicaObservation)
- // Recovery uses the committed good build without replacing the failed
- // deploy or rerunning its predecessor's release. The final gate checks it again.
- if id.Version != rt.Version && id.Version != "" && id.Digest != "" {
+ if rt.FleetBoxes != "" {
+ // A copy of an assigned instance (D4): its baseline is the record's,
+ // never the box's local good build, and it runs no release. A build
+ // the pointer does not name is never released here either. The final
+ // gate asks the record again (statelessFinalRecord).
+ if base := observation.record.ReplicaDeploy.Baseline(); base.Digest != "" && base.Digest == digest && base.Version == id.Version && base != observation.record.ReplicaDeploy.Target {
+ prepared := &statelessPreparation{route: rt, id: id, digest: digest, observation: observation, baseline: true}
+ return context.WithValue(observed, statelessPreparedKey{}, prepared), nil
+ }
+ if id.Version != rt.Version {
+ return ctx, errReplicaTurn
+ }
+ } else if id.Version != rt.Version && id.Version != "" && id.Digest != "" {
+ // Recovery uses the committed good build without replacing the failed
+ // deploy or rerunning its predecessor's release. The final gate checks it again.
good, err := a.committedGood(rt)
if err != nil {
return ctx, err
@@ -420,6 +443,9 @@ type statelessPreparation struct {
deployID string
observation replicaObservation
recovery bool
+ // baseline: a copy of an assigned instance starting its record's
+ // baseline (replicas.Deploy.Baseline), with no release.
+ baseline bool
}
func carryStatelessPreparation(ctx context.Context, p *statelessPreparation) context.Context {
diff --git a/internal/activator/stateless_assignment_test.go b/internal/activator/stateless_assignment_test.go
index 8e611a294..5d94d2548 100644
--- a/internal/activator/stateless_assignment_test.go
+++ b/internal/activator/stateless_assignment_test.go
@@ -63,13 +63,18 @@ func TestStatelessAssignmentFinalSpawnGate(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ // Task 2: the deploy is done, so the copy may start its target; only
+ // the membership is under test here.
+ target := replicas.Build{Version: "v1", Digest: "canonical"}
+ rec.ReplicaDeploy = &replicas.Deploy{ID: "deploy-v1", Incarnation: facts.Identity.Incarnation, Target: target, LastGood: target, Phase: "done", Revision: 4}
for _, removed := range []bool{false, true} {
t.Run(fmt.Sprint(removed), func(t *testing.T) {
current := rec
reads := 0
a := &Service{Routes: startupRoutes{rt.Host: rt}, Fleet: FleetWake{Mode: FleetWakeCheck, Fleet: "pi", Label: "a", Record: func(context.Context, registry.Route) (*provision.Record, error) { reads++; return &current, nil }}}
- ctx := WithReplicaReleaseObservation(context.Background(), facts, replicas.Build{Version: "v1", Digest: "canonical"}, true)
+ ctx := WithReplicaReleaseObservation(context.Background(), facts, target, true)
ctx = context.WithValue(ctx, statelessRecordKey{}, rt)
+ ctx = context.WithValue(ctx, statelessPreparedKey{}, &statelessPreparation{route: rt, id: release.StagedIdentity{Version: "v1"}, digest: "canonical", deployID: "deploy-v1"})
ctx = a.withStatelessFinalCheck(ctx, rt)
if removed {
current.ReplicaAssignment = &replicas.Assignment{Desired: 2, Revision: 1, Boxes: []string{"b"}}
@@ -122,7 +127,7 @@ func TestStatelessAssignmentRemovedImmediatelyBeforeSpawn(t *testing.T) {
r.b.procs["v2"] = map[string]release.Process{release.ProcessWeb: {Command: []string{"serve"}}}
r.a.Fleet = FleetWake{Mode: FleetWakeCheck, Fleet: "pi", Label: "a", Record: func(context.Context, registry.Route) (*provision.Record, error) {
current := rec
- current.ReplicaDeploy = store.snapshot()
+ current.ReplicaDeploy = permittedDeploy(store.snapshot())
return &current, nil
}}
r.a.BeforeExec = func(context.Context, string, string) error {
@@ -190,6 +195,7 @@ func TestStatelessAssignmentDeclaredWorkers(t *testing.T) {
r.rt.Stateless = true
rec := provision.Record{Schema: 1, Host: r.rt.Host, Account: r.rt.Account, App: r.rt.App, Channel: r.rt.Channel, Environment: r.rt.Environment, Runtime: r.rt.Runtime, Region: r.rt.Region, CreatedAt: time.Unix(1, 0), Hibernate: new(bool), ReplicaAssignment: &replicas.Assignment{Desired: 2, Revision: 1, Boxes: []string{"a", "b"}}}
r.rt.ReplicaIncarnation, _ = provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ r.rt.Version = r.next.Version // the pointer installed the build the wake boots
r.routes.set(r.rt)
workers := &fakeWorkerBackend{killBackend: &killBackend{fakeBackend: r.b.fakeBackend}}
r.a.backend = &statelessWakeBackend{r.b, workers}
@@ -198,7 +204,7 @@ func TestStatelessAssignmentDeclaredWorkers(t *testing.T) {
var workerReads atomic.Int32
r.a.Fleet = FleetWake{Mode: FleetWakeCheck, Fleet: "pi", Label: "a", Record: func(context.Context, registry.Route) (*provision.Record, error) {
current := rec
- current.ReplicaDeploy = store.snapshot()
+ current.ReplicaDeploy = permittedDeploy(store.snapshot())
if removed.Load() {
current.ReplicaAssignment = &replicas.Assignment{Desired: 2, Revision: 1, Boxes: []string{"b"}}
}
diff --git a/internal/activator/statelessrelease.go b/internal/activator/statelessrelease.go
index fc3322450..745ef4f10 100644
--- a/internal/activator/statelessrelease.go
+++ b/internal/activator/statelessrelease.go
@@ -7,6 +7,7 @@ import (
"sync"
"time"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/replicas"
@@ -64,6 +65,13 @@ func (a *Service) prepareStatelessRelease(ctx context.Context, rt registry.Route
return durable.ID, errReplicaReleaseFailed
}
}
+ if old.PermitOutstanding() {
+ // R2: no new attempt begins while another attempt's copy switch is
+ // unresolved; the new deploy waits for that step. The writer would
+ // refuse the begin too, but that refusal would read as an unknown
+ // release result. copy SR-4-C31
+ return "", provision.ErrReplicaSwitchOpen
+ }
if a.releaseOpen(rt.Host) {
return "", ErrReplicaReleaseUnknown
}
diff --git a/internal/activator/swap.go b/internal/activator/swap.go
index de6e4fa19..c9cb24cb4 100644
--- a/internal/activator/swap.go
+++ b/internal/activator/swap.go
@@ -103,6 +103,12 @@ type SwapResult struct {
// triage T9). A replacement still running at the end of the window is
// SwapDone with CleanExit false.
CleanExit bool
+ // Proven is ReplicaSwap's proof for a replicated deploy's step: the
+ // result's generation is current and healthy through its settle
+ // window, the workers are handed over and every older generation's
+ // stop is proven. A box acknowledges its permit only for a SwapDone
+ // with Proven set. Swap itself never sets it.
+ Proven bool
}
var (
@@ -367,6 +373,14 @@ func (a *Service) Swap(ctx context.Context, at Attempt, newest func(host string)
return abandon(ErrFenced)
}
ctx = withStorageMode(ctx, route, id, mode, digest)
+ set := route.FleetBoxes != ""
+ if set {
+ // A copy of an assigned instance: overlap only, refused before any
+ // release preparation (replicadeploy.go).
+ if err := a.replicaSwapRefusal(at, mode); err != nil {
+ return abandon(err)
+ }
+ }
if mode {
prepared, err := a.prepareStateless(ctx, route, id, digest)
if err != nil {
@@ -382,6 +396,12 @@ func (a *Service) Swap(ctx context.Context, at Attempt, newest func(host string)
}
ctx = prepared
}
+ if set && !a.replicaPolicyAllows(route, digest) {
+ // The release passed (or ran here) and this copy is not allowed the
+ // build yet: it waits for its permitted step. The exec gate would
+ // refuse it anyway; refusing here raises and spawns nothing.
+ return abandon(errReplicaTurn)
+ }
if mode != oldStateless {
at.Mode = ModeHold
}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index c5e3ed4c1..061f6d5b3 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -780,6 +780,9 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// fast tick; its transitions go through the console's /deploy.
deployAPI := &replicaCoordinatorAPI{base: strings.TrimRight(os.Getenv("CARLOS_TUNNEL_URL"), "/"), fleet: identity.Fleet, box: identity.Label, token: os.Getenv("CARLOS_TUNNEL_TOKEN"), client: &http.Client{Timeout: 30 * time.Second}}
deployWorker := newReplicaDeployWorker(deployAPI, identity.Label, svc)
+ // The box's permitted step runs on its rollout scheduler; the
+ // worker acknowledges only that step's proven answer.
+ deployWorker.step = func(rec provision.Record) (bool, bool) { return replicaStepOf(armedRollout())(rec) }
armedReplicaDeploy.Store(deployWorker)
defer func() { armedReplicaDeploy.Store(nil); deployWorker.close() }()
defer armedStatelessBindings.Store(nil)
@@ -4005,12 +4008,9 @@ func BoxProvisionConfig(reg *registry.Registry, getenv func(string) string, judg
placement, deploy := armedReplicaPlacement.Load(), armedReplicaDeploy.Load()
if placement != nil || deploy != nil {
cfg.ReplicaObserved = func(rec provision.Record) {
- if placement != nil {
- placement.observe(rec)
- }
- if deploy != nil {
- deploy.Note(rec)
- }
+ // The scheduler is looked up per observation: it arms after
+ // this config may have been built.
+ replicaObserved(placement, deploy, armedRollout())(rec)
}
}
if publisher := armedStatelessBindings.Load(); publisher != nil {
diff --git a/internal/host/replica_deploy_e2e_test.go b/internal/host/replica_deploy_e2e_test.go
new file mode 100644
index 000000000..0c4318460
--- /dev/null
+++ b/internal/host/replica_deploy_e2e_test.go
@@ -0,0 +1,358 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "path/filepath"
+ "slices"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+ "github.com/carlosframework/platform/internal/rollout"
+)
+
+// e2eAct is one box's activator as the scheduler and the swap worker see
+// it. Its replica half models the real gates: a plain Swap onto the target
+// runs only where the observed deploy allows it, and ReplicaSwap answers
+// for the permit it was handed. step decides a permitted step; the default
+// switches and proves it. It notes the record each step saw.
+type e2eAct struct {
+ label string
+ w *deployStoreWorld
+ mu sync.Mutex
+ gen activator.Gen
+ n uint64
+ plain []string
+ steps []provision.Record
+ pol replicas.Deploy
+ step func() activator.SwapResult
+}
+
+func (a *e2eAct) Current(string) (activator.Gen, bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return a.gen, a.gen.Build != ""
+}
+func (a *e2eAct) Owns(host string) bool { _, ok := a.Current(host); return ok }
+func (a *e2eAct) RootfsWorkers(string) []activator.WorkerReport { return nil }
+func (a *e2eAct) PublishHeldServing(string) {}
+func (a *e2eAct) EffectiveMode(_ string, m activator.SwapMode) activator.SwapMode { return m }
+func (a *e2eAct) ReplaceWorker(context.Context, activator.Attempt, *release.StagedIdentity, func(string) uint64) activator.SwapResult {
+ return activator.SwapResult{Outcome: activator.SwapAbandoned}
+}
+
+func (a *e2eAct) serveLocked(build string) activator.Gen {
+ a.n++
+ a.gen = activator.Gen{N: a.n, Build: build, StagedPath: "/opt/" + build, Digest: "sha-" + build}
+ return a.gen
+}
+
+func (a *e2eAct) Swap(_ context.Context, at activator.Attempt, _ func(string) uint64) activator.SwapResult {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.plain = append(a.plain, at.Build)
+ if at.Build == a.pol.Target.Version && !a.pol.TargetAllowed(a.label) {
+ return activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "waiting for its turn"}
+ }
+ return activator.SwapResult{Outcome: activator.SwapDone, Gen: a.serveLocked(at.Build), Executed: true}
+}
+
+func (a *e2eAct) SetReplicaDeploy(_ string, d replicas.Deploy, _ string) {
+ a.mu.Lock()
+ a.pol = d
+ a.mu.Unlock()
+}
+
+func (a *e2eAct) ReplicaSwap(_ context.Context, at activator.Attempt, d replicas.Deploy, box string, _ func(string) uint64) activator.SwapResult {
+ rec := a.w.record()
+ a.mu.Lock()
+ a.steps = append(a.steps, rec)
+ step := a.step
+ a.mu.Unlock()
+ if box != a.label || d.Swap.ActiveBox != box {
+ return activator.SwapResult{Outcome: activator.SwapAbandoned}
+ }
+ res := activator.SwapResult{Outcome: activator.SwapDone, Proven: true}
+ if step != nil {
+ res = step()
+ }
+ if res.Outcome == activator.SwapDone {
+ a.mu.Lock()
+ if a.gen.Build != at.Build {
+ a.serveLocked(at.Build)
+ }
+ res.Gen = a.gen
+ a.mu.Unlock()
+ }
+ return res
+}
+
+func (a *e2eAct) serving() string { g, _ := a.Current(""); return g.Build }
+
+func (a *e2eAct) counts() (plain []string, steps []provision.Record) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return slices.Clone(a.plain), slices.Clone(a.steps)
+}
+
+// e2eBox is one fleet box: its registry row, scheduler, swap worker and
+// the agent's record fan-out (replicaObserved), wired as runAgent wires them.
+type e2eBox struct {
+ label string
+ act *e2eAct
+ reg *registry.Registry
+ mgr *rollout.Manager
+ worker *replicaDeployWorker
+ notify func(provision.Record)
+}
+
+// e2eClient is the console's /deploy over the world's store: it orders the
+// fresh boxes it is told of, drops the next reply of a box when asked to
+// (lose: the write commits; fail: nothing is written).
+type e2eClient struct {
+ w *deployStoreWorld
+ mu sync.Mutex
+ fresh []string
+ lose map[string]bool
+ fail map[string]bool
+ ops []string
+}
+
+func (c *e2eClient) Transition(ctx context.Context, id replicas.Identity, change replicas.DeployChange) (replicas.Deploy, error) {
+ c.mu.Lock()
+ c.ops = append(c.ops, change.Op+":"+change.Box)
+ fail, lose := c.fail[change.Box], c.lose[change.Box]
+ delete(c.fail, change.Box)
+ delete(c.lose, change.Box)
+ if change.Op == "order" {
+ change.Order = slices.Clone(c.fresh)
+ }
+ c.mu.Unlock()
+ if fail {
+ return replicas.Deploy{}, replicas.ErrConsoleUnreachable
+ }
+ rec, err := provision.SetRecordReplicaDeploy(ctx, c.w.s, id, change.Revision, change, time.Now())
+ if err != nil {
+ return replicas.Deploy{}, err
+ }
+ if lose {
+ return replicas.Deploy{}, replicas.ErrConsoleUnreachable
+ }
+ return *rec.ReplicaDeploy, nil
+}
+
+func newE2EBox(t *testing.T, w *deployStoreWorld, client replicaDeployClient, label string, coordinator bool) *e2eBox {
+ t.Helper()
+ dir := t.TempDir()
+ reg, err := registry.Open(filepath.Join(dir, "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ rec := w.record()
+ boxes, err := registry.ReplicaBoxes(*rec.ReplicaAssignment)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt := registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Kind: "instance", Status: "ready", Channel: rec.Channel, Region: rec.Region,
+ Runtime: registry.RuntimeRootfsV1, Stateless: true, Version: "v2", GoodVersion: "v1", GoodDigest: "sha-v1", CreatedAt: rec.CreatedAt.Unix(),
+ FleetBoxes: boxes, Copies: rec.ReplicaAssignment.Desired, ReplicaRevision: rec.ReplicaAssignment.Revision, ReplicaIncarnation: w.id.Incarnation}
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ opt := filepath.Join(dir, "opt")
+ for _, v := range []string{"v1", "v2"} {
+ if err := release.StageArtifact(opt, rec.Account, v, rec.App, []byte(v)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ act := &e2eAct{label: label, w: w}
+ act.serveLocked("v1")
+ book, err := rollout.OpenFailureBook(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ mgr := rollout.NewManager(ctx, rollout.Deps{Act: act, Routes: reg, Book: book, OptDir: opt, DataDir: dir, Box: label,
+ Demand: func(_ context.Context, _, _, ver, _ string) (string, string, error) { return "", "sha-" + ver, nil },
+ Policy: func(context.Context, string, string) (*appconfig.Manifest, error) {
+ return &appconfig.Manifest{Schema: 1, App: rec.App}, nil
+ },
+ Logf: t.Logf})
+ worker := newReplicaDeployWorker(client, label, nil)
+ worker.terms = fixedTerm("")
+ if coordinator {
+ worker.terms = fixedTerm(w.term)
+ }
+ worker.step = replicaStepOf(mgr)
+ t.Cleanup(worker.close)
+ return &e2eBox{label: label, act: act, reg: reg, mgr: mgr, worker: worker, notify: replicaObserved(nil, worker, mgr)}
+}
+
+// round is one reconcile observation and fast tick on every live box.
+func round(t *testing.T, w *deployStoreWorld, boxes ...*e2eBox) {
+ t.Helper()
+ rec := w.record()
+ for _, b := range boxes {
+ b.notify(rec)
+ routes, err := b.reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.mgr.Pass(routes)
+ }
+ time.Sleep(20 * time.Millisecond)
+ for _, b := range boxes {
+ b.worker.Pass(context.Background())
+ }
+}
+
+func runUntil(t *testing.T, w *deployStoreWorld, what string, done func(provision.Record) bool, boxes ...*e2eBox) {
+ t.Helper()
+ for i := 0; i < 200; i++ {
+ round(t, w, boxes...)
+ if done(w.record()) {
+ return
+ }
+ }
+ t.Fatalf("never reached %s: %+v", what, w.record().ReplicaDeploy)
+}
+
+func deployDone(rec provision.Record) bool { return rec.ReplicaDeploy.Phase == "done" }
+
+// TestReplicaOrderedOverlap (Task 2): after one passed release, a switches
+// through its permitted step, acknowledges only once that step is proven,
+// and only then does b begin; neither box moves onto the target outside its
+// step, and no second release attempt starts.
+func TestReplicaOrderedOverlap(t *testing.T) {
+ w := newDeployStoreWorld(t)
+ client := &e2eClient{w: w, fresh: []string{"a", "b"}}
+ a, b := newE2EBox(t, w, client, "a", true), newE2EBox(t, w, client, "b", false)
+ runUntil(t, w, "done", deployDone, a, b)
+ _, stepsA := a.act.counts()
+ plainB, stepsB := b.act.counts()
+ plainA, _ := a.act.counts()
+ if len(stepsA) == 0 || len(stepsB) == 0 {
+ t.Fatalf("steps: a %d, b %d", len(stepsA), len(stepsB))
+ }
+ for _, rec := range stepsB {
+ if !slices.Contains(rec.ReplicaDeploy.Swap.Completed, "a") {
+ t.Fatalf("b began before a's switch was acknowledged: %+v", rec.ReplicaDeploy.Swap)
+ }
+ }
+ for _, rec := range stepsA {
+ if rec.ReplicaDeploy.Swap.ActiveBox != "a" {
+ t.Fatalf("a stepped without its permit: %+v", rec.ReplicaDeploy.Swap)
+ }
+ }
+ if slices.Contains(plainA, "v2") || slices.Contains(plainB, "v2") {
+ t.Fatalf("a box moved onto v2 outside its step: a %v, b %v", plainA, plainB)
+ }
+ if a.act.serving() != "v2" || b.act.serving() != "v2" {
+ t.Fatalf("serving: a %s, b %s", a.act.serving(), b.act.serving())
+ }
+ d := w.record().ReplicaDeploy
+ if d.ID != "deploy-2" || !slices.Equal(d.Swap.Completed, []string{"a", "b"}) {
+ t.Fatalf("deploy: %+v", d)
+ }
+ want := []string{"order:a", "permit:a", "ack:a", "permit:a", "ack:b", "done:a"}
+ if !slices.Equal(client.ops, want) {
+ t.Fatalf("transitions %v, want %v", client.ops, want)
+ }
+}
+
+// TestReplicaSwapUnknownHalts (Task 2): an ACK that never reached the
+// console leaves the step open, so no box gets the next permit until the
+// same answer lands; one whose reply was lost is recovered from the record.
+// A box lost during its step never answers: nothing proceeds, placement's
+// halt keeps the permit, and the other copy keeps serving its build.
+func TestReplicaSwapUnknownHalts(t *testing.T) {
+ t.Run("ack not delivered", func(t *testing.T) {
+ w := newDeployStoreWorld(t)
+ client := &e2eClient{w: w, fresh: []string{"a", "b"}, fail: map[string]bool{}, lose: map[string]bool{}}
+ a, b := newE2EBox(t, w, client, "a", true), newE2EBox(t, w, client, "b", false)
+ runUntil(t, w, "a's permit", func(rec provision.Record) bool { return rec.ReplicaDeploy.Swap.ActiveBox == "a" }, a, b)
+ client.mu.Lock()
+ client.fail["a"] = true
+ client.mu.Unlock()
+ runUntil(t, w, "a's ack after its first was not delivered", func(rec provision.Record) bool {
+ return slices.Contains(rec.ReplicaDeploy.Swap.Completed, "a")
+ }, a, b)
+ client.mu.Lock()
+ client.lose["b"] = true
+ client.mu.Unlock()
+ runUntil(t, w, "done after b's ack reply was lost", deployDone, a, b)
+ _, stepsB := b.act.counts()
+ for _, rec := range stepsB {
+ if !slices.Contains(rec.ReplicaDeploy.Swap.Completed, "a") {
+ t.Fatal("b's permit came before a's answer landed")
+ }
+ }
+ if acks := slices.DeleteFunc(slices.Clone(client.ops), func(op string) bool { return op != "ack:a" }); len(acks) != 2 {
+ t.Fatalf("a's acks: %v", client.ops)
+ }
+ })
+ t.Run("box lost during its step", func(t *testing.T) {
+ w := newDeployStoreWorld(t)
+ client := &e2eClient{w: w, fresh: []string{"a", "b"}}
+ a, b := newE2EBox(t, w, client, "a", true), newE2EBox(t, w, client, "b", false)
+ a.act.step = func() activator.SwapResult {
+ return activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "box lost", Err: errors.New("box lost")}
+ }
+ for i := 0; i < 40; i++ {
+ round(t, w, a, b)
+ }
+ d := w.record().ReplicaDeploy
+ if d.Swap.ActiveBox != "a" || len(d.Swap.Completed) != 0 {
+ t.Fatalf("the step resolved without an answer: %+v", d.Swap)
+ }
+ rec := w.record()
+ if _, err := provision.HaltRecordReplicaDeploy(context.Background(), w.s, w.id, replicas.Expect{Incarnation: w.id.Incarnation, Region: rec.Region, RecordSeq: rec.RecordSeq, Revision: rec.ReplicaAssignment.Revision}, d.Revision); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 20; i++ {
+ round(t, w, a, b)
+ }
+ d = w.record().ReplicaDeploy
+ if !d.Swap.Halted || d.Swap.ActiveBox != "a" {
+ t.Fatalf("halt: %+v", d.Swap)
+ }
+ if _, steps := b.act.counts(); len(steps) != 0 || b.act.serving() != "v1" {
+ t.Fatalf("b moved: %d steps, serving %s", len(steps), b.act.serving())
+ }
+ })
+}
+
+// TestReplicaOneSurvivorDeploy (Task 2): with b down, the order holds a
+// alone and a switches by itself. When b returns the deploy is done, so b
+// joins the committed target as an ordinary move: no step, no new attempt.
+func TestReplicaOneSurvivorDeploy(t *testing.T) {
+ w := newDeployStoreWorld(t)
+ client := &e2eClient{w: w, fresh: []string{"a"}}
+ a, b := newE2EBox(t, w, client, "a", true), newE2EBox(t, w, client, "b", false)
+ runUntil(t, w, "done with a alone", deployDone, a)
+ if d := w.record().ReplicaDeploy; !slices.Equal(d.Swap.Order, []string{"a"}) || !slices.Equal(d.Swap.Completed, []string{"a"}) {
+ t.Fatalf("survivor deploy: %+v", d.Swap)
+ }
+ before := w.record().ReplicaDeploy.Revision
+ for i := 0; i < 50 && b.act.serving() != "v2"; i++ {
+ round(t, w, a, b)
+ }
+ if b.act.serving() != "v2" {
+ t.Fatal("the returning copy did not join the committed target")
+ }
+ if _, steps := b.act.counts(); len(steps) != 0 {
+ t.Fatalf("the returning copy took a step: %d", len(steps))
+ }
+ if d := w.record().ReplicaDeploy; d.Revision != before || d.ID != "deploy-2" {
+ t.Fatalf("the return changed the deploy: %+v", d)
+ }
+}
diff --git a/internal/host/replicadeploy.go b/internal/host/replicadeploy.go
index 78121d254..59239bce4 100644
--- a/internal/host/replicadeploy.go
+++ b/internal/host/replicadeploy.go
@@ -9,6 +9,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/replicas"
+ "github.com/carlosframework/platform/internal/rollout"
)
// replicaDeployClient reports one swap transition through the console's
@@ -44,7 +45,8 @@ type replicaDeployWork struct {
// records the reconcile pass already observed (Note) on the agent's existing
// fast tick (Pass). It has no poller of its own. On the coordinator it
// orders the copies, grants one permit at a time and closes the deploy;
-// on the permit's box it hands the permit to swap (Task 2's ReplicaSwap).
+// on the permit's box it sends the ACK once the box's step has its answer
+// (step). The step itself runs on the box's rollout scheduler.
type replicaDeployWorker struct {
mu sync.Mutex
client replicaDeployClient
@@ -57,9 +59,11 @@ type replicaDeployWorker struct {
ctx context.Context
cancel context.CancelFunc
now func() time.Time
- // swap runs this box's permitted step and sends its ack. Nil until the
- // activator's ReplicaSwap is wired; a permit then waits, unresolved.
- swap func(context.Context, provision.Record)
+ // step is this box's answer to its permit on a record: ok once the
+ // scheduler's permitted step (activator.ReplicaSwap) has one, switched
+ // only after that step proved the switch (replicaStepOf). Nil, or no
+ // answer yet: the permit stays open and nothing is sent.
+ step func(provision.Record) (switched, ok bool)
}
var armedReplicaDeploy atomic.Pointer[replicaDeployWorker]
@@ -149,6 +153,25 @@ func replicaDeployStep(rec provision.Record, box, term string) (replicas.DeployC
return change, true
}
+// replicaAnswer is box's ACK of its permit on rec, once step has the
+// answer of the box's permitted step: Switched only when that step proved
+// the switch (the new generation healthy through its settle window, the
+// workers handed over, every older generation's stop proven), not switched
+// when the successor failed and the incumbent kept serving, which halts the
+// deploy. No answer, no ACK: the permit stays open, so no next permit is
+// granted. A halted permit is answered the same way, which resolves it.
+func replicaAnswer(rec provision.Record, box string, step func(provision.Record) (bool, bool)) (replicas.DeployChange, bool) {
+ d := rec.ReplicaDeploy
+ if step == nil || d == nil || d.Swap.ActiveBox != box || d.Phase != "released" {
+ return replicas.DeployChange{}, false
+ }
+ switched, ok := step(rec)
+ if !ok {
+ return replicas.DeployChange{}, false
+ }
+ return replicas.DeployChange{Op: "ack", ID: d.ID, Box: box, Revision: d.Revision, Target: d.Target, Permit: d.Swap.Permit, Switched: switched}, true
+}
+
// Pass runs at most one transition per noted host.
func (w *replicaDeployWorker) Pass(ctx context.Context) {
now := w.now()
@@ -163,18 +186,20 @@ func (w *replicaDeployWorker) Pass(ctx context.Context) {
for _, p := range work {
rec := p.rec
d := rec.ReplicaDeploy
- if d.Swap.ActiveBox == w.box && !d.Swap.Halted {
- if w.swap != nil {
- w.swap(ctx, rec)
- }
- continue
- }
inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
- if err != nil || w.terms == nil || w.client == nil {
+ if err != nil || w.client == nil {
continue
}
id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}
- change, ok := replicaDeployStep(rec, w.box, w.terms.HeldTerm(id))
+ var (
+ change replicas.DeployChange
+ ok bool
+ )
+ if d.Swap.ActiveBox == w.box {
+ change, ok = replicaAnswer(rec, w.box, w.step)
+ } else if w.terms != nil {
+ change, ok = replicaDeployStep(rec, w.box, w.terms.HeldTerm(id))
+ }
if !ok {
continue
}
@@ -197,3 +222,34 @@ func (w *replicaDeployWorker) Pass(ctx context.Context) {
w.mu.Unlock()
}
}
+
+// replicaStepOf is the swap worker's step on a box whose rollout scheduler
+// is m: the answer m's permitted step left for the record's permit
+// (rollout.Manager.ReplicaOutcome). The step runs on the scheduler, so it
+// keeps the slot, intent and failure book of any attempt.
+func replicaStepOf(m *rollout.Manager) func(provision.Record) (switched, ok bool) {
+ return func(rec provision.Record) (bool, bool) {
+ if m == nil || rec.ReplicaDeploy == nil {
+ return false, false
+ }
+ d := rec.ReplicaDeploy
+ return m.ReplicaOutcome(rec.Host, d.ID, d.Swap.Permit)
+ }
+}
+
+// replicaObserved is the reconcile pass's one record observation fanned out
+// (R7): to the placement worker, the swap worker and the rollout scheduler
+// (which hands it to the activator as policy). None reads the store itself.
+func replicaObserved(placement *replicaPlacementWorker, deploy *replicaDeployWorker, m *rollout.Manager) func(provision.Record) {
+ return func(rec provision.Record) {
+ if placement != nil {
+ placement.observe(rec)
+ }
+ if deploy != nil {
+ deploy.Note(rec)
+ }
+ if m != nil {
+ m.NoteReplicaDeploy(rec)
+ }
+ }
+}
diff --git a/internal/host/replicadeploy_test.go b/internal/host/replicadeploy_test.go
index 31cc01ba7..70621b58b 100644
--- a/internal/host/replicadeploy_test.go
+++ b/internal/host/replicadeploy_test.go
@@ -228,7 +228,13 @@ func TestReplicaDeployPermitReachesWorkerThroughReconcile(t *testing.T) {
}
permits := make(chan provision.Record, 4)
worker := newReplicaDeployWorker(&deployStoreClient{}, "b", nil)
- worker.swap = func(_ context.Context, r provision.Record) { permits <- r }
+ worker.step = func(r provision.Record) (bool, bool) {
+ select {
+ case permits <- r:
+ default:
+ }
+ return false, false
+ }
pctx, pcancel := context.WithCancel(ctx)
placement := &replicaPlacementWorker{box: "b", ctx: pctx, cancel: pcancel, reg: reg}
armedReplicaDeploy.Store(worker)
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index bb82926e7..df6204556 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := statelessReplicas4Task1WriteCensusInventory()
+ inventory := statelessReplicas4Task2WriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/replicadeploy.go b/internal/provision/replicadeploy.go
index e2fbd2549..24f2cfce6 100644
--- a/internal/provision/replicadeploy.go
+++ b/internal/provision/replicadeploy.go
@@ -24,8 +24,9 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
if err := replicaIdentity(rec, id); err != nil {
return err
}
- // The writer owns the swap, LastGood and a consumed retry; a
- // release change carries none of them except a begin's RetryOf.
+ // The writer owns the swap, LastGood, Previous and a consumed
+ // retry; a release change carries none of them except a begin's
+ // RetryOf. A Previous the box copied from the record is ignored.
if next.Incarnation != id.Incarnation || next.ID == "" || next.Term == "" || next.Target.Version == "" || next.Target.Digest == "" || !swapEmpty(next.Swap) || next.LastGood != (replicas.Build{}) || next.RetryRequest != "" || (next.RetryOf != "" && next.Phase != "pending") {
return replicas.ErrInvalid
}
@@ -35,7 +36,7 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
old := rec.ReplicaDeploy
// A committed success is evidence even when its reply was lost. Do not
// advance either revision or record sequence on this exact replay.
- if old != nil && replicas.ReleasePassed(old.Phase) && next.Phase == "released" && old.ID == next.ID && old.Incarnation == next.Incarnation && old.Term == next.Term && old.Target == next.Target && old.Previous == next.Previous {
+ if old != nil && replicas.ReleasePassed(old.Phase) && next.Phase == "released" && old.ID == next.ID && old.Incarnation == next.Incarnation && old.Term == next.Term && old.Target == next.Target {
return errRecordUnchanged
}
c := rec.Coordinator
@@ -48,7 +49,7 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
}
// An identical begin can be replayed after a lost reply, including
// with the pre-commit revision carried by that attempt.
- if old != nil && old.Phase == "pending" && next.Phase == "pending" && old.ID == next.ID && old.Term == next.Term && old.Incarnation == next.Incarnation && old.Target == next.Target && old.Previous == next.Previous {
+ if old != nil && old.Phase == "pending" && next.Phase == "pending" && old.ID == next.ID && old.Term == next.Term && old.Incarnation == next.Incarnation && old.Target == next.Target {
return errRecordUnchanged
}
if revision != expectedRevision || revision == math.MaxUint64 {
@@ -64,14 +65,21 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
return err
}
next.LastGood = replicas.CarryLastGood(old, id.Incarnation)
+ // The attempt's baseline (Deploy.Baseline): copies not yet
+ // allowed its target keep running this after its release
+ // passes and LastGood moves to the target. The writer owns it.
+ next.Previous = next.LastGood
if next.RetryOf != "" {
// The consuming attempt keeps the request that asked for it.
next.RetryRequest = old.RetryRequest
}
} else {
- if old.Incarnation != next.Incarnation || old.Target != next.Target || old.Previous != next.Previous {
+ if old.Incarnation != next.Incarnation || old.Target != next.Target {
return replicas.ErrFenced
}
+ // Previous is the writer's, set at begin; a box's copy of it
+ // is ignored.
+ next.Previous = old.Previous
if next.RetryOf != "" && next.RetryOf != old.RetryOf {
return replicas.ErrInvalid
}
diff --git a/internal/provision/replicadeploy_test.go b/internal/provision/replicadeploy_test.go
index 35329caad..5a0984271 100644
--- a/internal/provision/replicadeploy_test.go
+++ b/internal/provision/replicadeploy_test.go
@@ -933,3 +933,43 @@ func TestReplicaRetryReplayRefusedWhenChanged(t *testing.T) {
})
}
}
+
+// TestReplicaSwapBaselineSurvivesTheRelease (Task 2): a new attempt records
+// the LastGood it began with as Previous, so a copy that is not yet allowed
+// the target still knows its baseline after the release passes and LastGood
+// names the target. A failure keeps both, and the next attempt starts from
+// the last passed build.
+func TestReplicaSwapBaselineSurvivesTheRelease(t *testing.T) {
+ w := newSwapWorld(t)
+ w.swapThrough(t)
+ v3 := replicas.Build{Version: "v3", Digest: "canonical-3"}
+ w.release(t, "deploy-3", v3, "", "pending")
+ if d := w.rec.ReplicaDeploy; d.Previous != swapTarget || d.LastGood != swapTarget {
+ t.Fatalf("begin: %+v", d)
+ }
+ w.release(t, "deploy-3", v3, "", "releasing", "released")
+ if d := w.rec.ReplicaDeploy; d.Previous != swapTarget || d.LastGood != v3 || d.Want("b") != swapTarget || d.Allows("b", w.id.Incarnation, v3.Digest) {
+ t.Fatalf("released: %+v", d)
+ }
+ v4 := replicas.Build{Version: "v4", Digest: "canonical-4"}
+ // deploy-3 is released with no open permit and not done: halt it first,
+ // as an operator retry or a new pointer would find it.
+ order := w.change("order")
+ order.Order = []string{"a", "b"}
+ w.apply(t, order)
+ w.apply(t, w.change("halt"))
+ w.release(t, "deploy-4", v4, "", "pending", "failed")
+ if d := w.rec.ReplicaDeploy; d.Previous != v3 || d.LastGood != v3 || d.Want("b") != v3 {
+ t.Fatalf("failed: %+v", d)
+ }
+ // A box's begin replay carries the Previous it read; the writer keeps it.
+ d := *w.rec.ReplicaDeploy
+ forged := replicas.Deploy{ID: "deploy-5", Incarnation: w.id.Incarnation, Term: w.term, Target: replicas.Build{Version: "v5", Digest: "canonical-5"}, Phase: "pending", Previous: replicas.Build{Version: "v0", Digest: "canonical-0"}}
+ rec, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, d.Revision, forged)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rec.ReplicaDeploy.Previous != v3 {
+ t.Fatalf("a box chose the baseline: %+v", rec.ReplicaDeploy)
+ }
+}
diff --git a/internal/provision/stateless_replicas_4_task2_census_test.go b/internal/provision/stateless_replicas_4_task2_census_test.go
new file mode 100644
index 000000000..61360b4f0
--- /dev/null
+++ b/internal/provision/stateless_replicas_4_task2_census_test.go
@@ -0,0 +1,37 @@
+package provision
+
+// statelessReplicas4Task2WriteCensusInventory is stateless replicas Plan 4
+// Task 2's review of the record-write census, layered on Task 1's.
+// Self-review only; the independent #280 verdict is the controller's.
+//
+// - SetRecordReplicaRelease: the writer now owns Previous. A new attempt
+// records the LastGood it began with as Previous (the baseline copies
+// run until the target is allowed on them, replicas.Deploy.Baseline);
+// a same-ID transition keeps the record's Previous and ignores the
+// box's copy of it, and the two replay checks no longer compare it.
+// Same CAS, field key, F8 proof, term and lock; no new write path.
+// - prepareStateless: a set row's baseline is prepared from the record's
+// deploy with no release, and a build the row does not name is refused
+// before any release. It writes no record; its only record reference
+// is the unchanged statelessRecordKey observation.
+// - No new record writer. The swap worker's ACK goes through Task 1's
+// /deploy door and SetRecordReplicaDeploy, unchanged.
+func statelessReplicas4Task2WriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), statelessReplicas4Task1WriteCensusInventory()...)
+ for _, r := range []censusEntry{
+ {"internal/activator/stateless.go", "Service.prepareStateless", "reference", "key:statelessRecordKey", "2585582c2a68892b701f4d1fdf9f40bf4cec8a667cb1ff3a10477e354f668304"},
+ {"internal/provision/replicadeploy.go", "SetRecordReplicaRelease", "record-writer", "key:SetRecordReplicaRelease,key:updateRecord", "4cf65247d1cb0e75c0bd61aa18eefad95e877c2ab89790a718e075e091e249df"},
+ } {
+ replaced := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ entries[i], replaced = r, true
+ break
+ }
+ }
+ if !replaced {
+ entries = append(entries, r)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index ad9b154a5..4ab2616ea 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -172,3 +172,4 @@ plan14-root-reads-stateless-replicas-4-task1.tsv 3f066208f5e5fa2b9854f30118a9a27
plan14-root-reads-stateless-replicas-4-task1-fix1.tsv 3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5
plan14-root-reads-stateless-replicas-4-task1-fix2.tsv 3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5
plan14-root-reads-stateless-replicas-4-task1-fix3.tsv 3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5
+plan14-root-reads-stateless-replicas-4-task2.tsv 40c909a853a761733e9f837d4c8336bc91e174125cad65ac412f71141978be19
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task2.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task2.tsv
new file mode 100644
index 000000000..52a971e83
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task2.tsv
@@ -0,0 +1,36 @@
+# Census overlay stateless-replicas-4-task2, written by census-propose (#369). census-ruling-stateless-replicas-4-task2, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-replicas-4-task2.md.
+# 3 body, 2 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 10 new dispositions: 4 reads re-frozen at their disposition with the claim, 6 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy c160ef021652fd65f16fa19b46e70770a35accc6238f0d260d63155a9335e21e internal/activator/statelessrelease.go Service.prepareStatelessRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task1;basis=The former PrepareStatelessRelease body. R9: adopts the record's attempt for this lifetime and target in every phase before any coordination; otherwise acquires the term first and only then selects the ID (R1); a begin carries RetryOf only when consuming a durable retry. Same calls (ObserveReplicaRelease, coordinator, escrow initializer, actEntry, runReleaseAdmitted); same gates, proof and SafeUntil checks; no new store read or writer.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: refuses with provision.ErrReplicaSwitchOpen (SR-4-C31) before term acquisition when the observed record already has an unresolved copy-switch permit, instead of a begin the writer refuses and that read as an unknown result. Refusal only; same calls, no read added. registry:Account@634,registry:App@664,registry:GoodDemand@4032,registry:GoodDigest@4017,registry:GoodVersion@4001,registry:Host@1646,registry:Host@301,registry:Host@4088,registry:Host@4146,registry:Host@4362,registry:Host@4430,registry:Host@691,whole:Route@1093,whole:Route@4155,whole:Route@4162,whole:Route@4714,whole:Route@569 b167be541a3eb4d556c4f4fed71ad6034e354fbb7e570a32b79aada3867a1c1d
+@legacy 8b7ab4ddae3eec161fdcc1377d2627803ca0656885d094c0e900620ad7144886 internal/activator/activator.go Service.ConvergeAdopted legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: refuses (returns false) for a set row (route FleetBoxes) before any other check, so a repointed link never cycles a copy; a refusal only. registry:FleetBoxes@357,whole:Route@359 87022a2f85d1f663c813636585af0b2c81ccea2432563158058a54994ee09215
+@legacy bf8dd5ab4c386e65b400ad9c6c79834b0219f3fa9585a557568eeae85778a3fe internal/activator/replicadeploy.go Service.ReplicaSwap legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new. Checks the permit (box label, phase released, not halted, ActiveBox, build), refuses a hold, asks tenantStartRefusal on the in-memory entry route, then either re-proves an existing switch (replicaSettle) or runs the existing Swap as a canary and checks replicaStepProven. Reads the in-memory entry route only; no store, file or root call of its own. registry:FleetBoxes@739,whole:Route@649,whole:Route@659,whole:Route@827 5ba84cd20369a8319861cb386b0f4fcf0ea5455abfc71688297e269e09cd9e7b
+@legacy da603adf5b149e8c0bef3242d56acb1b9730734b682ce93c3199edd0d36d64af internal/activator/replicadeploy.go Service.replicaPolicyAllows legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new. Allows over the in-memory observed policy for the route Host and ReplicaIncarnation; no read beyond the route it is handed. registry:Host@141,registry:ReplicaIncarnation@228 ca258bbb35257c70fd1ea204029a5d18719e58cb0682cf68a8c0eabc3cd7cf2d
+@legacy 4a3d1b5852ece86e95a715c6d02d7f1d1ca15af3b4684e05cf2bddb1c9731639 internal/activator/replicadeploy.go Service.replicaSettle legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new. GET / health (genHealthy) and the settle window on the current in-memory generation, then replicaStepProven; reads the in-memory entry route only. whole:Route@262,whole:Route@320 d7db2d0a323fc43b6fb6eaf327ca33c044698cbe49fb82b9031547b70a1674ae
+@legacy 034316bbea34ea10c64d6b28418853ee9fb418ab648ab72afea88bbf0f57d306 internal/rollout/replicas.go Manager.replicaWant legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new. Reads the handed route FleetBoxes, Host and ReplicaIncarnation against the in-memory noted deploy; no store or file read. registry:FleetBoxes@78,registry:Host@209,registry:ReplicaIncarnation@246 7345ae771a15b66d8d92fc48a845d8f53c876bac326c93351c5566faa343f3d5
+@legacy b05f4a732de109b2bedea739b14bd8c2726e7e6f45de9079fa3583652b1d0697 internal/rollout/wakeplan.go decideReplicaWake legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new pure planner. Reads the handed route (App, Version, Good fields) and calls the existing Demand closure for the record baseline staged path (release.VersionPath under the box OptDir), as decideWake does for the installed build; no new reader. registry:App@145,registry:GoodDemand@368,registry:GoodDigest@347,registry:GoodVersion@291,registry:GoodVersion@325,registry:Version@274,registry:Version@309,whole:Route@140,whole:Route@328,whole:Route@350,whole:Route@371,whole:Route@99 f1ba5f831601b5b27bb8fd050be6f125ad0562378fdf1662ab6ad4baaad9bad7
+@legacy f366bf0ef25f36bd3e4318e25a488e50b8bec12182f7e8cc80093d9d55a8d9f7 internal/activator/activator.go Service.sweepOnce legacy accepted-legacy accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged).;rev3=census-ruling-plans-4c-box-throttle;basis=after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25.;rev3=census-ruling-plans-4d-lapse;basis=stops a live entry the turned-off hook names (never mid-command, never a move's active probe), stands down an exited worker it names instead of restarting it (Astra finding 4), and skips such rows in the due loop and the always-on arm so they are not woken (plans 4d). Four more whole-row reads: the row handed to the hook (a.disabled), as idleFor and maxRunFor already are. Only stops or skips.;rev3=census-ruling-remote-instance-metrics;basis=its two entries-map insertions go through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more call at the top, a.retryOwedMarkers() (harelease.go), which starts at most one background lease.RetryPending pass over owed region HA release markers, off a.mu; the due query, idle, max-run and lapse logic are unchanged; the same 38 sites, no read added; merge of origin/main d7ae1d76: main's change is kept as main has it (census-ruling-remote-instance-metrics: its two entries-map insertions go through putEntryLocked); this branch's change is the same as above; read sites the same 38, offsets moved;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8: a resident (Route.Resident) is never stopped for idleness or by the continuous-awake ceiling; the due-wake check is left on Hibernate (comment); stops less, not more;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: an entry whose host has a release record open (the in-memory a.releaseOps[e.host]) is not stopped by its plan's turn-off, by idleness or by the continuous-awake ceiling until the record goes; one more sweep pass, reapReleaseOpsLocked, retries an unproven release's stop (through finishPendingStops); the same 39 read sites, no read added; stops less, not more;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 9 (PF-18): the four checks that left an entry with a run attached alone (e.cmd == nil) now read holdsAttachedLocked(e), a run or a session attached, so a session holds the idle sleep, the plans awake ceiling, the plans turned-off stop and the turned-off worker's stand-down as a run does; in-memory under a.mu; only keeps an entry awake longer; no read added, read sites unchanged;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p1b3b-t;basis=Tag due entries as background duties; the wake evaluates the gate off a.mu before acquire or token preparation. No read added.;rev3=census-ruling-region-ha-g2-fixes;basis=Schedule bounded demanded HA recovery and owed-marker retries; reap completed withdrawal jobs whose row is gone, changed or locally eligible, via separately claimed registry reads; no new direct read.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: the drift cycle is skipped for a set row (route FleetBoxes); a refusal only, no read beyond the entry route already in hand. registry:FleetBoxes@13571,registry:Hibernate@10852,registry:Hibernate@14804,registry:Hibernate@24062,registry:Hibernate@5727,registry:Hibernate@7926,registry:Host@24131,registry:Host@24189,registry:Host@24656,registry:Host@24749,registry:Host@25501,registry:Host@25602,registry:Host@26666,registry:Host@26953,registry:Host@27009,registry:NextDue@25439,registry:Status@24078,whole:Route@10854,whole:Route@11713,whole:Route@13573,whole:Route@14806,whole:Route@16739,whole:Route@18449,whole:Route@18639,whole:Route@18932,whole:Route@19104,whole:Route@19251,whole:Route@23462,whole:Route@24238,whole:Route@25153,whole:Route@25510,whole:Route@25517,whole:Route@26481,whole:Route@26782,whole:Route@26986,whole:Route@5538,whole:Route@5729,whole:Route@7759,whole:Route@7928,whole:Route@8121,whole:Route@8584 17bb95bd0278ba9f81a8abc21241f68a54944e7b7de2840200989a4dcb89848b
+@legacy 2e63cc97650d7c25e4f50e522a50a1be858da0f5d267ce0469e536104272f7f4 internal/activator/stateless.go Service.prepareStateless legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Capture RecordFacts from the existing record source, obtain the durable FailureBook deploy ID, and call Task 2 PrepareStatelessRelease with the canonical verdict/digest carrier. Carry a successful attempt through its hold only after another current-record check; no serving lease or polling loop. Fix 3a round 1 I2: preparation uses reconcile observations and records the successful deploy ID. Carry prepared evidence through hold; fresh backend read must confirm that same released deploy before web runs.;rev3=census-ruling-stateless-failed-release-held;basis=For recovery onto a different installed version's exact committed good version and artifact digest, retain recovery evidence without selecting or writing another deploy. Adds the existing committedGood registry read, with its route and incarnation check. Canonical storage declaration and observed lifetime gates remain.;rev3=census-ruling-stateless-replicas-4-task1;basis=R1: no longer calls ReplicaDeployID before preparation; hands the same a.ReplicaDeployID selector to prepareStatelessRelease, which calls it only after coordinator term acquisition. The ObservedReplicaRelease call stays as a validity check. Same read sites; no new read, write or authority.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2 (D4): for a set row, prepares the record baseline with no release, and refuses a build the row Version does not name before any release; reads the route it is handed (FleetBoxes, Version). No store read or write added. registry:Account@284,registry:Account@310,registry:App@324,registry:App@346,registry:Digest@2027,registry:FleetBoxes@944,registry:Host@250,registry:Host@273,registry:Stateless@2325,registry:Version@1635,registry:Version@1707,registry:Version@1997,whole:Route@1458,whole:Route@1465,whole:Route@1947,whole:Route@2091,whole:Route@2098,whole:Route@2321,whole:Route@2475,whole:Route@2579,whole:Route@2586,whole:Route@259,whole:Route@293,whole:Route@333,whole:Route@540,whole:Route@597,whole:Route@714,whole:Route@821 2585582c2a68892b701f4d1fdf9f40bf4cec8a667cb1ff3a10477e354f668304
+@legacy 321c55ae641f0920a8627cd8d71822f971b449cce1f516a7515a9d6db4812943 internal/activator/stateless.go Service.statelessFinalRecord legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Fix 3a round 1 I2: one fresh record read at final exec, after pending write and release/escrow preparation. Reuse Fleet.Record result or cfg.Record, never both. Validate placement/config/lifetime and prepared deploy ID/target/released phase; registry checks before and after.;rev3=census-ruling-stateless-failed-release-held;basis=At final launch, a recovery must still match the committed good version and artifact digest. Adds the existing committedGood registry read. The current record's lifetime, placement and launch-input checks remain; a new deployment still requires matching released coordinator evidence.;rev3=census-ruling-stateless-replicas-4-task1;basis=A deploy whose swap finished reads phase done; the final launch check accepts released or done (replicas.ReleasePassed) for the same prepared ID, target and lifetime. Same reads; no check removed.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: for a set row, the record read here (unchanged read) must Allow this box the build (replicas.Deploy.Allows); refusal only. registry:Channel@398,registry:Digest@1543,registry:Environment@431,registry:FleetBoxes@868,registry:Region@492,registry:Runtime@464,registry:Version@1504,whole:Route@122,whole:Route@1480,whole:Route@1919,whole:Route@208,whole:Route@285,whole:Route@629 0a8ed3e85d0f717bd548ed2020ee7c9cbfa5f4fd53c4f8ab1896dc8382f172be
+@legacy 84f4fb2fc1c2212de39d75f81879cd5e011eaf9116f3bbaeaf2d52cf8bb63786 internal/activator/swap.go Service.Swap legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Verify the target canonical mode and prepare its durable stateless release before stopping the incumbent. A mode change forces the existing proven hold path; same-mode stateless overlap uses local lifecycle gates and the final current-record check, without a serving lease. CI fix 1: defer a missing registry row to the existing release checks only for stateful rootfs overlap, preserving disabled/newest checks and committedGood refusal. Stateless modes, transitions, binary/foreign/hold paths still fence before preparation. No new reads. Final review C1/R26: include incumbent Gen.Stateless as declaration evidence, so only matching good stateful recovery/config attempts can skip canonical lookup. Fresh route, release, ownership and stop gates unchanged.;rev3=census-ruling-stateless-failed-release-held;basis=Classify a proven stateless release failure, or the same deploy's durable failed or unknown phase, through the existing SwapFailed hold mechanism. Preparation precedes stopping the incumbent, so report overlap semantics even if the requested swap is hold. Stateful path unchanged; no new root input.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: for a set row (route FleetBoxes), refuses a stateful or non-overlap attempt before preparation, and a build the observed policy does not allow after it; refusals only, the route read is the row Swap already reads. registry:FleetBoxes@1723,registry:Stateless@1340,registry:Stateless@1369,whole:Route@1013,whole:Route@1063,whole:Route@1072,whole:Route@1257,whole:Route@1333,whole:Route@1446,whole:Route@1690,whole:Route@2012,whole:Route@2484,whole:Route@2902,whole:Route@785,whole:Route@801 4bac9312b06f40d72b14eb1e39c60f45b026670f67fc2c0b41469fd1315b1e9f
+@legacy 620cd4de41e59394bcdc8688dcca015b1950a030936069d71e7d232d504ce2a4 internal/rollout/scheduler.go scheduler.execute legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: a dispatch marked Replica (this box permitted step) calls Manager.replicaStep, which calls activator ReplicaSwap, instead of Swap, and emits the swapping event only when the step moves; the added Host and whole Route reads are the same registry row this unit already reads (rt). Agent, not root. registry:App@436,registry:GoodVersion@1739,registry:GoodVersion@1777,registry:Host@4758,registry:Host@5765,registry:Host@5963,whole:Route@129,whole:Route@2882,whole:Route@2923,whole:Route@3348,whole:Route@386,whole:Route@415,whole:Route@5720,whole:Route@6012,whole:Route@6146 88fd876700f63848060d687c20009b846ecfe8e4bb5bb400447d5c868cd9c93f
+@legacy de1d28103b3dd8751acaf7aa823688788b716e7596bfde7a8b5000c237b7fc8d internal/rollout/wakeplan.go Manager.planRow legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry each selection read by the existing planner on its WakePlan so wake uses that same canonical verdict/digest, including selected fallbacks.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: a set row with a noted deploy is planned by decideReplicaWake from the record deploy (Want) instead of decideWake; the added whole Route read passes the row already read to replicaWant. Agent, not root. registry:App@164,registry:Host@1062,registry:Version@1367,whole:Route@115,whole:Route@1176,whole:Route@1363,whole:Route@159,whole:Route@1605,whole:Route@1691,whole:Route@234,whole:Route@241,whole:Route@584,whole:Route@804 e2ae0ddccb1d31d86a46d9a883f0dac6440c1e45a8cf7232b2fce2fe3f40529b
+internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.;rev3=census-ruling-wake-storm-cap;basis=the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Add the B2 DutyStore interface field and process-local duty view, suppression and invalidation state. No read added. B2 adds the verified-successor identity callback; no read in the declaration. B3b adds a nonblocking departure-suspicion callback, invoked only after an accepted holder-forward failure and after cache locks release; it cannot authorize a take.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: immutable callbacks installed before Start for tenant admission, local start permission, fixed route exemptions and shutdown closure; nil callbacks preserve switch-off behavior; no new reads. Fix R1: add an immutable startup-phase callback for response copy, set before service startup. No new read or execution authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Add in-memory HA loss state and pool withdrawal jobs; no new read.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 1: one new field, drain (drainSources: two atomic func pointers for this box's and peers' drain state); no read added. region HA held-requests Task 2: one new field, moves (moveTable: per-host move state, hold counts and admission tickets in memory, under mu); no read added;rev3=census-ruling-held-move-speed;basis=the agent as carlos: one new field, moveStreams (per-host in-memory set of edge.StreamEnd for requests in flight, own mutex), for the move's early stream cut; actEntry gains drainRelease (bool, under a.mu), set by DrainStop; declarations only, no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: two fields, wakeFailMu and wakeFailLogged (per-host in-memory note of the last journalled wake failure); declaration only, no read;rev3=census-ruling-w6-ingress-drain;basis=new field TenantStartsClosed func() bool; when it answers true tenantStartRefusal refuses every start, exempt routes included. Wired only by fixedAdmission.bind to the ingress drain's closed flag. Struct field only; no read added.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: one field, replicaPolicies (host to the newest observed replica deploy and this box label, under mu), set only by SetReplicaDeploy; declaration only, no read. f0a681c9fbc58d69667f3fc08af05a823facede12a2293a6b7a9367e9b4964ae
+internal/activator/statelessrelease.go Service.prepareStatelessRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task1;basis=The former PrepareStatelessRelease body. R9: adopts the record's attempt for this lifetime and target in every phase before any coordination; otherwise acquires the term first and only then selects the ID (R1); a begin carries RetryOf only when consuming a durable retry. Same calls (ObserveReplicaRelease, coordinator, escrow initializer, actEntry, runReleaseAdmitted); same gates, proof and SafeUntil checks; no new store read or writer.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: refuses with provision.ErrReplicaSwitchOpen (SR-4-C31) before term acquisition when the observed record already has an unresolved copy-switch permit, instead of a begin the writer refuses and that read as an unknown result. Refusal only; same calls, no read added. registry:Account@634,registry:App@664,registry:GoodDemand@4032,registry:GoodDigest@4017,registry:GoodVersion@4001,registry:Host@1646,registry:Host@301,registry:Host@4088,registry:Host@4146,registry:Host@4362,registry:Host@4430,registry:Host@691,whole:Route@1093,whole:Route@4155,whole:Route@4162,whole:Route@4714,whole:Route@569 b167be541a3eb4d556c4f4fed71ad6034e354fbb7e570a32b79aada3867a1c1d
+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. file:Exec@20408,file:Open@2191,file:Statfs@54903,registry:App@13287,registry:Host@50546,whole:Route@13279,whole:Route@48893,whole:Route@50669,whole:Route@50731 162c6f94ffcc9ade0237c70a9005e2ad6bb1332704d5dc88da006d5f4b34df30
+internal/activator/activator.go Service.ConvergeAdopted legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: refuses (returns false) for a set row (route FleetBoxes) before any other check, so a repointed link never cycles a copy; a refusal only. registry:FleetBoxes@357,whole:Route@359 87022a2f85d1f663c813636585af0b2c81ccea2432563158058a54994ee09215
+internal/activator/replicadeploy.go Service.ReplicaSwap legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new. Checks the permit (box label, phase released, not halted, ActiveBox, build), refuses a hold, asks tenantStartRefusal on the in-memory entry route, then either re-proves an existing switch (replicaSettle) or runs the existing Swap as a canary and checks replicaStepProven. Reads the in-memory entry route only; no store, file or root call of its own. registry:FleetBoxes@739,whole:Route@649,whole:Route@659,whole:Route@827 5ba84cd20369a8319861cb386b0f4fcf0ea5455abfc71688297e269e09cd9e7b
+internal/activator/replicadeploy.go Service.replicaPolicyAllows legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new. Allows over the in-memory observed policy for the route Host and ReplicaIncarnation; no read beyond the route it is handed. registry:Host@141,registry:ReplicaIncarnation@228 ca258bbb35257c70fd1ea204029a5d18719e58cb0682cf68a8c0eabc3cd7cf2d
+internal/activator/replicadeploy.go Service.replicaSettle legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new. GET / health (genHealthy) and the settle window on the current in-memory generation, then replicaStepProven; reads the in-memory entry route only. whole:Route@262,whole:Route@320 d7db2d0a323fc43b6fb6eaf327ca33c044698cbe49fb82b9031547b70a1674ae
+internal/rollout/replicas.go Manager.replicaWant legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new. Reads the handed route FleetBoxes, Host and ReplicaIncarnation against the in-memory noted deploy; no store or file read. registry:FleetBoxes@78,registry:Host@209,registry:ReplicaIncarnation@246 7345ae771a15b66d8d92fc48a845d8f53c876bac326c93351c5566faa343f3d5
+internal/rollout/wakeplan.go decideReplicaWake legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: new pure planner. Reads the handed route (App, Version, Good fields) and calls the existing Demand closure for the record baseline staged path (release.VersionPath under the box OptDir), as decideWake does for the installed build; no new reader. registry:App@145,registry:GoodDemand@368,registry:GoodDigest@347,registry:GoodVersion@291,registry:GoodVersion@325,registry:Version@274,registry:Version@309,whole:Route@140,whole:Route@328,whole:Route@350,whole:Route@371,whole:Route@99 f1ba5f831601b5b27bb8fd050be6f125ad0562378fdf1662ab6ad4baaad9bad7
+internal/activator/activator.go Service.sweepOnce legacy accepted-legacy accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged).;rev3=census-ruling-plans-4c-box-throttle;basis=after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25.;rev3=census-ruling-plans-4d-lapse;basis=stops a live entry the turned-off hook names (never mid-command, never a move's active probe), stands down an exited worker it names instead of restarting it (Astra finding 4), and skips such rows in the due loop and the always-on arm so they are not woken (plans 4d). Four more whole-row reads: the row handed to the hook (a.disabled), as idleFor and maxRunFor already are. Only stops or skips.;rev3=census-ruling-remote-instance-metrics;basis=its two entries-map insertions go through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more call at the top, a.retryOwedMarkers() (harelease.go), which starts at most one background lease.RetryPending pass over owed region HA release markers, off a.mu; the due query, idle, max-run and lapse logic are unchanged; the same 38 sites, no read added; merge of origin/main d7ae1d76: main's change is kept as main has it (census-ruling-remote-instance-metrics: its two entries-map insertions go through putEntryLocked); this branch's change is the same as above; read sites the same 38, offsets moved;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8: a resident (Route.Resident) is never stopped for idleness or by the continuous-awake ceiling; the due-wake check is left on Hibernate (comment); stops less, not more;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: an entry whose host has a release record open (the in-memory a.releaseOps[e.host]) is not stopped by its plan's turn-off, by idleness or by the continuous-awake ceiling until the record goes; one more sweep pass, reapReleaseOpsLocked, retries an unproven release's stop (through finishPendingStops); the same 39 read sites, no read added; stops less, not more;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 9 (PF-18): the four checks that left an entry with a run attached alone (e.cmd == nil) now read holdsAttachedLocked(e), a run or a session attached, so a session holds the idle sleep, the plans awake ceiling, the plans turned-off stop and the turned-off worker's stand-down as a run does; in-memory under a.mu; only keeps an entry awake longer; no read added, read sites unchanged;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p1b3b-t;basis=Tag due entries as background duties; the wake evaluates the gate off a.mu before acquire or token preparation. No read added.;rev3=census-ruling-region-ha-g2-fixes;basis=Schedule bounded demanded HA recovery and owed-marker retries; reap completed withdrawal jobs whose row is gone, changed or locally eligible, via separately claimed registry reads; no new direct read.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: the drift cycle is skipped for a set row (route FleetBoxes); a refusal only, no read beyond the entry route already in hand. registry:FleetBoxes@13571,registry:Hibernate@10852,registry:Hibernate@14804,registry:Hibernate@24062,registry:Hibernate@5727,registry:Hibernate@7926,registry:Host@24131,registry:Host@24189,registry:Host@24656,registry:Host@24749,registry:Host@25501,registry:Host@25602,registry:Host@26666,registry:Host@26953,registry:Host@27009,registry:NextDue@25439,registry:Status@24078,whole:Route@10854,whole:Route@11713,whole:Route@13573,whole:Route@14806,whole:Route@16739,whole:Route@18449,whole:Route@18639,whole:Route@18932,whole:Route@19104,whole:Route@19251,whole:Route@23462,whole:Route@24238,whole:Route@25153,whole:Route@25510,whole:Route@25517,whole:Route@26481,whole:Route@26782,whole:Route@26986,whole:Route@5538,whole:Route@5729,whole:Route@7759,whole:Route@7928,whole:Route@8121,whole:Route@8584 17bb95bd0278ba9f81a8abc21241f68a54944e7b7de2840200989a4dcb89848b
+internal/activator/stateless.go Service.prepareStateless legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Capture RecordFacts from the existing record source, obtain the durable FailureBook deploy ID, and call Task 2 PrepareStatelessRelease with the canonical verdict/digest carrier. Carry a successful attempt through its hold only after another current-record check; no serving lease or polling loop. Fix 3a round 1 I2: preparation uses reconcile observations and records the successful deploy ID. Carry prepared evidence through hold; fresh backend read must confirm that same released deploy before web runs.;rev3=census-ruling-stateless-failed-release-held;basis=For recovery onto a different installed version's exact committed good version and artifact digest, retain recovery evidence without selecting or writing another deploy. Adds the existing committedGood registry read, with its route and incarnation check. Canonical storage declaration and observed lifetime gates remain.;rev3=census-ruling-stateless-replicas-4-task1;basis=R1: no longer calls ReplicaDeployID before preparation; hands the same a.ReplicaDeployID selector to prepareStatelessRelease, which calls it only after coordinator term acquisition. The ObservedReplicaRelease call stays as a validity check. Same read sites; no new read, write or authority.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2 (D4): for a set row, prepares the record baseline with no release, and refuses a build the row Version does not name before any release; reads the route it is handed (FleetBoxes, Version). No store read or write added. registry:Account@284,registry:Account@310,registry:App@324,registry:App@346,registry:Digest@2027,registry:FleetBoxes@944,registry:Host@250,registry:Host@273,registry:Stateless@2325,registry:Version@1635,registry:Version@1707,registry:Version@1997,whole:Route@1458,whole:Route@1465,whole:Route@1947,whole:Route@2091,whole:Route@2098,whole:Route@2321,whole:Route@2475,whole:Route@2579,whole:Route@2586,whole:Route@259,whole:Route@293,whole:Route@333,whole:Route@540,whole:Route@597,whole:Route@714,whole:Route@821 2585582c2a68892b701f4d1fdf9f40bf4cec8a667cb1ff3a10477e354f668304
+internal/activator/stateless.go Service.statelessFinalRecord legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Fix 3a round 1 I2: one fresh record read at final exec, after pending write and release/escrow preparation. Reuse Fleet.Record result or cfg.Record, never both. Validate placement/config/lifetime and prepared deploy ID/target/released phase; registry checks before and after.;rev3=census-ruling-stateless-failed-release-held;basis=At final launch, a recovery must still match the committed good version and artifact digest. Adds the existing committedGood registry read. The current record's lifetime, placement and launch-input checks remain; a new deployment still requires matching released coordinator evidence.;rev3=census-ruling-stateless-replicas-4-task1;basis=A deploy whose swap finished reads phase done; the final launch check accepts released or done (replicas.ReleasePassed) for the same prepared ID, target and lifetime. Same reads; no check removed.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: for a set row, the record read here (unchanged read) must Allow this box the build (replicas.Deploy.Allows); refusal only. registry:Channel@398,registry:Digest@1543,registry:Environment@431,registry:FleetBoxes@868,registry:Region@492,registry:Runtime@464,registry:Version@1504,whole:Route@122,whole:Route@1480,whole:Route@1919,whole:Route@208,whole:Route@285,whole:Route@629 0a8ed3e85d0f717bd548ed2020ee7c9cbfa5f4fd53c4f8ab1896dc8382f172be
+internal/activator/swap.go Service.Swap legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Verify the target canonical mode and prepare its durable stateless release before stopping the incumbent. A mode change forces the existing proven hold path; same-mode stateless overlap uses local lifecycle gates and the final current-record check, without a serving lease. CI fix 1: defer a missing registry row to the existing release checks only for stateful rootfs overlap, preserving disabled/newest checks and committedGood refusal. Stateless modes, transitions, binary/foreign/hold paths still fence before preparation. No new reads. Final review C1/R26: include incumbent Gen.Stateless as declaration evidence, so only matching good stateful recovery/config attempts can skip canonical lookup. Fresh route, release, ownership and stop gates unchanged.;rev3=census-ruling-stateless-failed-release-held;basis=Classify a proven stateless release failure, or the same deploy's durable failed or unknown phase, through the existing SwapFailed hold mechanism. Preparation precedes stopping the incumbent, so report overlap semantics even if the requested swap is hold. Stateful path unchanged; no new root input.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: for a set row (route FleetBoxes), refuses a stateful or non-overlap attempt before preparation, and a build the observed policy does not allow after it; refusals only, the route read is the row Swap already reads. registry:FleetBoxes@1723,registry:Stateless@1340,registry:Stateless@1369,whole:Route@1013,whole:Route@1063,whole:Route@1072,whole:Route@1257,whole:Route@1333,whole:Route@1446,whole:Route@1690,whole:Route@2012,whole:Route@2484,whole:Route@2902,whole:Route@785,whole:Route@801 4bac9312b06f40d72b14eb1e39c60f45b026670f67fc2c0b41469fd1315b1e9f
+internal/rollout/scheduler.go scheduler.execute legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: a dispatch marked Replica (this box permitted step) calls Manager.replicaStep, which calls activator ReplicaSwap, instead of Swap, and emits the swapping event only when the step moves; the added Host and whole Route reads are the same registry row this unit already reads (rt). Agent, not root. registry:App@436,registry:GoodVersion@1739,registry:GoodVersion@1777,registry:Host@4758,registry:Host@5765,registry:Host@5963,whole:Route@129,whole:Route@2882,whole:Route@2923,whole:Route@3348,whole:Route@386,whole:Route@415,whole:Route@5720,whole:Route@6012,whole:Route@6146 88fd876700f63848060d687c20009b846ecfe8e4bb5bb400447d5c868cd9c93f
+internal/rollout/wakeplan.go Manager.planRow legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry each selection read by the existing planner on its WakePlan so wake uses that same canonical verdict/digest, including selected fallbacks.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: a set row with a noted deploy is planned by decideReplicaWake from the record deploy (Want) instead of decideWake; the added whole Route read passes the row already read to replicaWant. Agent, not root. registry:App@164,registry:Host@1062,registry:Version@1367,whole:Route@115,whole:Route@1176,whole:Route@1363,whole:Route@159,whole:Route@1605,whole:Route@1691,whole:Route@234,whole:Route@241,whole:Route@584,whole:Route@804 e2ae0ddccb1d31d86a46d9a883f0dac6440c1e45a8cf7232b2fce2fe3f40529b
+@coverage internal/activator e7389ffc412493def8955d4769ba23908901f0b09f0c76ab848504d164818f61
+@coverage internal/host 7c959820614e6ad45b975705ce21d9c15f4a5c12336266fbdd7e6059221a7e95
+@coverage internal/provision 58c4ecdf4d878ac28863044ce713524c3e3d182aaad1884de6d4e001347ff270
+@coverage internal/replicas 7f51ca2a22e038d92a06a212c1bd57913b82aebf5b4fd5e55647927b258df881
+@coverage internal/rollout 5c41b4cb71c7b42f06f0ee7384e998859edaa45442ff8ac68d13b18e9a39b45f
diff --git a/internal/replicas/deploy.go b/internal/replicas/deploy.go
index db9757796..1d554abbf 100644
--- a/internal/replicas/deploy.go
+++ b/internal/replicas/deploy.go
@@ -191,3 +191,52 @@ func NextDeploy(cur Deploy, change DeployChange, coordinator Coordinator, now ti
next.Revision = cur.Revision + 1
return next, nil
}
+
+// Baseline is the build a copy runs while this attempt's target is not yet
+// allowed on it. Until the release passes that is LastGood. Once it passes,
+// LastGood names the target, so the baseline is Previous: the LastGood this
+// attempt began with, which the writer records at begin. It is empty when
+// no build of this lifetime ever passed a release.
+func (d *Deploy) Baseline() Build {
+ if d == nil {
+ return Build{}
+ }
+ if ReleasePassed(d.Phase) {
+ return d.Previous
+ }
+ return d.LastGood
+}
+
+// TargetAllowed reports whether box may run this attempt's target: the
+// release passed, and the deploy is done, the box completed its switch, or
+// the box holds the outstanding permit (halted or not, its step is still
+// unresolved and may already have switched).
+func (d *Deploy) TargetAllowed(box string) bool {
+ if d == nil || box == "" || !ReleasePassed(d.Phase) || d.Target.Digest == "" {
+ return false
+ }
+ return d.Phase == "done" || d.Swap.ActiveBox == box || slices.Contains(d.Swap.Completed, box)
+}
+
+// Allows is the launch rule for a copy of an assigned instance: box may
+// start the build with canonical manifestDigest in lifetime incarnation only
+// when it is the target and TargetAllowed, or it is the Baseline. Every
+// path onto a build asks it of the record it read; it is never a grant.
+func (d *Deploy) Allows(box, incarnation, manifestDigest string) bool {
+ if d == nil || manifestDigest == "" || incarnation == "" || d.Incarnation != incarnation {
+ return false
+ }
+ if manifestDigest == d.Target.Digest && d.TargetAllowed(box) {
+ return true
+ }
+ return manifestDigest == d.Baseline().Digest
+}
+
+// Want is the build box should run now: the target once it is allowed
+// there, the baseline otherwise (empty when there is none).
+func (d *Deploy) Want(box string) Build {
+ if d.TargetAllowed(box) {
+ return d.Target
+ }
+ return d.Baseline()
+}
diff --git a/internal/replicas/deploy_test.go b/internal/replicas/deploy_test.go
index 615f7dbae..663b2291d 100644
--- a/internal/replicas/deploy_test.go
+++ b/internal/replicas/deploy_test.go
@@ -411,3 +411,67 @@ func TestReplicaOnlyOneOutstandingPermit(t *testing.T) {
}
t.Logf("done=%d halted=%d starts=%d", dones, halts, starts)
}
+
+// TestReplicaSwapAllowsOnlyPermittedTarget is the launch rule every path
+// asks (Task 2): a box runs the attempt's target only after its release
+// passed and the box completed its switch, holds the permit, or the deploy
+// is done. Otherwise it runs the baseline: LastGood before the release
+// passes, and after it the LastGood the attempt began with (Previous).
+func TestReplicaSwapAllowsOnlyPermittedTarget(t *testing.T) {
+ good := Build{Version: "v1", Digest: "canonical-1"}
+ target := Build{Version: "v2", Digest: "canonical-2"}
+ attempt := func(phase string, swap Swap) *Deploy {
+ d := &Deploy{ID: "deploy-2", Incarnation: "life", Target: target, Previous: good, Phase: phase, LastGood: good, Swap: swap, Revision: 4}
+ if ReleasePassed(phase) {
+ d.LastGood = target
+ }
+ return d
+ }
+ swapping := Swap{Order: []string{"a", "b", "c"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 3}
+ for _, tc := range []struct {
+ name string
+ d *Deploy
+ box string
+ target bool // may run the target
+ want Build
+ allowed []Build
+ }{
+ {"absent", nil, "a", false, Build{}, nil},
+ {"pending", attempt("pending", Swap{}), "a", false, good, []Build{good}},
+ {"releasing", attempt("releasing", Swap{}), "a", false, good, []Build{good}},
+ {"failed", attempt("failed", Swap{}), "a", false, good, []Build{good}},
+ {"unknown", attempt("unknown", Swap{}), "a", false, good, []Build{good}},
+ {"released, not yet ordered", attempt("released", Swap{}), "a", false, good, []Build{good}},
+ {"released, completed", attempt("released", swapping), "a", true, target, []Build{target, good}},
+ {"released, holds the permit", attempt("released", swapping), "b", true, target, []Build{target, good}},
+ {"released, waiting", attempt("released", swapping), "c", false, good, []Build{good}},
+ {"released, not ordered", attempt("released", swapping), "d", false, good, []Build{good}},
+ {"halted, completed", attempt("released", Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, Halted: true}), "a", true, target, []Build{target, good}},
+ {"halted, waiting", attempt("released", Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, Halted: true}), "b", false, good, []Build{good}},
+ {"done", attempt("done", Swap{Order: []string{"a"}, Completed: []string{"a"}}), "z", true, target, []Build{target, good}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := tc.d.TargetAllowed(tc.box); got != tc.target {
+ t.Fatalf("TargetAllowed(%s) = %t", tc.box, got)
+ }
+ if got := tc.d.Want(tc.box); got != tc.want {
+ t.Fatalf("Want(%s) = %+v, want %+v", tc.box, got, tc.want)
+ }
+ for _, b := range []Build{good, target, {Version: "v0", Digest: "canonical-0"}, {}} {
+ want := slices.Contains(tc.allowed, b)
+ if got := tc.d.Allows(tc.box, "life", b.Digest); got != want {
+ t.Fatalf("Allows(%s, %q) = %t, want %t", tc.box, b.Digest, got, want)
+ }
+ if tc.d.Allows(tc.box, "another-life", b.Digest) {
+ t.Fatalf("Allows accepted another lifetime for %q", b.Digest)
+ }
+ }
+ })
+ }
+ // A record begun before Previous was written has no baseline once its
+ // release passed: nothing but a permitted target starts.
+ legacy := &Deploy{ID: "deploy-2", Incarnation: "life", Target: target, Phase: "released", LastGood: target, Swap: swapping}
+ if legacy.Allows("c", "life", target.Digest) || legacy.Allows("c", "life", "") || legacy.Want("c") != (Build{}) {
+ t.Fatal("a waiting box ran something without a baseline")
+ }
+}
diff --git a/internal/rollout/manager.go b/internal/rollout/manager.go
index 3995432e8..51fcb8957 100644
--- a/internal/rollout/manager.go
+++ b/internal/rollout/manager.go
@@ -17,6 +17,7 @@ import (
"github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
)
// Activator is the part of *activator.Service the scheduler drives. Swap is
@@ -203,6 +204,13 @@ type Manager struct {
// round 1). Each is one count in inflight, taken and given back exactly
// once whatever the order of plans and events.
wakes map[uint64]struct{}
+
+ // replicaMu is a leaf, like joinMu: it guards the set rows' observed
+ // deploys (NoteReplicaDeploy) and this box's answers to its permits
+ // (replicas.go), and is taken under scheduler.mu by the queue.
+ replicaMu sync.Mutex
+ replicaNotes map[string]replicas.Deploy
+ replicaOutcomes map[string]replicaOutcome
}
// NewManager builds the manager. Its schedulers run until ctx ends.
@@ -347,6 +355,7 @@ func (m *Manager) scheduler(k appKey) *scheduler {
q: newAppQueue(k.acct, k.app, func(build, host string, served bool) bool {
return book.Blocks(k.acct, k.app, build, host, served)
})}
+ s.q.replica = m.replicaDecision
m.apps[k] = s
go s.loop(m.ctx)
}
diff --git a/internal/rollout/queue.go b/internal/rollout/queue.go
index bee41720f..0a62645ec 100644
--- a/internal/rollout/queue.go
+++ b/internal/rollout/queue.go
@@ -64,6 +64,11 @@ type dispatch struct {
// carries it (HoldRan.Exec). SchedRev cannot serve: an abandoned
// attempt is derived again with the same revision.
ExecID string
+ // Replica: this box's permitted step of a replicated deploy
+ // (replicas.go), run through ReplicaSwap. The permit orders it across
+ // boxes, so the cohort's canary and halt rules do not; it is always
+ // settled as a canary.
+ Replica bool
}
// hostSlot is one instance's desired state. The attempt to run is derived
@@ -119,6 +124,10 @@ type appQueue struct {
rev uint64
// blocks is the failure book's answer for this app (spec §8.4).
blocks func(build, host string, served bool) bool
+ // replica is the replicated deploy's answer for a set row
+ // (Manager.replicaDecision): its permitted step's build, or whether
+ // its adoption waits. Nil, or neither: today's derivation.
+ replica func(host, serving, want string) (step string, hold bool)
}
func newAppQueue(acct, app string, blocks func(build, host string, served bool) bool) *appQueue {
@@ -250,8 +259,29 @@ func (q *appQueue) pending(h *hostSlot) (dispatch, bool) {
return dispatch{}, false
}
id := Identity{Host: h.host, ConfigRev: h.wantConfig, RestartID: h.wantRestart}
+ want := h.wantBuild
+ if q.replica != nil {
+ step, hold := q.replica(h.host, h.serving, h.wantBuild)
+ if step != "" {
+ // The permitted step, also when the copy already serves the
+ // target (its answer was lost, or the agent restarted): the step
+ // then proves the switch and swaps nothing.
+ id.Cause, id.Build = activator.CauseRelease, step
+ if step == h.wantBuild && h.wantCause != "" {
+ id.Cause = h.wantCause
+ }
+ class := classRecover
+ if step != h.serving && step != h.good {
+ class = classAdopt
+ }
+ return dispatch{ID: id, SchedRev: h.buildRev, Class: class, Cohort: cohortKey(step, class), Replica: true}, true
+ }
+ if hold {
+ want = ""
+ }
+ }
switch {
- case h.wantBuild != "" && h.wantBuild != h.serving && !q.blocks(h.wantBuild, h.host, h.wantBuild == h.good):
+ case want != "" && want != h.serving && !q.blocks(want, h.host, want == h.good):
id.Cause, id.Build = h.wantCause, h.wantBuild
case h.wantRestart != "":
id.Cause, id.Build = activator.CauseRestart, h.serving
@@ -350,6 +380,12 @@ func (q *appQueue) gate(h *hostSlot, now time.Time) (dispatch, bool) {
if d.ID.Cause == activator.CauseConfig && now.Before(h.configAfter) {
return dispatch{}, false
}
+ if d.Replica {
+ // The permit orders a set row's copies across boxes; this box's
+ // cohort does not. The step is still settled (Canary).
+ d.Canary = true
+ return d, true
+ }
c := q.cohortFor(d.Cohort)
// The flag is tied to the build it was set for, so a retry on a host with
// nothing pending cannot lift a later cohort's halt or turn an unrelated
@@ -380,7 +416,7 @@ func (q *appQueue) gate(h *hostSlot, now time.Time) (dispatch, bool) {
// the canary slot. A retried host's canary claims it like any other, and a
// settled flag left over from before the halt starts again from false.
func (q *appQueue) start(h *hostSlot, d dispatch) {
- if d.Canary {
+ if d.Canary && !d.Replica {
c := q.cohortFor(d.Cohort)
c.canary, c.settled = h.host, false
}
diff --git a/internal/rollout/replicas.go b/internal/rollout/replicas.go
new file mode 100644
index 000000000..0f64db362
--- /dev/null
+++ b/internal/rollout/replicas.go
@@ -0,0 +1,197 @@
+// replicas.go is the scheduler's part in a replicated deploy (stateless
+// replicas Plan 4, Task 2). A copy of an assigned instance (a set row) is
+// one host slot on each of several boxes, so this box's scheduler must not
+// move it onto a new build in parallel with the other boxes. The record's
+// deploy, observed through NoteReplicaDeploy, decides instead:
+//
+// - a build whose release has not begun gets one ordinary attempt: that
+// is how the coordinator's release runs (the activator then refuses the
+// move itself until this copy's turn);
+// - while that release runs, and after it passes, the adoption waits;
+// - the copy holding the permit runs one step, ReplicaSwap, as a settled
+// canary through the ordinary slot, intent and failure book; its
+// outcome is what the swap worker acknowledges (ReplicaOutcome);
+// - once the copy completed its switch or the deploy is done, a copy not
+// yet on the target joins it as an ordinary move: no new release;
+// - a new build waits while another attempt's step is open (R2).
+//
+// The cohort's canary and halt rules do not order these steps: the permit
+// does. Restart and config attempts on the serving build go on as before.
+// A wake is planned from the same record (replicaWant): the baseline while
+// the target is not allowed, never the row's local good build (D4).
+package rollout
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// ReplicaActivator is the activator's replica half (activator.Service).
+// A manager whose activator lacks it runs no permitted step.
+type ReplicaActivator interface {
+ SetReplicaDeploy(host string, deploy replicas.Deploy, box string)
+ ReplicaSwap(ctx context.Context, at activator.Attempt, deploy replicas.Deploy, box string, newest func(string) uint64) activator.SwapResult
+}
+
+// replicaOutcome is this box's answer to one permit: switched after its
+// proof, or kept when the successor failed and the incumbent serves.
+type replicaOutcome struct {
+ id string
+ permit uint64
+ switched bool
+}
+
+// replicaNoBuildRefusal refuses a copy's wake when its record names no
+// build that passed a release for it to run.
+// copy SR-4-C45 (provisional)
+const replicaNoBuildRefusal = "this copy waits for a release to pass before it starts"
+
+// NoteReplicaDeploy is the record observation the agent's reconcile pass
+// fans out (R7): the newest deploy of a set row this box is assigned. It
+// keeps the deploy for the scheduler and the planner, hands it to the
+// activator as policy, and wakes the host's scheduler. A record that is
+// not, or no longer, such a row forgets the host. An older revision of
+// the attempt already held is ignored.
+func (m *Manager) NoteReplicaDeploy(rec provision.Record) {
+ a, d := rec.ReplicaAssignment, rec.ReplicaDeploy
+ inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ keep := err == nil && a != nil && d != nil && d.Incarnation == inc && a.Contains(m.d.Box)
+ m.replicaMu.Lock()
+ cur, had := m.replicaNotes[rec.Host]
+ if keep && had && cur.ID == d.ID && cur.Incarnation == d.Incarnation && cur.Revision > d.Revision {
+ m.replicaMu.Unlock()
+ return
+ }
+ if keep {
+ if m.replicaNotes == nil {
+ m.replicaNotes = map[string]replicas.Deploy{}
+ }
+ m.replicaNotes[rec.Host] = d.Clone()
+ // An answer stands only for the permit it answered.
+ if out, ok := m.replicaOutcomes[rec.Host]; ok && (out.id != d.ID || out.permit != d.Swap.Permit || d.Swap.ActiveBox != m.d.Box) {
+ delete(m.replicaOutcomes, rec.Host)
+ }
+ } else {
+ delete(m.replicaNotes, rec.Host)
+ delete(m.replicaOutcomes, rec.Host)
+ }
+ m.replicaMu.Unlock()
+ if ra, ok := m.d.Act.(ReplicaActivator); ok {
+ if keep {
+ ra.SetReplicaDeploy(rec.Host, *d, m.d.Box)
+ } else {
+ ra.SetReplicaDeploy(rec.Host, replicas.Deploy{}, m.d.Box)
+ }
+ }
+ if s := m.schedulerOf(rec.Host); s != nil {
+ s.poke()
+ }
+}
+
+// ReplicaOutcome is this box's answer to permit of attempt id on host, once
+// its step has one: ok false while it has none, and the permit stays open.
+func (m *Manager) ReplicaOutcome(host, id string, permit uint64) (switched, ok bool) {
+ m.replicaMu.Lock()
+ defer m.replicaMu.Unlock()
+ out, ok := m.replicaOutcomes[host]
+ if !ok || out.id != id || out.permit != permit {
+ return false, false
+ }
+ return out.switched, true
+}
+
+// replicaDecision is the queue's question for host (appQueue.replica),
+// asked under the scheduler's lock: step names the build of this box's
+// permitted step, hold says the adoption of want waits. Neither: an
+// ordinary attempt. replicaMu is a leaf, so this takes no other lock.
+func (m *Manager) replicaDecision(host, serving, want string) (step string, hold bool) {
+ m.replicaMu.Lock()
+ defer m.replicaMu.Unlock()
+ d, ok := m.replicaNotes[host]
+ if !ok {
+ return "", false
+ }
+ box := m.d.Box
+ if d.Swap.ActiveBox == box {
+ // This box's step, once per permit. A halted permit is not stepped,
+ // and an answered one waits for its ACK to land.
+ out, answered := m.replicaOutcomes[host]
+ if d.Phase != "released" || d.Swap.Halted || (answered && out.id == d.ID && out.permit == d.Swap.Permit) {
+ return "", true
+ }
+ return d.Target.Version, false
+ }
+ if want == "" || want == serving {
+ return "", false
+ }
+ switch {
+ case d.PermitOutstanding():
+ // Another copy's step is open: this copy waits, whatever it wants.
+ return "", true
+ case want != d.Target.Version, replicas.RetryRequested(&d):
+ // Its release has not begun, or an explicit retry asks for a new
+ // attempt: one ordinary attempt runs it.
+ return "", false
+ case d.Phase == "failed" || d.Phase == "unknown":
+ // The ordinary attempt meets the durable result and is held (F10).
+ return "", false
+ case d.TargetAllowed(box):
+ // Switched already, or the deploy is done: join the target.
+ return "", false
+ }
+ // The release is pending or running, or passed and this copy waits for
+ // its permit.
+ return "", true
+}
+
+// replicaStep runs host's permitted step, a, through the activator, and
+// keeps its answer for the swap worker.
+func (m *Manager) replicaStep(ctx context.Context, a activator.Attempt, newest func(string) uint64) activator.SwapResult {
+ ra, ok := m.d.Act.(ReplicaActivator)
+ m.replicaMu.Lock()
+ d, noted := m.replicaNotes[a.Host]
+ m.replicaMu.Unlock()
+ if !ok || !noted || d.Swap.ActiveBox != m.d.Box {
+ return activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "this box holds no permit for the instance"}
+ }
+ res := ra.ReplicaSwap(ctx, a, d, m.d.Box, newest)
+ var switched bool
+ switch {
+ case res.Outcome == activator.SwapDone && res.Proven:
+ switched = true
+ case res.Outcome == activator.SwapFailed:
+ // The successor failed and the incumbent serves: kept.
+ default:
+ // Abandoned, refused, or switched without proof: no answer yet.
+ return res
+ }
+ m.replicaMu.Lock()
+ if cur, ok := m.replicaNotes[a.Host]; ok && cur.ID == d.ID && cur.Swap.Permit == d.Swap.Permit {
+ if m.replicaOutcomes == nil {
+ m.replicaOutcomes = map[string]replicaOutcome{}
+ }
+ m.replicaOutcomes[a.Host] = replicaOutcome{id: d.ID, permit: d.Swap.Permit, switched: switched}
+ }
+ m.replicaMu.Unlock()
+ return res
+}
+
+// replicaWant is the build a wake of rt, a set row with a noted deploy for
+// its lifetime, may boot on this box (replicas.Deploy.Want). ok false: no
+// such row or note; the exec gate still asks the record.
+func (m *Manager) replicaWant(rt registry.Route) (replicas.Build, bool) {
+ if rt.FleetBoxes == "" {
+ return replicas.Build{}, false
+ }
+ m.replicaMu.Lock()
+ defer m.replicaMu.Unlock()
+ d, ok := m.replicaNotes[rt.Host]
+ if !ok || d.Incarnation != rt.ReplicaIncarnation {
+ return replicas.Build{}, false
+ }
+ return d.Want(m.d.Box), true
+}
diff --git a/internal/rollout/replicas_test.go b/internal/rollout/replicas_test.go
new file mode 100644
index 000000000..d5f1f3d95
--- /dev/null
+++ b/internal/rollout/replicas_test.go
@@ -0,0 +1,331 @@
+package rollout
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+const replicaHost = "blog.example.com"
+
+var replicaCreated = time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
+
+// replicaAct is the harness's activator with its replica half: the policy
+// SetReplicaDeploy received, and every permitted step ReplicaSwap ran.
+// result decides a step; the default switches and proves it.
+type replicaAct struct {
+ *probeAct
+ mu sync.Mutex
+ policy map[string]replicas.Deploy
+ steps []activator.Attempt
+ result func(at activator.Attempt) activator.SwapResult
+}
+
+func (r *replicaAct) SetReplicaDeploy(host string, d replicas.Deploy, box string) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.policy == nil {
+ r.policy = map[string]replicas.Deploy{}
+ }
+ r.policy[host] = d
+}
+
+func (r *replicaAct) ReplicaSwap(_ context.Context, at activator.Attempt, d replicas.Deploy, box string, _ func(string) uint64) activator.SwapResult {
+ r.mu.Lock()
+ r.steps = append(r.steps, at)
+ decide := r.result
+ r.mu.Unlock()
+ res := activator.SwapResult{Outcome: activator.SwapDone, Proven: true}
+ if decide != nil {
+ res = decide(at)
+ }
+ if res.Outcome == activator.SwapDone {
+ r.fakeAct.serve(at.Host, at.Build)
+ res.Gen, _ = r.fakeAct.Current(at.Host)
+ }
+ return res
+}
+
+func (r *replicaAct) stepCount() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return len(r.steps)
+}
+
+func (r *replicaAct) lastStep() activator.Attempt {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.steps[len(r.steps)-1]
+}
+
+// newReplicaHarness is the harness with blog.example.com a set row assigned
+// to box-0 and box-1 (the harness's own box), awake on v1, and a manager
+// whose activator has the replica half.
+func newReplicaHarness(t *testing.T) (*harness, *replicaAct) {
+ t.Helper()
+ h := newHarness(t, replicaHost)
+ h.stage("v2", "v3")
+ ra := &replicaAct{probeAct: h.probe}
+ inc, err := provision.Incarnation("bab", "blog", replicaHost, replicaCreated)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := h.rows.get(replicaHost)
+ r.FleetBoxes, r.Copies, r.ReplicaRevision, r.ReplicaIncarnation, r.Stateless = `["box-0","box-1"]`, 2, 1, inc, true
+ h.rows.put(r)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ h.m = NewManager(ctx, Deps{
+ Act: ra, Routes: h.rows, Book: h.book, OptDir: h.opt, DataDir: h.data, Box: "box-1",
+ Demand: h.demand, Policy: h.policy, Pointer: h.pointerFor, Events: h.events,
+ Touch: func() { h.touched.Add(1) }, Now: h.clock, Logf: func(string, ...any) {},
+ })
+ return h, ra
+}
+
+// note feeds the manager the record observation the agent's reconcile pass
+// would, with d as its deploy.
+func noteReplica(h *harness, d *replicas.Deploy) {
+ inc, _ := provision.Incarnation("bab", "blog", replicaHost, replicaCreated)
+ rec := provision.Record{Schema: 1, Account: "bab", App: "blog", Host: replicaHost, Channel: "edge", Region: "fleet/pi", CreatedAt: replicaCreated,
+ ReplicaAssignment: &replicas.Assignment{Desired: 2, Revision: 1, Boxes: []string{"box-0", "box-1"}}}
+ if d != nil {
+ c := d.Clone()
+ c.Incarnation = inc
+ rec.ReplicaDeploy = &c
+ }
+ h.m.NoteReplicaDeploy(rec)
+}
+
+func deployOf(target, from string, phase string, swap replicas.Swap) *replicas.Deploy {
+ d := &replicas.Deploy{ID: "deploy-" + target, Target: replicas.Build{Version: target, Digest: "canonical-" + target}, Previous: replicas.Build{Version: from, Digest: "canonical-" + from}, Phase: phase, Term: "term", Revision: 7, Swap: swap}
+ d.LastGood = d.Previous
+ if replicas.ReleasePassed(phase) {
+ d.LastGood = d.Target
+ }
+ return d
+}
+
+// plainSwaps counts the scheduler's ordinary Swap calls onto build.
+func plainSwaps(h *harness, build string) int {
+ _, started, _ := h.act.snapshot()
+ n := 0
+ for _, s := range started {
+ if s == replicaHost+":"+build {
+ n++
+ }
+ }
+ return n
+}
+
+// settle lets the scheduler act on everything it has been told, past any
+// abandoned attempt's deferral.
+func settle(h *harness) {
+ for i := 0; i < 3; i++ {
+ time.Sleep(30 * time.Millisecond)
+ h.advance(abandonDeferral + time.Second)
+ h.pass()
+ }
+ time.Sleep(30 * time.Millisecond)
+}
+
+// TestReplicaOrderedOverlapWaitsForPermit (Task 2): the local scheduler does
+// not move a set row onto a target on its own. Once the target's release has
+// begun or passed, the adoption waits; the only attempt onto it is the
+// permitted step, run through ReplicaSwap as a settled canary, and its
+// outcome is what the box acknowledges. A build whose release has not begun
+// gets one ordinary attempt, which is how the release runs.
+func TestReplicaOrderedOverlapWaitsForPermit(t *testing.T) {
+ t.Run("permit", func(t *testing.T) {
+ h, ra := newReplicaHarness(t)
+ noteReplica(h, deployOf("v2", "v1", "pending", replicas.Swap{}))
+ h.install("v2", replicaHost)
+ settle(h)
+ noteReplica(h, deployOf("v2", "v1", "released", replicas.Swap{Order: []string{"box-0", "box-1"}, ActiveBox: "box-0", Permit: 8}))
+ settle(h)
+ if n := plainSwaps(h, "v2"); n != 0 || ra.stepCount() != 0 {
+ t.Fatalf("a waiting copy moved: %d plain swaps, %d steps", n, ra.stepCount())
+ }
+ if _, ok := h.m.ReplicaOutcome(replicaHost, "deploy-v2", 8); ok {
+ t.Fatal("an outcome for another box's permit")
+ }
+ permit := replicas.Swap{Order: []string{"box-0", "box-1"}, Completed: []string{"box-0"}, ActiveBox: "box-1", Permit: 9}
+ noteReplica(h, deployOf("v2", "v1", "released", permit))
+ waitFor(t, "the permitted step", func() bool { return ra.stepCount() == 1 })
+ if at := ra.lastStep(); at.Build != "v2" || !at.Canary || at.Mode != activator.ModeOverlap {
+ t.Fatalf("step: %+v", at)
+ }
+ waitFor(t, "its outcome", func() bool {
+ switched, ok := h.m.ReplicaOutcome(replicaHost, "deploy-v2", 9)
+ return ok && switched
+ })
+ if _, ok := h.m.ReplicaOutcome(replicaHost, "deploy-v2", 8); ok {
+ t.Fatal("the outcome answers another permit")
+ }
+ // The ack has not landed yet: the record still shows the permit.
+ noteReplica(h, deployOf("v2", "v1", "released", permit))
+ settle(h)
+ if ra.stepCount() != 1 || plainSwaps(h, "v2") != 0 {
+ t.Fatalf("the step ran again: %d steps, %d plain swaps", ra.stepCount(), plainSwaps(h, "v2"))
+ }
+ })
+ t.Run("release not begun", func(t *testing.T) {
+ h, _ := newReplicaHarness(t)
+ h.act.outcome = func(a activator.Attempt) activator.SwapOutcome {
+ // The activator refuses a target this copy is not allowed.
+ if a.Build == "v3" {
+ return activator.SwapAbandoned
+ }
+ return activator.SwapDone
+ }
+ noteReplica(h, deployOf("v2", "v1", "done", replicas.Swap{Order: []string{"box-0", "box-1"}, Completed: []string{"box-0", "box-1"}}))
+ h.install("v3", replicaHost)
+ h.pass()
+ waitFor(t, "the attempt that runs the release", func() bool { return plainSwaps(h, "v3") == 1 })
+ noteReplica(h, deployOf("v3", "v2", "released", replicas.Swap{Order: []string{"box-0", "box-1"}, ActiveBox: "box-0", Permit: 8}))
+ settle(h)
+ if n := plainSwaps(h, "v3"); n != 1 {
+ t.Fatalf("the waiting copy kept retrying: %d attempts", n)
+ }
+ })
+ t.Run("a new deploy waits for the open step", func(t *testing.T) {
+ h, _ := newReplicaHarness(t)
+ noteReplica(h, deployOf("v2", "v1", "released", replicas.Swap{Order: []string{"box-0", "box-1"}, ActiveBox: "box-0", Permit: 8}))
+ h.install("v3", replicaHost)
+ settle(h)
+ if n := plainSwaps(h, "v3"); n != 0 {
+ t.Fatalf("a new deploy began under an open permit: %d", n)
+ }
+ })
+}
+
+// TestReplicaReturnsAfterDeploy (Task 2, D4): a set row's wake is planned
+// from the record's deploy, never from the row's local good build. A copy
+// that returns after the deploy finished boots the committed target; one
+// that returns while it waits for its permit boots the attempt's baseline.
+func TestReplicaReturnsAfterDeploy(t *testing.T) {
+ h, _ := newReplicaHarness(t)
+ h.act.mu.Lock()
+ delete(h.act.gens, replicaHost)
+ h.act.mu.Unlock()
+ h.install("v2", replicaHost)
+ r := h.rows.get(replicaHost)
+ // Stale local state: a good build the record never passed.
+ r.GoodVersion, r.GoodDigest = "v0", "sha-v0"
+ h.rows.put(r)
+ noteReplica(h, deployOf("v2", "v1", "done", replicas.Swap{Order: []string{"box-0"}, Completed: []string{"box-0"}}))
+ plan := h.m.Plan(context.Background(), h.rows.get(replicaHost))
+ if plan.Refuse != "" || plan.Boot.Version != "v2" || plan.Fallback != nil {
+ t.Fatalf("returning copy: %+v", plan)
+ }
+ noteReplica(h, deployOf("v2", "v1", "released", replicas.Swap{Order: []string{"box-0", "box-1"}, ActiveBox: "box-0", Permit: 8}))
+ plan = h.m.Plan(context.Background(), h.rows.get(replicaHost))
+ if plan.Refuse != "" || plan.Boot.Version != "v1" || plan.Boot.StagedPath != release.VersionPath(h.opt, "bab", "v1", "blog") {
+ t.Fatalf("waiting copy: %+v", plan)
+ }
+}
+
+// TestReplicaReturnDuringFailedRelease (Task 2): while the target's release
+// failed or its result is unknown, a returning copy boots LastGood, the
+// record's Previous, never the target and never the row's local good build.
+// With no build the record ever passed, it boots nothing.
+func TestReplicaReturnDuringFailedRelease(t *testing.T) {
+ for _, phase := range []string{"failed", "unknown"} {
+ t.Run(phase, func(t *testing.T) {
+ h, _ := newReplicaHarness(t)
+ h.act.mu.Lock()
+ delete(h.act.gens, replicaHost)
+ h.act.mu.Unlock()
+ h.install("v2", replicaHost)
+ r := h.rows.get(replicaHost)
+ r.GoodVersion, r.GoodDigest = "v0", "sha-v0"
+ h.rows.put(r)
+ noteReplica(h, deployOf("v2", "v1", phase, replicas.Swap{}))
+ plan := h.m.Plan(context.Background(), h.rows.get(replicaHost))
+ if plan.Refuse != "" || plan.Boot.Version != "v1" {
+ t.Fatalf("plan: %+v", plan)
+ }
+ first := deployOf("v2", "", phase, replicas.Swap{})
+ first.Previous, first.LastGood = replicas.Build{}, replicas.Build{}
+ noteReplica(h, first)
+ if plan := h.m.Plan(context.Background(), h.rows.get(replicaHost)); plan.Refuse == "" {
+ t.Fatalf("booted with no passed build: %+v", plan)
+ }
+ })
+ }
+}
+
+// TestReplicaSwapUnknownHaltsWithoutOutcome (Task 2): a step whose old
+// generation is not proven stopped, or that was refused before it ran,
+// leaves no outcome, so the box sends no ACK and the permit stays open; the
+// scheduler asks again and only a proven step answers. A failed successor
+// answers "kept", which halts the deploy.
+func TestReplicaSwapUnknownHaltsWithoutOutcome(t *testing.T) {
+ permit := replicas.Swap{Order: []string{"box-0", "box-1"}, Completed: []string{"box-0"}, ActiveBox: "box-1", Permit: 9}
+ t.Run("unproven, then proven", func(t *testing.T) {
+ h, ra := newReplicaHarness(t)
+ calls := 0
+ ra.result = func(activator.Attempt) activator.SwapResult {
+ calls++
+ return activator.SwapResult{Outcome: activator.SwapDone, Proven: calls > 1}
+ }
+ h.install("v2", replicaHost)
+ noteReplica(h, deployOf("v2", "v1", "released", permit))
+ h.pass()
+ waitFor(t, "the first step", func() bool { return ra.stepCount() >= 1 })
+ if _, ok := h.m.ReplicaOutcome(replicaHost, "deploy-v2", 9); ok && ra.stepCount() == 1 {
+ t.Fatal("an unproven step answered")
+ }
+ settle(h)
+ waitFor(t, "the proof", func() bool { switched, ok := h.m.ReplicaOutcome(replicaHost, "deploy-v2", 9); return ok && switched })
+ if at := ra.lastStep(); at.Build != "v2" {
+ t.Fatalf("proof step: %+v", at)
+ }
+ })
+ t.Run("refused start", func(t *testing.T) {
+ h, ra := newReplicaHarness(t)
+ var refuse sync.Mutex
+ refusing := true
+ ra.result = func(activator.Attempt) activator.SwapResult {
+ refuse.Lock()
+ defer refuse.Unlock()
+ if refusing {
+ return activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: activator.ErrTenantAdmission.Error(), Err: activator.ErrTenantAdmission}
+ }
+ return activator.SwapResult{Outcome: activator.SwapDone, Proven: true}
+ }
+ h.install("v2", replicaHost)
+ noteReplica(h, deployOf("v2", "v1", "released", permit))
+ h.pass()
+ waitFor(t, "the refused step", func() bool { return ra.stepCount() == 1 })
+ time.Sleep(30 * time.Millisecond)
+ if _, ok := h.m.ReplicaOutcome(replicaHost, "deploy-v2", 9); ok {
+ t.Fatal("a refused start answered the permit")
+ }
+ refuse.Lock()
+ refusing = false
+ refuse.Unlock()
+ settle(h)
+ waitFor(t, "the retried step", func() bool { switched, ok := h.m.ReplicaOutcome(replicaHost, "deploy-v2", 9); return ok && switched })
+ })
+ t.Run("failed successor", func(t *testing.T) {
+ h, ra := newReplicaHarness(t)
+ ra.result = func(activator.Attempt) activator.SwapResult {
+ return activator.SwapResult{Outcome: activator.SwapFailed, Reason: "health check failed", Executed: true}
+ }
+ h.install("v2", replicaHost)
+ noteReplica(h, deployOf("v2", "v1", "released", permit))
+ h.pass()
+ waitFor(t, "the kept answer", func() bool { switched, ok := h.m.ReplicaOutcome(replicaHost, "deploy-v2", 9); return ok && !switched })
+ settle(h)
+ if ra.stepCount() != 1 || plainSwaps(h, "v2") != 0 {
+ t.Fatalf("the failed step was retried: %d steps, %d plain", ra.stepCount(), plainSwaps(h, "v2"))
+ }
+ })
+}
diff --git a/internal/rollout/scheduler.go b/internal/rollout/scheduler.go
index f14a6c08a..1f121848b 100644
--- a/internal/rollout/scheduler.go
+++ b/internal/rollout/scheduler.go
@@ -214,6 +214,15 @@ func (s *scheduler) execute(ctx context.Context, d dispatch) {
m.d.Act.PublishHeldServing(rt.Host)
return
}
+ if d.Replica {
+ // This box's permitted step of a replicated deploy (replicas.go).
+ // A step that only proves an earlier switch moves nothing.
+ if g, ok := m.d.Act.Current(rt.Host); !ok || g.Build != a.Build {
+ m.emit(*rt, EvSwapping, "info", textSwapping(a.Build, a.Cause))
+ }
+ s.done(d, m.replicaStep(ctx, a, s.newest), a.Mode)
+ return
+ }
m.emit(*rt, EvSwapping, "info", textSwapping(a.Build, a.Cause))
s.done(d, m.d.Act.Swap(ctx, a, s.newest), a.Mode)
}
diff --git a/internal/rollout/wakeplan.go b/internal/rollout/wakeplan.go
index bd71f2344..a0a964241 100644
--- a/internal/rollout/wakeplan.go
+++ b/internal/rollout/wakeplan.go
@@ -9,6 +9,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
)
// wakeBook is the failure book's read half the planner needs.
@@ -114,6 +115,34 @@ func decideWake(in wakeInputs) (activator.WakePlan, error) {
return plan, nil
}
+// decideReplicaWake is decideWake for a copy of an assigned instance whose
+// record deploy the manager holds (replicas.go): want is the build the
+// record lets this box run now (replicas.Deploy.Want). The row's own good
+// build is never a recovery or a fallback here (D4): a returning copy
+// boots the committed target once it is allowed, and the attempt's
+// baseline before that. With no build that passed a release, it boots
+// nothing. The exec gate asks the record again.
+func decideReplicaWake(in wakeInputs, want replicas.Build) (activator.WakePlan, error) {
+ rt := in.Route
+ acct, app := release.RouteAccount(rt), rt.App
+ switch {
+ case want.Version == "":
+ return activator.WakePlan{Refuse: replicaNoBuildRefusal}, nil
+ case want.Version == rt.Version:
+ if rt.GoodVersion != rt.Version {
+ in.Route.GoodVersion, in.Route.GoodDigest, in.Route.GoodDemand = "", "", ""
+ }
+ return decideWake(in)
+ }
+ path := release.VersionPath(in.OptDir, acct, want.Version, app)
+ demand, digest, err := in.Demand(want.Version, path)
+ if err != nil {
+ return activator.WakePlan{Refuse: fmt.Sprintf("build %s is not staged correctly on this box", want.Version)}, err
+ }
+ return activator.WakePlan{Boot: release.StagedIdentity{Version: want.Version, StagedPath: path, Digest: digest, Demand: demand},
+ Mode: AttemptMode(in.Policy, demand)}, nil
+}
+
// decideHoldRan is decideWake for an instance with a hold-ran marker (final
// review wave 2, N2; spec §6.4: once a hold build has executed against an
// instance's database, nothing falls back automatically on that instance).
@@ -356,7 +385,15 @@ func (m *Manager) planRow(ctx context.Context, rt registry.Route, tok uint64) ac
m.mu.Lock()
rev := m.track(rt.Host).delivered
m.mu.Unlock()
- plan, err := decideWake(in)
+ var (
+ plan activator.WakePlan
+ err error
+ )
+ if want, set := m.replicaWant(rt); set {
+ plan, err = decideReplicaWake(in, want)
+ } else {
+ plan, err = decideWake(in)
+ }
plan.Declarations = declarations
plan.ConfigRev = rev
if err != nil {