carlos / platform Public

feat: coordinate fleet release and ordered copy swaps

Stateless replicas Plan 4 Task 1 (#511). Plan 1's release record runs one
release per instance and build; this extends it into an ordered deploy
across copies with at most one outstanding box permit.

- replicas: Deploy gains a Swap sub-object (Order, Completed, ActiveBox,
  permit revision, halted, bootstrap), LastGood and RetryOf. NextDeploy is
  the typed order/permit/ack/halt/done table: coordinator ops need the
  live term of the calling box, an ack only the permit's box and revision,
  and an ack can never grant a permit or close the deploy.
- provision: SetRecordReplicaDeploy writes swap transitions through the
  judged CAS with the F8 proof and expected revision. The release writer
  now binds every box, including v0.34 boxes, to R9: the record's attempt
  for a lifetime and target wins in every phase, and a new ID needs a new
  target or lifetime or an unconsumed durable RetryOf. No new ID while a
  permit is unresolved (R2); done is terminal. LastGood is written at
  released, carried by every begin and normalized from legacy records.
  A halt keeps the release phase and the permit; only the box's ack, or
  its retirement stop proof after a halt, resolves it.
- activator, rollout: the box selects the deploy ID only after holding the
  coordinator term (R1) and its book yields to the record's attempt.
- console: POST .../deploy beside the unchanged /release; the console
  orders the active assigned boxes from its roster. Instance retry and
  promote --retry write RetryOf durably before any box is told, and are
  refused with SR-4-C31 while a switch is open. The instance list shows
  the deploy state from SR-4 rows (SR-4-C39 added, pending copy review).
- host: a swap worker fed by the reconcile observation fan-out and the
  existing fast tick (R7) drives order, permits and done on the
  coordinator, and hands a permit to its box.

Record-write census and API lock witness extended; root-read census
proposal stateless-replicas-4-task1 awaits the independent #280 verdict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 88605b6e9810d4185965c9d70bf64aa5f7be3639 parent d922887
44 files changed, +2,986 −112
  • apimode.go +4 −0
  • docs/parity.md +1 −1
  • docs/superpowers/notes/census-proposal-stateless-replicas-4-task1.md +31 −0
  • docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md +1 −0
  • instances_cli.go +4 −1
  • internal/activator/coordinator.go +16 −1
  • internal/activator/replicarelease_world_test.go +430 −0
  • internal/activator/stateless.go +5 −8
  • internal/activator/statelessrelease.go +63 −36
  • internal/activator/statelessrelease_test.go +8 −0
  • internal/console/apicli.go +11 −0
  • internal/console/apiinstances.go +5 −1
  • internal/console/apiretry.go +9 −0
  • internal/console/browserretry.go +4 −1
  • internal/console/pendinghandlers.go +9 −0
  • internal/console/replicacoordinator.go +3 −1
  • internal/console/replicacoordinator_test.go +5 −2
  • internal/console/replicadeploy.go +231 −0
  • internal/console/replicadeploy_test.go +303 −0
  • internal/console/replicaplacement.go +2 −2
  • internal/console/replicaplacement_fix_test.go +4 −4
  • internal/console/replicaplacement_test.go +4 −4
  • internal/console/routedecls.go +1 −0
  • internal/host/agent.go +21 −2
  • internal/host/replicacoordinator.go +1 −1
  • internal/host/replicadeploy.go +194 −0
  • internal/host/replicadeploy_test.go +252 −0
  • internal/host/stateless_runtime_test.go +3 −3
  • internal/provision/lifetimeindex.go +1 −4
  • internal/provision/plan9_b8_census_test.go +4 −2
  • internal/provision/replicaassignment.go +31 −8
  • internal/provision/replicacoordinator.go +4 −2
  • internal/provision/replicacoordinator_test.go +1 −1
  • internal/provision/replicadeploy.go +120 −3
  • internal/provision/replicadeploy_test.go +377 −2
  • internal/provision/stateless_replicas_4_task1_census_test.go +64 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1.tsv +20 −0
  • internal/replicas/deploy.go +193 −0
  • internal/replicas/deploy_test.go +412 −0
  • internal/replicas/types.go +36 −10
  • internal/rollout/failures.go +22 −10
  • internal/rollout/stateless_test.go +74 −1
  • parity/parity.tsv +1 −1

Intent

Human

<task-notification> <task-id>b23zr2zf6</task-id> <tool-use-id>toolu_01CMEtRXnVcT6fZd7jyXmNuf</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/b23zr2zf6.output</output-file> <status>completed</status> <summary>Background command "Ask Fable 5.2 for a steer on the deadlock" completed (exit code 0)</summary> </task-notification>

diff --git a/apimode.go b/apimode.go
index 34d8e90eb..f9b75f71b 100644
--- a/apimode.go
+++ b/apimode.go
@@ -3511,6 +3511,10 @@ type apiInstanceRecord struct {
// requests do not reach the fleet. Absent from an older console and for
// every other instance.
RouteHeld string `json:"route_held,omitempty"`
+ // DeployStatus is the console's one-line state of a replicated deploy
+ // (release, then one box at a time). Absent from an older console and
+ // for an instance without a copy assignment.
+ DeployStatus string `json:"deploy_status,omitempty"`
}
// apiConfigRefusal mirrors the console's configRefusalView
diff --git a/docs/parity.md b/docs/parity.md
index 7e830ca70..3589ed026 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -462,5 +462,5 @@ Discussion #742.
| legacy-apps | platform | | `GET /apps`<br>`GET /apps/{app}` | Old URLs kept as redirects into the account. |
| billing-webhook | platform | | `POST /billing/webhook` | Stripe calls it. |
| ses-events | platform | | `POST /api/ses/events` | Amazon SES delivery events. |
-| box-doors | platform | | `POST /api/fleet/enrol`<br>`GET /api/box/interactive/{id}`<br>`GET /api/box/runs/{id}`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/coordinator`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/release` | Doors boxes and managed fleets call, not people. |
+| box-doors | platform | | `POST /api/fleet/enrol`<br>`GET /api/box/interactive/{id}`<br>`GET /api/box/runs/{id}`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/coordinator`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/release`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/deploy` | Doors boxes and managed fleets call, not people. |
| plumbing | platform | `__demo-snapshot`<br>`__registry-child`<br>`__rootfs-check-probe`<br>`__rootfs-check-prepare`<br>`__cgexec`<br>`__cgprobe` | | Words the binary runs itself as, dispatched before the command switch. |
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-4-task1.md b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task1.md
new file mode 100644
index 000000000..a98f02fc5
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task1.md
@@ -0,0 +1,31 @@
+# Census approval: stateless-replicas-4-task1
+
+Ruling `census-ruling-stateless-replicas-4-task1`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/stateless.go` `Service.prepareStateless` | body | unchanged (24) | 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. |
+| `internal/activator/stateless.go` `Service.statelessFinalRecord` | body | unchanged (12) | 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. |
+| `internal/host/agent.go` `fastTick` | body | unchanged (1) | Signals the owned replica swap worker (armedReplicaDeploy.tick) beside the placement worker on the existing tick; coalesced background pass, no timer, no bucket read. Its transitions go through the console's authenticated /deploy. |
+| `internal/host/agent.go` `runAgent` | body | unchanged (9) | 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/activator/statelessrelease.go` `Service.PrepareStatelessRelease` | sites | -registry:Account, -registry:App, -registry:GoodDemand, -registry:GoodDigest, -registry:GoodVersion, -registry:Host ×7, -whole:Route ×4 | Now a thin wrapper that hands a fixed deploy ID to prepareStatelessRelease; its body moved there. No read of its own. |
+
+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/stateless.go` `Service.prepareStateless`: legacy, task accepted-legacy. Basis: 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.
+- `internal/activator/stateless.go` `Service.statelessFinalRecord`: legacy, task accepted-legacy. Basis: 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.
+- `internal/host/agent.go` `fastTick`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: signals the owned replica worker on the existing tick; coalesced asynchronous execution, no timer or bucket scan added. merge of origin/main 7920cccf: Retain main box-role reader pass on the existing tick alongside the replica worker signal; merge-only body change, unchanged read sites.;rev3=census-ruling-restart-new-box-gap;basis=calls the optional restartGain hook (restartGainSeed) once per existing tick before the serial read; no new root path, timer or read kind; nil hook is unchanged;rev3=census-ruling-agent-start-demo-3;basis=Refresh moved notices through the shared watch before normal convergence; no new per-box poll. Census read-site delta: unchanged (1).
+- `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).
+- `internal/activator/statelessrelease.go` `Service.PrepareStatelessRelease`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Read durable deploy evidence and canonical target via existing-record observation seam; use coordinator authority only for this path, persist releasing before exec and require proof plus SafeUntil before success; commandless binary verifies staged artifact separately; R11 lets the current term retake pending via the typed begin gate; R12 follows renewed SafeUntil through the existing command supervisor instead of a fixed initial context deadline; no new store polling or direct typed record writer callsite. Fix round 1 replaces the frozen-carrier re-observation with an identical released writer replay; command execution, proof and authority gates remain. Fix 3b round 1 I2 / R20: only the matching released branch calls the backend escrow initializer. Held authority is reused; absent trio can acquire through the existing coordinator adapter. No release rerun, deploy mutation, new record read or loop; existing final-exec checks from 3a remain unchanged. Final review I2: keep pre-releasing refusals pending; only a command ReleaseError or an actual artifact digest mismatch becomes failed. Releasing uncertainty still fences automatic reruns; begin, authority, execution and proof gates remain.;rev3=census-ruling-stateless-failed-release-held;basis=Distinguish an observed failed or unknown coordinator deploy from a transient release admission refusal using wrapped existing errors; preserve the existing unknown-result reason; no new read or coordinator write.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/statelessrelease.go:Service.prepareStatelessRelease`: reads +registry:Account, +registry:App, +registry:GoodDemand, +registry:GoodDigest, +registry:GoodVersion, +registry:Host ×7, +whole:Route ×5; written legacy, accepted-legacy, frozen
+
+Seal: `9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af` → `3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1.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 e3c24236a..d216e43bf 100644
--- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
+++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
@@ -110,3 +110,4 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| SR-4-C36 | internal/console/replicadeploy.go | release running | pending |
| SR-4-C37 | internal/console/replicadeploy.go | deploy complete | pending |
| SR-4-C38 | internal/console/replicadeploy.go | release result unknown | pending |
+| SR-4-C39 | internal/console/replicadeploy.go | release complete; no copy was running, so the first copy is starting on its own | pending (added by Plan 4 Task 1 for a bootstrap order; awaiting Paul's copy review) |
diff --git a/instances_cli.go b/instances_cli.go
index 2342db522..9d766cacd 100644
--- a/instances_cli.go
+++ b/instances_cli.go
@@ -708,7 +708,7 @@ var plainReasonWord = regexp.MustCompile(`^[a-z0-9_]{1,40}$`)
// instance is not running), then a held host (another route on the hub holds
// the instance's name, so requests do not reach its fleet; the console's
// FPR-C08 sentence, printed only when cleanConsoleText finds it fit for a
-// terminal), then a rollout reason (a failure hold outranks a preference),
+// terminal), then a replicated deploy's state, then a rollout reason (a failure hold outranks a preference),
// else the settings reason.
func reasonCell(r apiInstanceRecord) string {
if s := configRefusalReason(r); s != "" {
@@ -717,6 +717,9 @@ func reasonCell(r apiInstanceRecord) string {
if s := cleanConsoleText(r.RouteHeld, routeHeldMaxBytes); s != "" {
return s
}
+ if s := cleanConsoleText(r.DeployStatus, routeHeldMaxBytes); s != "" {
+ return s
+ }
if s := rolloutReason(r.Rollout); s != "" {
return s
}
diff --git a/internal/activator/coordinator.go b/internal/activator/coordinator.go
index e24fe8d38..4392cca70 100644
--- a/internal/activator/coordinator.go
+++ b/internal/activator/coordinator.go
@@ -52,6 +52,20 @@ func (c *CoordinationClient) Held(id replicas.Identity) replicas.Authority {
return nil
}
+// HeldTerm is the term of a currently held authority for this exact
+// lifetime, or "". Swap transitions name it; it performs no request.
+func (c *CoordinationClient) HeldTerm(id replicas.Identity) string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.closed {
+ return ""
+ }
+ if a := c.held[id]; a != nil && a.errLocked() == nil {
+ return a.term
+ }
+ return ""
+}
+
// HeldForHost refuses ambiguous lifetimes rather than selecting authority
// from a different incarnation of a hostname.
func (c *CoordinationClient) HeldForHost(host string) replicas.Authority {
@@ -238,7 +252,8 @@ func (c *CoordinationClient) ReleaseState(ctx context.Context, id replicas.Ident
if phase == "begin" {
phase = "pending"
}
- if d.Phase != phase || d.ID != change.ID || d.Term != change.Term || d.Incarnation != id.Incarnation || d.Target != change.Target {
+ // A lost success reply replayed after the swap finished reads done.
+ if (d.Phase != phase && !(phase == "released" && d.Phase == "done")) || d.ID != change.ID || d.Term != change.Term || d.Incarnation != id.Incarnation || d.Target != change.Target {
return replicas.Deploy{}, replicas.ErrFenced
}
return d, nil
diff --git a/internal/activator/replicarelease_world_test.go b/internal/activator/replicarelease_world_test.go
new file mode 100644
index 000000000..2af9938a5
--- /dev/null
+++ b/internal/activator/replicarelease_world_test.go
@@ -0,0 +1,430 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "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"
+)
+
+// replicaWorld is one bucket with real typed record writers behind every
+// box's coordination client, as the host's store adapter wires them. Its
+// clock offset lets a later box see an earlier term as expired.
+type replicaWorld struct {
+ t *testing.T
+ s release.Store
+ offset atomic.Int64
+}
+
+type replicaInstance struct {
+ w *replicaWorld
+ id replicas.Identity
+ rec provision.Record
+}
+
+var worldTarget = replicas.Build{Version: "v2", Digest: "canonical-2"}
+
+func newReplicaWorld(t *testing.T) *replicaWorld {
+ return &replicaWorld{t: t, s: release.NewDirStore(t.TempDir())}
+}
+
+func (w *replicaWorld) now() time.Time { return time.Now().Add(time.Duration(w.offset.Load())) }
+
+// instance creates host with copies on boxes a and b.
+func (w *replicaWorld) instance(host string) *replicaInstance {
+ t := w.t
+ t.Helper()
+ ctx := provision.WithRecordSequence(context.Background())
+ rec := provision.Record{Schema: 1, Account: "acme", App: "shop", Host: host, Slug: "shop", Channel: "edge", Region: "fleet/pi", Hibernate: new(bool), CreatedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)}
+ if err := provision.CreateRecord(ctx, w.s, rec); err != nil {
+ t.Fatal(err)
+ }
+ got, err := provision.GetRecord(ctx, w.s, rec.Account, rec.App, rec.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ inc, err := provision.Incarnation(got.Account, got.App, got.Host, got.CreatedAt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id := replicas.Identity{Account: got.Account, App: got.App, Host: got.Host, Incarnation: inc}
+ mctx, err := provision.WithReplicaAssignmentManifest(ctx, *got, &release.Manifest{Schema: 1, App: "shop", Version: "v2", Kind: "binary", Stateless: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.SetRecordReplicaAssignment(mctx, w.s, id, replicas.Expect{Incarnation: inc, Region: got.Region, RecordSeq: got.RecordSeq}, replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}}); err != nil {
+ t.Fatal(err)
+ }
+ return &replicaInstance{w: w, id: id, rec: *got}
+}
+
+func (in *replicaInstance) record() *provision.Record {
+ in.w.t.Helper()
+ rec, err := provision.GetRecord(context.Background(), in.w.s, in.id.Account, in.id.App, in.id.Host)
+ if err != nil {
+ in.w.t.Fatal(err)
+ }
+ return rec
+}
+
+func (in *replicaInstance) deploy() *replicas.Deploy { return in.record().ReplicaDeploy }
+
+// retire moves box out of the assignment, as placement does after a loss.
+func (in *replicaInstance) retire(box string) {
+ t := in.w.t
+ t.Helper()
+ rec := in.record()
+ ctx, err := provision.WithReplicaAssignmentManifest(provision.WithRecordSequence(context.Background()), *rec, &release.Manifest{Schema: 1, App: "shop", Version: "v2", Kind: "binary", Stateless: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := rec.ReplicaAssignment
+ next := replicas.Assignment{Revision: a.Revision, Desired: a.Desired, Retiring: []string{box}}
+ for _, b := range a.Boxes {
+ if b != box {
+ next.Boxes = append(next.Boxes, b)
+ }
+ }
+ if _, err := provision.SetRecordReplicaAssignment(ctx, in.w.s, in.id, replicas.Expect{Incarnation: in.id.Incarnation, Region: rec.Region, RecordSeq: rec.RecordSeq, Revision: a.Revision}, next); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// replicaBox is one box's activator and its coordination client.
+type replicaBox struct {
+ r *releaseRig
+ client *CoordinationClient
+ mints int
+ book map[string]string // a populated local book: host -> selected ID
+}
+
+// box wires a release rig for in on label through the real record writers.
+// Its selector is a book: it adopts the durable attempt for the target, or
+// keeps its own selection, and mints only for a requested retry or a new
+// target, as rollout.FailureBook.ReplicaDeployID does.
+func (in *replicaInstance) box(label, boot string) *replicaBox {
+ w := in.w
+ r := newReleaseRig(w.t)
+ if in.id.Host != r.rt.Host {
+ r.a.mu.Lock()
+ delete(r.a.entries, r.rt.Host)
+ r.rt.Host = in.id.Host
+ r.e.host, r.e.route.Host = in.id.Host, in.id.Host
+ r.a.entries[in.id.Host] = r.e
+ r.a.mu.Unlock()
+ }
+ exchange := func(ctx context.Context, id replicas.Identity, change replicas.CoordinatorChange) (replicas.CoordinatorReply, error) {
+ now := w.now()
+ rec, err := provision.SetRecordCoordinator(ctx, w.s, id, change, now)
+ if err != nil {
+ return replicas.CoordinatorReply{}, err
+ }
+ return replicas.CoordinatorReply{Lease: *rec.Coordinator, RemainingMS: max(0, rec.Coordinator.ExpiresAt.Sub(now).Milliseconds())}, nil
+ }
+ releaseState := func(ctx context.Context, id replicas.Identity, change replicas.ReleaseChange) (replicas.Deploy, error) {
+ current, err := provision.GetRecord(ctx, w.s, id.Account, id.App, id.Host)
+ if err != nil {
+ return replicas.Deploy{}, err
+ }
+ next := replicas.Deploy{ID: change.ID, Incarnation: id.Incarnation, Term: change.Term, Target: change.Target, Phase: change.Op, RetryOf: change.RetryOf}
+ if next.Phase == "begin" {
+ next.Phase = "pending"
+ }
+ if current.ReplicaDeploy != nil && current.ReplicaDeploy.ID == next.ID {
+ next.Previous = current.ReplicaDeploy.Previous
+ }
+ rec, err := provision.SetRecordReplicaRelease(ctx, w.s, id, change.Revision, next)
+ if err != nil {
+ return replicas.Deploy{}, err
+ }
+ return *rec.ReplicaDeploy, nil
+ }
+ b := &replicaBox{r: r, client: NewCoordinatorClient(label, boot, exchange, releaseState), book: map[string]string{}}
+ r.a.Coordinator = b.client
+ r.a.ObserveReplicaRelease = func(context.Context, registry.Route) (replicas.Identity, replicas.Build, *replicas.Deploy, error) {
+ return in.id, replicas.Build{Version: r.id.Version, Digest: worldTarget.Digest}, in.deploy(), nil
+ }
+ var mu sync.Mutex
+ r.a.ReplicaDeployID = func(id replicas.Identity, target replicas.Build, observed *replicas.Deploy) (string, error) {
+ mu.Lock()
+ defer mu.Unlock()
+ if d := replicas.DurableAttempt(observed, id.Incarnation, target); d != nil {
+ b.book[id.Host] = d.ID
+ return d.ID, nil
+ }
+ if sel := b.book[id.Host]; sel != "" && (observed == nil || sel != observed.ID) {
+ return sel, nil
+ }
+ b.mints++
+ b.book[id.Host] = label + "-" + id.Host + "-mint-" + string(rune('0'+b.mints))
+ return b.book[id.Host], nil
+ }
+ return b
+}
+
+// prepare is the production path: prepareStateless's selector call.
+func (b *replicaBox) prepare() error {
+ _, err := b.r.a.prepareStatelessRelease(context.Background(), b.r.rt, b.r.id, b.r.a.ReplicaDeployID)
+ return err
+}
+
+// loseTerm makes the client's held authority expire now.
+func (b *replicaBox) loseTerm() {
+ b.client.mu.Lock()
+ b.client.now = func() time.Time { return time.Now().Add(time.Hour) }
+ b.client.mu.Unlock()
+}
+
+// targetStarts counts swap permits and orders: a copy starts the target
+// only on one.
+func targetStarts(d *replicas.Deploy) int {
+ if d == nil {
+ return 0
+ }
+ return len(d.Swap.Order) + len(d.Swap.Completed)
+}
+
+// TestReplicaReleaseCoordinatorDiesBeforeCommit: the coordinator persists
+// releasing, runs the migration, then loses its term before the success
+// CAS. No copy moves, the phase ends unknown and terminal, no other box
+// reruns the command, and only an explicit retry starts another attempt.
+func TestReplicaReleaseCoordinatorDiesBeforeCommit(t *testing.T) {
+ w := newReplicaWorld(t)
+ in := w.instance("shop.example.com")
+ a := in.box("a", "boot-a")
+ migrations := 0
+ a.r.b.onStart = func() {
+ if d := in.deploy(); d == nil || d.Phase != "releasing" {
+ t.Error("releasing was not durable before the command")
+ }
+ migrations++
+ a.loseTerm()
+ }
+ a.r.b.unit.done("1", "0", "success")
+ if err := a.prepare(); !errors.Is(err, ErrReplicaReleaseUnknown) {
+ t.Fatalf("lost term: %v", err)
+ }
+ first := in.deploy()
+ if first.Phase != "releasing" {
+ t.Fatalf("success written without a term: %+v", first)
+ }
+ // Placement moves the dead coordinator out; b takes over after expiry.
+ in.retire("a")
+ w.offset.Store(int64(replicas.CoordinatorTTL + time.Minute))
+ b := in.box("b", "boot-b")
+ b.book[in.id.Host] = "b-stale-selection"
+ for i := 0; i < 3; i++ {
+ if err := b.prepare(); !errors.Is(err, ErrReplicaReleaseUnknown) {
+ t.Fatalf("successor %d: %v", i, err)
+ }
+ }
+ d := in.deploy()
+ phase, automaticRuns, starts := d.Phase, a.r.b.startCount()+b.r.b.startCount(), targetStarts(d)
+ if phase != "unknown" || automaticRuns != 1 || starts != 0 {
+ t.Fatal("unknown release was treated as success or retried")
+ }
+ if d.ID != first.ID || b.mints != 0 || migrations != 1 {
+ t.Fatalf("successor replaced the attempt: %+v mints=%d", d, b.mints)
+ }
+ // The explicit retry is durable; the coordinator mints once and may repeat.
+ if _, err := provision.RequestRecordReplicaRetry(context.Background(), w.s, in.id, first.ID); err != nil {
+ t.Fatal(err)
+ }
+ b.r.b.unit.done("1", "0", "success")
+ if err := b.prepare(); err != nil {
+ t.Fatal(err)
+ }
+ d = in.deploy()
+ if d.Phase != "released" || d.ID == first.ID || d.RetryOf != first.ID || b.r.b.startCount() != 1 || b.mints != 1 {
+ t.Fatalf("explicit retry: %+v runs=%d mints=%d", d, b.r.b.startCount(), b.mints)
+ }
+ if err := b.prepare(); err != nil || b.r.b.startCount() != 1 || b.mints != 1 {
+ t.Fatal("released retry reran")
+ }
+}
+
+// TestReplicaReleaseOncePerInstanceBuild: two instances run independently;
+// two copies of one instance run once; a duplicate notification or a
+// restarted coordinator runs nothing more; a release-free binary runs no
+// command at all.
+func TestReplicaReleaseOncePerInstanceBuild(t *testing.T) {
+ w := newReplicaWorld(t)
+ shop, other := w.instance("shop.example.com"), w.instance("www.example.com")
+ shopA, shopB, otherA := shop.box("a", "boot-a"), shop.box("b", "boot-b"), other.box("a", "boot-a2")
+ for _, b := range []*replicaBox{shopA, otherA} {
+ b.r.b.unit.done("1", "0", "success")
+ if err := b.prepare(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if shop.deploy().ID == other.deploy().ID || shop.deploy().Phase != "released" || other.deploy().Phase != "released" {
+ t.Fatalf("instances share a run: %+v %+v", shop.deploy(), other.deploy())
+ }
+ // The second copy adopts the passed release without coordination.
+ if err := shopB.prepare(); err != nil {
+ t.Fatal(err)
+ }
+ // Duplicate notifications, and the coordinator after a restart.
+ restarted := shop.box("a", "boot-a-restarted")
+ for _, b := range []*replicaBox{shopA, shopA, restarted, shopB} {
+ if err := b.prepare(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if runs := shopA.r.b.startCount() + shopB.r.b.startCount() + restarted.r.b.startCount(); runs != 1 || otherA.r.b.startCount() != 1 {
+ t.Fatalf("runs: shop %d other %d", runs, otherA.r.b.startCount())
+ }
+ if shopB.mints+restarted.mints != 0 || shopB.client.HeldTerm(shop.id) != "" || restarted.client.HeldTerm(shop.id) != "" {
+ t.Fatal("a passed release was coordinated again")
+ }
+ // A release-free binary records a passed release with zero commands.
+ free := w.instance("free.example.com").box("a", "boot-free")
+ delete(free.r.b.procs, release.ProcessRelease)
+ if err := free.prepare(); err != nil || free.r.b.startCount() != 0 {
+ t.Fatalf("release-free: %v runs=%d", err, free.r.b.startCount())
+ }
+}
+
+// TestReplicaReleaseTakeoverAdoptsDurableAttempt (R9): a coordinator
+// takeover by a box whose book holds its own selection adopts the record's
+// attempt after failed, unknown and done, runs no command and mints no ID;
+// a stale selection over a dead term's pending attempt is refused by the
+// writer before any command.
+func TestReplicaReleaseTakeoverAdoptsDurableAttempt(t *testing.T) {
+ for _, end := range []string{"failed", "unknown", "done", "pending"} {
+ t.Run(end, func(t *testing.T) {
+ w := newReplicaWorld(t)
+ in := w.instance("shop.example.com")
+ a := in.box("a", "boot-a")
+ switch end {
+ case "failed":
+ a.r.b.unit.done("1", "7", "exit-code")
+ case "unknown":
+ a.r.b.unit.done("1", "0", "success")
+ a.r.b.onStart = a.loseTerm
+ case "done":
+ a.r.b.unit.done("1", "0", "success")
+ }
+ if end == "pending" {
+ // Begin persisted; the box dies before command admission.
+ if _, err := a.client.Acquire(context.Background(), in.id); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.client.ReleaseState(context.Background(), in.id, replicas.ReleaseChange{Op: "begin", ID: "a-attempt", Target: worldTarget}); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ _ = a.prepare()
+ }
+ if end == "done" {
+ assignmentDone(t, w, in)
+ }
+ attempt := in.deploy()
+ runs := a.r.b.startCount()
+ in.retire("a")
+ w.offset.Store(int64(replicas.CoordinatorTTL + time.Minute))
+ b := in.box("b", "boot-b")
+ b.book[in.id.Host] = "b-populated-book"
+ b.r.b.unit.done("1", "0", "success")
+ err := b.prepare()
+ d := in.deploy()
+ switch end {
+ case "failed":
+ if !errors.Is(err, errReplicaReleaseFailed) {
+ t.Fatalf("takeover: %v", err)
+ }
+ case "unknown":
+ if !errors.Is(err, ErrReplicaReleaseUnknown) || d.Phase != "unknown" {
+ t.Fatalf("takeover: %v %+v", err, d)
+ }
+ case "done":
+ if err != nil || d.Phase != "done" {
+ t.Fatalf("takeover: %v %+v", err, d)
+ }
+ case "pending":
+ // The successor retakes the same attempt and runs it once.
+ if err != nil || d.Phase != "released" || b.r.b.startCount() != 1 {
+ t.Fatalf("pending retake: %v %+v", err, d)
+ }
+ }
+ if d.ID != attempt.ID || b.mints != 0 || b.book[in.id.Host] != attempt.ID && end == "pending" {
+ t.Fatalf("takeover replaced the attempt: %+v mints=%d book=%v", d, b.mints, b.book)
+ }
+ if end != "pending" && (b.r.b.startCount() != 0 || a.r.b.startCount() != runs) {
+ t.Fatal("takeover reran the command")
+ }
+ })
+ }
+}
+
+// assignmentDone closes in's passed release through the swap writer.
+func assignmentDone(t *testing.T, w *replicaWorld, in *replicaInstance) {
+ t.Helper()
+ rec := in.record()
+ d, term := rec.ReplicaDeploy, rec.Coordinator.Term
+ apply := func(c replicas.DeployChange) {
+ c.ID, c.Target = d.ID, d.Target
+ rec, err := provision.SetRecordReplicaDeploy(context.Background(), w.s, in.id, d.Revision, c, time.Now())
+ if err != nil {
+ t.Fatalf("%s: %v", c.Op, err)
+ }
+ d = rec.ReplicaDeploy
+ }
+ apply(replicas.DeployChange{Op: "order", Term: term, Box: "a", Order: []string{"a", "b"}})
+ for _, box := range []string{"a", "b"} {
+ apply(replicas.DeployChange{Op: "permit", Term: term, Box: "a", Grant: box})
+ apply(replicas.DeployChange{Op: "ack", Box: box, Permit: d.Swap.Permit, Switched: true})
+ }
+ apply(replicas.DeployChange{Op: "done", Term: term, Box: "a"})
+}
+
+// TestReplicaDeployFailedRelease: on a nonzero exit, a timeout, an
+// unreadable result or an unproven stop, the attempt ends failed or
+// unknown, no copy is ordered or permitted, the other copy stays on its
+// build without running anything, and LastGood keeps the last passed build.
+func TestReplicaDeployFailedRelease(t *testing.T) {
+ for _, kind := range []string{"exit", "timeout", "unreadable", "unproven"} {
+ t.Run(kind, func(t *testing.T) {
+ w := newReplicaWorld(t)
+ in := w.instance("shop.example.com")
+ a := in.box("a", "boot-a")
+ switch kind {
+ case "exit":
+ a.r.b.unit.done("1", "7", "exit-code")
+ case "timeout":
+ p := a.r.b.procs[release.ProcessRelease]
+ p.TimeoutSec = 1
+ a.r.b.procs[release.ProcessRelease] = p
+ case "unreadable":
+ a.r.b.unit.done("", "", "")
+ case "unproven":
+ a.r.b.unit.settle = func(int) error { return ErrStillRunning }
+ a.r.b.unit.done("1", "0", "success")
+ }
+ if err := a.prepare(); err == nil {
+ t.Fatal("failed release reported success")
+ }
+ d := in.deploy()
+ if d.Phase != "failed" && d.Phase != "unknown" && !(kind == "unproven" && d.Phase == "releasing") {
+ t.Fatalf("phase %s", d.Phase)
+ }
+ if targetStarts(d) != 0 || d.LastGood != (replicas.Build{}) {
+ t.Fatalf("a copy was allowed onto the target: %+v", d)
+ }
+ b := in.box("b", "boot-b")
+ if err := b.prepare(); err == nil || b.r.b.startCount() != 0 {
+ t.Fatalf("other copy moved: %v runs=%d", err, b.r.b.startCount())
+ }
+ if a.r.b.startCount() != 1 {
+ t.Fatalf("runs %d", a.r.b.startCount())
+ }
+ })
+ }
+}
diff --git a/internal/activator/stateless.go b/internal/activator/stateless.go
index a2d7b1e80..3a4a2bc67 100644
--- a/internal/activator/stateless.go
+++ b/internal/activator/stateless.go
@@ -327,7 +327,7 @@ func (a *Service) statelessFinalRecord(ctx context.Context, rt registry.Route) e
}
} else {
d := facts.ReplicaDeploy
- if d == nil || d.ID != prepared.deployID || d.Incarnation != identity.Incarnation || d.Target != (replicas.Build{Version: prepared.id.Version, Digest: prepared.digest}) || d.Phase != "released" {
+ if d == nil || d.ID != prepared.deployID || d.Incarnation != identity.Incarnation || d.Target != (replicas.Build{Version: prepared.id.Version, Digest: prepared.digest}) || !replicas.ReleasePassed(d.Phase) {
return ErrFenced
}
}
@@ -382,8 +382,7 @@ func (a *Service) prepareStateless(ctx context.Context, rt registry.Route, id re
if err != nil {
return ctx, err
}
- identity, target, old, err := ObservedReplicaRelease(observed, rt)
- if err != nil {
+ if _, _, _, err := ObservedReplicaRelease(observed, rt); err != nil {
return ctx, err
}
observation, _ := observed.Value(replicaObservationKey{}).(replicaObservation)
@@ -402,13 +401,11 @@ func (a *Service) prepareStateless(ctx context.Context, rt registry.Route, id re
if a.ReplicaDeployID == nil {
return ctx, ErrFenced
}
- deployID, err := a.ReplicaDeployID(identity, target, old)
- if err != nil {
- return ctx, err
- }
launch := rt
launch.Stateless = true
- if err := a.PrepareStatelessRelease(observed, launch, id, deployID); err != nil {
+ // The book is consulted only after the coordinator term is held (R1).
+ deployID, err := a.prepareStatelessRelease(observed, launch, id, a.ReplicaDeployID)
+ if err != nil {
return ctx, err
}
prepared := &statelessPreparation{route: rt, id: id, digest: digest, deployID: deployID, observation: observation}
diff --git a/internal/activator/statelessrelease.go b/internal/activator/statelessrelease.go
index 00941a47e..fc3322450 100644
--- a/internal/activator/statelessrelease.go
+++ b/internal/activator/statelessrelease.go
@@ -15,57 +15,80 @@ import (
var errReplicaReleaseFailed = fmt.Errorf("release: %w", errReleaseNotPassed)
var errReplicaReleaseUnknown = fmt.Errorf("release: %w", ErrReplicaReleaseUnknown)
+// PrepareStatelessRelease runs one release attempt named deployID. The
+// production path is prepareStatelessRelease with the box's ID selector.
func (a *Service) PrepareStatelessRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, deployID string) error {
+ _, err := a.prepareStatelessRelease(ctx, rt, id, func(replicas.Identity, replicas.Build, *replicas.Deploy) (string, error) {
+ if deployID == "" {
+ return "", replicas.ErrFenced
+ }
+ return deployID, nil
+ })
+ return err
+}
+
+// prepareStatelessRelease adopts the record's attempt whenever it is the
+// attempt for this lifetime and target (R9), whatever its phase, so a
+// passed, failed or unknown result never needs coordination. Otherwise it
+// acquires the coordinator term first and only then asks selectID for the
+// attempt (R1). It returns the attempt ID it acted on.
+func (a *Service) prepareStatelessRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, selectID func(replicas.Identity, replicas.Build, *replicas.Deploy) (string, error)) (string, error) {
ctx, end := a.attemptCtx(ctx)
defer end()
lock, _ := a.replicaReleaseLocks.LoadOrStore(rt.Host, &sync.Mutex{})
mu := lock.(*sync.Mutex)
if !mu.TryLock() {
- return errSwapBusy
+ return "", errSwapBusy
}
defer mu.Unlock()
- if a.ObserveReplicaRelease == nil || deployID == "" {
- return replicas.ErrFenced
+ if a.ObserveReplicaRelease == nil || selectID == nil {
+ return "", replicas.ErrFenced
}
identity, target, old, err := a.ObserveReplicaRelease(ctx, rt)
if err != nil {
- return err
+ return "", err
}
if identity.Account != rt.Account || identity.App != rt.App || identity.Host != rt.Host || identity.Incarnation == "" || target.Version != id.Version || target.Digest == "" {
- return replicas.ErrFenced
- }
- matches := func(d *replicas.Deploy) bool {
- return d != nil && d.ID == deployID && d.Incarnation == identity.Incarnation && d.Target == target
+ return "", replicas.ErrFenced
}
- if old != nil && old.ID == deployID {
- if !matches(old) {
- return replicas.ErrFenced
- }
- if old.Phase == "released" {
+ if durable := replicas.DurableAttempt(old, identity.Incarnation, target); durable != nil {
+ switch {
+ case replicas.ReleasePassed(durable.Phase):
if escrow, ok := a.backend.(statelessEscrowInitializer); ok {
- return escrow.prepareStatelessEscrow(ctx, rt, identity)
+ return durable.ID, escrow.prepareStatelessEscrow(ctx, rt, identity)
}
- return nil
- }
- if old.Phase == "unknown" {
- return errReplicaReleaseUnknown
- }
- if old.Phase == "failed" {
- return errReplicaReleaseFailed
+ return durable.ID, nil
+ case durable.Phase == "unknown":
+ return durable.ID, errReplicaReleaseUnknown
+ case durable.Phase == "failed":
+ return durable.ID, errReplicaReleaseFailed
}
}
if a.releaseOpen(rt.Host) {
- return ErrReplicaReleaseUnknown
+ return "", ErrReplicaReleaseUnknown
}
if a.Coordinator == nil {
- return replicas.ErrFenced
+ return "", replicas.ErrFenced
}
held, err := a.Coordinator.Acquire(ctx, identity)
if err != nil {
- return err
+ return "", err
}
if held == nil {
- return replicas.ErrFenced
+ return "", replicas.ErrFenced
+ }
+ // Only the term holder selects an attempt; the record's attempt still
+ // wins (R9), and the writer refuses any other new ID.
+ deployID, err := selectID(identity, target, old)
+ if err != nil {
+ return "", err
+ }
+ if deployID == "" || (old != nil && old.ID == deployID && (old.Incarnation != identity.Incarnation || old.Target != target)) {
+ return "", replicas.ErrFenced
+ }
+ retryOf := ""
+ if replicas.RetryRequested(old) && old.ID != deployID {
+ retryOf = old.ID
}
// Keep coordination with the client; its existing tick renews it, and
// an unproven command must retain its stop obligation through expiry.
@@ -77,7 +100,7 @@ func (a *Service) PrepareStatelessRelease(ctx context.Context, rt registry.Route
return ctx.Err()
}
if err := valid(); err != nil {
- return err
+ return deployID, err
}
revision := uint64(0)
if old != nil {
@@ -85,7 +108,11 @@ func (a *Service) PrepareStatelessRelease(ctx context.Context, rt registry.Route
}
term := ""
change := func(op string) (replicas.Deploy, error) {
- d, err := a.Coordinator.ReleaseState(ctx, identity, replicas.ReleaseChange{Op: op, ID: deployID, Target: target, Revision: revision, Term: term})
+ c := replicas.ReleaseChange{Op: op, ID: deployID, Target: target, Revision: revision, Term: term}
+ if op == "begin" {
+ c.RetryOf = retryOf
+ }
+ d, err := a.Coordinator.ReleaseState(ctx, identity, c)
if err == nil {
revision = d.Revision
term = d.Term
@@ -97,15 +124,15 @@ func (a *Service) PrepareStatelessRelease(ctx context.Context, rt registry.Route
// this client still holds its term after a lost begin/exec response.
closed, closeErr := a.Coordinator.ReleaseState(ctx, identity, replicas.ReleaseChange{Op: "unknown", ID: old.ID, Target: old.Target, Revision: old.Revision})
if closeErr != nil || old.ID == deployID {
- return ErrReplicaReleaseUnknown
+ return deployID, ErrReplicaReleaseUnknown
}
revision = closed.Revision
}
if old != nil && old.ID == deployID && old.Phase != "pending" {
- return ErrReplicaReleaseUnknown
+ return deployID, ErrReplicaReleaseUnknown
}
if _, err := change("begin"); err != nil {
- return ErrReplicaReleaseUnknown
+ return deployID, ErrReplicaReleaseUnknown
}
// Only this path discards stateful good-build inference. The durable
// deploy ID, canonical target and lifetime decide whether work is due.
@@ -158,11 +185,11 @@ func (a *Service) PrepareStatelessRelease(ctx context.Context, rt registry.Route
if errors.As(runErr, &failed) || errors.Is(runErr, release.ErrStagedDigestMismatch) {
phase = "failed"
} else if !releasing {
- return runErr
+ return deployID, runErr
}
}
if valid() != nil {
- return ErrReplicaReleaseUnknown
+ return deployID, ErrReplicaReleaseUnknown
}
_, err = change(phase)
if err != nil {
@@ -170,13 +197,13 @@ func (a *Service) PrepareStatelessRelease(ctx context.Context, rt registry.Route
// before this attempt and cannot reveal a committed success.
if phase == "released" {
if _, retryErr := change(phase); retryErr == nil {
- return nil
+ return deployID, nil
}
}
- return ErrReplicaReleaseUnknown
+ return deployID, ErrReplicaReleaseUnknown
}
if phase == "unknown" {
- return ErrReplicaReleaseUnknown
+ return deployID, ErrReplicaReleaseUnknown
}
- return runErr
+ return deployID, runErr
}
diff --git a/internal/activator/statelessrelease_test.go b/internal/activator/statelessrelease_test.go
index 138323ebd..7971c6dd1 100644
--- a/internal/activator/statelessrelease_test.go
+++ b/internal/activator/statelessrelease_test.go
@@ -141,6 +141,14 @@ func TestReplicaReleaseUnknownStopsDeploy(t *testing.T) {
r.b.unit = newReleaseUnit()
r.b.started = make(chan struct{})
r.b.unit.done("1", "0", "success")
+ // R9: a fresh ID alone never replaces the durable attempt; the explicit
+ // retry is the console's durable RetryOf on the record.
+ if err := r.a.PrepareStatelessRelease(context.Background(), r.rt, r.id, "deploy-2"); !errors.Is(err, ErrReplicaReleaseUnknown) || r.b.startCount() != 1 {
+ t.Fatalf("fresh ID without a retry request: %v", err)
+ }
+ s.mu.Lock()
+ s.d.RetryOf = s.d.ID
+ s.mu.Unlock()
if err := r.a.PrepareStatelessRelease(context.Background(), r.rt, r.id, "deploy-2"); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index e294ba2e7..831f54d22 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -1132,6 +1132,17 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) {
return deployScopeAllows(p, pp, channel, req.Hotfix)
}
}
+ if req.Retry {
+ // A replicated release retry is durable before the pointer moves (R1).
+ if err := s.requestReplicaRetries(ctx, acct.Sqid, app, channel, version); errors.Is(err, errReplicaSwapOpen) {
+ jsonError(w, http.StatusConflict, replicaDeploySwapOpen)
+ return
+ } else if err != nil {
+ log.Printf("console: api promote %s %s -> %s: replica retry: %v", app, version, channel, err)
+ jsonError(w, http.StatusBadGateway, apiRetryStore)
+ return
+ }
+ }
res, err := signer.PromoteOnLadder(ctx, s.cfg.Releases, acct.Sqid, app, channel, version,
release.PromoteOptions{Actor: addr, Hotfix: hotfix, Retry: req.Retry, Authorize: authorize})
if err != nil {
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index f5d8162df..476508d38 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -272,6 +272,9 @@ type instanceListRecord struct {
// It is set only on the caller's own record and says nothing of the
// row that holds the host. Absent otherwise.
RouteHeld string `json:"route_held,omitempty"`
+ // DeployStatus is replicaDeployStatus: the release and box-by-box swap
+ // state of a record with a copy assignment. Absent otherwise.
+ DeployStatus string `json:"deploy_status,omitempty"`
}
// hubRouting is the console box's registry as its edge routes it: the rows
@@ -1338,7 +1341,8 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) {
RegionName: regionlabel.ForRecord(rec, home, names).Text,
MovePhrase: regionlabel.MovePhrase(rec, home, names),
Egress: join.egressFor(rec.Host, acct.Sqid, app),
- RouteHeld: forwardHeldReason(held, rec)})
+ RouteHeld: forwardHeldReason(held, rec),
+ DeployStatus: replicaDeployStatus(rec)})
}
total := len(matched)
// provision.ListRecords returns records host-sorted and nothing above
diff --git a/internal/console/apiretry.go b/internal/console/apiretry.go
index 9871bde72..60e34a549 100644
--- a/internal/console/apiretry.go
+++ b/internal/console/apiretry.go
@@ -116,6 +116,11 @@ func (s *Server) requestHostRetry(ctx context.Context, acct, app, host string, h
if s.cfg.Key == nil {
return release.RestartRequest{}, errRetryNoKey
}
+ // A replicated release retry is durable on the record before any box is
+ // told (R1): the coordinator consumes it once, whatever its book says.
+ if err := s.requestReplicaRetry(ctx, acct, app, host, held.build); err != nil {
+ return release.RestartRequest{}, err
+ }
signed, err := release.SignHostRetry(release.RootSigner(s.cfg.Key), acct, app, host, held.build, held.book, held.epoch, time.Now())
if err != nil {
return release.RestartRequest{}, err
@@ -185,6 +190,10 @@ func (s *Server) handleAPIInstanceRetry(w http.ResponseWriter, r *http.Request)
}
build := held.build
rr, err := s.requestHostRetry(ctx, acct.Sqid, app, host, held)
+ if errors.Is(err, errReplicaSwapOpen) {
+ jsonError(w, http.StatusConflict, replicaDeploySwapOpen)
+ return
+ }
if err != nil {
log.Printf("console: api instance retry %s/%s/%s: %v", acct.Sqid, app, host, err)
jsonError(w, http.StatusBadGateway, apiRetryStore)
diff --git a/internal/console/browserretry.go b/internal/console/browserretry.go
index 24ce45c06..d4d6c1106 100644
--- a/internal/console/browserretry.go
+++ b/internal/console/browserretry.go
@@ -98,7 +98,10 @@ func (s *Server) handleInstanceRetry(w http.ResponseWriter, r *http.Request) {
flash("err", swapCopy.RetryLimited)
return
}
- if _, err := s.requestHostRetry(ctx, acct.Sqid, app, host, held); err != nil {
+ if _, err := s.requestHostRetry(ctx, acct.Sqid, app, host, held); errors.Is(err, errReplicaSwapOpen) {
+ flash("err", replicaDeploySwapOpen)
+ return
+ } else if err != nil {
log.Printf("console: browser retry %s/%s/%s: %v", acct.Sqid, app, host, err)
flash("err", swapCopy.RetryFailed)
return
diff --git a/internal/console/pendinghandlers.go b/internal/console/pendinghandlers.go
index c15250950..453499fcd 100644
--- a/internal/console/pendinghandlers.go
+++ b/internal/console/pendinghandlers.go
@@ -570,6 +570,15 @@ func (s *Server) executePendingPromote(ctx context.Context, acct *Account, app,
if ref := s.copiesPublicationRefusal(ctx, acct, app, nil, p.Version, false); ref != nil {
return "", &statelessSelectionError{ref}
}
+ if p.Retry {
+ // A replicated release retry is durable before the pointer moves (R1).
+ if err := s.requestReplicaRetries(ctx, acct.Sqid, app, p.Channel, p.Version); errors.Is(err, errReplicaSwapOpen) {
+ return "", err
+ } else if err != nil {
+ log.Printf("console: execute promote %s %s -> %s: replica retry: %v", app, p.Version, p.Channel, err)
+ return "", errors.New(apiRetryStore)
+ }
+ }
res, err := release.PromoteOnLadder(ctx, s.cfg.Releases, s.cfg.Key, acct.Sqid, app, p.Channel, p.Version,
release.PromoteOptions{Actor: actor, Hotfix: p.Hotfix, Retry: p.Retry})
if err != nil {
diff --git a/internal/console/replicacoordinator.go b/internal/console/replicacoordinator.go
index 53756d49c..170a29596 100644
--- a/internal/console/replicacoordinator.go
+++ b/internal/console/replicacoordinator.go
@@ -185,7 +185,9 @@ func (s *Server) handleReplicaRelease(w http.ResponseWriter, r *http.Request) {
if current.Coordinator == nil || current.Coordinator.Box != box || current.Coordinator.Term != req.Term {
return replicas.ErrFenced
}
- next := replicas.Deploy{ID: req.ID, Incarnation: req.Incarnation, Term: req.Term, Target: req.Target, Phase: req.Op}
+ // The writer derives LastGood and carries RetryOf; a begin may only
+ // name the retry it consumes.
+ next := replicas.Deploy{ID: req.ID, Incarnation: req.Incarnation, Term: req.Term, Target: req.Target, Phase: req.Op, RetryOf: req.RetryOf}
if next.Phase == "begin" {
next.Phase = "pending"
}
diff --git a/internal/console/replicacoordinator_test.go b/internal/console/replicacoordinator_test.go
index beabddf68..1c7f1db1d 100644
--- a/internal/console/replicacoordinator_test.go
+++ b/internal/console/replicacoordinator_test.go
@@ -57,7 +57,7 @@ func replicaPost(t *testing.T, fx *interactiveFx, path, name, token string, payl
func TestReplicaCoordinatorFleetIsolation(t *testing.T) {
fx, token, inc := replicaAPIFixture(t)
base := "/api/fleet/replicas/" + fx.acct + "/shop/" + ixHost
- for _, door := range []string{"coordinator", "release"} {
+ for _, door := range []string{"coordinator", "release", "deploy"} {
for _, tc := range []struct{ name, path, identity, token, extra string }{
{"other fleet", base, "away/a1", token, ""},
{"other account", strings.Replace(base, fx.acct, "baj", 1), "home/b1", token, ""},
@@ -74,6 +74,9 @@ func TestReplicaCoordinatorFleetIsolation(t *testing.T) {
if door == "release" {
p = map[string]any{"incarnation": inc, "op": "begin"}
}
+ if door == "deploy" {
+ p = map[string]any{"incarnation": inc, "op": "order"}
+ }
if tc.extra != "" {
p[tc.extra] = "spoofed"
}
@@ -190,7 +193,7 @@ func TestReplicaCoordinatorRevocationAndOwnerIsolation(t *testing.T) {
t.Fatal(err)
}
}
- for _, door := range []string{"coordinator", "release"} {
+ for _, door := range []string{"coordinator", "release", "deploy"} {
code, raw := replicaPost(t, fx, "/api/fleet/replicas/"+fx.acct+"/shop/"+ixHost+"/"+door, "home/b1", token, map[string]any{"op": "acquire"})
if code != 404 || string(raw) != "404 page not found\n" {
t.Fatalf("%s %d %q", door, code, raw)
diff --git a/internal/console/replicadeploy.go b/internal/console/replicadeploy.go
new file mode 100644
index 000000000..b3bda6ca4
--- /dev/null
+++ b/internal/console/replicadeploy.go
@@ -0,0 +1,231 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "slices"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// Deploy status and refusal text for a replicated deploy (stateless
+// replicas Plan 4). Every string is a pending row of the series copy deck.
+const (
+ // copy SR-4-C35 (provisional)
+ replicaDeployPending = "release pending"
+ // copy SR-4-C36 (provisional)
+ replicaDeployReleasing = "release running"
+ // copy SR-4-C38 (provisional)
+ replicaDeployUnknown = "release result unknown"
+ // copy SR-4-C15 (provisional)
+ replicaDeployFailed = "the release command failed, so no copy switched to the new build"
+ // copy SR-4-C18 (provisional)
+ replicaDeploySwapping = "release complete; copies are switching one box at a time"
+ // copy SR-4-C39 (provisional)
+ replicaDeployBootstrap = "release complete; no copy was running, so the first copy is starting on its own"
+ // copy SR-4-C17 (provisional)
+ replicaDeploySwitching = "switching %s to %s"
+ // copy SR-4-C16 (provisional)
+ replicaDeployHalted = "this copy's switch has not been confirmed. other copies keep serving and the deploy is stopped"
+ // copy SR-4-C37 (provisional)
+ replicaDeployDone = "deploy complete"
+ // copy SR-4-C31 (provisional)
+ replicaDeploySwapOpen = "another deploy is still finishing a copy's switch. wait for it to finish before deploying again"
+)
+
+// errReplicaSwapOpen refuses an explicit retry while a copy's switch is
+// unresolved: the new attempt could not start until its box answers.
+var errReplicaSwapOpen = errors.New(replicaDeploySwapOpen)
+
+// replicaDeployStatus is the one-line deploy state of a record with a copy
+// assignment, or "" for a record whose deploys do not switch box by box.
+func replicaDeployStatus(rec provision.Record) string {
+ d := rec.ReplicaDeploy
+ if rec.ReplicaAssignment == nil || d == nil {
+ return ""
+ }
+ switch d.Phase {
+ case "pending":
+ return replicaDeployPending
+ case "releasing":
+ return replicaDeployReleasing
+ case "unknown":
+ return replicaDeployUnknown
+ case "failed":
+ return replicaDeployFailed
+ case "done":
+ return replicaDeployDone
+ case "released":
+ switch {
+ case d.Swap.Halted:
+ return replicaDeployHalted
+ case d.Swap.ActiveBox != "":
+ return fmt.Sprintf(replicaDeploySwitching, d.Swap.ActiveBox, d.Target.Version)
+ case d.Swap.Bootstrap:
+ return replicaDeployBootstrap
+ }
+ return replicaDeploySwapping
+ }
+ return ""
+}
+
+// handleReplicaDeploy is POST /api/fleet/replicas/{account}/{app}/{host}/deploy:
+// the swap transitions after a passed release. It authenticates the box as
+// handleReplicaRelease does, then writes one typed transition under the
+// record lock. Coordinator ops need the box's live term; an ack is
+// authenticated as the permit's box by the writer. Only boxes at
+// StatelessReplicasFloor call it; /release stays for copies=1.
+func (s *Server) handleReplicaDeploy(w http.ResponseWriter, r *http.Request) {
+ rec, box, _, ok := s.replicaFleetRecord(r)
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ var req struct {
+ Incarnation string `json:"incarnation"`
+ replicas.DeployChange
+ }
+ // The order comes from the console's roster, never from the payload.
+ if !replicaPayload(r, &req) || (req.Box != "" && req.Box != box) || len(req.Order) != 0 || req.Bootstrap {
+ http.NotFound(w, r)
+ return
+ }
+ req.Box = box
+ id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: req.Incarnation}
+ var result *provision.Record
+ unauthorized := false
+ changed := false
+ err := s.withRecordLock(id.Account, id.App, func() error {
+ current, _, proof, ok := s.replicaFleetRecord(r)
+ if !ok {
+ unauthorized = true
+ return replicas.ErrFenced
+ }
+ change := req.DeployChange
+ if change.Op != "ack" && (current.Coordinator == nil || current.Coordinator.Box != box || current.Coordinator.Term != change.Term) {
+ return replicas.ErrFenced
+ }
+ if change.Op == "order" {
+ var err error
+ if change.Order, change.Bootstrap, err = s.replicaDeployOrder(*current, box); err != nil {
+ return err
+ }
+ }
+ var err error
+ result, err = provision.SetRecordReplicaDeploy(r.Context(), s.cfg.Releases, id, change.Revision, change, time.Now(), proof...)
+ if err == nil {
+ changed = result.RecordSeq != current.RecordSeq
+ }
+ return err
+ })
+ if unauthorized {
+ http.NotFound(w, r)
+ return
+ }
+ if err != nil {
+ status := http.StatusServiceUnavailable
+ if errors.Is(err, replicas.ErrFenced) || errors.Is(err, replicas.ErrInvalid) {
+ status = http.StatusConflict
+ }
+ jsonError(w, status, replicaReleaseChanged)
+ return
+ }
+ if changed {
+ s.bumpSerial(r.Context())
+ }
+ writeJSON(w, http.StatusOK, result.ReplicaDeploy)
+}
+
+// replicaDeployOrder is the swap order: the record's assigned boxes that
+// the fleet roster lists as active, in label order, which leaves out boxes
+// already down and keeps the coordinator in its normal place. With none
+// active the coordinator's own copy starts first, alone, as a bootstrap.
+func (s *Server) replicaDeployOrder(rec provision.Record, coordinator string) ([]string, bool, error) {
+ a := rec.ReplicaAssignment
+ fleet, ok := registry.FleetPlacement(rec.Region)
+ if a == nil || !ok {
+ return nil, false, replicas.ErrFenced
+ }
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ return nil, false, err
+ }
+ boxes, err := reg.ListFleetBoxes(fleet)
+ if err != nil {
+ return nil, false, err
+ }
+ var order []string
+ for _, b := range boxes {
+ if b.Status == "active" && a.Contains(b.Label) {
+ order = append(order, b.Label)
+ }
+ }
+ slices.Sort(order)
+ order = slices.Compact(order)
+ if len(order) == 0 {
+ if !a.Contains(coordinator) {
+ return nil, false, replicas.ErrFenced
+ }
+ return []string{coordinator}, true, nil
+ }
+ return order, false, nil
+}
+
+// requestReplicaRetryLocked durably asks for one explicit retry of rec's
+// replicated release attempt for build (R1): the coordinator consumes it
+// once by starting a new attempt. A record with nothing to retry is left
+// alone. The caller holds the app lock.
+func (s *Server) requestReplicaRetryLocked(ctx context.Context, rec provision.Record, build string) error {
+ d := rec.ReplicaDeploy
+ if d == nil || d.Target.Version != build {
+ return nil
+ }
+ if d.PermitOutstanding() {
+ return errReplicaSwapOpen
+ }
+ if !replicas.Retryable(d) || replicas.RetryRequested(d) {
+ return nil
+ }
+ inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ return err
+ }
+ id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}
+ _, err = provision.RequestRecordReplicaRetry(ctx, s.cfg.Releases, id, d.ID)
+ return err
+}
+
+// requestReplicaRetry is requestReplicaRetryLocked for one host, under the
+// record lock: `carlos instances retry` and the instance page's Retry.
+func (s *Server) requestReplicaRetry(ctx context.Context, acct, app, host, build string) error {
+ return s.withRecordLock(acct, app, func() error {
+ rec, _, err := s.readRecord(ctx, acct, app, host)
+ if err != nil {
+ return err
+ }
+ return s.requestReplicaRetryLocked(ctx, *rec, build)
+ })
+}
+
+// requestReplicaRetries is requestReplicaRetryLocked for every instance
+// on channel: `carlos promote --retry`. The caller holds the app lock.
+func (s *Server) requestReplicaRetries(ctx context.Context, acct, app, channel, build string) error {
+ recs, _, err := s.listRecords(ctx, acct, app, instanceListMax)
+ if err != nil {
+ return err
+ }
+ for _, rec := range recs {
+ if rec.Channel != channel || rec.Pin != "" {
+ continue
+ }
+ if err := s.requestReplicaRetryLocked(ctx, rec, build); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/console/replicadeploy_test.go b/internal/console/replicadeploy_test.go
new file mode 100644
index 000000000..f4305d126
--- /dev/null
+++ b/internal/console/replicadeploy_test.go
@@ -0,0 +1,303 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// replicaDeployFixture is the fleet API fixture with shop's record assigned
+// to b1 and b2, both active, b1 coordinating, and deploy-1's release passed.
+func replicaDeployFixture(t *testing.T) (fx *interactiveFx, b1, b2, inc, term string) {
+ t.Helper()
+ fx = newIxFx(t, "replica-deploy")
+ b1, b2, _ = ixFleetWorld(t, fx, fx.acct)
+ rec, _ := ixRecord(t, fx, ixHost)
+ if err := provision.SetRecordFleetBox(context.Background(), fx.rel, fx.acct, "shop", ixHost, provision.FleetBoxExpect{Region: rec.Region, CreatedAt: rec.CreatedAt}, "b1", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetFleetBoxStatus("home", "b2", "active"); err != nil {
+ t.Fatal(err)
+ }
+ replaceRecord(t, fx, func(r *provision.Record) {
+ r.ReplicaAssignment = &replicas.Assignment{Revision: r.RecordSeq, Desired: 2, Boxes: []string{"b1", "b2"}}
+ })
+ base := "/api/fleet/replicas/" + fx.acct + "/shop/" + ixHost
+ code, raw := replicaPost(t, fx, base+"/coordinator", "home/b1", b1, map[string]any{"incarnation": inc, "op": "acquire", "boot_id": "boot"})
+ if code != 200 {
+ t.Fatalf("acquire %d %s", code, raw)
+ }
+ var reply replicas.CoordinatorReply
+ if err := json.Unmarshal(raw, &reply); err != nil {
+ t.Fatal(err)
+ }
+ term = reply.Lease.Term
+ var d replicas.Deploy
+ for _, op := range []string{"begin", "releasing", "released"} {
+ code, raw = replicaPost(t, fx, base+"/release", "home/b1", b1, map[string]any{"incarnation": inc, "op": op, "id": "deploy-1", "term": term, "revision": d.Revision, "target": replicas.Build{Version: "v1", Digest: "digest"}})
+ if code != 200 {
+ t.Fatalf("%s %d %s", op, code, raw)
+ }
+ if err := json.Unmarshal(raw, &d); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return fx, b1, b2, inc, term
+}
+
+func replaceRecord(t *testing.T, fx *interactiveFx, f func(*provision.Record)) {
+ t.Helper()
+ key := provision.RecordKey(fx.acct, "shop", ixHost)
+ raw, etag, err := fx.rel.Get(context.Background(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var rec provision.Record
+ if err := json.Unmarshal(raw, &rec); err != nil {
+ t.Fatal(err)
+ }
+ f(&rec)
+ raw, err = json.Marshal(rec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.rel.Put(context.Background(), key, raw, etag); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestReplicaDeployFleetAPIConsole: POST .../deploy carries the swap. The
+// console orders the active assigned boxes itself, the coordinator grants
+// one permit at a time under its term, only the permit's box acknowledges
+// it, and the deploy closes once every ordered box switched.
+func TestReplicaDeployFleetAPIConsole(t *testing.T) {
+ fx, b1, b2, inc, term := replicaDeployFixture(t)
+ base := "/api/fleet/replicas/" + fx.acct + "/shop/" + ixHost + "/deploy"
+ var d replicas.Deploy
+ post := func(identity, token string, p map[string]any) (int, []byte) {
+ p["incarnation"], p["id"], p["target"] = inc, "deploy-1", replicas.Build{Version: "v1", Digest: "digest"}
+ if _, ok := p["revision"]; !ok {
+ p["revision"] = d.Revision
+ }
+ code, raw := replicaPost(t, fx, base, identity, token, p)
+ if code == 200 {
+ d = replicas.Deploy{}
+ if err := json.Unmarshal(raw, &d); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return code, raw
+ }
+ rec, _ := ixRecord(t, fx, ixHost)
+ d = *rec.ReplicaDeploy
+ // The payload never chooses the order, and the box is its tunnel identity.
+ for _, spoof := range []map[string]any{
+ {"op": "order", "term": term, "order": []string{"b2"}},
+ {"op": "order", "term": term, "bootstrap": true},
+ {"op": "order", "term": term, "box": "b2"},
+ } {
+ if code, raw := post("home/b1", b1, spoof); code != 404 {
+ t.Fatalf("spoofed order: %d %s", code, raw)
+ }
+ }
+ if code, raw := post("home/b2", b2, map[string]any{"op": "order", "term": term}); code != 409 {
+ t.Fatalf("non-coordinator ordered: %d %s", code, raw)
+ }
+ if code, raw := post("home/b1", b1, map[string]any{"op": "order", "term": term}); code != 200 || !slices.Equal(d.Swap.Order, []string{"b1", "b2"}) || d.Swap.Bootstrap {
+ t.Fatalf("order: %d %s", code, raw)
+ }
+ for _, box := range []struct{ label, token string }{{"b1", b1}, {"b2", b2}} {
+ if code, raw := post("home/b1", b1, map[string]any{"op": "permit", "term": term, "grant": box.label}); code != 200 || d.Swap.ActiveBox != box.label {
+ t.Fatalf("permit %s: %d %s", box.label, code, raw)
+ }
+ other := map[string]string{"b1": "b2", "b2": "b1"}[box.label]
+ otherToken := map[string]string{"b1": b2, "b2": b1}[box.label]
+ if code, _ := post("home/"+other, otherToken, map[string]any{"op": "ack", "permit": d.Swap.Permit, "switched": true}); code != 409 {
+ t.Fatalf("%s acked %s's permit", other, box.label)
+ }
+ if code, _ := post("home/"+box.label, box.token, map[string]any{"op": "ack", "permit": d.Swap.Permit - 1, "switched": true}); code != 409 {
+ t.Fatal("ack of another permit revision")
+ }
+ if code, _ := post("home/"+box.label, box.token, map[string]any{"op": "permit", "term": term, "grant": box.label}); code != 409 {
+ t.Fatal("a box granted itself a permit")
+ }
+ if code, raw := post("home/"+box.label, box.token, map[string]any{"op": "ack", "permit": d.Swap.Permit, "switched": true}); code != 200 || d.Swap.ActiveBox != "" {
+ t.Fatalf("ack %s: %d %s", box.label, code, raw)
+ }
+ }
+ if code, raw := post("home/b1", b1, map[string]any{"op": "done", "term": term}); code != 200 || d.Phase != "done" {
+ t.Fatalf("done: %d %s", code, raw)
+ }
+ got, _ := ixRecord(t, fx, ixHost)
+ if got.ReplicaDeploy.Phase != "done" || !slices.Equal(got.ReplicaDeploy.Swap.Completed, []string{"b1", "b2"}) {
+ t.Fatalf("record: %+v", got.ReplicaDeploy)
+ }
+ if replicaDeployStatus(got) != replicaDeployDone {
+ t.Fatalf("status %q", replicaDeployStatus(got))
+ }
+}
+
+// TestReplicaDeployOrderOmitsDownBoxes: a box the roster no longer lists as
+// active is left out of the order; with none active the coordinator's own
+// copy starts alone and is reported as a bootstrap.
+func TestReplicaDeployOrderOmitsDownBoxes(t *testing.T) {
+ fx, _, _, _, _ := replicaDeployFixture(t)
+ rec, _ := ixRecord(t, fx, ixHost)
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetFleetBoxStatus("home", "b2", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ order, bootstrap, err := fx.srv.replicaDeployOrder(rec, "b1")
+ if err != nil || bootstrap || !slices.Equal(order, []string{"b1"}) {
+ t.Fatalf("down box ordered: %v %t %v", order, bootstrap, err)
+ }
+ if err := reg.SetFleetBoxStatus("home", "b1", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ order, bootstrap, err = fx.srv.replicaDeployOrder(rec, "b1")
+ if err != nil || !bootstrap || !slices.Equal(order, []string{"b1"}) {
+ t.Fatalf("bootstrap: %v %t %v", order, bootstrap, err)
+ }
+ rec.ReplicaDeploy.Swap = replicas.Swap{Order: order, Bootstrap: true}
+ if replicaDeployStatus(rec) != replicaDeployBootstrap {
+ t.Fatal("bootstrap reported as a rolling deploy")
+ }
+}
+
+// TestReplicaReleaseOldBoxFreshIDRefusedConsole (R9 at the v0.34 door): a
+// box running Plans 1-3 code posts a plain begin with a fresh ID for the
+// unchanged target; after released, failed or unknown it is refused unless
+// the console recorded an explicit retry of that attempt.
+func TestReplicaReleaseOldBoxFreshIDRefusedConsole(t *testing.T) {
+ for _, end := range []string{"released", "failed", "unknown"} {
+ t.Run(end, func(t *testing.T) {
+ fx, token, inc := replicaAPIFixture(t)
+ base := "/api/fleet/replicas/" + fx.acct + "/shop/" + ixHost
+ code, raw := replicaPost(t, fx, base+"/coordinator", "home/b1", token, map[string]any{"incarnation": inc, "op": "acquire", "boot_id": "boot"})
+ if code != 200 {
+ t.Fatalf("%d %s", code, raw)
+ }
+ var reply replicas.CoordinatorReply
+ _ = json.Unmarshal(raw, &reply)
+ target := replicas.Build{Version: "v1", Digest: "digest"}
+ var d replicas.Deploy
+ for _, op := range []string{"begin", "releasing", end} {
+ code, raw = replicaPost(t, fx, base+"/release", "home/b1", token, map[string]any{"incarnation": inc, "op": op, "id": "deploy-1", "term": reply.Lease.Term, "revision": d.Revision, "target": target})
+ if code != 200 {
+ t.Fatalf("%s %d %s", op, code, raw)
+ }
+ _ = json.Unmarshal(raw, &d)
+ }
+ fresh := map[string]any{"incarnation": inc, "op": "begin", "id": "deploy-fresh", "term": reply.Lease.Term, "revision": d.Revision, "target": target}
+ if code, raw := replicaPost(t, fx, base+"/release", "home/b1", token, fresh); code != 409 {
+ t.Fatalf("old box started a second run: %d %s", code, raw)
+ }
+ rec, _ := ixRecord(t, fx, ixHost)
+ err := fx.srv.requestReplicaRetry(context.Background(), fx.acct, "shop", ixHost, "v1")
+ if end == "released" {
+ after, _ := ixRecord(t, fx, ixHost)
+ if err != nil || after.RecordSeq != rec.RecordSeq {
+ t.Fatalf("passed release retried: %v", err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec, _ = ixRecord(t, fx, ixHost)
+ fresh["revision"] = rec.ReplicaDeploy.Revision
+ if code, _ := replicaPost(t, fx, base+"/release", "home/b1", token, fresh); code != 409 {
+ t.Fatal("a plain begin consumed the retry")
+ }
+ fresh["retry_of"] = "deploy-1"
+ if code, raw := replicaPost(t, fx, base+"/release", "home/b1", token, fresh); code != 200 {
+ t.Fatalf("retry begin: %d %s", code, raw)
+ }
+ })
+ }
+}
+
+// TestReplicaRetryRefusedWhileSwitchOpen: an explicit retry, host or
+// app-wide, is refused with SR-4-C31 while a copy's switch is unresolved,
+// and writes nothing.
+func TestReplicaRetryRefusedWhileSwitchOpen(t *testing.T) {
+ fx, _, _, _, _ := replicaDeployFixture(t)
+ replaceRecord(t, fx, func(r *provision.Record) {
+ r.ReplicaDeploy.Swap = replicas.Swap{Order: []string{"b1", "b2"}, ActiveBox: "b2", Permit: r.ReplicaDeploy.Revision, Halted: true}
+ })
+ before, raw := ixRecord(t, fx, ixHost)
+ err := fx.srv.requestReplicaRetry(context.Background(), fx.acct, "shop", ixHost, "v1")
+ if !errors.Is(err, errReplicaSwapOpen) || err.Error() != replicaDeploySwapOpen {
+ t.Fatalf("host retry: %v", err)
+ }
+ unlock := fx.srv.lockApp(fx.acct, "shop")
+ err = fx.srv.requestReplicaRetries(context.Background(), fx.acct, "shop", before.Channel, "v1")
+ unlock()
+ if !errors.Is(err, errReplicaSwapOpen) {
+ t.Fatalf("promote retry: %v", err)
+ }
+ if _, after := ixRecord(t, fx, ixHost); string(after) != string(raw) {
+ t.Fatal("refused retry wrote")
+ }
+ if !strings.Contains(replicaDeployStatus(before), "not been confirmed") {
+ t.Fatalf("halted status %q", replicaDeployStatus(before))
+ }
+}
+
+// TestReplicaDeployWritesHoldTheAppLock is the API lock witness for the
+// two new console record writers: every record write the swap door and the
+// retry request make lands while the writing goroutine holds the app lock.
+func TestReplicaDeployWritesHoldTheAppLock(t *testing.T) {
+ fx, b1, _, inc, term := replicaDeployFixture(t)
+ ds, ok := fx.rel.(*deletableStore)
+ if !ok {
+ t.Fatalf("fixture store is %T", fx.rel)
+ }
+ key := provision.RecordKey(fx.acct, "shop", ixHost)
+ var writes, unlocked atomic.Int32
+ w := func(k string, _, _ []byte) {
+ if k != key {
+ return
+ }
+ if _, console := consoleCaller(); !console {
+ return
+ }
+ writes.Add(1)
+ if !fx.srv.appLocks.held(fx.acct+"/shop") || !stackHoldsAppLock(t) {
+ unlocked.Add(1)
+ }
+ }
+ ds.putWitness.Store(&w)
+ defer ds.putWitness.Store(nil)
+ rec, _ := ixRecord(t, fx, ixHost)
+ code, raw := replicaPost(t, fx, "/api/fleet/replicas/"+fx.acct+"/shop/"+ixHost+"/deploy", "home/b1", b1, map[string]any{"incarnation": inc, "op": "order", "id": "deploy-1", "term": term, "revision": rec.ReplicaDeploy.Revision, "target": replicas.Build{Version: "v1", Digest: "digest"}})
+ if code != 200 {
+ t.Fatalf("order: %d %s", code, raw)
+ }
+ replaceRecord(t, fx, func(r *provision.Record) { r.ReplicaDeploy.Phase = "failed"; r.ReplicaDeploy.Swap = replicas.Swap{} })
+ if err := fx.srv.requestReplicaRetry(context.Background(), fx.acct, "shop", ixHost, "v1"); err != nil {
+ t.Fatal(err)
+ }
+ if writes.Load() != 2 || unlocked.Load() != 0 {
+ t.Fatalf("writes %d, without the app lock %d", writes.Load(), unlocked.Load())
+ }
+}
diff --git a/internal/console/replicaplacement.go b/internal/console/replicaplacement.go
index 8b308492d..899548a83 100644
--- a/internal/console/replicaplacement.go
+++ b/internal/console/replicaplacement.go
@@ -198,7 +198,7 @@ func (s *Server) replicaAction(rec provision.Record, v fleetView, n int) (replic
if _, err := provision.WithReplicaAssignmentManifest(context.Background(), rec, v.ReplicaManifests[replicaRecordKey(rec)]); err != nil {
return replicaPlacementAction{}, err
}
- if provision.ReplicaSwapActive(&rec) {
+ if provision.ReplicaSwapFrozen(&rec) {
if rec.ReplicaAssignment == nil || !replicaMemberLost(rec, v) {
return replicaPlacementAction{}, nil
}
@@ -288,7 +288,7 @@ func replicaMayChange(rec provision.Record, v fleetView, old replicaPlacementObs
if a == nil {
return false
}
- if provision.ReplicaSwapActive(&rec) {
+ if provision.ReplicaSwapFrozen(&rec) {
return replicaMemberLost(rec, v)
}
if a.Desired != old.desired {
diff --git a/internal/console/replicaplacement_fix_test.go b/internal/console/replicaplacement_fix_test.go
index 41790a704..d9813da98 100644
--- a/internal/console/replicaplacement_fix_test.go
+++ b/internal/console/replicaplacement_fix_test.go
@@ -165,7 +165,7 @@ func TestReplicaHaltDoesNotProjectUnwrittenLoad(t *testing.T) {
copiesBeat(t, fx, "pi-3", release.StatelessReplicasFloor, time.Now())
placementEdit(t, fx, "a.example.com", func(rec *provision.Record) {
inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
- rec.ReplicaDeploy = &replicas.Deploy{ID: "swap", Phase: "swapping", ActiveBox: "pi-2", Incarnation: inc, Revision: 1}
+ rec.ReplicaDeploy = &replicas.Deploy{ID: "swap", Phase: "released", Swap: replicas.Swap{Order: []string{"pi-1", "pi-2"}, Completed: []string{"pi-1"}, ActiveBox: "pi-2", Permit: 1}, Incarnation: inc, Revision: 1}
})
copiesBeat(t, fx, "pi-2", release.StatelessReplicasFloor, time.Now().Add(-time.Hour))
v, err := fx.srv.loadFleetView(context.Background(), "pi")
@@ -186,7 +186,7 @@ func TestReplicaHaltDoesNotProjectUnwrittenLoad(t *testing.T) {
if !reflect.DeepEqual(actual, v.Load) {
t.Fatalf("halt charged an unwritten assignment: %v actual %v", v.Load, actual)
}
- if shopRec(t, fx, "a.example.com").ReplicaDeploy.Phase != "unknown" {
+ if d := shopRec(t, fx, "a.example.com").ReplicaDeploy; !d.Swap.Halted || d.Phase != "released" || d.Swap.ActiveBox != "pi-2" {
t.Fatal("loss did not halt")
}
}
@@ -195,10 +195,10 @@ func TestReplicaLegacyActiveSwapDoesNotCreateSet(t *testing.T) {
fx, _, _ := replicaPlacementWorld(t)
placementEdit(t, fx, "a.example.com", func(rec *provision.Record) {
inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
- rec.ReplicaDeploy = &replicas.Deploy{ID: "swap", Phase: "swapping", ActiveBox: "pi-1", Incarnation: inc, Revision: 1}
+ rec.ReplicaDeploy = &replicas.Deploy{ID: "swap", Phase: "released", Swap: replicas.Swap{Order: []string{"pi-1"}, ActiveBox: "pi-1", Permit: 1}, Incarnation: inc, Revision: 1}
})
relabelPass(t, fx)
- if rec := shopRec(t, fx, "a.example.com"); rec.ReplicaAssignment != nil || rec.ReplicaDeploy.Phase != "swapping" {
+ if rec := shopRec(t, fx, "a.example.com"); rec.ReplicaAssignment != nil || rec.ReplicaDeploy.Swap.ActiveBox != "pi-1" || rec.ReplicaDeploy.Swap.Halted {
t.Fatalf("legacy swap changed: %+v", rec)
}
}
diff --git a/internal/console/replicaplacement_test.go b/internal/console/replicaplacement_test.go
index 0754df905..588510827 100644
--- a/internal/console/replicaplacement_test.go
+++ b/internal/console/replicaplacement_test.go
@@ -499,7 +499,7 @@ func TestReplicaSwapFreezeAndLossHalt(t *testing.T) {
relabelPass(t, fx)
placementEdit(t, fx, "a.example.com", func(rec *provision.Record) {
inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
- rec.ReplicaDeploy = &replicas.Deploy{ID: "swap", Incarnation: inc, Phase: "swapping", ActiveBox: "pi-1", Revision: 1}
+ rec.ReplicaDeploy = &replicas.Deploy{ID: "swap", Incarnation: inc, Phase: "released", Swap: replicas.Swap{Order: []string{"pi-1", "pi-2"}, ActiveBox: "pi-1", Permit: 1}, Revision: 1}
})
before := shopRec(t, fx, "a.example.com")
if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 {
@@ -507,7 +507,7 @@ func TestReplicaSwapFreezeAndLossHalt(t *testing.T) {
}
relabelPass(t, fx)
got := shopRec(t, fx, before.Host)
- if got.ReplicaDeploy.Phase != "swapping" || !reflect.DeepEqual(got.ReplicaAssignment, before.ReplicaAssignment) {
+ if got.ReplicaDeploy.Swap.Halted || got.ReplicaDeploy.Swap.ActiveBox != "pi-1" || !reflect.DeepEqual(got.ReplicaAssignment, before.ReplicaAssignment) {
t.Fatal("active swap changed membership or halted without loss")
}
if _, err := reg.SetFleetBoxDraining("pi", "pi-1", time.Now().UnixNano()); err != nil {
@@ -515,13 +515,13 @@ func TestReplicaSwapFreezeAndLossHalt(t *testing.T) {
}
relabelPass(t, fx)
got = shopRec(t, fx, before.Host)
- if got.ReplicaDeploy.Phase != "swapping" || !reflect.DeepEqual(got.ReplicaAssignment, before.ReplicaAssignment) {
+ if got.ReplicaDeploy.Swap.Halted || got.ReplicaDeploy.Swap.ActiveBox != "pi-1" || !reflect.DeepEqual(got.ReplicaAssignment, before.ReplicaAssignment) {
t.Fatal("drain interrupted active swap")
}
copiesBeat(t, fx, "pi-1", release.StatelessReplicasFloor, time.Now().Add(-time.Hour))
relabelPass(t, fx)
got = shopRec(t, fx, before.Host)
- if got.ReplicaDeploy.Phase != "unknown" || !reflect.DeepEqual(got.ReplicaAssignment, before.ReplicaAssignment) {
+ if !got.ReplicaDeploy.Swap.Halted || got.ReplicaDeploy.Phase != "released" || got.ReplicaDeploy.Swap.ActiveBox != "pi-1" || !reflect.DeepEqual(got.ReplicaAssignment, before.ReplicaAssignment) {
t.Fatalf("loss did not halt first: %+v", got)
}
relabelPass(t, fx)
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index c7eb06a09..b407d4620 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -420,6 +420,7 @@ var routeDecls = []routeDecl{
// TestEveryCLIDoorNamesItsRoles.
{Pattern: "POST /api/fleet/replicas/{account}/{app}/{host}/coordinator", Handler: (*Server).handleReplicaCoordinator},
{Pattern: "POST /api/fleet/replicas/{account}/{app}/{host}/release", Handler: (*Server).handleReplicaRelease},
+ {Pattern: "POST /api/fleet/replicas/{account}/{app}/{host}/deploy", Handler: (*Server).handleReplicaDeploy},
{Pattern: "POST /auth/cli/start", Handler: (*Server).handleCLIStart},
{Pattern: "POST /auth/cli/poll", Handler: (*Server).handleCLIPoll},
{Pattern: "GET /auth/cli", Handler: (*Server).handleCLIApprovePage},
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 0953b729d..c5e3ed4c1 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -776,6 +776,12 @@ func runAgent(args []string, buildClaims ClaimFactory) {
replicaWorker := newReplicaPlacementWorker(agentCtx, reg, svc, eb, publisher, os.Getenv("CARLOS_TUNNEL_URL"), os.Getenv("CARLOS_TUNNEL_TOKEN"), dd)
armedReplicaPlacement.Store(replicaWorker)
defer func() { armedReplicaPlacement.Store(nil); replicaWorker.close() }()
+ // The swap worker reads the same reconcile observations and
+ // 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)
+ armedReplicaDeploy.Store(deployWorker)
+ defer func() { armedReplicaDeploy.Store(nil); deployWorker.close() }()
defer armedStatelessBindings.Store(nil)
}
}
@@ -3235,6 +3241,9 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) {
if worker := armedReplicaPlacement.Load(); worker != nil {
worker.tick()
}
+ if worker := armedReplicaDeploy.Load(); worker != nil {
+ worker.tick()
+ }
if d.coordinator != nil {
d.coordinator.SignalTick()
}
@@ -3991,8 +4000,18 @@ func BoxProvisionConfig(reg *registry.Registry, getenv func(string) string, judg
// The process's one lifetime index, which the activator reads before
// every wake of a provisioned instance (region HA P1a).
cfg.Lifetimes = boxLifetimes
- if worker := armedReplicaPlacement.Load(); worker != nil {
- cfg.ReplicaObserved = worker.observe
+ // One reconcile observation fans out to the placement worker and the
+ // swap worker (R7); neither reads the store on its own.
+ 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)
+ }
+ }
}
if publisher := armedStatelessBindings.Load(); publisher != nil {
cfg.StatelessBinding = publisher.publish
diff --git a/internal/host/replicacoordinator.go b/internal/host/replicacoordinator.go
index a8fefe31d..990c18e88 100644
--- a/internal/host/replicacoordinator.go
+++ b/internal/host/replicacoordinator.go
@@ -51,7 +51,7 @@ func (s *replicaCoordinatorStore) releaseState(ctx context.Context, id replicas.
if err != nil {
return err
}
- next := replicas.Deploy{ID: change.ID, Incarnation: id.Incarnation, Term: change.Term, Target: change.Target, Phase: change.Op}
+ next := replicas.Deploy{ID: change.ID, Incarnation: id.Incarnation, Term: change.Term, Target: change.Target, Phase: change.Op, RetryOf: change.RetryOf}
if next.Phase == "begin" {
next.Phase = "pending"
}
diff --git a/internal/host/replicadeploy.go b/internal/host/replicadeploy.go
new file mode 100644
index 000000000..6c4a39353
--- /dev/null
+++ b/internal/host/replicadeploy.go
@@ -0,0 +1,194 @@
+package host
+
+import (
+ "context"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// replicaDeployClient reports one swap transition through the console's
+// authenticated fleet transport (POST .../deploy). The console writes the
+// record under its record lock; a box never writes the bucket for a swap.
+type replicaDeployClient interface {
+ Transition(context.Context, replicas.Identity, replicas.DeployChange) (replicas.Deploy, error)
+}
+
+// Transition is the fleet adapter of replicaDeployClient.
+func (a *replicaCoordinatorAPI) Transition(ctx context.Context, id replicas.Identity, change replicas.DeployChange) (replicas.Deploy, error) {
+ var reply replicas.Deploy
+ err := a.post(ctx, id, "deploy", struct {
+ Incarnation string `json:"incarnation"`
+ replicas.DeployChange
+ }{id.Incarnation, change}, &reply)
+ return reply, err
+}
+
+// heldTerms is the part of the coordination client the worker reads: the
+// term this process holds for a lifetime, without a request.
+type heldTerms interface {
+ HeldTerm(replicas.Identity) string
+}
+
+type replicaDeployWork struct {
+ rec provision.Record
+ retry time.Time
+ delay time.Duration
+}
+
+// replicaDeployWorker drives the swap after a passed release from the
+// 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).
+type replicaDeployWorker struct {
+ mu sync.Mutex
+ client replicaDeployClient
+ box string
+ terms heldTerms
+ pending map[string]replicaDeployWork
+ busy bool
+ stopped bool
+ wg sync.WaitGroup
+ 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)
+}
+
+var armedReplicaDeploy atomic.Pointer[replicaDeployWorker]
+
+func newReplicaDeployWorker(client replicaDeployClient, box string, svc *activator.Service) *replicaDeployWorker {
+ ctx, cancel := context.WithCancel(context.Background())
+ w := &replicaDeployWorker{client: client, box: box, ctx: ctx, cancel: cancel, now: time.Now}
+ if svc != nil {
+ w.terms, _ = svc.Coordinator.(heldTerms)
+ }
+ return w
+}
+
+// Note keeps the newest observed record of each assigned host that has a
+// deploy. A record older than the one the worker already holds, for the
+// same lifetime, is ignored, so a reply the worker applied is not undone.
+func (w *replicaDeployWorker) Note(rec provision.Record) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ a, d := rec.ReplicaAssignment, rec.ReplicaDeploy
+ if a == nil || d == nil || !a.Contains(w.box) {
+ delete(w.pending, rec.Host)
+ return
+ }
+ if w.pending == nil {
+ w.pending = map[string]replicaDeployWork{}
+ }
+ old, ok := w.pending[rec.Host]
+ if ok && old.rec.CreatedAt.Equal(rec.CreatedAt) && old.rec.ReplicaDeploy.ID == d.ID && old.rec.ReplicaDeploy.Revision > d.Revision {
+ return
+ }
+ if !ok || old.rec.ReplicaDeploy.Revision != d.Revision || old.rec.ReplicaDeploy.ID != d.ID {
+ old.retry, old.delay = time.Time{}, 0
+ }
+ old.rec = rec
+ w.pending[rec.Host] = old
+}
+
+// tick starts one background Pass unless one is running; the fast tick
+// calls it and never waits on the console.
+func (w *replicaDeployWorker) tick() {
+ w.mu.Lock()
+ if w.stopped || w.busy || len(w.pending) == 0 {
+ w.mu.Unlock()
+ return
+ }
+ w.busy = true
+ w.wg.Add(1)
+ w.mu.Unlock()
+ go func() {
+ defer w.wg.Done()
+ defer func() { w.mu.Lock(); w.busy = false; w.mu.Unlock() }()
+ w.Pass(w.ctx)
+ }()
+}
+
+func (w *replicaDeployWorker) close() {
+ w.mu.Lock()
+ w.stopped = true
+ w.mu.Unlock()
+ w.cancel()
+ w.wg.Wait()
+}
+
+// replicaDeployStep is the coordinator's next transition for rec, decided
+// only from the durable record: a lost reply is reconciled by reading the
+// record again, never by repeating a step the record already shows.
+func replicaDeployStep(rec provision.Record, box, term string) (replicas.DeployChange, bool) {
+ d, a, c := rec.ReplicaDeploy, rec.ReplicaAssignment, rec.Coordinator
+ if d == nil || a == nil || c == nil || term == "" || c.Box != box || c.Term != term || d.Phase != "released" || d.Swap.Halted || d.Swap.ActiveBox != "" {
+ return replicas.DeployChange{}, false
+ }
+ change := replicas.DeployChange{ID: d.ID, Term: term, Box: box, Revision: d.Revision, Target: d.Target}
+ switch next := d.Swap.NextSwapBox(); {
+ case len(d.Swap.Order) == 0:
+ change.Op = "order"
+ case next != "":
+ change.Op, change.Grant = "permit", next
+ default:
+ change.Op = "done"
+ }
+ return change, true
+}
+
+// Pass runs at most one transition per noted host.
+func (w *replicaDeployWorker) Pass(ctx context.Context) {
+ now := w.now()
+ w.mu.Lock()
+ work := make([]replicaDeployWork, 0, len(w.pending))
+ for _, p := range w.pending {
+ if !now.Before(p.retry) {
+ work = append(work, p)
+ }
+ }
+ w.mu.Unlock()
+ 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 {
+ 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))
+ if !ok {
+ continue
+ }
+ rctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ next, err := w.client.Transition(rctx, id, change)
+ cancel()
+ w.mu.Lock()
+ current, ok := w.pending[rec.Host]
+ if ok && current.rec.CreatedAt.Equal(rec.CreatedAt) && current.rec.ReplicaDeploy.ID == d.ID && current.rec.ReplicaDeploy.Revision == d.Revision {
+ if err == nil && next.ID == d.ID && next.Revision == d.Revision+1 {
+ current.rec.ReplicaDeploy = &next
+ current.retry, current.delay = time.Time{}, 0
+ } else {
+ // Wait for the next observed record rather than repeat blind.
+ current.delay = min(max(current.delay*2, time.Second), time.Minute)
+ current.retry = now.Add(current.delay)
+ }
+ w.pending[rec.Host] = current
+ }
+ w.mu.Unlock()
+ }
+}
diff --git a/internal/host/replicadeploy_test.go b/internal/host/replicadeploy_test.go
new file mode 100644
index 000000000..30f135c49
--- /dev/null
+++ b/internal/host/replicadeploy_test.go
@@ -0,0 +1,252 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "path/filepath"
+ "slices"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// deployStoreWorld is one record assigned to boxes a and b, coordinated by
+// a, with deploy-2's release passed, behind the real typed swap writer.
+type deployStoreWorld struct {
+ t *testing.T
+ s release.Store
+ id replicas.Identity
+ term string
+}
+
+func newDeployStoreWorld(t *testing.T) *deployStoreWorld {
+ t.Helper()
+ ctx := provision.WithRecordSequence(context.Background())
+ s := release.NewDirStore(t.TempDir())
+ rec := provision.Record{Schema: 1, Account: "acme", App: "shop", Host: "shop.example.com", Slug: "shop", Channel: "edge", Region: "fleet/pi", Hibernate: new(bool), CreatedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)}
+ if err := provision.CreateRecord(ctx, s, rec); err != nil {
+ t.Fatal(err)
+ }
+ got, err := provision.GetRecord(ctx, s, rec.Account, rec.App, rec.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ inc, _ := provision.Incarnation(got.Account, got.App, got.Host, got.CreatedAt)
+ id := replicas.Identity{Account: got.Account, App: got.App, Host: got.Host, Incarnation: inc}
+ mctx, err := provision.WithReplicaAssignmentManifest(ctx, *got, &release.Manifest{Schema: 1, App: "shop", Version: "v2", Kind: "binary", Stateless: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.SetRecordReplicaAssignment(mctx, s, id, replicas.Expect{Incarnation: inc, Region: got.Region, RecordSeq: got.RecordSeq}, replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}}); err != nil {
+ t.Fatal(err)
+ }
+ r, err := provision.SetRecordCoordinator(ctx, s, id, replicas.CoordinatorChange{Op: "acquire", Box: "a", BootID: "boot"}, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := &deployStoreWorld{t: t, s: s, id: id, term: r.Coordinator.Term}
+ var revision uint64
+ for _, phase := range []string{"pending", "releasing", "released"} {
+ r, err = provision.SetRecordReplicaRelease(ctx, s, id, revision, replicas.Deploy{ID: "deploy-2", Incarnation: inc, Term: w.term, Target: replicas.Build{Version: "v2", Digest: "canonical-2"}, Phase: phase})
+ if err != nil {
+ t.Fatal(err)
+ }
+ revision = r.ReplicaDeploy.Revision
+ }
+ return w
+}
+
+func (w *deployStoreWorld) record() provision.Record {
+ w.t.Helper()
+ rec, err := provision.GetRecord(context.Background(), w.s, w.id.Account, w.id.App, w.id.Host)
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ return *rec
+}
+
+// deployStoreClient stands in for the console's /deploy: it orders the
+// assigned boxes and writes through the typed writer. lose drops the reply
+// of the next committed transition.
+type deployStoreClient struct {
+ w *deployStoreWorld
+ mu sync.Mutex
+ calls []replicas.DeployChange
+ lose bool
+}
+
+func (c *deployStoreClient) Transition(ctx context.Context, id replicas.Identity, change replicas.DeployChange) (replicas.Deploy, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.calls = append(c.calls, change)
+ if change.Op == "order" {
+ change.Order = slices.Clone(c.w.record().ReplicaAssignment.Boxes)
+ }
+ rec, err := provision.SetRecordReplicaDeploy(ctx, c.w.s, id, change.Revision, change, time.Now())
+ if err != nil {
+ return replicas.Deploy{}, err
+ }
+ if c.lose {
+ c.lose = false
+ return replicas.Deploy{}, replicas.ErrConsoleUnreachable
+ }
+ return *rec.ReplicaDeploy, nil
+}
+
+type fixedTerm string
+
+func (f fixedTerm) HeldTerm(replicas.Identity) string { return string(f) }
+
+func (w *deployStoreWorld) ack(box string) {
+ w.t.Helper()
+ d := w.record().ReplicaDeploy
+ if _, err := provision.SetRecordReplicaDeploy(context.Background(), w.s, w.id, d.Revision, replicas.DeployChange{Op: "ack", ID: d.ID, Box: box, Target: d.Target, Permit: d.Swap.Permit, Switched: true}, time.Now()); err != nil {
+ w.t.Fatal(err)
+ }
+}
+
+// TestReplicaDeployWorkerOrdersOnePermitAtATime: the coordinator's worker
+// orders the copies, grants one permit and waits for its ack before the
+// next, closes the deploy, and after a lost reply rereads the record rather
+// than repeating a step.
+func TestReplicaDeployWorkerOrdersOnePermitAtATime(t *testing.T) {
+ w := newDeployStoreWorld(t)
+ client := &deployStoreClient{w: w}
+ worker := newReplicaDeployWorker(client, "a", nil)
+ worker.terms = fixedTerm(w.term)
+ clock := time.Now()
+ worker.now = func() time.Time { return clock }
+ pass := func() {
+ worker.Note(w.record())
+ worker.Pass(context.Background())
+ }
+ pass()
+ if d := w.record().ReplicaDeploy; !slices.Equal(d.Swap.Order, []string{"a", "b"}) {
+ t.Fatalf("order: %+v", d.Swap)
+ }
+ // The coordinator is itself first in label order; its permit goes out.
+ client.lose = true
+ pass()
+ if d := w.record().ReplicaDeploy; d.Swap.ActiveBox != "a" {
+ t.Fatalf("permit: %+v", d.Swap)
+ }
+ // The lost reply is reconciled by the record, not by a second request.
+ calls := len(client.calls)
+ clock = clock.Add(time.Hour)
+ pass()
+ pass()
+ if len(client.calls) != calls {
+ t.Fatalf("a step repeated while its permit was open: %+v", client.calls[calls:])
+ }
+ w.ack("a")
+ pass()
+ if d := w.record().ReplicaDeploy; d.Swap.ActiveBox != "b" || !slices.Equal(d.Swap.Completed, []string{"a"}) {
+ t.Fatalf("second permit: %+v", d.Swap)
+ }
+ pass()
+ if d := w.record().ReplicaDeploy; d.Swap.ActiveBox != "b" {
+ t.Fatal("a second permit was granted before the ack")
+ }
+ w.ack("b")
+ pass()
+ if d := w.record().ReplicaDeploy; d.Phase != "done" {
+ t.Fatalf("done: %+v", d)
+ }
+ calls = len(client.calls)
+ pass()
+ if len(client.calls) != calls {
+ t.Fatal("a closed deploy kept moving")
+ }
+ // A box without the term moves nothing.
+ other := newReplicaDeployWorker(client, "b", nil)
+ other.terms = fixedTerm("")
+ other.Note(w.record())
+ other.Pass(context.Background())
+ if len(client.calls) != calls {
+ t.Fatal("a box without the term sent a transition")
+ }
+}
+
+// TestReplicaDeployPermitReachesWorkerThroughReconcile (R7): a permit that
+// lands while no launch attempt runs reaches the permit's box through the
+// production reconcile observation and the fast tick; the placement worker
+// keeps its own observation of the same record.
+func TestReplicaDeployPermitReachesWorkerThroughReconcile(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ acct := domains.Sqid(4242)
+ manifest, _ := json.Marshal(map[string]any{"id": 4242, "sqid": acct, "name": "shop", "created_at": time.Now().UTC()})
+ if _, err := s.Put(ctx, domains.AccountManifestKey(acct), manifest, ""); err != nil {
+ t.Fatal(err)
+ }
+ rec := provision.Record{Schema: 1, Account: acct, App: "shop", Host: "shop.example.com", Slug: "shop", Channel: "edge", Region: "fleet/pi", CreatedAt: time.Now().UTC(), RecordSeq: 3, Hibernate: new(bool),
+ ReplicaAssignment: &replicas.Assignment{Revision: 1, Desired: 2, Boxes: []string{"a", "b"}}}
+ inc, _ := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ rec.ReplicaDeploy = &replicas.Deploy{ID: "deploy-2", Incarnation: inc, Target: replicas.Build{Version: "v2", Digest: "canonical-2"}, Phase: "released", Swap: replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 7}, Revision: 7}
+ raw, _ := json.Marshal(rec)
+ if _, err := s.Put(ctx, provision.RecordKey(acct, rec.App, rec.Host), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ dd := t.TempDir()
+ getenv := func(k string) string {
+ switch k {
+ case "CARLOS_REGION":
+ return "fleet/pi"
+ case "CARLOS_FLEET":
+ return "pi"
+ case "CARLOS_FLEET_BOX":
+ return "b"
+ case "CARLOS_DATA_DIR":
+ return dd
+ }
+ return ""
+ }
+ permits := make(chan provision.Record, 4)
+ worker := newReplicaDeployWorker(&deployStoreClient{}, "b", nil)
+ worker.swap = func(_ context.Context, r provision.Record) { permits <- r }
+ pctx, pcancel := context.WithCancel(ctx)
+ placement := &replicaPlacementWorker{box: "b", ctx: pctx, cancel: pcancel, reg: reg}
+ armedReplicaDeploy.Store(worker)
+ armedReplicaPlacement.Store(placement)
+ defer func() {
+ armedReplicaDeploy.Store(nil)
+ armedReplicaPlacement.Store(nil)
+ worker.close()
+ placement.close()
+ }()
+ cfg := BoxProvisionConfig(reg, getenv, nil, nil)
+ cfg.Layout = flatLayout
+ if cfg.ReplicaObserved == nil {
+ t.Fatal("the reconcile pass does not report replica records")
+ }
+ if err := reconcileSerializedWith(ctx, s, reg, cfg, nil); err != nil {
+ t.Fatal(err)
+ }
+ placement.mu.Lock()
+ _, placed := placement.pending[rec.Host]
+ placement.mu.Unlock()
+ if !placed {
+ t.Fatal("placement worker lost its observation")
+ }
+ d := &fastDeps{reg: reg, store: s, fullPass: func(context.Context) {}}
+ fastTick(ctx, d, time.Now())
+ select {
+ case got := <-permits:
+ if got.ReplicaDeploy.Swap.ActiveBox != "b" || got.ReplicaDeploy.Swap.Permit != 7 {
+ t.Fatalf("permit: %+v", got.ReplicaDeploy)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("the permit never reached the box's worker")
+ }
+}
diff --git a/internal/host/stateless_runtime_test.go b/internal/host/stateless_runtime_test.go
index f6494914c..cfdaca558 100644
--- a/internal/host/stateless_runtime_test.go
+++ b/internal/host/stateless_runtime_test.go
@@ -99,12 +99,12 @@ func TestStatelessPreparationUsesReconcileObservation(t *testing.T) {
if _, err := read(rt); err == nil {
t.Fatal("missing reconcile observation accepted")
}
- rec := provision.Record{Account: rt.Account, App: rt.App, Host: rt.Host, CreatedAt: time.Unix(1, 0), ReplicaDeploy: &replicas.Deploy{ID: "deploy", Phase: "released", Order: []string{"a"}}}
+ rec := provision.Record{Account: rt.Account, App: rt.App, Host: rt.Host, CreatedAt: time.Unix(1, 0), ReplicaDeploy: &replicas.Deploy{ID: "deploy", Phase: "released", Swap: replicas.Swap{Order: []string{"a"}}}}
index.Merge(map[string]provision.Record{rt.Host: rec})
rec.ReplicaDeploy.Phase = "failed"
- rec.ReplicaDeploy.Order[0] = "changed"
+ rec.ReplicaDeploy.Swap.Order[0] = "changed"
first, err := read(rt)
- if err != nil || first.ReplicaDeploy.Phase != "released" || first.ReplicaDeploy.Order[0] != "a" {
+ if err != nil || first.ReplicaDeploy.Phase != "released" || first.ReplicaDeploy.Swap.Order[0] != "a" {
t.Fatalf("observation=%+v err=%v", first, err)
}
first.ReplicaDeploy.Phase = "unknown"
diff --git a/internal/provision/lifetimeindex.go b/internal/provision/lifetimeindex.go
index 2b0142d4e..381efdedd 100644
--- a/internal/provision/lifetimeindex.go
+++ b/internal/provision/lifetimeindex.go
@@ -2,7 +2,6 @@ package provision
import (
"fmt"
- "slices"
"sync"
"time"
)
@@ -151,9 +150,7 @@ func replicaRecordSnapshot(rec Record) Record {
snapshot.Coordinator = &c
}
if rec.ReplicaDeploy != nil {
- d := *rec.ReplicaDeploy
- d.Order = slices.Clone(d.Order)
- d.Completed = slices.Clone(d.Completed)
+ d := rec.ReplicaDeploy.Clone()
snapshot.ReplicaDeploy = &d
}
return snapshot
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 796626fa5..e1e4d21cc 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -53,7 +53,7 @@ var censusMethods = map[string]bool{
// typed-record-writer touchpoint. Keep these names aligned with the APIs above.
var (
censusKeySuffixes = []string{"recordkey", "recordsprefix", "sidecarsprefix", "sidecarkey", "sidecarmanifestkey", "writerecord", "sequencedrecord"}
- censusKeyExact = map[string]bool{"createrecord": true, "updaterecord": true, "setrecordregion": true, "setrecordmove": true, "setrecordrun": true, "setrecordinteractive": true, "setrecordseed": true, "setrecordfleetbox": true, "setrecordcoordinator": true, "setrecordreplicarelease": true, "setrecordreplicaassignment": true, "recordreplicaretired": true, "clearrecordreplicaassignment": true, "haltrecordreplicadeploy": true, "setrecordassetgen": true, "mintrecordassetgen": true, "createsidecarrecord": true, "claimrawupdaterecord": true}
+ censusKeyExact = map[string]bool{"createrecord": true, "updaterecord": true, "setrecordregion": true, "setrecordmove": true, "setrecordrun": true, "setrecordinteractive": true, "setrecordseed": true, "setrecordfleetbox": true, "setrecordcoordinator": true, "setrecordreplicarelease": true, "setrecordreplicaassignment": true, "recordreplicaretired": true, "clearrecordreplicaassignment": true, "haltrecordreplicadeploy": true, "setrecordreplicadeploy": true, "requestrecordreplicaretry": true, "setrecordassetgen": true, "mintrecordassetgen": true, "createsidecarrecord": true, "claimrawupdaterecord": true}
censusLitWords = []string{"instances", "sidecars"}
)
@@ -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 := billingOverviewSpeedWriteCensusInventory()
+ inventory := statelessReplicas4Task1WriteCensusInventory()
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 "))
@@ -426,6 +426,8 @@ func Reviewed(ctx context.Context, s Store, k string) error {
{"clear assignment callsite", base + "\nfunc Cleared() { provision.ClearRecordReplicaAssignment() }\n", "unlisted site x.go:Cleared [key:ClearRecordReplicaAssignment]"},
{"halt deploy callsite", base + "\nfunc Halted() { provision.HaltRecordReplicaDeploy() }\n", "unlisted site x.go:Halted [key:HaltRecordReplicaDeploy]"},
{"retirement writer callsite", base + "\nfunc Retired() { provision.RecordReplicaRetired() }\n", "unlisted site x.go:Retired [key:RecordReplicaRetired]"},
+ {"swap writer callsite", base + "\nfunc Swapped() { provision.SetRecordReplicaDeploy() }\n", "unlisted site x.go:Swapped [key:SetRecordReplicaDeploy]"},
+ {"retry request callsite", base + "\nfunc Retried() { provision.RequestRecordReplicaRetry() }\n", "unlisted site x.go:Retried [key:RequestRecordReplicaRetry]"},
{"record path literal", base + "\nfunc Lit(h string) string { return \"apps/a/b/instances/\" + h + \".json\" }\n", "unlisted site x.go:Lit [lit:instances]"},
{"sidecar path literal", base + "\nconst sidecarDir = \"sidecars\"\n", "unlisted site x.go:const sidecarDir [lit:sidecars]"},
{"reflective name", base + "\nfunc Reflect(v any) { _ = reflect.ValueOf(v).MethodByName(\"Put\") }\n", "unlisted site x.go:Reflect [str:Put]"},
diff --git a/internal/provision/replicaassignment.go b/internal/provision/replicaassignment.go
index 65bc6e789..a343c09f4 100644
--- a/internal/provision/replicaassignment.go
+++ b/internal/provision/replicaassignment.go
@@ -86,7 +86,9 @@ func SetRecordReplicaAssignment(ctx context.Context, s release.Store, id replica
if err := replicaAssignmentEligible(ctx, rec, id); err != nil {
return err
}
- if ReplicaSwapActive(rec) {
+ // A halted permit unfreezes membership; its box may only move to
+ // Retiring (below), whose stop proof resolves the permit.
+ if ReplicaSwapFrozen(rec) {
return replicas.ErrFenced
}
old := rec.ReplicaAssignment
@@ -140,19 +142,30 @@ func SetRecordReplicaAssignment(ctx context.Context, s release.Store, id replica
func RecordReplicaRetired(ctx context.Context, s release.Store, id replicas.Identity, revision uint64, box string) (*Record, error) {
var result *Record
err := release.WithAppMutation(ctx, s, id.Account, id.App, "provision.RecordReplicaRetired", func(ctx context.Context) error {
- ctx = context.WithValue(WithRecordSequence(ctx), replicaWriteKey{}, "replica_assignment")
+ ctx = context.WithValue(WithRecordSequence(ctx), replicaWriteKey{}, "replica_retired")
var err error
result, err = updateRecord(ctx, s, id.Account, id.App, id.Host, func(rec *Record) error {
if err := replicaIdentity(rec, id); err != nil {
return err
}
- if ReplicaSwapActive(rec) {
+ if ReplicaSwapFrozen(rec) {
return replicas.ErrFenced
}
old := rec.ReplicaAssignment
if old == nil || old.HasUnknownFields() || replicas.ValidateAssignment(*old) != nil || old.Revision != revision {
return replicas.ErrFenced
}
+ // This root termination proof is the halted permit's stop proof:
+ // the permit resolves without completing, and no permit is granted.
+ if d := rec.ReplicaDeploy; d.PermitOutstanding() && d.Swap.ActiveBox == box && slices.Contains(old.Retiring, box) {
+ if d.Revision == math.MaxUint64 {
+ return replicas.ErrFenced
+ }
+ resolved := d.Clone()
+ resolved.Swap.ActiveBox = ""
+ resolved.Revision++
+ rec.ReplicaDeploy = &resolved
+ }
i := slices.Index(old.Retiring, box)
if i < 0 {
return errRecordUnchanged
@@ -265,9 +278,17 @@ func ClearRecordReplicaAssignment(ctx context.Context, s release.Store, id repli
return result, err
}
+// ReplicaSwapActive reports an unresolved swap permit, halted or not. Only
+// the permit's matching ACK, or its box's retirement stop proof after a halt,
+// resolves it; a release phase never does. No new attempt starts meanwhile.
func ReplicaSwapActive(rec *Record) bool {
- d := rec.ReplicaDeploy
- return d != nil && d.ActiveBox != "" && (d.Phase == "swapping" || d.Phase == "releasing")
+ return rec.ReplicaDeploy.PermitOutstanding()
+}
+
+// ReplicaSwapFrozen reports an unresolved permit that is not halted: the
+// membership stays fixed until its step settles or placement halts it.
+func ReplicaSwapFrozen(rec *Record) bool {
+ return ReplicaSwapActive(rec) && !rec.ReplicaDeploy.Swap.Halted
}
func HaltRecordReplicaDeploy(ctx context.Context, s release.Store, id replicas.Identity, want replicas.Expect, deployRevision uint64) (*Record, error) {
@@ -280,11 +301,13 @@ func HaltRecordReplicaDeploy(ctx context.Context, s release.Store, id replicas.I
return err
}
a, d := rec.ReplicaAssignment, rec.ReplicaDeploy
- if a == nil || want.Incarnation != id.Incarnation || want.Region != rec.Region || want.RecordSeq != rec.RecordSeq || want.Revision != a.Revision || !ReplicaSwapActive(rec) || d.Incarnation != id.Incarnation || d.Revision != deployRevision || d.Revision == math.MaxUint64 {
+ if a == nil || want.Incarnation != id.Incarnation || want.Region != rec.Region || want.RecordSeq != rec.RecordSeq || want.Revision != a.Revision || !ReplicaSwapFrozen(rec) || d.Incarnation != id.Incarnation || d.Revision != deployRevision || d.Revision == math.MaxUint64 {
return replicas.ErrFenced
}
- next := *d
- next.Phase = "unknown"
+ // The release phase is kept: a halted swap after a passed release
+ // is not an unknown release. The permit stays unresolved.
+ next := d.Clone()
+ next.Swap.Halted = true
next.Revision++
rec.ReplicaDeploy = &next
return nil
diff --git a/internal/provision/replicacoordinator.go b/internal/provision/replicacoordinator.go
index 72275514f..cc34afc84 100644
--- a/internal/provision/replicacoordinator.go
+++ b/internal/provision/replicacoordinator.go
@@ -88,13 +88,15 @@ func replicaFieldsFixed(ctx context.Context, before, body []byte) error {
return ErrRecordSequence
}
field, _ := ctx.Value(replicaWriteKey{}).(string)
- if field != "replica_assignment" && !reflect.DeepEqual(old.ReplicaAssignment, next.ReplicaAssignment) {
+ // replica_retired is RecordReplicaRetired: it removes a retiring box and
+ // may resolve that box's halted permit in the same write.
+ if field != "replica_assignment" && field != "replica_retired" && !reflect.DeepEqual(old.ReplicaAssignment, next.ReplicaAssignment) {
return replicas.ErrFenced
}
if field != "coordinator" && !reflect.DeepEqual(old.Coordinator, next.Coordinator) {
return replicas.ErrFenced
}
- if field != "replica_deploy" && !reflect.DeepEqual(old.ReplicaDeploy, next.ReplicaDeploy) {
+ if field != "replica_deploy" && field != "replica_retired" && !reflect.DeepEqual(old.ReplicaDeploy, next.ReplicaDeploy) {
return replicas.ErrFenced
}
return nil
diff --git a/internal/provision/replicacoordinator_test.go b/internal/provision/replicacoordinator_test.go
index 477b248d1..46ad1f7b0 100644
--- a/internal/provision/replicacoordinator_test.go
+++ b/internal/provision/replicacoordinator_test.go
@@ -159,7 +159,7 @@ func TestCoordinatorPreservesDurableDeploy(t *testing.T) {
ctx, id := replicaFixture(t)
s, rec := fleetBoxFixture(t)
id.Incarnation, _ = Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
- rec.ReplicaDeploy = &replicas.Deploy{ID: "deploy-a", Incarnation: id.Incarnation, Target: replicas.Build{Version: "v1", Digest: "digest"}, Previous: replicas.Build{Version: "v0", Digest: "previous"}, Phase: "released", Term: "old-term", Order: []string{"local"}, Completed: []string{"local"}, ActiveBox: "local", Revision: 4}
+ rec.ReplicaDeploy = &replicas.Deploy{ID: "deploy-a", Incarnation: id.Incarnation, Target: replicas.Build{Version: "v1", Digest: "digest"}, Previous: replicas.Build{Version: "v0", Digest: "previous"}, Phase: "released", Term: "old-term", Swap: replicas.Swap{Order: []string{"local"}, Completed: []string{"local"}, ActiveBox: "local", Permit: 3}, LastGood: replicas.Build{Version: "v1", Digest: "digest"}, RetryOf: "deploy-0", Revision: 4}
rec.FleetBox = "local"
key := RecordKey(id.Account, id.App, id.Host)
_, tag, err := s.Get(ctx, key)
diff --git a/internal/provision/replicadeploy.go b/internal/provision/replicadeploy.go
index c83d789f2..5caa58197 100644
--- a/internal/provision/replicadeploy.go
+++ b/internal/provision/replicadeploy.go
@@ -3,6 +3,7 @@ package provision
import (
"context"
"math"
+ "slices"
"time"
"github.com/carlosframework/platform/internal/release"
@@ -17,10 +18,14 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
ctx = context.WithValue(ctx, replicaWriteKey{}, "replica_deploy")
var err error
result, err = updateRecord(ctx, s, id.Account, id.App, id.Host, func(rec *Record) error {
+ // A store conflict reruns this closure with the original request.
+ next := next
if err := replicaIdentity(rec, id); err != nil {
return err
}
- if next.Incarnation != id.Incarnation || next.ID == "" || next.Term == "" || next.Target.Version == "" || next.Target.Digest == "" || len(next.Order) != 0 || len(next.Completed) != 0 || next.ActiveBox != "" {
+ // The writer owns the swap, LastGood and a consumed retry; a
+ // release change carries none of them except a begin's RetryOf.
+ if next.Incarnation != id.Incarnation || next.ID == "" || next.Term == "" || next.Target.Version == "" || next.Target.Digest == "" || !swapEmpty(next.Swap) || next.LastGood != (replicas.Build{}) || (next.RetryOf != "" && next.Phase != "pending") {
return replicas.ErrInvalid
}
if len(proof) != 0 && (len(proof) != 1 || rec.Coordinator == nil || !proof[0].matches(rec, rec.Coordinator.Box)) {
@@ -29,7 +34,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 && old.Phase == "released" && 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 && old.Previous == next.Previous {
return errRecordUnchanged
}
c := rec.Coordinator
@@ -49,13 +54,27 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
return replicas.ErrFenced
}
if old == nil || old.ID != next.ID {
- if next.Phase != "pending" || (old != nil && old.Phase != "released" && old.Phase != "failed" && old.Phase != "unknown" && !(old.Phase == "pending" && old.Term != next.Term)) {
+ // R9 and R2: the durable attempt wins, and a new ID never
+ // replaces an unresolved permit. Old boxes are bound here too.
+ if next.Phase != "pending" {
return replicas.ErrInvalid
}
+ if err := replicas.NewAttemptAllowed(old, next); err != nil {
+ return err
+ }
+ next.LastGood = replicas.CarryLastGood(old, id.Incarnation)
} else {
if old.Incarnation != next.Incarnation || old.Target != next.Target || old.Previous != next.Previous {
return replicas.ErrFenced
}
+ if next.RetryOf != "" && next.RetryOf != old.RetryOf {
+ return replicas.ErrInvalid
+ }
+ next.RetryOf = old.RetryOf
+ next.LastGood = old.LastGood
+ if next.Phase == "released" {
+ next.LastGood = next.Target
+ }
// Pending precedes command admission: a successor may retake it.
// Releasing may only be closed as unknown by a successor.
retake := old.Phase == "pending" && old.Term != next.Term && next.Phase == "pending"
@@ -75,3 +94,101 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
})
return result, err
}
+
+func swapEmpty(s replicas.Swap) bool {
+ return len(s.Order) == 0 && len(s.Completed) == 0 && s.ActiveBox == "" && s.Permit == 0 && !s.Halted && !s.Bootstrap
+}
+
+// SetRecordReplicaDeploy persists one swap transition (replicas.NextDeploy)
+// through the judged record CAS. Coordinator ops recheck the live term and the
+// coordinator box on every retry, exactly as SetRecordReplicaRelease does; an
+// ack rechecks that its box is still assigned or retiring. Ordered and
+// granted boxes must be assigned. Only records with an assignment swap.
+func SetRecordReplicaDeploy(ctx context.Context, s release.Store, id replicas.Identity, expectedRevision uint64, change replicas.DeployChange, now time.Time, proof ...SoleFleetBox) (*Record, error) {
+ started := time.Now()
+ change.Revision = expectedRevision
+ change.Order = slices.Clone(change.Order)
+ var result *Record
+ err := release.WithAppMutation(ctx, s, id.Account, id.App, "provision.SetRecordReplicaDeploy", func(ctx context.Context) error {
+ ctx = context.WithValue(ctx, replicaWriteKey{}, "replica_deploy")
+ var err error
+ result, err = updateRecord(ctx, s, id.Account, id.App, id.Host, func(rec *Record) error {
+ at := now.Add(time.Since(started))
+ if err := replicaIdentity(rec, id); err != nil {
+ return err
+ }
+ if len(proof) != 0 && (len(proof) != 1 || rec.Coordinator == nil || !proof[0].matches(rec, rec.Coordinator.Box)) {
+ return replicas.ErrFenced
+ }
+ d, a := rec.ReplicaDeploy, rec.ReplicaAssignment
+ if d == nil || d.Incarnation != id.Incarnation || a == nil || a.HasUnknownFields() || replicas.ValidateAssignment(*a) != nil {
+ return replicas.ErrFenced
+ }
+ var coordinator replicas.Coordinator
+ if change.Op == "ack" {
+ if !a.Contains(change.Box) && !slices.Contains(a.Retiring, change.Box) {
+ return replicas.ErrFenced
+ }
+ } else {
+ c := rec.Coordinator
+ if c == nil || ReplicaCoordinatorBox(rec, at) != c.Box {
+ return replicas.ErrFenced
+ }
+ coordinator = *c
+ }
+ for _, box := range change.Order {
+ if !a.Contains(box) {
+ return replicas.ErrInvalid
+ }
+ }
+ if change.Grant != "" && !a.Contains(change.Grant) {
+ return replicas.ErrInvalid
+ }
+ next, err := replicas.NextDeploy(*d, change, coordinator, at)
+ if err != nil {
+ return err
+ }
+ rec.ReplicaDeploy = &next
+ return nil
+ })
+ return err
+ })
+ return result, err
+}
+
+// RequestRecordReplicaRetry durably asks for one explicit retry of the
+// record's failed, unknown or halted attempt named deployID. The coordinator
+// consumes it once by writing a new pending attempt that carries RetryOf.
+// A request that is already pending is an unchanged replay.
+func RequestRecordReplicaRetry(ctx context.Context, s release.Store, id replicas.Identity, deployID string) (*Record, error) {
+ var result *Record
+ err := release.WithAppMutation(ctx, s, id.Account, id.App, "provision.RequestRecordReplicaRetry", func(ctx context.Context) error {
+ ctx = context.WithValue(ctx, replicaWriteKey{}, "replica_deploy")
+ var err error
+ result, err = updateRecord(ctx, s, id.Account, id.App, id.Host, func(rec *Record) error {
+ if err := replicaIdentity(rec, id); err != nil {
+ return err
+ }
+ d := rec.ReplicaDeploy
+ if d == nil || d.Incarnation != id.Incarnation || d.ID != deployID || deployID == "" {
+ return replicas.ErrFenced
+ }
+ if replicas.RetryRequested(d) {
+ return errRecordUnchanged
+ }
+ if d.PermitOutstanding() {
+ return replicas.ErrFenced
+ }
+ if !replicas.Retryable(d) || d.Revision == math.MaxUint64 {
+ return replicas.ErrInvalid
+ }
+ next := d.Clone()
+ next.RetryOf = d.ID
+ next.Revision++
+ rec.ReplicaDeploy = &next
+ return nil
+ })
+ return err
+ })
+ return result, err
+}
diff --git a/internal/provision/replicadeploy_test.go b/internal/provision/replicadeploy_test.go
index fb900ea4f..f15cdef15 100644
--- a/internal/provision/replicadeploy_test.go
+++ b/internal/provision/replicadeploy_test.go
@@ -1,11 +1,15 @@
package provision
import (
+ "bytes"
"context"
"encoding/json"
- "github.com/carlosframework/platform/internal/replicas"
+ "errors"
"testing"
"time"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
)
func TestReplicaReleaseTermFencesLateResults(t *testing.T) {
@@ -192,6 +196,14 @@ func TestReplicaReleaseUnknownStopsDeployProvision(t *testing.T) {
}
d.ID = "explicit-retry"
d.Phase = "pending"
+ // R9: an unchanged target needs the durable retry request first.
+ if _, err := SetRecordReplicaRelease(ctx, s, id, r.ReplicaDeploy.Revision, d); err == nil {
+ t.Fatal("fresh ID without a retry request")
+ }
+ if r, err = RequestRecordReplicaRetry(ctx, s, id, "deploy"); err != nil {
+ t.Fatal(err)
+ }
+ d.RetryOf = "deploy"
if _, err := SetRecordReplicaRelease(ctx, s, id, r.ReplicaDeploy.Revision, d); err != nil {
t.Fatal(err)
}
@@ -243,7 +255,18 @@ func TestReplicaReleaseLegalTransitions(t *testing.T) {
t.Fatal("terminal deploy rerun")
}
attempt.ID = "explicit-retry"
- if _, err := SetRecordReplicaRelease(ctx, s, id, 3, attempt); err != nil {
+ if _, err := SetRecordReplicaRelease(ctx, s, id, 3, attempt); err == nil {
+ t.Fatal("fresh ID for an unchanged target")
+ }
+ if terminal == "released" {
+ attempt.Target = replicas.Build{Version: "v2", Digest: "digest-2"}
+ } else {
+ if r, err = RequestRecordReplicaRetry(ctx, s, id, "deploy"); err != nil {
+ t.Fatal(err)
+ }
+ attempt.RetryOf = "deploy"
+ }
+ if _, err := SetRecordReplicaRelease(ctx, s, id, r.ReplicaDeploy.Revision, attempt); err != nil {
t.Fatal(err)
}
})
@@ -270,7 +293,9 @@ func TestReplicaReleasePendingSuccessor(t *testing.T) {
}
next := d
if !sameID {
+ // R9: only a changed target supersedes a dead term's pending.
next.ID = "retry"
+ next.Target = replicas.Build{Version: "v2", Digest: "digest-2"}
}
if replay, err := SetRecordReplicaRelease(ctx, s, id, 1, next); sameID {
if err != nil || replay.RecordSeq != r.RecordSeq {
@@ -343,3 +368,353 @@ func TestReplicaReleasePendingSuccessor(t *testing.T) {
})
}
}
+
+// swapWorld is a two-box assignment whose coordinator a has passed the
+// release of deploy-2.
+type swapWorld struct {
+ ctx context.Context
+ s release.Store
+ id replicas.Identity
+ want replicas.Expect
+ rec *Record
+ term string
+}
+
+var swapTarget = replicas.Build{Version: "v2", Digest: "canonical-2"}
+
+func newSwapWorld(t *testing.T, phases ...string) *swapWorld {
+ t.Helper()
+ ctx, s, _, id, want := assignmentFixture(t)
+ rec, err := SetRecordReplicaAssignment(ctx, s, id, want, replicas.Assignment{Desired: 2, Boxes: []string{"a", "b"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec, err = SetRecordCoordinator(ctx, s, id, replicas.CoordinatorChange{Op: "acquire", Box: "a", BootID: "boot"}, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := &swapWorld{ctx: ctx, s: s, id: id, want: want, rec: rec, term: rec.Coordinator.Term}
+ if len(phases) == 0 {
+ phases = []string{"pending", "releasing", "released"}
+ }
+ w.release(t, "deploy-2", swapTarget, "", phases...)
+ return w
+}
+
+func (w *swapWorld) revision() uint64 {
+ if w.rec.ReplicaDeploy == nil {
+ return 0
+ }
+ return w.rec.ReplicaDeploy.Revision
+}
+
+func (w *swapWorld) release(t *testing.T, deployID string, target replicas.Build, retryOf string, phases ...string) {
+ t.Helper()
+ for _, phase := range phases {
+ d := replicas.Deploy{ID: deployID, Incarnation: w.id.Incarnation, Term: w.term, Target: target, Phase: phase}
+ if phase == "pending" {
+ d.RetryOf = retryOf
+ }
+ rec, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), d)
+ if err != nil {
+ t.Fatalf("%s %s: %v", deployID, phase, err)
+ }
+ w.rec = rec
+ }
+}
+
+func (w *swapWorld) change(op string) replicas.DeployChange {
+ d := w.rec.ReplicaDeploy
+ c := replicas.DeployChange{Op: op, ID: d.ID, Box: "a", Target: d.Target}
+ if op != "ack" {
+ c.Term = w.term
+ }
+ return c
+}
+
+func (w *swapWorld) apply(t *testing.T, c replicas.DeployChange) {
+ t.Helper()
+ rec, err := SetRecordReplicaDeploy(w.ctx, w.s, w.id, w.revision(), c, time.Now())
+ if err != nil {
+ t.Fatalf("%s: %v", c.Op, err)
+ }
+ w.rec = rec
+}
+
+func (w *swapWorld) ack(box string, switched bool) replicas.DeployChange {
+ d := w.rec.ReplicaDeploy
+ return replicas.DeployChange{Op: "ack", ID: d.ID, Box: box, Target: d.Target, Permit: d.Swap.Permit, Switched: switched}
+}
+
+// swapThrough orders a and b and switches both, then closes the deploy.
+func (w *swapWorld) swapThrough(t *testing.T) {
+ t.Helper()
+ order := w.change("order")
+ order.Order = []string{"a", "b"}
+ w.apply(t, order)
+ for _, box := range []string{"a", "b"} {
+ permit := w.change("permit")
+ permit.Grant = box
+ w.apply(t, permit)
+ w.apply(t, w.ack(box, true))
+ }
+ w.apply(t, w.change("done"))
+}
+
+// TestReplicaDeployTransitionCASStore: the typed writer rejudges the
+// lifetime, live term, coordinator box, assignment and revision on every
+// attempt, including a store-conflict retry, and only an assigned box
+// holding the permit acknowledges it.
+func TestReplicaDeployTransitionCASStore(t *testing.T) {
+ w := newSwapWorld(t)
+ order := w.change("order")
+ order.Order = []string{"a", "c"}
+ if _, err := SetRecordReplicaDeploy(w.ctx, w.s, w.id, w.revision(), order, time.Now()); err == nil {
+ t.Fatal("ordered an unassigned box")
+ }
+ stale := w.id
+ stale.Incarnation = "recreated"
+ order.Order = []string{"a", "b"}
+ if _, err := SetRecordReplicaDeploy(w.ctx, w.s, stale, w.revision(), order, time.Now()); err == nil {
+ t.Fatal("stale lifetime accepted")
+ }
+ if _, err := SetRecordReplicaDeploy(w.ctx, w.s, w.id, w.revision(), order, time.Now(), SoleFleetBox{Fleet: "pi", Box: "a"}); err == nil {
+ t.Fatal("legacy sole-box proof accepted on an assignment")
+ }
+ w.apply(t, order)
+ permit := w.change("permit")
+ permit.Grant = "a"
+ for _, kind := range []string{"term", "expiry", "revision", "assignment", "lifetime"} {
+ t.Run(kind, func(t *testing.T) {
+ base := w.s
+ raced := assignmentReplace(t, base, w.id, func(r *Record) {})
+ conflict := &replicaConflictStore{Store: base}
+ conflict.hook = func(ctx context.Context, key string, body []byte, etag string) {
+ raced = assignmentReplace(t, base, w.id, func(r *Record) {
+ switch kind {
+ case "term":
+ r.Coordinator.Term = "successor"
+ case "expiry":
+ r.Coordinator.ExpiresAt = time.Now().Add(-time.Second)
+ case "revision":
+ r.ReplicaDeploy.Revision++
+ case "assignment":
+ r.ReplicaAssignment.Boxes = []string{"b"}
+ r.ReplicaAssignment.Retiring = []string{"a"}
+ case "lifetime":
+ r.CreatedAt = r.CreatedAt.Add(time.Second)
+ }
+ })
+ }
+ if _, err := SetRecordReplicaDeploy(w.ctx, conflict, w.id, w.revision(), permit, time.Now()); err == nil {
+ t.Fatal("CAS retry accepted fenced state")
+ }
+ if got := assignmentBytes(t, base, w.id); !bytes.Equal(got, raced) {
+ t.Fatal("retry wrote")
+ }
+ // Restore the world for the next case.
+ assignmentReplace(t, base, w.id, func(r *Record) { *r = *w.rec })
+ w.rec, _ = GetRecord(w.ctx, base, w.id.Account, w.id.App, w.id.Host)
+ })
+ }
+ w.apply(t, permit)
+ if !ReplicaSwapActive(w.rec) || !ReplicaSwapFrozen(w.rec) {
+ t.Fatal("granted permit is not active")
+ }
+ for _, box := range []string{"b", "c"} {
+ ack := w.ack(box, true)
+ if _, err := SetRecordReplicaDeploy(w.ctx, w.s, w.id, w.revision(), ack, time.Now()); err == nil {
+ t.Fatalf("%s acked a's permit", box)
+ }
+ }
+ w.apply(t, w.ack("a", true))
+ if ReplicaSwapActive(w.rec) || w.rec.ReplicaDeploy.Swap.Completed[0] != "a" {
+ t.Fatalf("ack did not resolve: %+v", w.rec.ReplicaDeploy.Swap)
+ }
+}
+
+// TestReplicaReleaseDurableAttemptWins (R9): the release writer binds every
+// box, including a v0.34 box posting a plain begin: an unchanged target
+// keeps the record's attempt after released, failed, unknown and done,
+// unless an unconsumed durable RetryOf names that failed attempt.
+func TestReplicaReleaseDurableAttemptWins(t *testing.T) {
+ for _, end := range []string{"released", "failed", "unknown", "done"} {
+ t.Run(end, func(t *testing.T) {
+ phases := []string{"pending", "releasing", end}
+ if end == "done" {
+ phases = phases[:2]
+ phases = append(phases, "released")
+ }
+ w := newSwapWorld(t, phases...)
+ if end == "done" {
+ w.swapThrough(t)
+ }
+ fresh := replicas.Deploy{ID: "v034-fresh", Incarnation: w.id.Incarnation, Term: w.term, Target: swapTarget, Phase: "pending"}
+ if _, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), fresh); err == nil {
+ t.Fatal("old-box begin with a fresh ID started a second run")
+ }
+ forged := fresh
+ forged.RetryOf = "deploy-2"
+ if _, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), forged); err == nil {
+ t.Fatal("RetryOf without a durable request")
+ }
+ _, err := RequestRecordReplicaRetry(w.ctx, w.s, w.id, "deploy-2")
+ if end == "released" || end == "done" {
+ if err == nil {
+ t.Fatal("retry requested for a passed release")
+ }
+ changed := fresh
+ changed.Target = replicas.Build{Version: "v3", Digest: "canonical-3"}
+ if _, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), changed); err != nil {
+ t.Fatalf("new build refused: %v", err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.rec, _ = GetRecord(w.ctx, w.s, w.id.Account, w.id.App, w.id.Host)
+ // A lost reply to the retry request: asking again changes nothing.
+ again, err := RequestRecordReplicaRetry(w.ctx, w.s, w.id, "deploy-2")
+ if err != nil || again.RecordSeq != w.rec.RecordSeq {
+ t.Fatalf("retry replay: %v", err)
+ }
+ if _, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), fresh); err == nil {
+ t.Fatal("plain begin consumed the retry")
+ }
+ w.release(t, "retry-1", swapTarget, "deploy-2", "pending")
+ if w.rec.ReplicaDeploy.RetryOf != "deploy-2" || replicas.RetryRequested(w.rec.ReplicaDeploy) {
+ t.Fatalf("retry not consumed: %+v", w.rec.ReplicaDeploy)
+ }
+ second := forged
+ second.ID = "retry-2"
+ if _, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), second); err == nil {
+ t.Fatal("consumed retry minted a second attempt")
+ }
+ w.release(t, "retry-1", swapTarget, "", "releasing", "released")
+ if w.rec.ReplicaDeploy.RetryOf != "deploy-2" || w.rec.ReplicaDeploy.LastGood != swapTarget {
+ t.Fatalf("retry lost its fields: %+v", w.rec.ReplicaDeploy)
+ }
+ })
+ }
+}
+
+// TestReplicaDeployPermitBlocksNewAttempt (R2): an unresolved permit,
+// halted or not, refuses any new attempt from either writer; only its box's
+// ack, or that box's retirement proof after a halt, resolves it. Two
+// complete deploys run back to back.
+func TestReplicaDeployPermitBlocksNewAttempt(t *testing.T) {
+ w := newSwapWorld(t)
+ order := w.change("order")
+ order.Order = []string{"a", "b"}
+ w.apply(t, order)
+ permit := w.change("permit")
+ permit.Grant = "a"
+ w.apply(t, permit)
+ next := replicas.Deploy{ID: "deploy-3", Incarnation: w.id.Incarnation, Term: w.term, Target: replicas.Build{Version: "v3", Digest: "canonical-3"}, Phase: "pending"}
+ if _, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), next); !errors.Is(err, replicas.ErrFenced) {
+ t.Fatalf("new attempt over an open permit: %v", err)
+ }
+ // Placement halts the swap; membership unfreezes but the permit stays.
+ want := w.want
+ want.Revision, want.RecordSeq = w.rec.ReplicaAssignment.Revision, w.rec.RecordSeq
+ rec, err := HaltRecordReplicaDeploy(w.ctx, w.s, w.id, want, w.revision())
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.rec = rec
+ d := w.rec.ReplicaDeploy
+ if d.Phase != "released" || !d.Swap.Halted || d.Swap.ActiveBox != "a" || !ReplicaSwapActive(w.rec) || ReplicaSwapFrozen(w.rec) {
+ t.Fatalf("halt: %+v", d)
+ }
+ if _, err := HaltRecordReplicaDeploy(w.ctx, w.s, w.id, want, w.revision()); err == nil {
+ t.Fatal("halted twice")
+ }
+ if _, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), next); !errors.Is(err, replicas.ErrFenced) {
+ t.Fatalf("new attempt over a halted permit: %v", err)
+ }
+ if _, err := RequestRecordReplicaRetry(w.ctx, w.s, w.id, "deploy-2"); err == nil {
+ t.Fatal("retry over a halted permit")
+ }
+ // The old box returns and answers its permit: resolved, not completed.
+ w.apply(t, w.ack("a", false))
+ if ReplicaSwapActive(w.rec) || len(w.rec.ReplicaDeploy.Swap.Completed) != 0 {
+ t.Fatalf("returning box: %+v", w.rec.ReplicaDeploy.Swap)
+ }
+ w.release(t, "deploy-3", next.Target, "", "pending", "releasing", "released")
+ if w.rec.ReplicaDeploy.LastGood != next.Target {
+ t.Fatalf("LastGood: %+v", w.rec.ReplicaDeploy)
+ }
+ w.swapThrough(t)
+ w.release(t, "deploy-4", replicas.Build{Version: "v4", Digest: "canonical-4"}, "", "pending", "releasing", "released")
+ w.swapThrough(t)
+ if w.rec.ReplicaDeploy.Phase != "done" || w.rec.ReplicaDeploy.ID != "deploy-4" {
+ t.Fatalf("second deploy: %+v", w.rec.ReplicaDeploy)
+ }
+}
+
+// TestReplicaDeployRetiredResolvesHaltedPermit: a halted permit's box that
+// placement moved to Retiring resolves the permit with its root termination
+// proof, in the same write, without completing it.
+func TestReplicaDeployRetiredResolvesHaltedPermit(t *testing.T) {
+ w := newSwapWorld(t)
+ order := w.change("order")
+ order.Order = []string{"a", "b"}
+ w.apply(t, order)
+ permit := w.change("permit")
+ permit.Grant = "a"
+ w.apply(t, permit)
+ want := w.want
+ want.Revision, want.RecordSeq = w.rec.ReplicaAssignment.Revision, w.rec.RecordSeq
+ if _, err := SetRecordReplicaAssignment(w.ctx, w.s, w.id, want, replicas.Assignment{Revision: want.Revision, Desired: 2, Boxes: []string{"b"}, Retiring: []string{"a"}}); err == nil {
+ t.Fatal("membership changed under an active swap")
+ }
+ rec, err := HaltRecordReplicaDeploy(w.ctx, w.s, w.id, want, w.revision())
+ if err != nil {
+ t.Fatal(err)
+ }
+ want.RecordSeq = rec.RecordSeq
+ rec, err = SetRecordReplicaAssignment(w.ctx, w.s, w.id, want, replicas.Assignment{Revision: want.Revision, Desired: 2, Boxes: []string{"b"}, Retiring: []string{"a"}})
+ if err != nil {
+ t.Fatalf("halted swap still froze membership: %v", err)
+ }
+ if !ReplicaSwapActive(rec) {
+ t.Fatal("membership change resolved the permit")
+ }
+ rec, err = RecordReplicaRetired(w.ctx, w.s, w.id, rec.ReplicaAssignment.Revision, "a")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ReplicaSwapActive(rec) || len(rec.ReplicaDeploy.Swap.Completed) != 0 || !rec.ReplicaDeploy.Swap.Halted || len(rec.ReplicaAssignment.Retiring) != 0 {
+ t.Fatalf("retirement proof: %+v %+v", rec.ReplicaDeploy.Swap, rec.ReplicaAssignment)
+ }
+}
+
+// TestReplicaDeployLastGoodSurvivesFailures (R3, R13): a legacy released
+// record without LastGood normalizes on the next begin; failures and unknown
+// results never clear it; the next pass sets it to its own target.
+func TestReplicaDeployLastGoodSurvivesFailures(t *testing.T) {
+ w := newSwapWorld(t)
+ // Make the record legacy: released without LastGood.
+ assignmentReplace(t, w.s, w.id, func(r *Record) { r.ReplicaDeploy.LastGood = replicas.Build{} })
+ w.rec, _ = GetRecord(w.ctx, w.s, w.id.Account, w.id.App, w.id.Host)
+ v3 := replicas.Build{Version: "v3", Digest: "canonical-3"}
+ w.release(t, "deploy-3", v3, "", "pending")
+ if w.rec.ReplicaDeploy.LastGood != swapTarget {
+ t.Fatalf("legacy released not normalized: %+v", w.rec.ReplicaDeploy)
+ }
+ w.release(t, "deploy-3", v3, "", "failed")
+ v4 := replicas.Build{Version: "v4", Digest: "canonical-4"}
+ w.release(t, "deploy-4", v4, "", "pending", "releasing", "unknown")
+ if w.rec.ReplicaDeploy.LastGood != swapTarget {
+ t.Fatalf("failure cleared LastGood: %+v", w.rec.ReplicaDeploy)
+ }
+ w.release(t, "deploy-5", replicas.Build{Version: "v5", Digest: "canonical-5"}, "", "pending", "failed")
+ if w.rec.ReplicaDeploy.LastGood != swapTarget {
+ t.Fatalf("second failure cleared LastGood: %+v", w.rec.ReplicaDeploy)
+ }
+ forged := replicas.Deploy{ID: "deploy-6", Incarnation: w.id.Incarnation, Term: w.term, Target: v3, Phase: "pending", LastGood: v3}
+ if _, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, w.revision(), forged); err == nil {
+ t.Fatal("a box wrote LastGood")
+ }
+}
diff --git a/internal/provision/stateless_replicas_4_task1_census_test.go b/internal/provision/stateless_replicas_4_task1_census_test.go
new file mode 100644
index 000000000..fc40c605d
--- /dev/null
+++ b/internal/provision/stateless_replicas_4_task1_census_test.go
@@ -0,0 +1,64 @@
+package provision
+
+// statelessReplicas4Task1WriteCensusInventory is stateless replicas Plan 4
+// Task 1's review of the record-write census, layered on
+// billingOverviewSpeedWriteCensusInventory. Self-review only; the
+// independent #280 verdict is the controller's.
+//
+// - Two new typed writers, both under WithAppMutation and the judged
+// updateRecord CAS with the replica_deploy field key, so no other
+// replica field can change in the same write:
+// SetRecordReplicaDeploy (swap transitions through replicas.NextDeploy;
+// rechecks lifetime, F8 proof, coordinator term and box, assignment
+// membership and revision on every CAS attempt) and
+// RequestRecordReplicaRetry (writes RetryOf on the record's own failed,
+// unknown or halted attempt; refuses while a permit is open).
+// - Their only callers are console handlers holding the app lock:
+// handleReplicaDeploy (withRecordLock after fleet identity and
+// assignment checks, as handleReplicaRelease) and
+// requestReplicaRetryLocked (withRecordLock for the host retry door,
+// beginCopiesMutation's app lock for promote --retry).
+// - SetRecordReplicaRelease: R9 new-attempt rule, R2 open-permit refusal,
+// writer-owned LastGood and RetryOf. Same CAS, keys and lock.
+// - SetRecordReplicaAssignment, HaltRecordReplicaDeploy: the active-swap
+// guard reads ReplicaSwapFrozen; halt keeps the phase and the permit.
+// - RecordReplicaRetired: field key replica_retired lets the retiring
+// box's stop proof resolve its own halted permit in the same write
+// (replicaFieldsFixed allows exactly assignment and deploy there).
+// - handleReplicaRelease, replicaCoordinatorStore.releaseState: pass the
+// begin's RetryOf through; no other change.
+// - prepareStateless: the ID selector moved after term acquisition; no
+// record write here. routeDecls: one /deploy route. replicaAction,
+// handleAPIInstanceList, handleInstanceRetry: reads and a refusal only.
+func statelessReplicas4Task1WriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), billingOverviewSpeedWriteCensusInventory()...)
+ for _, r := range []censusEntry{
+ {"internal/activator/stateless.go", "Service.prepareStateless", "reference", "key:statelessRecordKey", "c5bcac73de222c9e4a6c9b76ec541bad32c37a66eff1e5638cb68b2fc0592a5d"},
+ {"internal/console/apiinstances.go", "Server.handleAPIInstanceList", "key-site", "lit:instances", "0d04c22e1f8b2cddc7180209ad72a736cc7cf86767d2e80d7e5a66e1281def27"},
+ {"internal/console/browserretry.go", "Server.handleInstanceRetry", "key-site", "lit:instances", "01aaaf179641d30c361dec338ff3b8d00d815c01198c74a718af58bdf83c49fc"},
+ {"internal/console/replicacoordinator.go", "Server.handleReplicaRelease", "record-writer", "key:SetRecordReplicaRelease", "7545f866084af5d8069df94d978de65791d5acf18601371193ea445edb765110"},
+ {"internal/console/replicadeploy.go", "Server.handleReplicaDeploy", "record-writer", "key:SetRecordReplicaDeploy", "38418bf94d94e8cbded10800c7656def229453f63759b57274f8982bc91170eb"},
+ {"internal/console/replicadeploy.go", "Server.requestReplicaRetryLocked", "record-writer", "key:RequestRecordReplicaRetry", "630d09e107a85ae68d06e44dbd32fb008487c2ae45185d7dd5e6fe0d9837d4be"},
+ {"internal/console/replicaplacement.go", "Server.replicaAction", "key-site", "key:replicaRecordKey", "4ea765ce2d3131f8a9b26fb256493c2b68efebe928711f11e9570ec2c3212321"},
+ {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "71de6f3bd690ea07da6b2740429dbe90e1925174709807087b9274aa80454040"},
+ {"internal/host/replicacoordinator.go", "replicaCoordinatorStore.releaseState", "record-writer", "key:SetRecordReplicaRelease", "e1ae48005ee0663fa337cdeb50dcda09a9c5c34ad41eace7fc2db4b946f7b065"},
+ {"internal/provision/replicaassignment.go", "HaltRecordReplicaDeploy", "record-writer", "key:HaltRecordReplicaDeploy,key:updateRecord", "f8044b6f03638c0098266b603a49203537980572438a9d657a1474998d2ab6b8"},
+ {"internal/provision/replicaassignment.go", "RecordReplicaRetired", "record-writer", "key:RecordReplicaRetired,key:updateRecord", "c5ee5437291b4f39966cb6bd7e155ae98a9eaa041125be0b6195a488bd6da9e9"},
+ {"internal/provision/replicaassignment.go", "SetRecordReplicaAssignment", "record-writer", "key:SetRecordReplicaAssignment,key:updateRecord", "504fc1b4e3e2af75fe2088d033370e881d7e8be7ecc291b4a60c81eb16283754"},
+ {"internal/provision/replicadeploy.go", "RequestRecordReplicaRetry", "record-writer", "key:RequestRecordReplicaRetry,key:updateRecord", "41d3f84b0301455bf0a02c32fa52e10ebd979b69509bb3365229a11dc1847fba"},
+ {"internal/provision/replicadeploy.go", "SetRecordReplicaDeploy", "record-writer", "key:SetRecordReplicaDeploy,key:updateRecord", "65dc3acdfc55671b18e82936237da4fa013216ac95b1bec42ef9c41fadbc384d"},
+ {"internal/provision/replicadeploy.go", "SetRecordReplicaRelease", "record-writer", "key:SetRecordReplicaRelease,key:updateRecord", "a43483f00d489665844cd469b937c30d9a2aae5f0eaddb5b6b42dd917e5b6ad9"},
+ } {
+ 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 32c681bec..b368f732a 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -168,3 +168,4 @@ plan14-root-reads-w6-ingress-drain.tsv 43260792034a1a20791d14c4e4476e762b40d7bcc
plan14-root-reads-group-capacity-damping.tsv 0c649af234a7b89a75479e59e705307e3293a59439b7b251dd4558bd46ef2100
plan14-root-reads-group-verb-followups.tsv 9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af
plan14-root-reads-group-read-transport-retry.tsv 9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af
+plan14-root-reads-stateless-replicas-4-task1.tsv 3f066208f5e5fa2b9854f30118a9a2707f3a5a51bcf55ae6b0949cb0307804f5
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1.tsv
new file mode 100644
index 000000000..9da7d5b2c
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task1.tsv
@@ -0,0 +1,20 @@
+# Census overlay stateless-replicas-4-task1, written by census-propose (#369). census-ruling-stateless-replicas-4-task1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-replicas-4-task1.md.
+# 4 body, 1 sites, 6 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 93982299041597b16c7cdb098db380fbfece099227f111d36feed328d371b102 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. registry:Account@284,registry:Account@310,registry:App@324,registry:App@346,registry:Digest@1276,registry:Host@250,registry:Host@273,registry:Stateless@1574,registry:Version@1113,registry:Version@1246,whole:Route@1196,whole:Route@1340,whole:Route@1347,whole:Route@1570,whole:Route@1724,whole:Route@1828,whole:Route@1835,whole:Route@259,whole:Route@293,whole:Route@333,whole:Route@540,whole:Route@597,whole:Route@714,whole:Route@821 c5bcac73de222c9e4a6c9b76ec541bad32c37a66eff1e5638cb68b2fc0592a5d
+@legacy 64dc45c29ab4e8104c9118f3802a162d982ed016d67631d8f23979e3c1b6c744 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. registry:Channel@398,registry:Digest@993,registry:Environment@431,registry:Region@492,registry:Runtime@464,registry:Version@954,whole:Route@122,whole:Route@1369,whole:Route@208,whole:Route@285,whole:Route@629,whole:Route@930 699af25a27cd475af742f31ae5929c1c54ceb32c94b7a3b3e45b91be107581e8
+@legacy 97f1d70b5a4374973bdfff5994a925110962b2cf77b394368d1f9695349ca6b9 internal/host/agent.go fastTick legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: signals the owned replica worker on the existing tick; coalesced asynchronous execution, no timer or bucket scan added. merge of origin/main 7920cccf: Retain main box-role reader pass on the existing tick alongside the replica worker signal; merge-only body change, unchanged read sites.;rev3=census-ruling-restart-new-box-gap;basis=calls the optional restartGain hook (restartGainSeed) once per existing tick before the serial read; no new root path, timer or read kind; nil hook is unchanged;rev3=census-ruling-agent-start-demo-3;basis=Refresh moved notices through the shared watch before normal convergence; no new per-box poll. Census read-site delta: unchanged (1).;rev3=census-ruling-stateless-replicas-4-task1;basis=Signals the owned replica swap worker (armedReplicaDeploy.tick) beside the placement worker on the existing tick; coalesced background pass, no timer, no bucket read. Its transitions go through the console's authenticated /deploy. registry:Host@5464 a1b5f450c4662fa1e8e02f236e9d35da4194f85c6efb21364f697accda8809d9
+@legacy 8a86089ecb92ff8312a62345654bc67b4abc156b9d3bde8f5a0d6ca7790260bb 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. registry:Account@634,registry:App@664,registry:GoodDemand@3711,registry:GoodDigest@3696,registry:GoodVersion@3680,registry:Host@1325,registry:Host@301,registry:Host@3767,registry:Host@3825,registry:Host@4041,registry:Host@4109,registry:Host@691,whole:Route@1093,whole:Route@3834,whole:Route@3841,whole:Route@4393,whole:Route@569 ba9878930e6b1451e3521fef74f93f8fc4eb1cb1b027bea27e0e057d36696582
+@legacy 2c0edcc56401764a4e839be2b439ce13f351e546924eb11e47f3d3dd8d5500ef internal/activator/statelessrelease.go Service.PrepareStatelessRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Read durable deploy evidence and canonical target via existing-record observation seam; use coordinator authority only for this path, persist releasing before exec and require proof plus SafeUntil before success; commandless binary verifies staged artifact separately; R11 lets the current term retake pending via the typed begin gate; R12 follows renewed SafeUntil through the existing command supervisor instead of a fixed initial context deadline; no new store polling or direct typed record writer callsite. Fix round 1 replaces the frozen-carrier re-observation with an identical released writer replay; command execution, proof and authority gates remain. Fix 3b round 1 I2 / R20: only the matching released branch calls the backend escrow initializer. Held authority is reused; absent trio can acquire through the existing coordinator adapter. No release rerun, deploy mutation, new record read or loop; existing final-exec checks from 3a remain unchanged. Final review I2: keep pre-releasing refusals pending; only a command ReleaseError or an actual artifact digest mismatch becomes failed. Releasing uncertainty still fences automatic reruns; begin, authority, execution and proof gates remain.;rev3=census-ruling-stateless-failed-release-held;basis=Distinguish an observed failed or unknown coordinator deploy from a transient release admission refusal using wrapped existing errors; preserve the existing unknown-result reason; no new read or coordinator write.;rev3=census-ruling-stateless-replicas-4-task1;basis=Now a thin wrapper that hands a fixed deploy ID to prepareStatelessRelease; its body moved there. No read of its own. whole:Route@176 0bd933ebb58e11f97be051eea8baa6da3283e4541ac2e7fe8de632f38c7a667c
+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. registry:Account@284,registry:Account@310,registry:App@324,registry:App@346,registry:Digest@1276,registry:Host@250,registry:Host@273,registry:Stateless@1574,registry:Version@1113,registry:Version@1246,whole:Route@1196,whole:Route@1340,whole:Route@1347,whole:Route@1570,whole:Route@1724,whole:Route@1828,whole:Route@1835,whole:Route@259,whole:Route@293,whole:Route@333,whole:Route@540,whole:Route@597,whole:Route@714,whole:Route@821 c5bcac73de222c9e4a6c9b76ec541bad32c37a66eff1e5638cb68b2fc0592a5d
+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. registry:Channel@398,registry:Digest@993,registry:Environment@431,registry:Region@492,registry:Runtime@464,registry:Version@954,whole:Route@122,whole:Route@1369,whole:Route@208,whole:Route@285,whole:Route@629,whole:Route@930 699af25a27cd475af742f31ae5929c1c54ceb32c94b7a3b3e45b91be107581e8
+internal/host/agent.go fastTick legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=observes the change index before any pass (observeIndex), runs the backstop's requested full pass and a scoped pass for moved app scopes (indexTick), and arms the canary pointer gate on the sweep (canaryPointerGate) only on a tick whose own index observation succeeded; read site unchanged, offset moved;rev3=census-ruling-stateless-replicas-1;basis=Call coordinator Tick on the existing tick before convergence; client renews held terms only at the pinned interval. Existing registry read unchanged. Final review I3: signal the owned renewal worker instead of waiting for its sequential console HTTP calls. Existing convergence and record read unchanged.;rev3=census-ruling-region-ha-p3a;basis=Run the optional desired-role reader on the existing tick after observing the armed change index; no new root path or timer, nil reader is unchanged.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: signals the owned replica worker on the existing tick; coalesced asynchronous execution, no timer or bucket scan added. merge of origin/main 7920cccf: Retain main box-role reader pass on the existing tick alongside the replica worker signal; merge-only body change, unchanged read sites.;rev3=census-ruling-restart-new-box-gap;basis=calls the optional restartGain hook (restartGainSeed) once per existing tick before the serial read; no new root path, timer or read kind; nil hook is unchanged;rev3=census-ruling-agent-start-demo-3;basis=Refresh moved notices through the shared watch before normal convergence; no new per-box poll. Census read-site delta: unchanged (1).;rev3=census-ruling-stateless-replicas-4-task1;basis=Signals the owned replica swap worker (armedReplicaDeploy.tick) beside the placement worker on the existing tick; coalesced background pass, no timer, no bucket read. Its transitions go through the console's authenticated /deploy. registry:Host@5464 a1b5f450c4662fa1e8e02f236e9d35da4194f85c6efb21364f697accda8809d9
+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. file:Exec@20408,file:Open@2191,file:Statfs@54667,registry:App@13287,registry:Host@50310,whole:Route@13279,whole:Route@48657,whole:Route@50433,whole:Route@50495 ac4db6d8bc9ba474d734df9a93446e96e80294fe6d7614e395984bad4f3c7d21
+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. registry:Account@634,registry:App@664,registry:GoodDemand@3711,registry:GoodDigest@3696,registry:GoodVersion@3680,registry:Host@1325,registry:Host@301,registry:Host@3767,registry:Host@3825,registry:Host@4041,registry:Host@4109,registry:Host@691,whole:Route@1093,whole:Route@3834,whole:Route@3841,whole:Route@4393,whole:Route@569 ba9878930e6b1451e3521fef74f93f8fc4eb1cb1b027bea27e0e057d36696582
+internal/activator/statelessrelease.go Service.PrepareStatelessRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Read durable deploy evidence and canonical target via existing-record observation seam; use coordinator authority only for this path, persist releasing before exec and require proof plus SafeUntil before success; commandless binary verifies staged artifact separately; R11 lets the current term retake pending via the typed begin gate; R12 follows renewed SafeUntil through the existing command supervisor instead of a fixed initial context deadline; no new store polling or direct typed record writer callsite. Fix round 1 replaces the frozen-carrier re-observation with an identical released writer replay; command execution, proof and authority gates remain. Fix 3b round 1 I2 / R20: only the matching released branch calls the backend escrow initializer. Held authority is reused; absent trio can acquire through the existing coordinator adapter. No release rerun, deploy mutation, new record read or loop; existing final-exec checks from 3a remain unchanged. Final review I2: keep pre-releasing refusals pending; only a command ReleaseError or an actual artifact digest mismatch becomes failed. Releasing uncertainty still fences automatic reruns; begin, authority, execution and proof gates remain.;rev3=census-ruling-stateless-failed-release-held;basis=Distinguish an observed failed or unknown coordinator deploy from a transient release admission refusal using wrapped existing errors; preserve the existing unknown-result reason; no new read or coordinator write.;rev3=census-ruling-stateless-replicas-4-task1;basis=Now a thin wrapper that hands a fixed deploy ID to prepareStatelessRelease; its body moved there. No read of its own. whole:Route@176 0bd933ebb58e11f97be051eea8baa6da3283e4541ac2e7fe8de632f38c7a667c
+@coverage . 480de7cd1921c3d2dab1ce5d03a496fa5d2e07a94ba401ab1453193eab0f1fa8
+@coverage internal/activator c03e7d7fcc79c4b5c8fc2cfe34392b9267caa5476f6efd5cb2521803e83939c6
+@coverage internal/host ccecf8327a290a539e302411e3cea27d5209a263dc803c24796221695871c1f9
+@coverage internal/provision 6a94edf3a908a66e5a176cc707c8c30bac4b470a131b6ca6b4c722f6683eff95
+@coverage internal/replicas 80d4528b426d1e60750753315e38e94ebdcd266357fd85bef68b3d20ea9bd5cc
+@coverage internal/rollout 6088a832582896228f25600a9008d52ff230a76e097f375ff484e6a5ce7ffde4
diff --git a/internal/replicas/deploy.go b/internal/replicas/deploy.go
new file mode 100644
index 000000000..db9757796
--- /dev/null
+++ b/internal/replicas/deploy.go
@@ -0,0 +1,193 @@
+package replicas
+
+import (
+ "math"
+ "slices"
+ "time"
+
+ "github.com/carlosframework/platform/internal/controlname"
+)
+
+// DeployChange is one swap transition after a passed release. The
+// coordinator writes order, permit, halt and done under its term. Only the
+// box holding the permit writes ack, and an ack can only resolve that permit.
+type DeployChange struct {
+ Op string `json:"op,omitempty"`
+ ID string `json:"id,omitempty"`
+ Term string `json:"term,omitempty"`
+ Box string `json:"box,omitempty"`
+ Revision uint64 `json:"revision,omitempty"`
+ Target Build `json:"target,omitempty"`
+ // Order and Bootstrap are filled by the console for op order.
+ Order []string `json:"order,omitempty"`
+ Bootstrap bool `json:"bootstrap,omitempty"`
+ // Grant is the box a permit is granted to.
+ Grant string `json:"grant,omitempty"`
+ // Permit is the permit revision an ack resolves. Switched reports that
+ // the box serves Target and proved its old generation stopped; an ack
+ // without it reports the box kept its incumbent, which halts the swap.
+ Permit uint64 `json:"permit,omitempty"`
+ Switched bool `json:"switched,omitempty"`
+}
+
+// ReleasePassed reports a phase whose release command succeeded.
+func ReleasePassed(phase string) bool { return phase == "released" || phase == "done" }
+
+// PermitOutstanding reports an unresolved permit, including a halted one.
+func (d *Deploy) PermitOutstanding() bool { return d != nil && d.Swap.ActiveBox != "" }
+
+// RetryRequested reports an explicit retry not yet consumed by a new attempt.
+func RetryRequested(d *Deploy) bool { return d != nil && d.ID != "" && d.RetryOf == d.ID }
+
+// Retryable reports an attempt an explicit retry may replace: a release that
+// failed or whose result is unknown, or a halted swap with no open permit.
+func Retryable(d *Deploy) bool {
+ if d == nil || d.ID == "" || d.PermitOutstanding() {
+ return false
+ }
+ return d.Phase == "failed" || d.Phase == "unknown" || (d.Phase == "released" && d.Swap.Halted)
+}
+
+// DurableAttempt returns old when the record's attempt is the one for this
+// lifetime and target: every coordinator adopts it, in every phase, unless an
+// unconsumed explicit retry asks for a new attempt.
+func DurableAttempt(old *Deploy, incarnation string, target Build) *Deploy {
+ if old == nil || old.ID == "" || old.Incarnation != incarnation || old.Target != target || RetryRequested(old) {
+ return nil
+ }
+ return old
+}
+
+// NewAttemptAllowed judges a begin with a new ID against the record's
+// attempt. A new ID needs a changed target or lifetime, or consumes an
+// unconsumed retry of old; it never replaces an unresolved permit.
+func NewAttemptAllowed(old *Deploy, next Deploy) error {
+ if old == nil {
+ if next.RetryOf != "" {
+ return ErrInvalid
+ }
+ return nil
+ }
+ if old.PermitOutstanding() {
+ return ErrFenced
+ }
+ if !ReleasePassed(old.Phase) && old.Phase != "failed" && old.Phase != "unknown" && !(old.Phase == "pending" && old.Term != next.Term) {
+ return ErrInvalid
+ }
+ if next.RetryOf != "" {
+ if !RetryRequested(old) || next.RetryOf != old.ID || !Retryable(old) || old.Incarnation != next.Incarnation || old.Target != next.Target {
+ return ErrInvalid
+ }
+ return nil
+ }
+ if old.Incarnation == next.Incarnation && old.Target == next.Target {
+ return ErrInvalid
+ }
+ return nil
+}
+
+// CarryLastGood is the LastGood a new attempt of incarnation inherits. A
+// legacy released record without LastGood normalizes to its own target.
+func CarryLastGood(old *Deploy, incarnation string) Build {
+ if old == nil || old.Incarnation != incarnation {
+ return Build{}
+ }
+ if ReleasePassed(old.Phase) {
+ return old.Target
+ }
+ return old.LastGood
+}
+
+// Clone copies d without sharing its swap slices.
+func (d Deploy) Clone() Deploy {
+ d.Swap.Order = slices.Clone(d.Swap.Order)
+ d.Swap.Completed = slices.Clone(d.Swap.Completed)
+ return d
+}
+
+// NextSwapBox is the first ordered box that has not completed, or "".
+func (s Swap) NextSwapBox() string {
+ for _, box := range s.Order {
+ if !slices.Contains(s.Completed, box) {
+ return box
+ }
+ }
+ return ""
+}
+
+func validOrder(order []string) bool {
+ if len(order) == 0 {
+ return false
+ }
+ for i, box := range order {
+ if !controlname.ValidLabel(box) || (i > 0 && order[i-1] >= box) {
+ return false
+ }
+ }
+ return true
+}
+
+// NextDeploy is the swap transition table. Every op names the exact attempt,
+// pinned target and expected revision. Coordinator ops need the live term of
+// the calling box. An ack needs the permit's box and revision and only clears
+// that permit; nothing but a coordinator permit sets ActiveBox.
+func NextDeploy(cur Deploy, change DeployChange, coordinator Coordinator, now time.Time) (Deploy, error) {
+ if cur.ID == "" || change.ID != cur.ID || change.Target != cur.Target || change.Target.Digest == "" || change.Box == "" {
+ return Deploy{}, ErrFenced
+ }
+ if change.Revision != cur.Revision || cur.Revision == math.MaxUint64 {
+ return Deploy{}, ErrFenced
+ }
+ switch change.Op {
+ case "order", "permit", "halt", "done":
+ if change.Term == "" || coordinator.Term != change.Term || coordinator.Box != change.Box || !now.Before(coordinator.ExpiresAt) {
+ return Deploy{}, ErrFenced
+ }
+ case "ack":
+ if change.Term != "" || cur.Swap.ActiveBox == "" || change.Box != cur.Swap.ActiveBox || change.Permit != cur.Swap.Permit {
+ return Deploy{}, ErrFenced
+ }
+ default:
+ return Deploy{}, ErrInvalid
+ }
+ // Every swap op follows a passed release; done closes the attempt.
+ if cur.Phase != "released" {
+ return Deploy{}, ErrInvalid
+ }
+ next := cur.Clone()
+ s := &next.Swap
+ switch change.Op {
+ case "order":
+ if len(s.Order) != 0 || s.Halted || s.ActiveBox != "" || !validOrder(change.Order) || (change.Bootstrap && len(change.Order) != 1) {
+ return Deploy{}, ErrInvalid
+ }
+ s.Order = slices.Clone(change.Order)
+ s.Bootstrap = change.Bootstrap
+ case "permit":
+ if len(s.Order) == 0 || s.Halted || s.ActiveBox != "" || change.Grant == "" || change.Grant != s.NextSwapBox() {
+ return Deploy{}, ErrInvalid
+ }
+ s.ActiveBox = change.Grant
+ s.Permit = cur.Revision + 1
+ case "ack":
+ if change.Switched {
+ s.Completed = append(s.Completed, s.ActiveBox)
+ } else {
+ s.Halted = true
+ }
+ s.ActiveBox = ""
+ case "halt":
+ if len(s.Order) == 0 || s.Halted {
+ return Deploy{}, ErrInvalid
+ }
+ // The permit stays unresolved until its box answers.
+ s.Halted = true
+ case "done":
+ if len(s.Order) == 0 || s.Halted || s.ActiveBox != "" || s.NextSwapBox() != "" {
+ return Deploy{}, ErrInvalid
+ }
+ next.Phase = "done"
+ }
+ next.Revision = cur.Revision + 1
+ return next, nil
+}
diff --git a/internal/replicas/deploy_test.go b/internal/replicas/deploy_test.go
new file mode 100644
index 000000000..4f9ae220d
--- /dev/null
+++ b/internal/replicas/deploy_test.go
@@ -0,0 +1,412 @@
+package replicas
+
+import (
+ "errors"
+ "math/rand"
+ "slices"
+ "testing"
+ "time"
+)
+
+var deployNow = time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
+
+func releasedDeploy() Deploy {
+ return Deploy{ID: "deploy-2", Incarnation: "life", Target: Build{Version: "v2", Digest: "canonical-2"}, Phase: "released", Term: "term-a", LastGood: Build{Version: "v2", Digest: "canonical-2"}, Revision: 3}
+}
+
+func coordinatorA() Coordinator {
+ return Coordinator{Term: "term-a", Box: "a", BootID: "boot", ExpiresAt: deployNow.Add(time.Minute)}
+}
+
+func coordinatorChange(d Deploy, op string) DeployChange {
+ return DeployChange{Op: op, ID: d.ID, Term: "term-a", Box: "a", Revision: d.Revision, Target: d.Target}
+}
+
+func mustNext(t *testing.T, d Deploy, c DeployChange) Deploy {
+ t.Helper()
+ next, err := NextDeploy(d, c, coordinatorA(), deployNow)
+ if err != nil {
+ t.Fatalf("%s: %v", c.Op, err)
+ }
+ if next.Revision != d.Revision+1 {
+ t.Fatalf("%s: revision %d after %d", c.Op, next.Revision, d.Revision)
+ }
+ return next
+}
+
+// TestReplicaDeployTransitionCAS: every swap op names the exact attempt,
+// pinned digest, live term of the calling box and the expected revision; an
+// ack names the permit's box and revision; illegal edges and late results
+// are refused, and a refusal leaves the input untouched.
+func TestReplicaDeployTransitionCAS(t *testing.T) {
+ d := releasedDeploy()
+ order := coordinatorChange(d, "order")
+ order.Order = []string{"a", "b"}
+ ordered := mustNext(t, d, order)
+ permit := coordinatorChange(ordered, "permit")
+ permit.Grant = "a"
+ granted := mustNext(t, ordered, permit)
+ if granted.Swap.ActiveBox != "a" || granted.Swap.Permit != granted.Revision {
+ t.Fatalf("permit: %+v", granted.Swap)
+ }
+ ack := DeployChange{Op: "ack", ID: granted.ID, Box: "a", Revision: granted.Revision, Target: granted.Target, Permit: granted.Swap.Permit, Switched: true}
+ acked := mustNext(t, granted, ack)
+ if acked.Swap.ActiveBox != "" || !slices.Equal(acked.Swap.Completed, []string{"a"}) {
+ t.Fatalf("ack: %+v", acked.Swap)
+ }
+
+ refused := []struct {
+ name string
+ cur Deploy
+ c func(DeployChange) DeployChange
+ base DeployChange
+ co Coordinator
+ now time.Time
+ }{
+ {name: "wrong id", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.ID = "deploy-1"; return c }},
+ {name: "target digest", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Target.Digest = "other"; return c }},
+ {name: "target version", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Target.Version = "v3"; return c }},
+ {name: "empty digest", cur: Deploy{ID: "x", Phase: "released", Target: Build{Version: "v2"}}, base: DeployChange{Op: "order", ID: "x", Term: "term-a", Box: "a", Target: Build{Version: "v2"}, Order: []string{"a"}}, c: func(c DeployChange) DeployChange { return c }},
+ {name: "term", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Term = "term-old"; return c }},
+ {name: "expired term", cur: ordered, base: permit, now: deployNow.Add(time.Hour), c: func(c DeployChange) DeployChange { return c }},
+ {name: "other box as coordinator", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Box = "b"; return c }},
+ {name: "stale revision", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Revision--; return c }},
+ {name: "future revision", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Revision++; return c }},
+ {name: "permit out of order", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Grant = "b"; return c }},
+ {name: "second permit", cur: granted, base: coordinatorChange(granted, "permit"), c: func(c DeployChange) DeployChange { c.Grant = "b"; return c }},
+ {name: "permit renewed for the active box", cur: granted, base: coordinatorChange(granted, "permit"), c: func(c DeployChange) DeployChange { c.Grant = "a"; return c }},
+ {name: "order twice", cur: ordered, base: coordinatorChange(ordered, "order"), c: func(c DeployChange) DeployChange { c.Order = []string{"a"}; return c }},
+ {name: "unsorted order", cur: d, base: order, c: func(c DeployChange) DeployChange { c.Order = []string{"b", "a"}; return c }},
+ {name: "duplicate order", cur: d, base: order, c: func(c DeployChange) DeployChange { c.Order = []string{"a", "a"}; return c }},
+ {name: "bootstrap of two", cur: d, base: order, c: func(c DeployChange) DeployChange { c.Bootstrap = true; return c }},
+ {name: "done early", cur: acked, base: coordinatorChange(acked, "done"), c: func(c DeployChange) DeployChange { return c }},
+ {name: "done with open permit", cur: granted, base: coordinatorChange(granted, "done"), c: func(c DeployChange) DeployChange { return c }},
+ {name: "ack from other box", cur: granted, base: ack, c: func(c DeployChange) DeployChange { c.Box = "b"; return c }},
+ {name: "ack wrong permit", cur: granted, base: ack, c: func(c DeployChange) DeployChange { c.Permit--; return c }},
+ {name: "ack with a term", cur: granted, base: ack, c: func(c DeployChange) DeployChange { c.Term = "term-a"; return c }},
+ {name: "late ack", cur: acked, base: ack, c: func(c DeployChange) DeployChange { c.Revision = acked.Revision; return c }},
+ {name: "unknown op", cur: ordered, base: permit, c: func(c DeployChange) DeployChange { c.Op = "released"; return c }},
+ }
+ for _, phase := range []string{"pending", "releasing", "failed", "unknown", "done"} {
+ cur := d
+ cur.Phase = phase
+ refused = append(refused, struct {
+ name string
+ cur Deploy
+ c func(DeployChange) DeployChange
+ base DeployChange
+ co Coordinator
+ now time.Time
+ }{name: "order after " + phase, cur: cur, base: order, c: func(c DeployChange) DeployChange { return c }})
+ }
+ for _, tc := range refused {
+ t.Run(tc.name, func(t *testing.T) {
+ co, now := coordinatorA(), deployNow
+ if tc.now != (time.Time{}) {
+ now = tc.now
+ }
+ before := tc.cur.Clone()
+ next, err := NextDeploy(tc.cur, tc.c(tc.base), co, now)
+ if err == nil || next.ID != "" {
+ t.Fatalf("accepted: %+v", next)
+ }
+ if tc.cur.Revision != before.Revision || !slices.Equal(tc.cur.Swap.Order, before.Swap.Order) || tc.cur.Swap.ActiveBox != before.Swap.ActiveBox {
+ t.Fatal("refusal changed the input")
+ }
+ })
+ }
+
+ // Retry rereads every guard: the same permit retried after a halt landed
+ // is refused even though nothing else about the request changed.
+ halted := mustNext(t, granted, coordinatorChange(granted, "halt"))
+ if !halted.Swap.Halted || halted.Swap.ActiveBox != "a" || halted.Phase != "released" {
+ t.Fatalf("halt: %+v", halted)
+ }
+ retry := permit
+ retry.Revision = halted.Revision
+ if _, err := NextDeploy(halted, retry, coordinatorA(), deployNow); err == nil {
+ t.Fatal("permit after halt")
+ }
+ // The halted permit's own box still resolves it, without completing it
+ // unless it switched, and the ack cannot grant anything.
+ late := ack
+ late.Revision = halted.Revision
+ late.Switched = false
+ resolved := mustNext(t, halted, late)
+ if resolved.Swap.ActiveBox != "" || len(resolved.Swap.Completed) != 0 || !resolved.Swap.Halted {
+ t.Fatalf("halted ack: %+v", resolved.Swap)
+ }
+}
+
+// TestReplicaDeployNewAttemptRules is R9 and R2 at the writer's rule: the
+// record's attempt for this lifetime and target wins in every phase; a new ID
+// needs a changed target or lifetime or an unconsumed retry; nothing replaces
+// an unresolved permit; LastGood survives failures and normalizes legacy.
+func TestReplicaDeployNewAttemptRules(t *testing.T) {
+ target := Build{Version: "v2", Digest: "canonical-2"}
+ fresh := Deploy{ID: "fresh", Incarnation: "life", Target: target, Phase: "pending", Term: "term-b"}
+ for _, phase := range []string{"released", "failed", "unknown", "done"} {
+ old := &Deploy{ID: "old", Incarnation: "life", Target: target, Phase: phase, Term: "term-a"}
+ if err := NewAttemptAllowed(old, fresh); err == nil {
+ t.Fatalf("%s: fresh ID for an unchanged target", phase)
+ }
+ if DurableAttempt(old, "life", target) != old {
+ t.Fatalf("%s: durable attempt not adopted", phase)
+ }
+ changed := fresh
+ changed.Target = Build{Version: "v3", Digest: "canonical-3"}
+ if err := NewAttemptAllowed(old, changed); err != nil {
+ t.Fatalf("%s: changed target refused: %v", phase, err)
+ }
+ retry := fresh
+ retry.RetryOf = "old"
+ err := NewAttemptAllowed(old, retry)
+ if phase == "failed" || phase == "unknown" {
+ if err == nil {
+ t.Fatalf("%s: retry without a durable request", phase)
+ }
+ old.RetryOf = "old"
+ if DurableAttempt(old, "life", target) != nil {
+ t.Fatalf("%s: requested retry still adopted", phase)
+ }
+ if err := NewAttemptAllowed(old, retry); err != nil {
+ t.Fatalf("%s: requested retry refused: %v", phase, err)
+ }
+ if err := NewAttemptAllowed(old, fresh); err == nil {
+ t.Fatalf("%s: requested retry consumed without RetryOf", phase)
+ }
+ // Consumed: the new attempt carries RetryOf and is itself adopted.
+ consumed := &Deploy{ID: "fresh", Incarnation: "life", Target: target, Phase: "pending", Term: "term-b", RetryOf: "old"}
+ if RetryRequested(consumed) || DurableAttempt(consumed, "life", target) != consumed {
+ t.Fatalf("%s: consumed retry is not durable", phase)
+ }
+ again := retry
+ again.ID = "third"
+ if err := NewAttemptAllowed(consumed, again); err == nil {
+ t.Fatalf("%s: consumed retry minted twice", phase)
+ }
+ } else if err == nil {
+ t.Fatalf("%s: retry of a passed release", phase)
+ }
+ }
+ // A pending attempt of a dead term is retaken, not replaced.
+ pending := &Deploy{ID: "old", Incarnation: "life", Target: target, Phase: "pending", Term: "term-a"}
+ if err := NewAttemptAllowed(pending, fresh); err == nil {
+ t.Fatal("pending replaced for an unchanged target")
+ }
+ // An unresolved permit blocks any new attempt, halted or not.
+ for _, halted := range []bool{false, true} {
+ open := &Deploy{ID: "old", Incarnation: "life", Target: target, Phase: "released", Swap: Swap{Order: []string{"a", "b"}, ActiveBox: "a", Permit: 4, Halted: halted}}
+ changed := fresh
+ changed.Target = Build{Version: "v3", Digest: "canonical-3"}
+ if err := NewAttemptAllowed(open, changed); !errors.Is(err, ErrFenced) {
+ t.Fatalf("halted=%t: new attempt over an open permit: %v", halted, err)
+ }
+ if Retryable(open) {
+ t.Fatal("retry requested over an open permit")
+ }
+ }
+ // LastGood: written at released, carried by every begin, never cleared.
+ legacy := &Deploy{ID: "old", Incarnation: "life", Target: target, Phase: "released"}
+ if got := CarryLastGood(legacy, "life"); got != target {
+ t.Fatalf("legacy released not normalized: %+v", got)
+ }
+ failed := &Deploy{ID: "old", Incarnation: "life", Target: Build{Version: "v3", Digest: "c3"}, Phase: "failed", LastGood: target}
+ if got := CarryLastGood(failed, "life"); got != target {
+ t.Fatalf("failure cleared LastGood: %+v", got)
+ }
+ if got := CarryLastGood(failed, "other-life"); got != (Build{}) {
+ t.Fatalf("LastGood crossed lifetimes: %+v", got)
+ }
+ legacyFailed := &Deploy{ID: "old", Incarnation: "life", Target: target, Phase: "failed"}
+ if got := CarryLastGood(legacyFailed, "life"); got != (Build{}) {
+ t.Fatalf("legacy failure invented LastGood: %+v", got)
+ }
+}
+
+// deploySim is a randomized world: one durable Deploy, coordinators that
+// crash and change term, and boxes that see delayed, duplicated, reordered
+// or lost copies of the record and act on them.
+type deploySim struct {
+ rng *rand.Rand
+ durable Deploy
+ co Coordinator
+ boxes []string
+ inbox map[string][]Deploy // stale record copies in flight to each box
+ acked map[string]uint64 // each box's memory of permits it acked
+ switched map[string]bool // box serves the target
+ starts int // target generations started on permits
+ mid map[string]uint64 // box mid-switch on this permit
+ seen map[string]uint64 // newest revision each box observed
+ terms int
+ accepted int
+ maxActive int
+}
+
+func (s *deploySim) apply(c DeployChange) bool {
+ next, err := NextDeploy(s.durable, c, s.co, deployNow)
+ if err != nil {
+ return false
+ }
+ if c.Op == "ack" && next.Swap.ActiveBox != "" {
+ panic("an ack granted a permit")
+ }
+ s.durable = next
+ s.accepted++
+ for _, b := range s.boxes {
+ if s.rng.Intn(4) != 0 { // a lost copy never arrives
+ s.inbox[b] = append(s.inbox[b], next.Clone())
+ }
+ }
+ return true
+}
+
+func (s *deploySim) coordinatorStep() {
+ d := s.durable
+ if d.Phase != "released" || d.Swap.Halted || d.Swap.ActiveBox != "" {
+ return
+ }
+ c := DeployChange{ID: d.ID, Term: s.co.Term, Box: s.co.Box, Revision: d.Revision, Target: d.Target}
+ switch next := d.Swap.NextSwapBox(); {
+ case len(d.Swap.Order) == 0:
+ c.Op, c.Order = "order", slices.Clone(s.boxes)
+ case next != "":
+ c.Op, c.Grant = "permit", next
+ default:
+ c.Op = "done"
+ }
+ // A stale coordinator view sometimes sends an older revision.
+ if s.rng.Intn(5) == 0 && c.Revision > 0 {
+ c.Revision--
+ }
+ s.apply(c)
+ if s.rng.Intn(3) == 0 { // duplicate delivery
+ s.apply(c)
+ }
+}
+
+func (s *deploySim) boxStep(b string) {
+ q := s.inbox[b]
+ if len(q) == 0 {
+ return
+ }
+ i := s.rng.Intn(len(q)) // reordered delivery
+ view := q[i]
+ s.inbox[b] = append(q[:i:i], q[i+1:]...)
+ if s.rng.Intn(4) == 0 { // duplicate stays queued
+ s.inbox[b] = append(s.inbox[b], view)
+ }
+ // The worker keeps the newest observation (Note): an older copy is dropped.
+ if view.Revision < s.seen[b] {
+ return
+ }
+ s.seen[b] = view.Revision
+ if view.Swap.ActiveBox == b && view.Swap.Permit != 0 && s.acked[b] != view.Swap.Permit && s.mid[b] != view.Swap.Permit {
+ if !ReleasePassed(view.Phase) {
+ panic("permit on an unreleased attempt")
+ }
+ s.mid[b] = view.Swap.Permit
+ if !s.switched[b] {
+ s.starts++
+ }
+ }
+ if p := s.mid[b]; p != 0 {
+ switched := s.rng.Intn(5) != 0
+ ack := DeployChange{Op: "ack", ID: view.ID, Box: b, Revision: view.Revision, Target: view.Target, Permit: p, Switched: switched}
+ if s.rng.Intn(3) == 0 {
+ ack.Revision = s.durable.Revision // a reread
+ }
+ if s.apply(ack) {
+ s.acked[b] = p
+ s.seen[b] = s.durable.Revision
+ delete(s.mid, b)
+ s.switched[b] = s.switched[b] || switched
+ }
+ }
+ // A rogue box replays any permit it saw for another box.
+ if other := view.Swap.ActiveBox; other != "" && other != b {
+ rogue := DeployChange{Op: "ack", ID: view.ID, Box: b, Revision: s.durable.Revision, Target: view.Target, Permit: view.Swap.Permit, Switched: true}
+ if s.apply(rogue) {
+ panic("a box acked another box's permit")
+ }
+ }
+}
+
+// TestReplicaOnlyOneOutstandingPermit: under duplicated, reordered and
+// lost messages, coordinator crashes and box crashes, at most one box is
+// ever switching, permits follow the order, an unreleased attempt starts
+// no target, and only the matching ACK clears ActiveBox.
+func TestReplicaOnlyOneOutstandingPermit(t *testing.T) {
+ dones, starts, halts := 0, 0, 0
+ for seed := int64(1); seed <= 400; seed++ {
+ rng := rand.New(rand.NewSource(seed))
+ phase := []string{"released", "released", "released", "failed", "unknown", "pending", "releasing"}[rng.Intn(7)]
+ d := releasedDeploy()
+ d.Phase = phase
+ s := &deploySim{rng: rng, durable: d, co: coordinatorA(), boxes: []string{"a", "b", "c"}, inbox: map[string][]Deploy{}, acked: map[string]uint64{}, switched: map[string]bool{}, mid: map[string]uint64{}, seen: map[string]uint64{}}
+ for step := 0; step < 300; step++ {
+ switch r := rng.Intn(10); {
+ case r < 3:
+ s.coordinatorStep()
+ case r == 3 && rng.Intn(6) == 0:
+ // The coordinator dies; a successor takes a new term on any box.
+ s.terms++
+ s.co = Coordinator{Term: "term-" + string(rune('b'+s.terms)), Box: s.boxes[rng.Intn(3)], BootID: "boot", ExpiresAt: deployNow.Add(time.Minute)}
+ case r == 4 && rng.Intn(6) == 0:
+ // A box restarts and forgets what it was doing; a stop proof
+ // is lost with it, so its permit stays unresolved.
+ // Messages to the old process are lost; the new one starts from
+ // a fresh read of the record.
+ b := s.boxes[rng.Intn(3)]
+ delete(s.acked, b)
+ delete(s.mid, b)
+ delete(s.seen, b)
+ s.inbox[b] = []Deploy{s.durable.Clone()}
+ case r == 5 && rng.Intn(8) == 0 && s.durable.Phase == "released" && len(s.durable.Swap.Order) != 0:
+ s.apply(DeployChange{Op: "halt", ID: s.durable.ID, Term: s.co.Term, Box: s.co.Box, Revision: s.durable.Revision, Target: s.durable.Target})
+ default:
+ s.boxStep(s.boxes[rng.Intn(3)])
+ }
+ if len(s.mid) > s.maxActive {
+ s.maxActive = len(s.mid)
+ }
+ sw := s.durable.Swap
+ activePermits := 0
+ if sw.ActiveBox != "" {
+ activePermits = 1
+ if sw.ActiveBox != sw.NextSwapBox() {
+ t.Fatalf("seed %d: permit %s is not the next ordered box %+v", seed, sw.ActiveBox, sw)
+ }
+ }
+ if activePermits > 1 || len(s.mid) > 1 {
+ t.Fatalf("seed %d: %d permits, %d boxes switching", seed, activePermits, len(s.mid))
+ }
+ for b, p := range s.mid {
+ if sw.ActiveBox != b || sw.Permit != p {
+ t.Fatalf("seed %d: %s switching on permit %d, durable holds %s/%d", seed, b, p, sw.ActiveBox, sw.Permit)
+ }
+ }
+ if !slices.Equal(sw.Completed, sw.Order[:len(sw.Completed)]) {
+ t.Fatalf("seed %d: completed %v is not an order prefix of %v", seed, sw.Completed, sw.Order)
+ }
+ }
+ if !ReleasePassed(phase) && (s.starts != 0 || s.accepted != 0) {
+ t.Fatalf("seed %d: release %s started %d targets, %d transitions", seed, phase, s.starts, s.accepted)
+ }
+ starts += s.starts
+ if s.durable.Phase == "done" {
+ dones++
+ if !slices.Equal(s.durable.Swap.Completed, s.boxes) {
+ t.Fatalf("seed %d: done before every box switched: %+v", seed, s.durable.Swap)
+ }
+ }
+ if s.durable.Swap.Halted {
+ halts++
+ }
+ }
+ // The world must actually reach both ends, or the invariants say nothing.
+ if dones == 0 || halts == 0 || starts == 0 {
+ t.Fatalf("simulation never progressed: done=%d halted=%d starts=%d", dones, halts, starts)
+ }
+ t.Logf("done=%d halted=%d starts=%d", dones, halts, starts)
+}
diff --git a/internal/replicas/types.go b/internal/replicas/types.go
index 9d45cff6d..f9abb0e89 100644
--- a/internal/replicas/types.go
+++ b/internal/replicas/types.go
@@ -53,17 +53,41 @@ type Authority interface {
Release(context.Context) error
}
+// Deploy is one release run of an instance lifetime and build, and the
+// ordered copy swaps that follow a passed release (deploy.go).
type Deploy struct {
- ID string `json:"id,omitempty"`
- Incarnation string `json:"incarnation,omitempty"`
- Target Build `json:"target,omitempty"`
- Previous Build `json:"previous,omitempty"`
- Phase string `json:"phase,omitempty"`
- Term string `json:"term,omitempty"`
- Order []string `json:"order,omitempty"`
- Completed []string `json:"completed,omitempty"`
- ActiveBox string `json:"active_box,omitempty"`
- Revision uint64 `json:"revision,omitempty"`
+ ID string `json:"id,omitempty"`
+ Incarnation string `json:"incarnation,omitempty"`
+ Target Build `json:"target,omitempty"`
+ Previous Build `json:"previous,omitempty"`
+ // Phase is the release phase: pending, releasing, released, failed,
+ // unknown, or done once every ordered copy switched.
+ Phase string `json:"phase,omitempty"`
+ Term string `json:"term,omitempty"`
+ // LastGood is the target of this lifetime's last attempt whose release
+ // passed. The writer sets it at released and carries it forward on every
+ // begin; failed and unknown never clear it.
+ LastGood Build `json:"last_good,omitzero"`
+ // RetryOf equal to ID asks for one explicit retry of this failed or
+ // unknown attempt. On a different ID it names the attempt whose retry
+ // this attempt consumed.
+ RetryOf string `json:"retry_of,omitempty"`
+ // Swap is the box-by-box switch after a passed release.
+ Swap Swap `json:"swap,omitzero"`
+ Revision uint64 `json:"revision,omitempty"`
+}
+
+// Swap holds at most one outstanding permit. ActiveBox is unresolved from
+// grant until its matching ACK; Permit is the deploy revision that granted it.
+type Swap struct {
+ Order []string `json:"order,omitempty"`
+ Completed []string `json:"completed,omitempty"`
+ ActiveBox string `json:"active_box,omitempty"`
+ Permit uint64 `json:"permit,omitempty"`
+ Halted bool `json:"halted,omitempty"`
+ // Bootstrap marks an order made when no assigned box was up: its first
+ // copy started alone, so it was not an availability-preserving rollout.
+ Bootstrap bool `json:"bootstrap,omitempty"`
}
type ReleaseChange struct {
@@ -72,4 +96,6 @@ type ReleaseChange struct {
Term string `json:"term,omitempty"`
Revision uint64 `json:"revision,omitempty"`
Target Build `json:"target,omitempty"`
+ // RetryOf is set only on the begin that consumes an explicit retry.
+ RetryOf string `json:"retry_of,omitempty"`
}
diff --git a/internal/rollout/failures.go b/internal/rollout/failures.go
index 32e7b9f69..75d8fe36b 100644
--- a/internal/rollout/failures.go
+++ b/internal/rollout/failures.go
@@ -231,6 +231,9 @@ type replicaReleaseSelection struct {
Identity replicas.Identity `json:"identity"`
Target replicas.Build `json:"target"`
ID string `json:"id"`
+ // RetryOf names the record attempt whose durable retry this ID was
+ // minted for; only that retry reuses it.
+ RetryOf string `json:"retry_of,omitempty"`
}
type failureFile struct {
@@ -1325,9 +1328,11 @@ func (b *FailureBook) List() []FailureRecord {
return out
}
-// ReplicaDeployID persists the selected release attempt before preparation can
-// acquire authority. Only a changed target/lifetime or an explicit retry changes
-// the ID. A durable terminal result never creates another attempt by itself.
+// ReplicaDeployID persists the release attempt the coordinator term holder
+// uses. The record's attempt for this lifetime and target always wins, in
+// every phase, and overwrites the local selection (R9). Only a changed
+// target or lifetime, or an unconsumed durable retry on the record, selects
+// a new ID; a local retry clear alone never does.
func (b *FailureBook) ReplicaDeployID(id replicas.Identity, target replicas.Build, observed *replicas.Deploy) (string, error) {
b.mu.Lock()
defer b.mu.Unlock()
@@ -1340,14 +1345,21 @@ func (b *FailureBook) ReplicaDeployID(id replicas.Identity, target replicas.Buil
}
key := id.Host
selected, exists := b.replicaReleases[key]
- if exists && selected.Identity == id && selected.Target == target && selected.ID != "" {
+ same := exists && selected.Identity == id && selected.Target == target && selected.ID != ""
+ next, retryOf := "", ""
+ if durable := replicas.DurableAttempt(observed, id.Incarnation, target); durable != nil {
+ next = durable.ID
+ } else if replicas.RetryRequested(observed) && observed.Incarnation == id.Incarnation && observed.Target == target {
+ // Keep the ID minted for this retry stable across restarts.
+ retryOf = observed.ID
+ if same && selected.RetryOf == retryOf {
+ return selected.ID, nil
+ }
+ } else if same {
return selected.ID, nil
}
- next := ""
- // Recover an attempt made by this or a previous box, unless the local
- // durable selection explicitly invalidated it for a retry.
- if !exists && observed != nil && observed.ID != "" && observed.Incarnation == id.Incarnation && observed.Target == target {
- next = observed.ID
+ if same && selected.ID == next && selected.RetryOf == "" {
+ return next, nil
}
if next == "" {
var err error
@@ -1359,7 +1371,7 @@ func (b *FailureBook) ReplicaDeployID(id replicas.Identity, target replicas.Buil
if b.replicaReleases == nil {
b.replicaReleases = map[string]replicaReleaseSelection{}
}
- b.replicaReleases[key] = replicaReleaseSelection{Identity: id, Target: target, ID: next}
+ b.replicaReleases[key] = replicaReleaseSelection{Identity: id, Target: target, ID: next, RetryOf: retryOf}
if err := b.saveLocked(); err != nil {
return "", err
}
diff --git a/internal/rollout/stateless_test.go b/internal/rollout/stateless_test.go
index a07c27839..35d5c77d1 100644
--- a/internal/rollout/stateless_test.go
+++ b/internal/rollout/stateless_test.go
@@ -101,9 +101,15 @@ func TestStatelessDeployIDExplicitRetry(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ // R9: the local clear alone never replaces the durable attempt.
+ kept, err := b.ReplicaDeployID(id, target, old)
+ if err != nil || kept != first {
+ t.Fatalf("local clear replaced the durable attempt = %q, %v", kept, err)
+ }
+ old.RetryOf = old.ID
next, err := b.ReplicaDeployID(id, target, old)
if err != nil || next == first || next == "" {
- t.Fatalf("retry after restart = %q, %v", next, err)
+ t.Fatalf("durable retry = %q, %v", next, err)
}
same, err := b.ReplicaDeployID(id, target, old)
if err != nil || same != next {
@@ -201,3 +207,70 @@ func TestStatelessDeployIDRejectedRetryKeepsID(t *testing.T) {
t.Fatalf("rejected retry changed ID = %q, %v", same, err)
}
}
+
+// TestReplicaDeployIDDurableAttemptWins (R9): a book holding its own
+// selection adopts the record's attempt for the same lifetime and target in
+// every phase and keeps it across a restart; it mints only for an
+// unconsumed durable retry, keeps that minted ID stable, and adopts the
+// attempt that consumed the retry.
+func TestReplicaDeployIDDurableAttemptWins(t *testing.T) {
+ id := replicas.Identity{Account: "bab", App: "shop", Host: "example.com", Incarnation: "lifetime"}
+ target := replicas.Build{Version: "v1", Digest: "canonical"}
+ for _, phase := range []string{"pending", "releasing", "released", "failed", "unknown", "done"} {
+ t.Run(phase, func(t *testing.T) {
+ dir := t.TempDir()
+ b, err := OpenFailureBook(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ local, err := b.ReplicaDeployID(id, target, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ durable := &replicas.Deploy{ID: "record-attempt", Incarnation: id.Incarnation, Target: target, Phase: phase}
+ got, err := b.ReplicaDeployID(id, target, durable)
+ if err != nil || got != durable.ID || got == local {
+ t.Fatalf("book won over the record: %q, %v", got, err)
+ }
+ b, err = OpenFailureBook(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, err := b.ReplicaDeployID(id, target, nil); err != nil || got != durable.ID {
+ t.Fatalf("adoption not durable: %q, %v", got, err)
+ }
+ if phase != "failed" && phase != "unknown" {
+ return
+ }
+ durable.RetryOf = durable.ID
+ retry, err := b.ReplicaDeployID(id, target, durable)
+ if err != nil || retry == durable.ID || retry == "" {
+ t.Fatalf("retry = %q, %v", retry, err)
+ }
+ b, err = OpenFailureBook(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if again, err := b.ReplicaDeployID(id, target, durable); err != nil || again != retry {
+ t.Fatalf("retry ID changed across restart: %q, %v", again, err)
+ }
+ // An older selection of this box is never reused for a retry it
+ // was not minted for.
+ fresh, err := OpenFailureBook(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ stale, err := fresh.ReplicaDeployID(id, target, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, err := fresh.ReplicaDeployID(id, target, durable); err != nil || got == stale || got == durable.ID {
+ t.Fatalf("stale selection reused for a retry: %q, %v", got, err)
+ }
+ consumed := &replicas.Deploy{ID: "other-box-retry", Incarnation: id.Incarnation, Target: target, Phase: "pending", RetryOf: durable.ID}
+ if got, err := b.ReplicaDeployID(id, target, consumed); err != nil || got != consumed.ID {
+ t.Fatalf("consumed retry minted again: %q, %v", got, err)
+ }
+ })
+ }
+}
diff --git a/parity/parity.tsv b/parity/parity.tsv
index cf2743a10..88bc031ea 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -246,5 +246,5 @@ alert-signing-key platform internal GET /alerts/signing-key The public key al
legacy-apps platform internal GET /apps ; GET /apps/{app} Old URLs kept as redirects into the account.
billing-webhook platform internal POST /billing/webhook Stripe calls it.
ses-events platform internal POST /api/ses/events Amazon SES delivery events.
-box-doors platform internal POST /api/fleet/enrol ; GET /api/box/interactive/{id} ; GET /api/box/runs/{id} ; POST /api/fleet/replicas/{account}/{app}/{host}/coordinator ; POST /api/fleet/replicas/{account}/{app}/{host}/release Doors boxes and managed fleets call, not people.
+box-doors platform internal POST /api/fleet/enrol ; GET /api/box/interactive/{id} ; GET /api/box/runs/{id} ; POST /api/fleet/replicas/{account}/{app}/{host}/coordinator ; POST /api/fleet/replicas/{account}/{app}/{host}/release ; POST /api/fleet/replicas/{account}/{app}/{host}/deploy Doors boxes and managed fleets call, not people.
plumbing platform internal __demo-snapshot ; __registry-child ; __rootfs-check-probe ; __rootfs-check-prepare ; __cgexec ; __cgprobe Words the binary runs itself as, dispatched before the command switch.