carlos / platform Public

replicas: keep each box's baseline across attempts (#511)

A new attempt after a halted swap set Previous to the halted target,
so a box that never switched could cold-start that target without a
permit while the retry's release ran or after it failed (Astra C1,
Fable I2).

The writer now records a per-box baseline at begin
(replicas.CarryBaselines): a box in the old Swap.Completed keeps the
old target, every other box keeps the old baseline. Deploy gains
Baselines, overriding Previous per box; Baseline, Allows and Want read
it, so the writer, the wake planner and the final launch gate all
agree. A record with no assignment keeps CarryLastGood.

Witnesses through the real writer: the activator's planned wake and
final gate, the rollout planner, and the writer's chain of halts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 705641644d8a489b0f7e581f5157926075d57276 parent 1ac90c5
9 files changed, +561 −21
  • internal/activator/replicabaseline_test.go +195 −0
  • internal/activator/replicadeploy_test.go +1 −0
  • internal/activator/statelessrelease_test.go +5 −2
  • internal/provision/replicadeploy.go +11 −7
  • internal/provision/replicadeploy_test.go +79 −3
  • internal/replicas/deploy.go +57 −8
  • internal/replicas/deploy_test.go +60 −0
  • internal/replicas/types.go +9 −1
  • internal/rollout/replicabaseline_test.go +144 −0

Intent

Human

<task-notification> <task-id>a52656b6810285089</task-id> <tool-use-id>toolu_01W62XmdLpawvcZwHhMi3u6i</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a52656b6810285089.output</output-file> <status>completed</status> <summary>Agent "Fix CI failures on Plan 4 branch" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Seven of the ten failures are fixed and committed; two I stopped on because they conflict with approved copy. All targeted tests pass except those two. I also made a mistake with `/tmp/g` (last bullet). - **Five census and claim tests plus the two linked-policy tests** (`TestBuyDoorClaimBoundaries`, `TestClaimConsoleRouteCensus`, the moves and region-HA censuses, `TestClaimConsoleMutationInvariant`, `TestLinkedAppRefusedOnAppRoutes`, `TestLinkedPolicyCoversEveryAppRoute`): inventory this branch owed. `/deploy` is now classified everywhere `/release` is. Its claim door fixture runs the first swap step ("order"): a foreign claim must leave the swap order empty, and an open app must record the console's order. In main's linked policy it is refused like `/release` and `/coordinator`, and the linked walk skips it the same way. It is the only route this branch adds. The moves and region-HA censuses only needed the fixture. - **Follow-on census failure:** `TestPlan9B8RecordWriteCensus` then failed because the record-write census pins main's `linkedPolicies` table by digest. I re-pinned it in the Task 5 overlay with the same class and kinds. It writes no record, and `make census-card` stays clean. - **`TestReplicaReleaseTakeoverAdoptsDurableAttempt`:** not a conflict with main. It is a timing flake in this branch's test world. Its fake console worked out the remaining lease time from a clock read before the write, so any write slower than 1 ms reported more than the full lease and the client rightly refused the acquire. It now reads the clock after the write, as the real console handler does. A store slowed by 2 ms reproduced the failure before the fix and passes after; the test is not weakened. - **STOPPED: `TestRolloutReason` and `TestRolloutNoteConsoleUnreachable`.** Main's tests expect the reason text "console unreachable". The Luna pass (484d4fe2) changed it to "console could not be reached" (SR-1-C14, approved). Per your rule I changed neither the copy nor the tests, so both still fail. The text is also a wire value: boxes send it as their rollout reason, and the CLI and instance page match on it. A box on an older build that still sends "console unreachable" would show "rolling out" against the new CLI and console. This needs a ruling: either separate the wire value from the displayed words, or update main's two tests. - **Commits:** cff9d23f (classify `/deploy` like `/release`), 758ef7f4 (lease time read after the write), 1ac90c53 (census re-pin). Not pushed. - **Tests:** passing are the seven inventory tests, `TestReplicaCoordinatorClaimMutations` (now covering deploy), the activator test (also 300 repeat runs at 1 and 4 CPUs) and `go test ./internal/provision -run 'Census|Plan14|Plan9'`. The darwin/arm64, linux/arm64 and windows/amd64 cross-builds are OK. - **My mistake:** to clean up I ran `rm -rf /tmp/g/*`, which deleted everything in `/tmp/g`, not just what I created. If another session had files there, they are gone and I can't restore them.</result> <usage><subagent_tokens>134588</subagent_tokens><tool_uses>52</tool_uses><duration_ms>1000083</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>aed60289598fdcb62</task-id> <tool-use-id>toolu_01ULp9dJZpuk1dzTysnfejA4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/aed60289598fdcb62.output</output-file> <status>completed</status> <summary>Agent "Investigate v0.35.900 version safety" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I've written the answer to [version-safety.md](/home/paulca/.cache/tmp/claude-1001/sr4-drill/version-safety.md) (141 lines, with file:line evidence for each check). - **Q1, "newest seen" memory: SAFE WITH STEPS.** Nothing records a highest version seen; every floor is either published by an operator or a fixed constant. Four things need care: - Don't run `console hosts-used activate` or `raise-floor` while the candidate console is installed. Either would set the hostname history's floor to v0.35.900, and every CLI below that, including a real v0.35.0, would then be refused for `carlos accounts migrate`. - After rolling back, the console channel's rollback target is v0.35.900, so a later `carlos rollback` would reinstall the candidate. Roll forward only, or delete the candidate's release objects. - Keep the candidate CLI off PATH. A v0.35.900 CLI treats v0.35.0 as older and `carlos update` says there is nothing to do. - Never publish v0.35.900 to GitHub, apt, the tap or latest.txt. - **Q2, downgrade guards: SAFE WITH STEPS.** The console rollback is the usual `carlos promote -app console v0.34.46 canary/console`, run straight against the bucket. That is a pointer change for the console app, not a platform channel publication, so none of the floors, the replica judge or the hold rule ever see it. Steps: - Before the promote, set copies back to 1 and delete the instances and the app. The replica record format changed on this branch, and v0.34.46 would drop the new fields when it rewrites a record. - Check the healthz endpoint and the running binary's hash afterwards. If v0.34.46 fails to start, sophie automatically puts v0.35.900 back. - If canary or stable ever move to the candidate, the candidate console refuses to move them below v0.35.0 while copies are in use, and there is no override. - **Q3, console.db: SAFE.** Since v0.34.46 there are no new migrations, no schema changes and no SQL changes, and the user_version stays 1. The file gives the `sqlite3 -readonly .backup` command and a restore procedure for console.service on sophie. Never restore registry.db, because sophie's own box process uses it too. Two things block the drill itself, beyond what you asked: - **No way to publish `drill-sr`.** The console only publishes canary and stable, so that pointer would have to be signed by hand with the root key. - **Copies 2 is refused.** It stays refused while any dev channel is below v0.35.0; drill-scope.md already lists this as B1.</result> <usage><subagent_tokens>217062</subagent_tokens><tool_uses>89</tool_uses><duration_ms>733120</duration_ms></usage> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="19109a9f-eaaf-44bf-97b3-8f93017b8afa"> Agent manager 8a3d302: OK on all of it: the order (B2 window closes on v0.34.46 before the candidate; copies back to 1 and drill app deleted before the rollback; candidate release objects deleted; candidate CLI off PATH; nothing published), the console.db backup, and drill-sr with no pointer and the binary installed over SSM. One thing for the re-review, explicitly: &quot;no pointer passes&quot; the copies check. In production that means a fleet box following an unpublished or deleted channel counts as at the floor although nobody knows what it runs. Ask Astra whether the check should instead (or also) use the boxes&apos; own reported versions, and whether &quot;no pointer passes&quot; is safe. If Astra says it&apos;s unsafe, fix it in the product, and the drill uses the boxes&apos; reported v0.35.900 to pass. </paseo-system>

diff --git a/internal/activator/replicabaseline_test.go b/internal/activator/replicabaseline_test.go
new file mode 100644
index 000000000..b2e9c701b
--- /dev/null
+++ b/internal/activator/replicabaseline_test.go
@@ -0,0 +1,195 @@
+package activator
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// haltedRetryDeploys drives one record through the real typed writers
+// (#511 final wave, item 1) and returns its deploy after each of phases of
+// the retry attempt: deploy-v1 done on first and second; deploy-v2's
+// release passed and its swap halted (first kept v1, or, with
+// firstSwitched, first switched and second kept v1); an explicit retry of
+// deploy-v2 requested; and the retry's attempt, deploy-v2-retry, taken
+// through phases.
+func haltedRetryDeploys(t *testing.T, first, second string, firstSwitched bool, phases ...string) []*replicas.Deploy {
+ t.Helper()
+ s := release.NewDirStore(t.TempDir())
+ ctx := provision.WithRecordSequence(context.Background())
+ 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, 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}
+ ctx, err = provision.WithReplicaAssignmentManifest(ctx, *got, &release.Manifest{Schema: 1, App: "shop", Version: "v1", Kind: "binary", Stateless: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.SetRecordReplicaAssignment(ctx, s, id, replicas.Expect{Incarnation: inc, Region: got.Region, RecordSeq: got.RecordSeq}, replicas.Assignment{Desired: 2, Boxes: []string{first, second}}); err != nil {
+ t.Fatal(err)
+ }
+ cur, err := provision.SetRecordCoordinator(ctx, s, id, replicas.CoordinatorChange{Op: "acquire", Box: first, BootID: "boot"}, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ term := cur.Coordinator.Term
+ revision := func() uint64 {
+ if cur.ReplicaDeploy == nil {
+ return 0
+ }
+ return cur.ReplicaDeploy.Revision
+ }
+ rel := func(deployID string, b replicas.Build, retryOf string, phases ...string) {
+ t.Helper()
+ for _, phase := range phases {
+ d := replicas.Deploy{ID: deployID, Incarnation: inc, Term: term, Target: b, Phase: phase}
+ if phase == "pending" {
+ d.RetryOf = retryOf
+ }
+ if cur, err = provision.SetRecordReplicaRelease(ctx, s, id, revision(), d); err != nil {
+ t.Fatalf("%s %s: %v", deployID, phase, err)
+ }
+ }
+ }
+ swap := func(c replicas.DeployChange) {
+ t.Helper()
+ d := cur.ReplicaDeploy
+ c.ID, c.Target = d.ID, d.Target
+ if c.Op == "ack" {
+ c.Permit = d.Swap.Permit
+ } else {
+ c.Term, c.Box = term, first
+ }
+ if cur, err = provision.SetRecordReplicaDeploy(ctx, s, id, revision(), c, time.Now()); err != nil {
+ t.Fatalf("%s: %v", c.Op, err)
+ }
+ }
+ v1 := replicas.Build{Version: "v1", Digest: "canonical-v1"}
+ v2 := replicas.Build{Version: "v2", Digest: "canonical-v2"}
+ rel("deploy-v1", v1, "", "pending", "releasing", "released")
+ swap(replicas.DeployChange{Op: "order", Order: []string{first, second}})
+ for _, box := range []string{first, second} {
+ swap(replicas.DeployChange{Op: "permit", Grant: box})
+ swap(replicas.DeployChange{Op: "ack", Box: box, Switched: true})
+ }
+ swap(replicas.DeployChange{Op: "done"})
+ rel("deploy-v2", v2, "", "pending", "releasing", "released")
+ swap(replicas.DeployChange{Op: "order", Order: []string{first, second}})
+ swap(replicas.DeployChange{Op: "permit", Grant: first})
+ swap(replicas.DeployChange{Op: "ack", Box: first, Switched: firstSwitched})
+ if firstSwitched {
+ swap(replicas.DeployChange{Op: "permit", Grant: second})
+ swap(replicas.DeployChange{Op: "ack", Box: second})
+ }
+ if d := cur.ReplicaDeploy; !d.Swap.Halted || d.PermitOutstanding() {
+ t.Fatalf("deploy-v2 not halted: %+v", d)
+ }
+ if cur, err = provision.RequestRecordReplicaRetry(ctx, s, id, "deploy-v2", "retry-1"); err != nil {
+ t.Fatal(err)
+ }
+ var out []*replicas.Deploy
+ for _, phase := range phases {
+ rel("deploy-v2-retry", v2, "deploy-v2", phase)
+ d := cur.ReplicaDeploy.Clone()
+ out = append(out, &d)
+ }
+ return out
+}
+
+// TestReplicaRetryKeepsPerBoxBaseline (#511 final wave, item 1; Astra C1,
+// Fable I2): v2's release passed, a's switch failed and a kept v1, so the
+// deploy halted; then a retry began. While the retry's release runs, after
+// it passes with no permit yet, and after it fails, box b may not
+// cold-start v2: the record the real writer left names v1 as its baseline,
+// so the planned wake (with its fallback), the final launch gate and the
+// policy all refuse v2, and b's baseline wake starts v1. When a switched
+// and b failed, a's baseline is v2 and b's stays v1.
+func TestReplicaRetryKeepsPerBoxBaseline(t *testing.T) {
+ phases := []string{"pending", "releasing", "released"}
+ for _, firstSwitched := range []bool{false, true} {
+ for i, d := range haltedRetryDeploys(t, "a", "b", firstSwitched, phases...) {
+ name := phases[i]
+ if firstSwitched {
+ name += "/a switched"
+ }
+ t.Run(name, func(t *testing.T) {
+ state := func(inc string) *replicas.Deploy {
+ c := d.Clone()
+ c.Incarnation = inc
+ return &c
+ }
+ if d.Baseline("b") != replicaGood || d.Allows("b", d.Incarnation, replicaTarget.Digest) || d.Want("b") != replicaGood {
+ t.Fatalf("b may run v2 without a permit: %+v", d)
+ }
+ if firstSwitched != d.Allows("a", d.Incarnation, replicaTarget.Digest) {
+ t.Fatalf("a's baseline: %+v", d)
+ }
+ t.Run("planned first wake", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", state)
+ r.setPlan(WakePlan{Boot: r.next, Mode: ModeOverlap, FirstWake: true, Fallback: &r.good, Token: 1})
+ waitErr(t, r.wake(r.a))
+ if r.started("v2") {
+ t.Fatalf("b cold-started v2 without a permit: %v", r.b.events())
+ }
+ })
+ t.Run("final launch gate", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", state)
+ facts, err := r.a.cfg.ReplicaRecord(r.rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if facts.ReplicaDeploy.Allows("b", r.inc, replicaTarget.Digest) || !facts.ReplicaDeploy.Allows("b", r.inc, replicaGood.Digest) {
+ t.Fatalf("final gate on the record: %+v", facts.ReplicaDeploy)
+ }
+ if r.a.replicaPolicyAllows(r.rt, replicaTarget.Digest) {
+ t.Fatal("the observed policy allows v2 on b")
+ }
+ })
+ t.Run("baseline wake", func(t *testing.T) {
+ r := newReplicaSetRig(t, "b", state)
+ r.setPlan(WakePlan{Boot: r.good, Mode: ModeOverlap, Token: 1})
+ if err := waitErr(t, r.wake(r.a)); err != nil || !r.started("v1") {
+ t.Fatalf("b's baseline wake: %v %v", err, r.b.events())
+ }
+ })
+ if firstSwitched {
+ t.Run("a keeps v2", func(t *testing.T) {
+ r := newReplicaSetRig(t, "a", state)
+ r.setPlan(WakePlan{Boot: r.next, Mode: ModeOverlap, FirstWake: true, Token: 1})
+ if err := waitErr(t, r.wake(r.a)); err != nil || !r.started("v2") {
+ t.Fatalf("a's baseline wake on v2: %v %v", err, r.b.events())
+ }
+ })
+ }
+ })
+ }
+ }
+ // After the retry's release fails, b still may not run v2.
+ failed := haltedRetryDeploys(t, "a", "b", false, "pending", "failed")[1]
+ if failed.Allows("b", failed.Incarnation, replicaTarget.Digest) || failed.Want("b") != replicaGood || failed.Want("a") != replicaGood {
+ t.Fatalf("failed retry: %+v", failed)
+ }
+ r := newReplicaSetRig(t, "b", func(inc string) *replicas.Deploy {
+ c := failed.Clone()
+ c.Incarnation = inc
+ return &c
+ })
+ r.setPlan(WakePlan{Boot: r.next, Mode: ModeOverlap, FirstWake: true, Fallback: &r.good, Token: 1})
+ waitErr(t, r.wake(r.a))
+ if r.started("v2") {
+ t.Fatalf("b cold-started v2 after the retry failed: %v", r.b.events())
+ }
+}
diff --git a/internal/activator/replicadeploy_test.go b/internal/activator/replicadeploy_test.go
index c8bfec08e..6cb4335d3 100644
--- a/internal/activator/replicadeploy_test.go
+++ b/internal/activator/replicadeploy_test.go
@@ -45,6 +45,7 @@ func newReplicaSetRigOn(t *testing.T, label string, shared *replicaReleaseStore,
store = shared
r.a.Coordinator = shared
}
+ store.assigned = true
rec := provision.Record{Schema: 1, Host: r.rt.Host, Account: r.rt.Account, App: r.rt.App, Channel: r.rt.Channel, Environment: r.rt.Environment, Runtime: r.rt.Runtime, Region: "fleet/pi", CreatedAt: time.Unix(1, 0), Hibernate: new(bool), ReplicaAssignment: &replicas.Assignment{Desired: 2, Revision: 1, Boxes: []string{"a", "b"}}}
inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
if err != nil {
diff --git a/internal/activator/statelessrelease_test.go b/internal/activator/statelessrelease_test.go
index ec25f381f..b4642f4d7 100644
--- a/internal/activator/statelessrelease_test.go
+++ b/internal/activator/statelessrelease_test.go
@@ -21,6 +21,9 @@ type replicaReleaseStore struct {
acquires int
lostReply bool
beginHook func() error
+ // assigned: the record has a replica assignment, for the writer's
+ // per-box baseline (replicas.CarryBaselines).
+ assigned bool
}
func (s *replicaReleaseStore) Acquire(context.Context, replicas.Identity) (replicas.Authority, error) {
@@ -59,10 +62,10 @@ func (s *replicaReleaseStore) ReleaseState(_ context.Context, id replicas.Identi
// LastGood and Previous as the real writer keeps them
// (provision.SetRecordReplicaRelease).
if s.d != nil && s.d.ID == c.ID {
- d.LastGood, d.Previous = s.d.LastGood, s.d.Previous
+ d.LastGood, d.Previous, d.Baselines = s.d.LastGood, s.d.Previous, s.d.Clone().Baselines
} else {
d.LastGood = replicas.CarryLastGood(s.d, id.Incarnation)
- d.Previous = d.LastGood
+ d.Previous, d.Baselines = replicas.CarryBaselines(s.d, id.Incarnation, s.assigned)
}
if phase == "released" {
d.LastGood = d.Target
diff --git a/internal/provision/replicadeploy.go b/internal/provision/replicadeploy.go
index 24f2cfce6..8424ed9a6 100644
--- a/internal/provision/replicadeploy.go
+++ b/internal/provision/replicadeploy.go
@@ -65,10 +65,14 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
return err
}
next.LastGood = replicas.CarryLastGood(old, id.Incarnation)
- // The attempt's baseline (Deploy.Baseline): copies not yet
- // allowed its target keep running this after its release
- // passes and LastGood moves to the target. The writer owns it.
- next.Previous = next.LastGood
+ // The attempt's baseline (Deploy.Baseline), per box: copies
+ // not yet allowed its target keep running the build each was
+ // authorised to run under the attempt it replaces, after its
+ // release passes and LastGood moves to the target. A box a
+ // halted swap switched keeps that target; every other box
+ // keeps that attempt's baseline, never a target it was not
+ // permitted. The writer owns it.
+ next.Previous, next.Baselines = replicas.CarryBaselines(old, id.Incarnation, rec.ReplicaAssignment != nil)
if next.RetryOf != "" {
// The consuming attempt keeps the request that asked for it.
next.RetryRequest = old.RetryRequest
@@ -77,9 +81,9 @@ func SetRecordReplicaRelease(ctx context.Context, s release.Store, id replicas.I
if old.Incarnation != next.Incarnation || old.Target != next.Target {
return replicas.ErrFenced
}
- // Previous is the writer's, set at begin; a box's copy of it
- // is ignored.
- next.Previous = old.Previous
+ // Previous and Baselines are the writer's, set at begin; a
+ // box's copy of them is ignored.
+ next.Previous, next.Baselines = old.Previous, old.Clone().Baselines
if next.RetryOf != "" && next.RetryOf != old.RetryOf {
return replicas.ErrInvalid
}
diff --git a/internal/provision/replicadeploy_test.go b/internal/provision/replicadeploy_test.go
index 5a0984271..f8c144355 100644
--- a/internal/provision/replicadeploy_test.go
+++ b/internal/provision/replicadeploy_test.go
@@ -953,13 +953,15 @@ func TestReplicaSwapBaselineSurvivesTheRelease(t *testing.T) {
}
v4 := replicas.Build{Version: "v4", Digest: "canonical-4"}
// deploy-3 is released with no open permit and not done: halt it first,
- // as an operator retry or a new pointer would find it.
+ // as an operator retry or a new pointer would find it. No copy switched
+ // to v3, so every copy keeps its baseline, v2 (final wave, item 1);
+ // LastGood still names v3.
order := w.change("order")
order.Order = []string{"a", "b"}
w.apply(t, order)
w.apply(t, w.change("halt"))
w.release(t, "deploy-4", v4, "", "pending", "failed")
- if d := w.rec.ReplicaDeploy; d.Previous != v3 || d.LastGood != v3 || d.Want("b") != v3 {
+ if d := w.rec.ReplicaDeploy; d.Previous != swapTarget || d.LastGood != v3 || d.Want("b") != swapTarget || len(d.Baselines) != 0 {
t.Fatalf("failed: %+v", d)
}
// A box's begin replay carries the Previous it read; the writer keeps it.
@@ -969,7 +971,81 @@ func TestReplicaSwapBaselineSurvivesTheRelease(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if rec.ReplicaDeploy.Previous != v3 {
+ if rec.ReplicaDeploy.Previous != swapTarget {
t.Fatalf("a box chose the baseline: %+v", rec.ReplicaDeploy)
}
}
+
+// TestReplicaWriterCarriesPerBoxBaseline (#511 final wave, item 1; Astra
+// C1, Fable I2): a new attempt keeps, for each box, the build that box was
+// authorised to run under the attempt it replaces. A box in the old
+// Swap.Completed keeps the old target; every other box keeps the old
+// baseline. It holds through a retry of a halted swap, through that
+// retry's own halt, and through a new build after it, and a box's copy of
+// the baselines is ignored.
+func TestReplicaWriterCarriesPerBoxBaseline(t *testing.T) {
+ w := newSwapWorld(t)
+ w.swapThrough(t) // v2 done on a and b
+ v3 := replicas.Build{Version: "v3", Digest: "canonical-3"}
+ // a switches to v3, b's switch fails: halted with a completed.
+ halt := func(t *testing.T, switched map[string]bool) {
+ 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, switched[box]))
+ if !switched[box] {
+ return
+ }
+ }
+ }
+ w.release(t, "deploy-3", v3, "", "pending", "releasing", "released")
+ halt(t, map[string]bool{"a": true})
+ if _, err := RequestRecordReplicaRetry(w.ctx, w.s, w.id, "deploy-3", "retry-1"); err != nil {
+ t.Fatal(err)
+ }
+ w.rec, _ = GetRecord(w.ctx, w.s, w.id.Account, w.id.App, w.id.Host)
+ check := func(t *testing.T, step string, previous replicas.Build, a replicas.Build) {
+ t.Helper()
+ d := w.rec.ReplicaDeploy
+ if d.Previous != previous || d.Want("a") != a || d.Want("b") != previous || d.Allows("b", w.id.Incarnation, d.Target.Digest) && d.Target != previous {
+ t.Fatalf("%s: %+v", step, d)
+ }
+ }
+ for _, phase := range []string{"pending", "releasing", "released"} {
+ w.release(t, "deploy-3r", v3, "deploy-3", phase)
+ check(t, "retry "+phase, swapTarget, v3)
+ }
+ if d := w.rec.ReplicaDeploy; len(d.Baselines) != 1 || d.Baselines["a"] != v3 {
+ t.Fatalf("retry baselines: %+v", d.Baselines)
+ }
+ // The retry halts the same way; a new build after it keeps both.
+ halt(t, map[string]bool{"a": true})
+ v4 := replicas.Build{Version: "v4", Digest: "canonical-4"}
+ w.release(t, "deploy-4", v4, "", "pending")
+ check(t, "v4 pending", swapTarget, v3)
+ w.release(t, "deploy-4", v4, "", "releasing", "released")
+ check(t, "v4 released", swapTarget, v3)
+ // v4 halts before any box switched: the next build still keeps both.
+ halt(t, nil)
+ v5 := replicas.Build{Version: "v5", Digest: "canonical-5"}
+ d := *w.rec.ReplicaDeploy
+ forged := replicas.Deploy{ID: "deploy-5", Incarnation: w.id.Incarnation, Term: w.term, Target: v5, Phase: "pending", Baselines: map[string]replicas.Build{"b": v4}}
+ rec, err := SetRecordReplicaRelease(w.ctx, w.s, w.id, d.Revision, forged)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.rec = rec
+ check(t, "v5 pending", swapTarget, v3)
+ // A done deploy resets every box to its target.
+ w.release(t, "deploy-5", v5, "", "releasing", "released")
+ w.swapThrough(t)
+ w.release(t, "deploy-6", replicas.Build{Version: "v6", Digest: "canonical-6"}, "", "pending")
+ if d := w.rec.ReplicaDeploy; d.Previous != v5 || len(d.Baselines) != 0 {
+ t.Fatalf("after done: %+v", d)
+ }
+}
diff --git a/internal/replicas/deploy.go b/internal/replicas/deploy.go
index a401de492..3fcfc43cc 100644
--- a/internal/replicas/deploy.go
+++ b/internal/replicas/deploy.go
@@ -102,10 +102,55 @@ func CarryLastGood(old *Deploy, incarnation string) Build {
return old.LastGood
}
-// Clone copies d without sharing its swap slices.
+// CarryBaselines is the baseline a new attempt of incarnation inherits
+// from old, per box: each box keeps the build it was authorised to run
+// under old (old.Want), so a new attempt never authorises a build on a box
+// that old did not. A box in old's Swap.Completed keeps old's target (it
+// switched); every other box keeps old's baseline for it, whatever old's
+// release did. previous is the baseline of a box old never named, and
+// boxes lists only the boxes whose baseline differs from it.
+//
+// assigned says the record has a replica assignment. A record with none
+// runs one copy, which runs whatever release passed without a permit, so
+// its new attempt starts from CarryLastGood, as before copies.
+func CarryBaselines(old *Deploy, incarnation string, assigned bool) (previous Build, boxes map[string]Build) {
+ if old == nil || old.Incarnation != incarnation {
+ return Build{}, nil
+ }
+ if !assigned || old.Phase == "done" {
+ return CarryLastGood(old, incarnation), nil
+ }
+ previous = old.Baseline("")
+ named := slices.Clone(old.Swap.Completed)
+ for box := range old.Baselines {
+ named = append(named, box)
+ }
+ slices.Sort(named)
+ for _, box := range slices.Compact(named) {
+ if box == "" {
+ continue
+ }
+ if b := old.Want(box); b != previous {
+ if boxes == nil {
+ boxes = map[string]Build{}
+ }
+ boxes[box] = b
+ }
+ }
+ return previous, boxes
+}
+
+// Clone copies d without sharing its swap slices or its baselines.
func (d Deploy) Clone() Deploy {
d.Swap.Order = slices.Clone(d.Swap.Order)
d.Swap.Completed = slices.Clone(d.Swap.Completed)
+ if d.Baselines != nil {
+ baselines := make(map[string]Build, len(d.Baselines))
+ for box, b := range d.Baselines {
+ baselines[box] = b
+ }
+ d.Baselines = baselines
+ }
return d
}
@@ -208,19 +253,23 @@ func NextDeploy(cur Deploy, change DeployChange, coordinator Coordinator, now ti
// says. Once the deploy is done, and for a box that completed its switch,
// it is the target: the previous build is no longer that box's fallback,
// so returning to it is a new attempt (a rollback takes the same path as a
-// promotion). For any other box it is Previous, the LastGood the attempt
-// began with, which the writer records at begin; before the release passes
-// that equals LastGood, which a legacy record without Previous falls back
-// to. It is empty when no build of this lifetime ever passed a release.
+// promotion). For any other box it is that box's entry in Baselines, or
+// else Previous: the per-box baseline the writer recorded at begin
+// (CarryBaselines), so a box a halted attempt never switched keeps the
+// build it ran, not the halted target. A legacy record without Previous
+// falls back to LastGood before its release passes. It is empty when no
+// build of this lifetime ever passed a release.
func (d *Deploy) Baseline(box string) Build {
switch {
case d == nil:
return Build{}
case d.Phase == "done", ReleasePassed(d.Phase) && box != "" && slices.Contains(d.Swap.Completed, box):
return d.Target
- case ReleasePassed(d.Phase):
- return d.Previous
- case d.Previous != (Build{}):
+ }
+ if b, ok := d.Baselines[box]; ok && box != "" {
+ return b
+ }
+ if ReleasePassed(d.Phase) || d.Previous != (Build{}) {
return d.Previous
}
return d.LastGood
diff --git a/internal/replicas/deploy_test.go b/internal/replicas/deploy_test.go
index 1b1c8c4ec..d170bd15c 100644
--- a/internal/replicas/deploy_test.go
+++ b/internal/replicas/deploy_test.go
@@ -504,3 +504,63 @@ func TestReplicaSwapWorkersFailedAckHalts(t *testing.T) {
t.Fatalf("workers failed without a switch: %v", err)
}
}
+
+// TestReplicaCarryBaselinesPerBox (#511 final wave, item 1): a new attempt
+// inherits, per box, the build that box was authorised to run under the
+// old attempt: the old target for a box in its Completed, the old
+// baseline for every other box, the target for all once done, and
+// LastGood for a record with no assignment (one copy, no permits).
+func TestReplicaCarryBaselinesPerBox(t *testing.T) {
+ v1, v2, v3 := Build{Version: "v1", Digest: "c1"}, Build{Version: "v2", Digest: "c2"}, Build{Version: "v3", Digest: "c3"}
+ halted := Deploy{ID: "d2", Incarnation: "life", Target: v2, Previous: v1, LastGood: v2, Phase: "released", Swap: Swap{Order: []string{"a", "b", "c"}, Completed: []string{"a"}, Halted: true}}
+ cases := []struct {
+ name string
+ old *Deploy
+ assigned bool
+ previous Build
+ boxes map[string]Build
+ }{
+ {"none", nil, true, Build{}, nil},
+ {"other lifetime", &Deploy{Incarnation: "old", Target: v2, Phase: "done"}, true, Build{}, nil},
+ {"done", &Deploy{Incarnation: "life", Target: v2, Previous: v1, Phase: "done"}, true, v2, nil},
+ {"halted, a switched", &halted, true, v1, map[string]Build{"a": v2}},
+ {"halted, nobody switched", &Deploy{Incarnation: "life", Target: v2, Previous: v1, LastGood: v2, Phase: "released", Swap: Swap{Order: []string{"a", "b"}, Halted: true}}, true, v1, nil},
+ {"failed after a halt", &Deploy{Incarnation: "life", Target: v3, Previous: v1, Baselines: map[string]Build{"a": v2}, LastGood: v2, Phase: "failed"}, true, v1, map[string]Build{"a": v2}},
+ {"halted again, b switched", &Deploy{Incarnation: "life", Target: v3, Previous: v1, Baselines: map[string]Build{"a": v2}, LastGood: v3, Phase: "released", Swap: Swap{Order: []string{"a", "b"}, Completed: []string{"b"}, Halted: true}}, true, v1, map[string]Build{"a": v2, "b": v3}},
+ {"legacy failed", &Deploy{Incarnation: "life", Target: v2, LastGood: v1, Phase: "failed"}, true, v1, nil},
+ {"unassigned released", &Deploy{Incarnation: "life", Target: v2, Previous: v1, Phase: "released"}, false, v2, nil},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ previous, boxes := CarryBaselines(c.old, "life", c.assigned)
+ if previous != c.previous || len(boxes) != len(c.boxes) {
+ t.Fatalf("got %+v %+v, want %+v %+v", previous, boxes, c.previous, c.boxes)
+ }
+ for box, b := range c.boxes {
+ if boxes[box] != b {
+ t.Fatalf("box %s: got %+v, want %+v", box, boxes[box], b)
+ }
+ }
+ next := Deploy{Incarnation: "life", Target: Build{Version: "v9", Digest: "c9"}, Phase: "released", Previous: previous, Baselines: boxes}
+ for _, box := range []string{"a", "b", "c", "z"} {
+ if c.old == nil || c.old.Incarnation != "life" {
+ break
+ }
+ want := c.old.Want(box)
+ if !c.assigned {
+ want = previous
+ }
+ if got := next.Baseline(box); got != want {
+ t.Fatalf("box %s keeps %+v, was authorised %+v", box, got, want)
+ }
+ }
+ })
+ }
+ // Clone shares no baselines.
+ d := Deploy{Baselines: map[string]Build{"a": v1}}
+ c := d.Clone()
+ c.Baselines["a"] = v2
+ if d.Baselines["a"] != v1 {
+ t.Fatal("Clone shared Baselines")
+ }
+}
diff --git a/internal/replicas/types.go b/internal/replicas/types.go
index 6d8930ca4..d8e7183dd 100644
--- a/internal/replicas/types.go
+++ b/internal/replicas/types.go
@@ -85,7 +85,15 @@ type Deploy struct {
ID string `json:"id,omitempty"`
Incarnation string `json:"incarnation,omitempty"`
Target Build `json:"target,omitempty"`
- Previous Build `json:"previous,omitempty"`
+ // Previous is the baseline the writer set at begin: the build a copy
+ // runs while this attempt's target is not allowed on it.
+ Previous Build `json:"previous,omitempty"`
+ // Baselines overrides Previous for the boxes whose baseline differs
+ // from it: the per-box build each was authorised to run when this
+ // attempt began (CarryBaselines). A box absent from it has Previous.
+ // The writer sets it at begin and carries it unchanged; only a new
+ // attempt after a halted swap needs it.
+ Baselines map[string]Build `json:"baselines,omitempty"`
// Phase is the release phase: pending, releasing, released, failed,
// unknown, or done once every ordered copy switched.
Phase string `json:"phase,omitempty"`
diff --git a/internal/rollout/replicabaseline_test.go b/internal/rollout/replicabaseline_test.go
new file mode 100644
index 000000000..212ffd7ed
--- /dev/null
+++ b/internal/rollout/replicabaseline_test.go
@@ -0,0 +1,144 @@
+package rollout
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// haltedRetryDeploys drives one record through the real typed writers
+// (#511 final wave, item 1; the activator test has its twin) and returns its deploy after each of phases of
+// the retry attempt: deploy-v1 done on first and second; deploy-v2's
+// release passed and its swap halted (first kept v1, or, with
+// firstSwitched, first switched and second kept v1); an explicit retry of
+// deploy-v2 requested; and the retry's attempt, deploy-v2-retry, taken
+// through phases.
+func haltedRetryDeploys(t *testing.T, first, second string, firstSwitched bool, phases ...string) []*replicas.Deploy {
+ t.Helper()
+ s := release.NewDirStore(t.TempDir())
+ ctx := provision.WithRecordSequence(context.Background())
+ 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, 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}
+ ctx, err = provision.WithReplicaAssignmentManifest(ctx, *got, &release.Manifest{Schema: 1, App: "shop", Version: "v1", Kind: "binary", Stateless: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.SetRecordReplicaAssignment(ctx, s, id, replicas.Expect{Incarnation: inc, Region: got.Region, RecordSeq: got.RecordSeq}, replicas.Assignment{Desired: 2, Boxes: []string{first, second}}); err != nil {
+ t.Fatal(err)
+ }
+ cur, err := provision.SetRecordCoordinator(ctx, s, id, replicas.CoordinatorChange{Op: "acquire", Box: first, BootID: "boot"}, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ term := cur.Coordinator.Term
+ revision := func() uint64 {
+ if cur.ReplicaDeploy == nil {
+ return 0
+ }
+ return cur.ReplicaDeploy.Revision
+ }
+ rel := func(deployID string, b replicas.Build, retryOf string, phases ...string) {
+ t.Helper()
+ for _, phase := range phases {
+ d := replicas.Deploy{ID: deployID, Incarnation: inc, Term: term, Target: b, Phase: phase}
+ if phase == "pending" {
+ d.RetryOf = retryOf
+ }
+ if cur, err = provision.SetRecordReplicaRelease(ctx, s, id, revision(), d); err != nil {
+ t.Fatalf("%s %s: %v", deployID, phase, err)
+ }
+ }
+ }
+ swap := func(c replicas.DeployChange) {
+ t.Helper()
+ d := cur.ReplicaDeploy
+ c.ID, c.Target = d.ID, d.Target
+ if c.Op == "ack" {
+ c.Permit = d.Swap.Permit
+ } else {
+ c.Term, c.Box = term, first
+ }
+ if cur, err = provision.SetRecordReplicaDeploy(ctx, s, id, revision(), c, time.Now()); err != nil {
+ t.Fatalf("%s: %v", c.Op, err)
+ }
+ }
+ v1 := replicas.Build{Version: "v1", Digest: "canonical-v1"}
+ v2 := replicas.Build{Version: "v2", Digest: "canonical-v2"}
+ rel("deploy-v1", v1, "", "pending", "releasing", "released")
+ swap(replicas.DeployChange{Op: "order", Order: []string{first, second}})
+ for _, box := range []string{first, second} {
+ swap(replicas.DeployChange{Op: "permit", Grant: box})
+ swap(replicas.DeployChange{Op: "ack", Box: box, Switched: true})
+ }
+ swap(replicas.DeployChange{Op: "done"})
+ rel("deploy-v2", v2, "", "pending", "releasing", "released")
+ swap(replicas.DeployChange{Op: "order", Order: []string{first, second}})
+ swap(replicas.DeployChange{Op: "permit", Grant: first})
+ swap(replicas.DeployChange{Op: "ack", Box: first, Switched: firstSwitched})
+ if firstSwitched {
+ swap(replicas.DeployChange{Op: "permit", Grant: second})
+ swap(replicas.DeployChange{Op: "ack", Box: second})
+ }
+ if d := cur.ReplicaDeploy; !d.Swap.Halted || d.PermitOutstanding() {
+ t.Fatalf("deploy-v2 not halted: %+v", d)
+ }
+ if cur, err = provision.RequestRecordReplicaRetry(ctx, s, id, "deploy-v2", "retry-1"); err != nil {
+ t.Fatal(err)
+ }
+ var out []*replicas.Deploy
+ for _, phase := range phases {
+ rel("deploy-v2-retry", v2, "deploy-v2", phase)
+ d := cur.ReplicaDeploy.Clone()
+ out = append(out, &d)
+ }
+ return out
+}
+
+// TestReplicaRetryPlanKeepsPerBoxBaseline (#511 final wave, item 1): the
+// wake planner on box-1 plans its copy from the record the real writer
+// left after a halted deploy and a retry. While the retry's release runs,
+// after it passes with no permit yet, and after it fails, box-1 boots v1,
+// the build it was authorised to run, never v2. When box-0 switched before
+// the halt, box-0's baseline is v2 and box-1's stays v1.
+func TestReplicaRetryPlanKeepsPerBoxBaseline(t *testing.T) {
+ for _, firstSwitched := range []bool{false, true} {
+ for _, phases := range [][]string{{"pending"}, {"pending", "releasing"}, {"pending", "releasing", "released"}, {"pending", "failed"}} {
+ deploys := haltedRetryDeploys(t, "box-0", "box-1", firstSwitched, phases...)
+ d := deploys[len(deploys)-1]
+ name := phases[len(phases)-1]
+ if firstSwitched {
+ name += "/box-0 switched"
+ }
+ t.Run(name, func(t *testing.T) {
+ h, _ := newReplicaHarness(t)
+ h.act.mu.Lock()
+ delete(h.act.gens, replicaHost)
+ h.act.mu.Unlock()
+ h.install("v2", replicaHost)
+ noteReplica(h, d)
+ plan := h.m.Plan(context.Background(), h.rows.get(replicaHost))
+ if plan.Refuse != "" || plan.Boot.Version != "v1" || plan.Fallback != nil {
+ t.Fatalf("box-1 planned %+v; want v1, its baseline", plan)
+ }
+ if want := d.Want("box-0"); (want.Version == "v2") != firstSwitched {
+ t.Fatalf("box-0's baseline: %+v", want)
+ }
+ })
+ }
+ }
+}