carlos / platform Public

rootfs: release runs before an overlap swap is admitted; the swap runs only on a proven pass; a failure keeps the incumbent

Group R, R2. Service.Swap refuses every mode and cause while a release
record of the host is open (INV-R4), before anything reads the build.
For an overlap of a rootfs row, releaseBeforeSwap runs the build's
release from the new image under the incumbent's lease and the
attempt's context; swapOverlap's admission and exec gate refuse an open
record and, when a release was due, any pass but this attempt's for
this build (INV-R5). Both hold admissions refuse an open record. Only a
proven *ReleaseError is SwapFailed ("release: ..." / "release timed
out: ..."); every other outcome is an abandonment. reasonWord maps the
two prefixes to ReasonRelease and ReasonReleaseTimeout, rendered as
RFS-3-C01 and C02.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev c0075b32b8aa8acdb59f2ccf213fc88b6da3a676 parent 1c04bf1
11 files changed, +1,483 −6
  • approved_rootfs_copy_test.go +3 −0
  • internal/activator/rootfs_invariants_test.go +11 −0
  • internal/activator/rootfs_swap_release_harness_test.go +98 −0
  • internal/activator/rootfs_swap_release_test.go +1,105 −0
  • internal/activator/rootfsrelease.go +139 −0
  • internal/activator/swap.go +44 −4
  • internal/activator/swaphold.go +6 −1
  • internal/rollout/events.go +7 −0
  • internal/rollout/rootfs_reason_test.go +64 −0
  • internal/rolloutwords/words.go +4 −0
  • internal/rolloutwords/words_test.go +2 −1
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go
index 4f832aed8..4aa69ae8b 100644
--- a/approved_rootfs_copy_test.go
+++ b/approved_rootfs_copy_test.go
@@ -201,6 +201,9 @@ var rootfsCopyBuilt = []string{
// Plan 3 Group R, R1b: the release command's events
// (internal/rolloutwords/words.go)
"RFS-3-C03", "RFS-3-C04", "RFS-3-C05", "RFS-3-C06", "RFS-3-C07", "RFS-3-C29",
+ // Plan 3 Group R, R2: the release's failure reasons
+ // (internal/rolloutwords/words.go)
+ "RFS-3-C01", "RFS-3-C02",
// Plan 4 Task 2: what the creating release says, and where a rootfs row
// may run (internal/console/rootfs.go)
"RFS-4-C01", "RFS-4-C02", "RFS-4-C05", "RFS-4-C06", "RFS-4-C07", "RFS-4-C08",
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go
index e892ba4c2..00af978a2 100644
--- a/internal/activator/rootfs_invariants_test.go
+++ b/internal/activator/rootfs_invariants_test.go
@@ -944,6 +944,13 @@ var rootfsRefusals = []struct {
{"a release whose declared processes cannot be read (marked)", refuseRootfs(refuseRootfs(fmt.Errorf("x: %w", errNoStagedManifest)))},
{"root's refusal of a release start (ErrStagedImage, marked)", refuseRootfs(fmt.Errorf("x: start release: %w", instancectl.ErrStagedImage))},
{"root's pre-start refusal of a release (ErrStartRefused, marked)", refuseRootfs(fmt.Errorf("x: start release: %w", instancectl.ErrStartRefused))},
+ // Group R, R2: the overlap swap's release gates, at the admission and
+ // at the exec (where a successor's start surfaces them through
+ // classifyStep).
+ {"an open release record at a swap (errReleaseOpen)", errReleaseOpen},
+ {"an open release record at a successor's exec (launchRefused)", launchRefused{errReleaseOpen}},
+ {"an overlap without its release pass (errReleaseNotPassed)", errReleaseNotPassed},
+ {"a release for a plan-disabled route (errReleaseTurnedOff)", errReleaseTurnedOff},
}
// rootfsReleaseResults are the release's results that are not the build's
@@ -969,6 +976,10 @@ var rootfsReleaseResults = []struct {
{"the unit vanished (errReleaseVanished)", errReleaseVanished, false, releaseCancelled},
{"no exit recorded (errReleaseNoExit)", errReleaseNoExit, false, releaseCancelled},
{"the caller's context", context.Canceled, false, releaseCancelled},
+ // Group R, R2: the swap's gate refusing a plan-disabled route, before
+ // the record and at the release's exec.
+ {"a plan-disabled route (errReleaseTurnedOff)", errReleaseTurnedOff, false, releaseRefused},
+ {"the exec gate over a plan-disabled route", launchRefused{errReleaseTurnedOff}, false, releaseRefused},
}
func TestRootfsRefusalsAreNotBuildFailures(t *testing.T) {
diff --git a/internal/activator/rootfs_swap_release_harness_test.go b/internal/activator/rootfs_swap_release_harness_test.go
new file mode 100644
index 000000000..8a9965fa3
--- /dev/null
+++ b/internal/activator/rootfs_swap_release_harness_test.go
@@ -0,0 +1,98 @@
+//go:build linux
+
+package activator
+
+// Group R, R2 [pf R2.8]: the release before an overlap swap through the
+// real control handler (rootfsCtlHarness) and the production backend. The
+// awake rootfs incumbent is installed directly (a fake process and an
+// ownedRep, through installProcLocked), so no root start is needed: root's
+// front answers /cmd 503 before anything starts. Off linux-arm64 the staged
+// manifest is refused first [pf R0.4], and the test checks that refusal.
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// INV-4: root refusing the release's start is the swap's abandonment,
+// never the build's failure. Nothing of the build ran (Executed false), no
+// planned-wake outcome is reported (OnGen), and the incumbent keeps
+// serving.
+func TestSwapReleaseRefusedByRootAbandons(t *testing.T) {
+ shrinkCmdBounds(t)
+ h := newRootfsCtlHarness(t)
+ h.runProbes()
+ id := stageRootfsWithProcesses(t, h.eb, "v2", releaseProcs())
+ a, hb, _, _ := harnessService(t, h)
+ sink := &rootfsSink{}
+ a.Logs = sink
+ a.GenerationsFile = filepath.Join(t.TempDir(), "generations.json")
+ var genEvents atomic.Int32
+ a.OnGen = func(GenEvent) { genEvents.Add(1) }
+
+ rt := h.rt
+ rt.GoodVersion = "v1"
+ proc := &fakeProc{label: "incumbent"}
+ rep := newOwnedRep(&fakeRep{}, time.Now().Add(time.Hour))
+ t.Cleanup(func() { rep.timer.Stop() })
+ incumbent := Gen{N: 1 << 40, Build: "v1", Socket: "/run/carlos/g/incumbent.sock", Control: "/run/carlos/g/incumbent.sock.control"}
+ e := &actEntry{host: rt.Host, route: rt, state: actAwake}
+ a.mu.Lock()
+ a.entries[rt.Host] = e
+ a.installProcLocked(e, rep, proc, incumbent)
+ a.mu.Unlock()
+ t.Cleanup(func() {
+ a.mu.Lock()
+ if a.entries[rt.Host] == e {
+ delete(a.entries, rt.Host)
+ }
+ a.mu.Unlock()
+ })
+
+ h.mu.Lock()
+ h.cmdStatus = 503
+ h.mu.Unlock()
+ at := Attempt{Host: rt.Host, Cause: CauseRelease, Build: "v2", StagedPath: id.StagedPath, Digest: id.Digest, Mode: ModeOverlap, SchedRev: 1}
+ res := a.Swap(context.Background(), at, func(string) uint64 { return 1 })
+ if res.Outcome != SwapAbandoned || res.Executed || res.Mode != ModeOverlap {
+ t.Fatalf("Swap with root refusing the release = %+v; want abandoned, not executed", res)
+ }
+ if release.BoxPlatform() != "linux-arm64" {
+ // Off linux-arm64 the staged manifest's artifact is not one a
+ // rootfs release may carry, so the declared processes are refused
+ // (an INV-4 refusal of its own) before the release's start; the
+ // /cmd half runs on linux-arm64 (and under arm64 emulation).
+ if !strings.Contains(res.Reason, "a rootfs release carries one artifact") || h.requested("POST /cmd") != 0 {
+ t.Fatalf("on %s: %+v, POST /cmd %d; want the manifest's refusal before any start", release.BoxPlatform(), res, h.requested("POST /cmd"))
+ }
+ } else if n := h.requested("POST /cmd"); n != 1 || !strings.Contains(res.Reason, "refused by the test") {
+ t.Fatalf("POST /cmd sent %d times, want 1 (the release's start, refused by root); %+v", n, res)
+ }
+ if n := genEvents.Load(); n != 0 {
+ t.Errorf("OnGen heard %d outcomes for a refused release", n)
+ }
+ if n := h.requested("POST /start"); n != 0 {
+ t.Errorf("POST /start sent %d times: a successor was started", n)
+ }
+ if acq, _ := hb.counts(); acq != 0 {
+ t.Errorf("%d lease acquires: the release runs under the incumbent's lease", acq)
+ }
+ a.mu.Lock()
+ serving := a.entries[rt.Host] == e && e.state == actAwake && e.gen.N == incumbent.N && len(e.ops.members) == 0 && a.releaseOps[rt.Host] == nil
+ a.mu.Unlock()
+ if !serving || proc.isStopped() {
+ t.Fatalf("after the refusal: incumbent serving %v, stopped %v", serving, proc.isStopped())
+ }
+ if sock, ok := a.AppSocket(rt.Host); !ok || sock != incumbent.Socket {
+ t.Errorf("AppSocket = %q, %v; want the incumbent's", sock, ok)
+ }
+ if pinned(t, a, rt.Host, "v2") {
+ t.Error("the generations file still names v2 after root's refusal")
+ }
+}
diff --git a/internal/activator/rootfs_swap_release_test.go b/internal/activator/rootfs_swap_release_test.go
new file mode 100644
index 000000000..1a2b70aaa
--- /dev/null
+++ b/internal/activator/rootfs_swap_release_test.go
@@ -0,0 +1,1105 @@
+package activator
+
+// Rootfs apps Plan 3, Group R, R2: the release before an overlap swap. A
+// rootfs build that declares `release` runs it from the new image under
+// the incumbent's lease before the swap is admitted (releaseBeforeSwap);
+// the swap is admitted only on that attempt's proven pass (INV-R5); a
+// failure is the build's and the incumbent keeps serving (C8); an open
+// release record blocks every transition of the host (INV-R4). Not
+// parallel: some tests shrink the release's package vars.
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rolloutwords"
+)
+
+// relSwapBackend is the swap fake (fakeSwapBackend) with the release seam
+// and the process read. Processes answers procs by build version (a build
+// not there declares web alone) and counts every read. Each StartRelease
+// asks the exec gate, records release:start:<build> in the order log and
+// hands out a fresh releaseUnit on units; a settle of it fails while stuck
+// and records release:proven:<build> when it proves the unit gone.
+type relSwapBackend struct {
+ *fakeSwapBackend
+ rmu sync.Mutex
+ procs map[string]map[string]release.Process
+ reads int
+ onProcesses func(id release.StagedIdentity)
+ onEnv func()
+ units chan *releaseUnit
+ starts []string
+ stuck bool
+ onSettle func()
+ settling int
+ maxSettling int
+}
+
+func (b *relSwapBackend) Processes(_ registry.Route, id release.StagedIdentity) (map[string]release.Process, error) {
+ b.rmu.Lock()
+ b.reads++
+ hook := b.onProcesses
+ p, ok := b.procs[id.Version]
+ b.rmu.Unlock()
+ if hook != nil {
+ hook(id)
+ }
+ if !ok {
+ return map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}}, nil
+ }
+ return p, nil
+}
+
+func (b *relSwapBackend) ReleaseEnv(_ context.Context, rt registry.Route) (map[string]string, error) {
+ b.rmu.Lock()
+ hook := b.onEnv
+ b.rmu.Unlock()
+ if hook != nil {
+ hook()
+ }
+ return map[string]string{"CARLOS_SOCKET": rt.Socket}, nil
+}
+
+func (b *relSwapBackend) StartRelease(ctx context.Context, _ registry.Route, id release.StagedIdentity, _ map[string]string, _ io.Writer) (CmdUnit, error) {
+ // The exec gate, as startRootfsCmd asks it right before root.
+ if err := runExecGate(ctx); err != nil {
+ return nil, err
+ }
+ b.record("release:start:" + id.Version)
+ u := newReleaseUnit()
+ u.settle = func(int) error { return b.settle(id.Version) }
+ b.rmu.Lock()
+ b.starts = append(b.starts, id.Version)
+ b.rmu.Unlock()
+ b.units <- u
+ return u, nil
+}
+
+func (b *relSwapBackend) settle(build string) error {
+ b.rmu.Lock()
+ b.settling++
+ b.maxSettling = max(b.maxSettling, b.settling)
+ stuck, hook := b.stuck, b.onSettle
+ b.rmu.Unlock()
+ if hook != nil {
+ hook()
+ }
+ b.rmu.Lock()
+ b.settling--
+ b.rmu.Unlock()
+ if stuck {
+ return errors.New("processes remained in the release command's cgroup")
+ }
+ b.record("release:proven:" + build)
+ return nil
+}
+
+func (b *relSwapBackend) setStuck(stuck bool) {
+ b.rmu.Lock()
+ b.stuck = stuck
+ b.rmu.Unlock()
+}
+
+func (b *relSwapBackend) readCount() int {
+ b.rmu.Lock()
+ defer b.rmu.Unlock()
+ return b.reads
+}
+
+func (b *relSwapBackend) startList() []string {
+ b.rmu.Lock()
+ defer b.rmu.Unlock()
+ return slices.Clone(b.starts)
+}
+
+var (
+ _ ReleaseBackend = (*relSwapBackend)(nil)
+ _ ProcessReader = (*relSwapBackend)(nil)
+ _ SwapBackend = (*relSwapBackend)(nil)
+)
+
+// relSwapFixture is the swap fixture over relSwapBackend: an awake
+// incumbent on build v1 (made a rootfs row good on v1, its replica an
+// ownedRep with the lease's own signal), build v2 staged (f.staged)
+// declaring a release, build v3 staged declaring one too, the events
+// captured and the generations file on disk.
+type relSwapFixture struct {
+ *swapFixture
+ rb *relSwapBackend
+ sink *rootfsSink
+ rep *ownedRep
+ binRoute registry.Route // the row as it woke, before it was made rootfs
+ v3, v3d string // v3's staged path and digest
+}
+
+func newRelSwapFixture(t *testing.T, rootfs bool) *relSwapFixture {
+ t.Helper()
+ var rb *relSwapBackend
+ f := newSwapFixtureOn(t, func(b *fakeSwapBackend) Backend {
+ rb = &relSwapBackend{fakeSwapBackend: b, units: make(chan *releaseUnit, 16),
+ procs: map[string]map[string]release.Process{"v2": releaseDeclared(), "v3": releaseDeclared()}}
+ return rb
+ })
+ rf := &relSwapFixture{swapFixture: f, rb: rb, sink: &rootfsSink{}}
+ f.a.Logs = rf.sink
+ f.a.GenerationsFile = filepath.Join(t.TempDir(), "generations.json")
+ f.a.mu.Lock()
+ rf.binRoute = f.a.entries[f.host].route
+ f.a.mu.Unlock()
+ rf.v3, rf.v3d = stageTestBuild(t, "v3")
+ if rootfs {
+ rf.rep = makeRootfsIncumbent(t, f.a, f.host)
+ }
+ return rf
+}
+
+// makeRootfsIncumbent makes host's awake entry a hibernating rootfs row
+// of acme/shop, good on v1, its replica an ownedRep an hour ahead,
+// installed through installProcLocked.
+func makeRootfsIncumbent(t *testing.T, a *Service, host string) *ownedRep {
+ t.Helper()
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[host]
+ e.route.Runtime, e.route.App, e.route.Account = registry.RuntimeRootfsV1, "shop", "acme"
+ e.route.GoodVersion, e.route.GoodDigest = "v1", "aa11"
+ fr, ok := e.rep.(*fakeRep)
+ if !ok {
+ t.Fatalf("the incumbent's replica is %T", e.rep)
+ }
+ rep := newOwnedRep(fr, time.Now().Add(time.Hour))
+ t.Cleanup(func() { rep.timer.Stop() })
+ a.installProcLocked(e, rep, e.proc, e.gen)
+ return rep
+}
+
+// stageTestBuild writes build ver's artifact and answers its path and
+// digest.
+func stageTestBuild(t *testing.T, ver string) (string, string) {
+ t.Helper()
+ dir := filepath.Join(t.TempDir(), "versions", ver)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "app")
+ body := []byte("build " + ver)
+ if err := writeExecutable(path, body, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(body)
+ return path, hex.EncodeToString(sum[:])
+}
+
+func (f *relSwapFixture) attemptV3(mode SwapMode) Attempt {
+ at := f.attempt(mode)
+ at.Build, at.StagedPath, at.Digest = "v3", f.v3, f.v3d
+ return at
+}
+
+// swapAsync runs Swap in the background.
+func (f *relSwapFixture) swapAsync(at Attempt) <-chan SwapResult {
+ ch := make(chan SwapResult, 1)
+ go func() { ch <- f.a.Swap(context.Background(), at, f.newest) }()
+ return ch
+}
+
+func waitSwap(t *testing.T, ch <-chan SwapResult) SwapResult {
+ t.Helper()
+ select {
+ case res := <-ch:
+ return res
+ case <-time.After(30 * time.Second):
+ t.Fatal("Swap did not return")
+ }
+ return SwapResult{}
+}
+
+// nextUnit waits for the next release unit StartRelease hands out.
+func (f *relSwapFixture) nextUnit(t *testing.T) *releaseUnit {
+ t.Helper()
+ select {
+ case u := <-f.rb.units:
+ return u
+ case <-time.After(10 * time.Second):
+ t.Fatal("no release started")
+ }
+ return nil
+}
+
+// noUnit fails t if a release unit was handed out.
+func (f *relSwapFixture) noUnit(t *testing.T, when string) {
+ t.Helper()
+ select {
+ case <-f.rb.units:
+ t.Fatalf("%s: a release started", when)
+ default:
+ }
+}
+
+func (f *relSwapFixture) record() *releaseOp {
+ f.a.mu.Lock()
+ defer f.a.mu.Unlock()
+ return f.a.releaseOps[f.host]
+}
+
+// incumbentServing fails t unless the incumbent is still current, awake,
+// unstopped and the host's socket, with no member in its operation set.
+func (f *relSwapFixture) incumbentServing(t *testing.T, proc *fakeProc, when string) {
+ t.Helper()
+ cur, members := f.a.genStateForTest(f.host)
+ if cur.N != f.incumbent.N || len(members) != 0 {
+ t.Errorf("%s: current generation %d, members %v; want the incumbent %d alone", when, cur.N, members, f.incumbent.N)
+ }
+ if proc.isStopped() {
+ t.Errorf("%s: the incumbent was stopped", when)
+ }
+ if got := f.appSocket(t); got != f.incumbent.Socket {
+ t.Errorf("%s: AppSocket %q, want the incumbent's %q", when, got, f.incumbent.Socket)
+ }
+ f.a.mu.Lock()
+ e := f.a.entries[f.host]
+ awake := e != nil && e.state == actAwake && e.stopWhy == ""
+ f.a.mu.Unlock()
+ if !awake {
+ t.Errorf("%s: the incumbent is no longer awake", when)
+ }
+}
+
+// nothingAdmitted fails t if any successor was admitted or started.
+func (f *relSwapFixture) nothingAdmitted(t *testing.T, when string) {
+ t.Helper()
+ if gens, raises, _ := f.b.calls(); gens != 0 || raises != 0 {
+ t.Errorf("%s: StartStaged %d, raises %d; want neither", when, gens, raises)
+ }
+}
+
+// proveRecord ends the stuck settle and has the sweep's pass prove the
+// record (retrySettle is paced by actStopTimeout of the fake clock).
+func (f *relSwapFixture) proveRecord(t *testing.T) {
+ t.Helper()
+ f.rb.setStuck(false)
+ f.clk.advance(actStopTimeout + time.Second)
+ f.a.mu.Lock()
+ f.a.finishPendingStops()
+ f.a.mu.Unlock()
+ waitFor(t, "the reaper to prove the release record", func() bool { return f.record() == nil })
+}
+
+func eventsLike(msgs []string, head string) int {
+ n := 0
+ for _, m := range msgs {
+ if strings.HasPrefix(m, head) {
+ n++
+ }
+ }
+ return n
+}
+
+func TestOverlapReleaseFailureKeepsTheIncumbent(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ incumbent := f.b.lastProc()
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ f.nextUnit(t).done("1", "1", "exit-code")
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapFailed || !strings.HasPrefix(res.Reason, "release: ") || !res.Executed || res.Mode != ModeOverlap {
+ t.Fatalf("Swap = %+v; want failed, executed, overlap, reason \"release: …\"", res)
+ }
+ if want := "release: " + (&ReleaseError{Build: "v2", Exit: 1}).Error(); res.Reason != want {
+ t.Errorf("Reason = %q, want %q", res.Reason, want)
+ }
+ f.nothingAdmitted(t, "after the release failed")
+ f.incumbentServing(t, incumbent, "after the release failed")
+ if op := f.record(); op != nil {
+ t.Error("the release record outlived its proof")
+ }
+ if n := eventsLike(f.sink.msgs(), "the release command of build v2 exited with status 1"); n != 1 {
+ t.Errorf("C05 emitted %d times: %q", n, f.sink.msgs())
+ }
+}
+
+func TestOverlapReleaseTimeoutKeepsTheIncumbent(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ procs := releaseDeclared()
+ p := procs[release.ProcessRelease]
+ p.TimeoutSec = 1
+ procs[release.ProcessRelease] = p
+ f.rb.procs["v2"] = procs
+ incumbent := f.b.lastProc()
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ u := f.nextUnit(t) // never answers: the release runs into its timeout
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapFailed || !strings.HasPrefix(res.Reason, "release timed out: ") || !res.Executed {
+ t.Fatalf("Swap = %+v; want failed, executed, reason \"release timed out: …\"", res)
+ }
+ if !u.isProven() {
+ t.Error("the timed-out release's unit was not proven gone before the failure")
+ }
+ f.nothingAdmitted(t, "after the timeout")
+ f.incumbentServing(t, incumbent, "after the timeout")
+ if n := eventsLike(f.sink.msgs(), "the release command of build v2 did not finish within 1s"); n != 1 {
+ t.Errorf("C07 emitted %d times: %q", n, f.sink.msgs())
+ }
+}
+
+func TestOverlapRunsReleaseBeforeTheSwapIsAdmitted(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ var admittedClean atomic.Bool
+ f.b.onRaise = func() {
+ // The raise follows the admission at once: the member is in the
+ // set and the release record is already gone.
+ f.a.mu.Lock()
+ e := f.a.entries[f.host]
+ admittedClean.Store(len(e.ops.members) == 1 && f.a.releaseOps[f.host] == nil)
+ f.a.mu.Unlock()
+ f.b.record("admitted")
+ }
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ u := f.nextUnit(t)
+ if f.record() == nil {
+ t.Fatal("no release record while the release runs")
+ }
+ if _, members := f.a.genStateForTest(f.host); len(members) != 0 {
+ t.Fatalf("a member was admitted while the release ran: %v", members)
+ }
+ u.done("1", "0", "success")
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapDone || res.Gen.Build != "v2" || !res.Executed {
+ t.Fatalf("Swap = %+v", res)
+ }
+ ev := f.b.events()
+ order := []int{
+ indexPrefix(ev, "release:start:v2"),
+ indexPrefix(ev, "release:proven:v2"),
+ indexPrefix(ev, "admitted"),
+ indexPrefix(ev, "startGen:"+f.staged),
+ indexPrefix(ev, "switch:"),
+ }
+ for i := range order {
+ if order[i] < 0 || (i > 0 && order[i] < order[i-1]) {
+ t.Fatalf("event order %v (indexes %v): want release start, release proven, admission, StartStaged, switch", ev, order)
+ }
+ }
+ if !admittedClean.Load() {
+ t.Error("the member was admitted beside an open release record")
+ }
+ if msgs := f.sink.msgs(); eventsLike(msgs, "running the release command of build v2") != 1 ||
+ eventsLike(msgs, "the release command of build v2 finished in") != 1 {
+ t.Errorf("events %q: want C03 and C04 once each", msgs)
+ }
+}
+
+// INV-R5: an overlap of a build that needs a release is admitted only with
+// this attempt's pass for this build, with no record open, and with
+// ownership rechecked at the admission and at the exec.
+func TestSwapAdmittedOnlyOnAProvenPass(t *testing.T) {
+ overlap := func(f *relSwapFixture, pass *releasePass, due bool) SwapResult {
+ return f.a.swapOverlap(context.Background(), f.a.backend.(SwapBackend), f.attempt(ModeOverlap), f.newest, pass, due)
+ }
+ passOf := func(f *relSwapFixture) *releasePass {
+ at := f.attempt(ModeOverlap)
+ return &releasePass{host: at.Host, schedRev: at.SchedRev,
+ build: release.StagedIdentity{Version: at.Build, StagedPath: at.StagedPath, Digest: at.Digest, Demand: at.Demand}}
+ }
+ for _, tc := range []struct {
+ name string
+ pass func(f *relSwapFixture) *releasePass
+ }{
+ {"none", func(*relSwapFixture) *releasePass { return nil }},
+ {"another SchedRev", func(f *relSwapFixture) *releasePass { p := passOf(f); p.schedRev++; return p }},
+ {"another digest of the build", func(f *relSwapFixture) *releasePass {
+ p := passOf(f)
+ p.build.Digest = strings.Repeat("f", 64)
+ return p
+ }},
+ {"another staged path", func(f *relSwapFixture) *releasePass { p := passOf(f); p.build.StagedPath += ".old"; return p }},
+ {"another demand", func(f *relSwapFixture) *releasePass { p := passOf(f); p.build.Demand = "hold"; return p }},
+ {"another build", func(f *relSwapFixture) *releasePass { p := passOf(f); p.build.Version = "v3"; return p }},
+ {"another host", func(f *relSwapFixture) *releasePass { p := passOf(f); p.host = "other.example.com"; return p }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ incumbent := f.b.lastProc()
+ res := overlap(f, tc.pass(f), true)
+ if res.Outcome != SwapAbandoned || res.Reason != errReleaseNotPassed.Error() || res.Executed {
+ t.Fatalf("swapOverlap = %+v; want abandoned with errReleaseNotPassed, not executed", res)
+ }
+ f.nothingAdmitted(t, tc.name)
+ f.incumbentServing(t, incumbent, tc.name)
+ })
+ }
+ t.Run("the attempt's own pass", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ if res := overlap(f, passOf(f), true); res.Outcome != SwapDone {
+ t.Fatalf("swapOverlap with the matching pass = %+v", res)
+ }
+ })
+ t.Run("no release due", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ if res := overlap(f, nil, false); res.Outcome != SwapDone {
+ t.Fatalf("swapOverlap with nothing due = %+v", res)
+ }
+ })
+ t.Run("ownership at the admission", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ f.rep.lose(lease.ErrLost)
+ if res := overlap(f, passOf(f), true); res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errSwapLeaseLost.Error()) {
+ t.Fatalf("swapOverlap after the lease was lost = %+v", res)
+ }
+ f.nothingAdmitted(t, "the lease lost before the admission")
+ })
+ t.Run("ownership at the exec", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ f.b.onRaise = func() { f.rep.lose(lease.ErrLost) }
+ if res := overlap(f, passOf(f), true); res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errSwapLeaseLost.Error()) {
+ t.Fatalf("swapOverlap with the lease lost after the admission = %+v", res)
+ }
+ if gens, _, _ := f.b.calls(); gens != 0 {
+ t.Errorf("StartStaged %d times after the lease was lost", gens)
+ }
+ })
+ t.Run("an unproven release issues no pass", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ f.rb.setStuck(true)
+ type answer struct {
+ pass *releasePass
+ due bool
+ res SwapResult
+ passed bool
+ }
+ ch := make(chan answer, 1)
+ go func() {
+ p, due, res, ok := f.a.releaseBeforeSwap(context.Background(), f.attempt(ModeOverlap), f.newest)
+ ch <- answer{p, due, res, ok}
+ }()
+ f.nextUnit(t).done("1", "0", "success")
+ var got answer
+ select {
+ case got = <-ch:
+ case <-time.After(30 * time.Second):
+ t.Fatal("releaseBeforeSwap did not return")
+ }
+ if got.pass != nil || got.passed || got.res.Outcome != SwapAbandoned || !got.res.Executed ||
+ !strings.Contains(got.res.Reason, errReleaseUnproven.Error()) {
+ t.Fatalf("releaseBeforeSwap with the unit unproven = pass %v, ok %v, %+v", got.pass, got.passed, got.res)
+ }
+ if f.record() == nil {
+ t.Fatal("the unproven release left no record")
+ }
+ f.nothingAdmitted(t, "after an unproven release")
+ f.proveRecord(t)
+ })
+}
+
+// INV-R4: an open release record blocks every transition of the host,
+// checked first: before anything reads the build or decides whether it
+// needs a release, and again at the admission and at the exec.
+func TestOpenReleaseBlocksEveryTransition(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ incumbent := f.b.lastProc()
+ f.rb.setStuck(true)
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ f.nextUnit(t).done("1", "0", "success")
+ if res := waitSwap(t, ch); res.Outcome != SwapAbandoned || !res.Executed {
+ t.Fatalf("B's unproven release = %+v; want abandoned, executed", res)
+ }
+ op := f.record()
+ if op == nil || op.state != releaseNotProven {
+ t.Fatal("B's release left no unproven record")
+ }
+ reads := f.rb.readCount()
+ good := f.attempt(ModeOverlap)
+ // A config or restart attempt re-runs the good build. Its staged copy
+ // here is not on disk: an attempt that read anything before the
+ // record would be refused as staging instead.
+ good.Build, good.StagedPath, good.Digest = "v1", f.incumbent.StagedPath, strings.Repeat("a", 64)
+ config, restart := good, good
+ config.Cause, config.ConfigRev = CauseConfig, "cfg-2"
+ restart.Cause, restart.RestartID = CauseRestart, "rs-1"
+ hold := f.attempt(ModeHold)
+ noRelease := f.attemptV3(ModeOverlap)
+ delete(f.rb.procs, "v3") // C declares web alone
+ for name, at := range map[string]Attempt{
+ "a config attempt onto the good build": config,
+ "a restart attempt": restart,
+ "a hold attempt": hold,
+ "an overlap of a build with no release": noRelease,
+ } {
+ res := f.a.Swap(context.Background(), at, f.newest)
+ if res.Outcome != SwapAbandoned || res.Reason != errReleaseOpen.Error() || res.Executed {
+ t.Errorf("%s: Swap = %+v; want abandoned with errReleaseOpen, not executed", name, res)
+ }
+ }
+ if n := f.rb.readCount(); n != reads {
+ t.Errorf("the declared processes were read %d times beside the open record", n-reads)
+ }
+ f.nothingAdmitted(t, "beside the open record")
+ f.noUnit(t, "beside the open record")
+ f.incumbentServing(t, incumbent, "beside the open record")
+
+ // Both hold admissions ask the record (holdAdmitLocked), and so does
+ // the overlap's own release half (releaseAdmitsSwapLocked).
+ f.a.mu.Lock()
+ holdErr := f.a.holdAdmitLocked(f.a.entries[f.host], hold, f.newest)
+ overlapErr := f.a.releaseAdmitsSwapLocked(noRelease, Gen{Build: "v3", StagedPath: f.v3, Digest: f.v3d}, nil, false)
+ f.a.mu.Unlock()
+ if !errors.Is(holdErr, errReleaseOpen) || !errors.Is(overlapErr, errReleaseOpen) {
+ t.Errorf("with the record open: holdAdmitLocked = %v, the overlap's release check = %v", holdErr, overlapErr)
+ }
+
+ f.proveRecord(t)
+ ch = f.swapAsync(f.attempt(ModeOverlap))
+ f.nextUnit(t).done("1", "0", "success")
+ if res := waitSwap(t, ch); res.Outcome != SwapDone || res.Gen.Build != "v2" {
+ t.Fatalf("the next attempt once the record is proven = %+v", res)
+ }
+ if got := f.rb.startList(); !slices.Equal(got, []string{"v2", "v2"}) {
+ t.Errorf("releases started %v; want B's twice (the unproven one, then the next attempt's)", got)
+ }
+}
+
+// A record that opens after the top of Swap is still refused at the
+// admission, at Step 3a and at the exec, and each is an abandonment,
+// never the build's failure. (Only a stand-in record can appear there:
+// the incumbent's own release refuses beside a member.)
+func TestOpenReleaseIsAskedAtTheAdmissionAndTheExec(t *testing.T) {
+ standIn := func(f *relSwapFixture) func() {
+ return func() {
+ f.a.mu.Lock()
+ defer f.a.mu.Unlock()
+ if f.a.releaseOps == nil {
+ f.a.releaseOps = map[string]*releaseOp{}
+ }
+ f.a.releaseOps[f.host] = &releaseOp{host: f.host, state: releaseRunning, done: make(chan struct{})}
+ }
+ }
+ dropStandIn := func(t *testing.T, f *relSwapFixture) {
+ t.Cleanup(func() {
+ f.a.mu.Lock()
+ delete(f.a.releaseOps, f.host)
+ f.a.mu.Unlock()
+ })
+ }
+ t.Run("the admission", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ dropStandIn(t, f)
+ delete(f.rb.procs, "v3")
+ f.rb.onProcesses = func(release.StagedIdentity) { standIn(f)() }
+ res := f.a.Swap(context.Background(), f.attemptV3(ModeOverlap), f.newest)
+ if res.Outcome != SwapAbandoned || res.Reason != errReleaseOpen.Error() || res.Executed {
+ t.Fatalf("Swap = %+v", res)
+ }
+ f.nothingAdmitted(t, "a record opened before the admission")
+ })
+ t.Run("Step 3a", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ dropStandIn(t, f)
+ delete(f.rb.procs, "v3")
+ f.b.onRaise = standIn(f)
+ res := f.a.Swap(context.Background(), f.attemptV3(ModeOverlap), f.newest)
+ if res.Outcome != SwapAbandoned || res.Reason != errReleaseOpen.Error() || res.Executed {
+ t.Fatalf("Swap = %+v", res)
+ }
+ if gens, _, _ := f.b.calls(); gens != 0 {
+ t.Errorf("StartStaged %d times beside the record", gens)
+ }
+ })
+ t.Run("the exec", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ dropStandIn(t, f)
+ delete(f.rb.procs, "v3")
+ gate := make(chan struct{})
+ f.b.genGate = gate
+ ch := f.swapAsync(f.attemptV3(ModeOverlap))
+ waitFor(t, "StartStaged", func() bool { return indexPrefix(f.b.events(), "startGen:") >= 0 })
+ standIn(f)()
+ close(gate)
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errReleaseOpen.Error()) || res.Executed {
+ t.Fatalf("Swap = %+v; want abandoned at the exec, never failed", res)
+ }
+ if _, p := f.b.lastGen(); p != nil {
+ t.Error("a successor was launched beside the record")
+ }
+ })
+}
+
+func TestOverlapAbandonsWhileARunIsOpen(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ incumbent := f.b.lastProc()
+ f.a.mu.Lock()
+ e := f.a.entries[f.host]
+ e.cmd = newCmdHold("run_a", func() {}, f.a.now)
+ f.a.mu.Unlock()
+ t.Cleanup(func() {
+ f.a.mu.Lock()
+ e.cmd = nil
+ f.a.mu.Unlock()
+ })
+ res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest)
+ if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errSwapBusy.Error()) || res.Executed {
+ t.Fatalf("Swap beside an open run = %+v; want abandoned busy, not executed", res)
+ }
+ f.noUnit(t, "beside an open run")
+ f.nothingAdmitted(t, "beside an open run")
+ f.incumbentServing(t, incumbent, "beside an open run")
+ if f.record() != nil {
+ t.Error("a release record was left beside an open run")
+ }
+}
+
+// Review Focus 6: a lease loss while the release runs stops it and proves
+// its unit gone before the safety deadline; the attempt is abandoned,
+// never the build's failure.
+func TestSwapReleaseStopsOnLeaseLoss(t *testing.T) {
+ shrinkRelease(t, 200*time.Millisecond, 50*time.Millisecond)
+ f := newRelSwapFixture(t, true)
+ until := time.Now().Add(10 * time.Second)
+ f.rep.mu.Lock()
+ f.rep.until = until
+ f.rep.mu.Unlock()
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ u := f.nextUnit(t)
+ f.rep.lose(lease.ErrLost)
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapAbandoned || !res.Executed || !strings.Contains(res.Reason, errReleaseLeaseLost.Error()) {
+ t.Fatalf("Swap after the lease was lost = %+v; want abandoned, executed, the lease lost", res)
+ }
+ stops := u.stopTimes()
+ if !u.isProven() || len(stops) == 0 || !stops[len(stops)-1].Before(until) {
+ t.Fatalf("the release unit: proven %v, stops %v, deadline %v", u.isProven(), stops, until)
+ }
+ f.nothingAdmitted(t, "after the lease loss")
+ msgs := f.sink.msgs()
+ for _, head := range []string{"the release command of build v2 exited", "the release command of build v2 was ended by signal", "the release command of build v2 did not finish"} {
+ if eventsLike(msgs, head) != 0 {
+ t.Errorf("a failure event %q after a lease loss: %q", head, msgs)
+ }
+ }
+ if n := eventsLike(msgs, "the release command of build v2 was stopped because this box no longer holds the instance"); n != 1 {
+ t.Errorf("C29 emitted %d times: %q", n, msgs)
+ }
+}
+
+// A passed release ran the build's release process against the database,
+// so an attempt abandoned after it (here superseded between the pass and
+// the admission) is executed: the scheduler must not count it as having
+// spent nothing (SwapResult.Executed).
+func TestPassedReleaseCountsAsExecuted(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ incumbent := f.b.lastProc()
+ f.rb.onSettle = func() { f.rev.Add(1) } // a newer attempt arrives as the release is proven
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ f.nextUnit(t).done("1", "0", "success")
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapAbandoned || res.Reason != errSwapSuperseded.Error() || !res.Executed {
+ t.Fatalf("Swap superseded after its release passed = %+v; want abandoned, executed", res)
+ }
+ f.nothingAdmitted(t, "after the pass, superseded")
+ f.incumbentServing(t, incumbent, "after the pass, superseded")
+}
+
+// [pf R2.6]: the release runs under the attempt's own context, so the
+// agent's life ending (Shutdown's first step, lifeStop) ends it: its unit
+// is settled and proven, and the attempt is abandoned, never failed.
+func TestShutdownCancelsAReleaseBeforeASwap(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ u := f.nextUnit(t)
+ f.a.lifeStop()
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapAbandoned || !res.Executed {
+ t.Fatalf("Swap after the agent's life ended = %+v; want abandoned, executed", res)
+ }
+ if !u.isProven() || f.record() != nil {
+ t.Fatalf("the release unit proven %v, record left %v", u.isProven(), f.record() != nil)
+ }
+ f.nothingAdmitted(t, "after the agent's life ended")
+}
+
+// RACE: the lease's loss and the sweep's lease check at once. One settle
+// at a time on the record, the incumbent stopped once (one stop begun; the
+// pending stop's proof asks the exited process's Stop again, which is not
+// a second stop), and its replica closed (the lease given back) only after
+// the record is gone.
+func TestSwapReleaseLeaseLossRacesTheSweep(t *testing.T) {
+ shrinkRelease(t, 200*time.Millisecond, 50*time.Millisecond)
+ logs := captureLockedLog(t)
+ for round := 0; round < 5; round++ {
+ f := newRelSwapFixture(t, true)
+ incumbent := f.b.lastProc()
+ f.rb.onSettle = func() { time.Sleep(5 * time.Millisecond) }
+ var closedOverRecord atomic.Bool
+ f.rep.setOnClose(func() {
+ if f.record() != nil {
+ closedOverRecord.Store(true)
+ }
+ })
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ f.nextUnit(t)
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() { defer wg.Done(); <-start; f.rep.lose(lease.ErrLost) }()
+ go func() { defer wg.Done(); <-start; f.a.sweepOnce() }()
+ close(start)
+ wg.Wait()
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapAbandoned || !res.Executed {
+ t.Fatalf("round %d: Swap = %+v; want abandoned, executed", round, res)
+ }
+ for i := 0; i < 200 && f.a.entryCount() > 0; i++ {
+ f.a.sweepOnce()
+ time.Sleep(10 * time.Millisecond)
+ }
+ if f.a.entryCount() != 0 {
+ t.Fatalf("round %d: the incumbent's stop never finished", round)
+ }
+ f.rb.rmu.Lock()
+ most := f.rb.maxSettling
+ f.rb.rmu.Unlock()
+ if most != 1 {
+ t.Errorf("round %d: %d settles of the record ran at once", round, most)
+ }
+ if n := strings.Count(logs.String(), "LEASE LOST for "+f.host); n != round+1 {
+ t.Errorf("round %d: %d stops begun for the lease's loss over %d rounds", round, n, round+1)
+ }
+ // The stop's last step logs it, after the generations file's write.
+ waitFor(t, "the stop's end", func() bool { return strings.Count(logs.String(), f.host+" hibernated") >= round+1 })
+ if n := strings.Count(logs.String(), f.host+" hibernated"); n != round+1 || !incumbent.isStopped() {
+ t.Errorf("round %d: %d stops finished over %d rounds, the incumbent stopped %v", round, n, round+1, incumbent.isStopped())
+ }
+ if closedOverRecord.Load() || f.rep.closeCount() != 1 {
+ t.Errorf("round %d: replica closed %d times, over an open record %v", round, f.rep.closeCount(), closedOverRecord.Load())
+ }
+ f.nothingAdmitted(t, "after the race")
+ }
+}
+
+// INV-R3: a release that exits 1 and whose settle fails is unproven, not
+// the build's failure; once proven, the next attempt runs it again.
+func TestUnprovenSwapReleaseIsNotABuildFailure(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ incumbent := f.b.lastProc()
+ f.rb.setStuck(true)
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ f.nextUnit(t).done("1", "1", "exit-code")
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapAbandoned || !res.Executed || !strings.Contains(res.Reason, errReleaseUnproven.Error()) {
+ t.Fatalf("Swap = %+v; want abandoned (unproven), executed", res)
+ }
+ if eventsLike(f.sink.msgs(), "the release command of build v2 exited") != 0 {
+ t.Errorf("a failure event for an unproven release: %q", f.sink.msgs())
+ }
+ f.nothingAdmitted(t, "after the unproven release")
+ f.incumbentServing(t, incumbent, "after the unproven release")
+ f.proveRecord(t)
+ ch = f.swapAsync(f.attempt(ModeOverlap))
+ f.nextUnit(t).done("1", "1", "exit-code")
+ if res := waitSwap(t, ch); res.Outcome != SwapFailed {
+ t.Fatalf("the next attempt = %+v; want the release run again, and failed", res)
+ }
+ if got := f.rb.startList(); !slices.Equal(got, []string{"v2", "v2"}) {
+ t.Errorf("releases started %v", got)
+ }
+}
+
+// C8: a hibernating incumbent is neither idled nor ceilinged while the
+// release runs; the ceiling fires on the first sweep after it ends.
+func TestIncumbentNeverIdlesThroughAMigration(t *testing.T) {
+ logs := captureLockedLog(t)
+ f := newRelSwapFixture(t, true)
+ incumbent := f.b.lastProc()
+ f.a.SetMaxRunFor(func(registry.Route) time.Duration { return 3 * time.Hour })
+ ch := f.swapAsync(f.attempt(ModeOverlap))
+ u := f.nextUnit(t)
+ stopping := func() bool {
+ f.a.mu.Lock()
+ defer f.a.mu.Unlock()
+ e := f.a.entries[f.host]
+ return e == nil || e.state != actAwake || e.stopWhy != ""
+ }
+ // Past the idle window (an hour), below the ceiling.
+ f.clk.advance(2 * time.Hour)
+ f.a.sweepOnce()
+ if stopping() || incumbent.isStopped() {
+ t.Fatal("the incumbent was idled while its successor's release ran")
+ }
+ // Past the ceiling too, with a request in flight so only the ceiling
+ // could stop it.
+ f.a.mu.Lock()
+ f.a.entries[f.host].inflight++
+ f.a.mu.Unlock()
+ f.clk.advance(2 * time.Hour)
+ f.a.sweepOnce()
+ if stopping() || incumbent.isStopped() {
+ t.Fatal("the incumbent was stopped by the ceiling while its successor's release ran")
+ }
+ u.done("1", "1", "exit-code")
+ if res := waitSwap(t, ch); res.Outcome != SwapFailed {
+ t.Fatalf("Swap = %+v", res)
+ }
+ f.a.sweepOnce()
+ if !stopping() || !strings.Contains(logs.String(), "past its plan's ceiling") {
+ t.Fatalf("the ceiling did not fire on the first sweep after the release (log %q)", logs.String())
+ }
+ f.a.mu.Lock()
+ if e := f.a.entries[f.host]; e != nil {
+ e.inflight--
+ }
+ f.a.mu.Unlock()
+ for i := 0; i < 200 && f.a.entryCount() > 0; i++ {
+ f.a.sweepOnce()
+ time.Sleep(10 * time.Millisecond)
+ }
+ if f.a.entryCount() != 0 {
+ t.Fatal("the ceiling's stop never finished")
+ }
+ waitFor(t, "the stop's end", func() bool { return strings.Contains(logs.String(), f.host+" hibernated") })
+}
+
+// swapNoRelease runs at and fails t at once if a release starts for it.
+func (f *relSwapFixture) swapNoRelease(t *testing.T, at Attempt) SwapResult {
+ t.Helper()
+ ch := f.swapAsync(at)
+ select {
+ case res := <-ch:
+ return res
+ case <-f.rb.units:
+ t.Fatal("a release started")
+ case <-time.After(30 * time.Second):
+ t.Fatal("Swap did not return")
+ }
+ return SwapResult{}
+}
+
+func TestNoReleaseForADisabledRoute(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ f.a.SetDisabledFor(func(rt registry.Route) bool { return rt.Host == f.host })
+ res := f.swapNoRelease(t, f.attempt(ModeOverlap))
+ if res.Outcome != SwapAbandoned || res.Reason != errReleaseTurnedOff.Error() || res.Executed {
+ t.Fatalf("Swap of a plan-disabled route = %+v", res)
+ }
+ if verdictOf(errReleaseTurnedOff) != gateNoOwnership {
+ t.Error("errReleaseTurnedOff is not a refusal")
+ }
+ f.noUnit(t, "for a disabled route")
+ if n := f.rb.readCount(); n != 0 {
+ t.Errorf("the declared processes were read %d times for a disabled route", n)
+ }
+ f.nothingAdmitted(t, "for a disabled route")
+}
+
+// [pf R2.3]: the release's gate is the swap's own checks, asked before
+// anything is read and again at the release's exec: a superseded attempt
+// starts no release.
+func TestNoReleaseForASupersededAttempt(t *testing.T) {
+ t.Run("before the release", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ at := f.attempt(ModeOverlap)
+ f.rev.Add(1)
+ res := f.swapNoRelease(t, at)
+ if res.Outcome != SwapAbandoned || res.Reason != errSwapSuperseded.Error() || res.Executed {
+ t.Fatalf("Swap of a superseded attempt = %+v", res)
+ }
+ if n := f.rb.readCount(); n != 0 {
+ t.Errorf("the declared processes were read %d times for a superseded attempt", n)
+ }
+ f.noUnit(t, "for a superseded attempt")
+ f.nothingAdmitted(t, "for a superseded attempt")
+ })
+ t.Run("at the release's exec", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ f.rb.onEnv = func() { f.rev.Add(1) }
+ res := f.swapNoRelease(t, f.attempt(ModeOverlap))
+ if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errSwapSuperseded.Error()) || res.Executed {
+ t.Fatalf("Swap superseded before the release's exec = %+v", res)
+ }
+ f.noUnit(t, "superseded at the exec")
+ f.nothingAdmitted(t, "superseded at the exec")
+ if f.record() != nil {
+ t.Error("a release record outlived the refused start")
+ }
+ })
+}
+
+func TestNoReleaseBesideAnUnfinishedOperation(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ delete(f.rb.procs, "v2") // B declares no release
+ incumbent := f.b.lastProc()
+ incumbent.mu.Lock()
+ incumbent.stuck = true
+ incumbent.mu.Unlock()
+ res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest)
+ if res.Outcome != SwapDone || !strings.Contains(res.Reason, "not yet proven stopped") {
+ t.Fatalf("the swap to B = %+v; want done with its retiring generation unproven", res)
+ }
+ f.a.mu.Lock()
+ e := f.a.entries[f.host]
+ outstanding, raised := len(e.ops.members), e.ops.raised
+ f.a.mu.Unlock()
+ if outstanding != 1 || !raised {
+ t.Fatalf("after B: members %d, raised %v", outstanding, raised)
+ }
+ f.rev.Add(1)
+ res = f.a.Swap(context.Background(), f.attemptV3(ModeOverlap), f.newest)
+ if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errSwapBusy.Error()) || res.Executed {
+ t.Fatalf("C beside the unfinished operation = %+v; want abandoned busy, not executed", res)
+ }
+ f.noUnit(t, "beside the unfinished operation")
+ if f.record() != nil {
+ t.Fatal("a release record beside the unfinished operation")
+ }
+ incumbent.exit()
+ waitFor(t, "the retiring generation's proof and the parent's restore", func() bool {
+ f.a.mu.Lock()
+ f.a.finishPendingStops()
+ e := f.a.entries[f.host]
+ done := len(e.ops.members) == 0 && !e.ops.raised
+ f.a.mu.Unlock()
+ return done
+ })
+ ch := f.swapAsync(f.attemptV3(ModeOverlap))
+ f.nextUnit(t).done("1", "0", "success")
+ if res := waitSwap(t, ch); res.Outcome != SwapDone || res.Gen.Build != "v3" {
+ t.Fatalf("C once the operation finished = %+v", res)
+ }
+ if got := f.rb.startList(); !slices.Equal(got, []string{"v3"}) {
+ t.Errorf("releases started %v", got)
+ }
+}
+
+// D3: the pass lives only on the Swap call's stack. A Service replaced
+// between the pass and the swap runs the release again before admitting
+// the build.
+func TestReleaseRerunsAfterAnAgentRestart(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ type answer struct {
+ pass *releasePass
+ ok bool
+ }
+ ch := make(chan answer, 1)
+ go func() {
+ p, _, _, ok := f.a.releaseBeforeSwap(context.Background(), f.attempt(ModeOverlap), f.newest)
+ ch <- answer{p, ok}
+ }()
+ f.nextUnit(t).done("1", "0", "success")
+ got := <-ch
+ if got.pass == nil || !got.ok {
+ t.Fatalf("the first Service's release = %+v; want a pass", got)
+ }
+ // The seam between the pass and swapOverlap: the agent restarts. A new
+ // Service over the same registry and backend wakes the incumbent.
+ b := New(Config{Bucket: "test-bucket", Idle: time.Hour}, f.rb, f.reg)
+ b.gens, b.now = true, f.clk.now
+ b.genHealth = func(context.Context, Gen) error { return nil }
+ b.Logs = f.sink
+ b.GenerationsFile = f.a.GenerationsFile
+ arrangeAwake(t, b, f.binRoute)
+ setCurrentGen(t, b, f.host, f.incumbent)
+ makeRootfsIncumbent(t, b, f.host)
+ if b.releaseOps[f.host] != nil {
+ t.Fatal("the new Service starts with a release record")
+ }
+ sw := make(chan SwapResult, 1)
+ go func() { sw <- b.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) }()
+ f.nextUnit(t).done("1", "0", "success")
+ res := waitSwap(t, sw)
+ if res.Outcome != SwapDone || res.Gen.Build != "v2" {
+ t.Fatalf("the new Service's swap = %+v", res)
+ }
+ if got := f.rb.startList(); !slices.Equal(got, []string{"v2", "v2"}) {
+ t.Errorf("releases started %v; want B's release again on the new Service", got)
+ }
+ ev := f.b.events()
+ second := slices.Index(ev, "release:start:v2")
+ second += 1 + slices.Index(ev[second+1:], "release:start:v2")
+ if second <= 0 || indexPrefix(ev[second:], "startGen:"+f.staged) < 0 {
+ t.Errorf("events %v: the new Service's StartStaged does not follow its own release", ev)
+ }
+}
+
+// INV-6: a binary overlap and hold run as on main: no process read, no
+// release, and the same order of backend calls as a fixture without the
+// release seam.
+func TestBinarySwapUnchangedByTheReleaseCheck(t *testing.T) {
+ norm := regexp.MustCompile(`(switch|gen):\d+`)
+ normalize := func(ev []string, staged string) []string {
+ out := make([]string, len(ev))
+ for i, e := range ev {
+ out[i] = norm.ReplaceAllString(strings.ReplaceAll(e, staged, "<staged>"), "$1:N")
+ }
+ return out
+ }
+ for _, mode := range []SwapMode{ModeOverlap, ModeHold} {
+ t.Run(string(mode), func(t *testing.T) {
+ plain := newSwapFixture(t)
+ want := plain.a.Swap(context.Background(), plain.attempt(mode), plain.newest)
+ f := newRelSwapFixture(t, false)
+ got := f.a.Swap(context.Background(), f.attempt(mode), f.newest)
+ if got.Outcome != SwapDone || got.Outcome != want.Outcome || got.Executed != want.Executed || got.Mode != want.Mode || got.Reason != want.Reason {
+ t.Fatalf("Swap = %+v, without the release seam %+v", got, want)
+ }
+ if n := f.rb.readCount(); n != 0 {
+ t.Errorf("a binary %s read the declared processes %d times", mode, n)
+ }
+ f.noUnit(t, "a binary "+string(mode))
+ if a, b := normalize(f.b.events(), f.staged), normalize(plain.b.events(), plain.staged); !slices.Equal(a, b) {
+ t.Errorf("backend calls %v, without the release seam %v", a, b)
+ }
+ })
+ }
+}
+
+// The release-word phrases reach the swap's reason through the approved
+// rows (RFS-3-C01, C02 are rendered by rollout; the reason text here is
+// what reasonWord reads).
+func TestReleaseSwapResultIsTheOverlapColumn(t *testing.T) {
+ failed := &ReleaseError{Build: "v2", Exit: 3}
+ timedOut := &ReleaseError{Build: "v2", TimedOut: true, Took: time.Minute}
+ for _, tc := range []struct {
+ name string
+ err error
+ executed bool
+ open bool
+ outcome SwapOutcome
+ exec bool
+ prefix string
+ }{
+ {"failed", failed, true, false, SwapFailed, true, "release: "},
+ {"timed out", timedOut, true, false, SwapFailed, true, "release timed out: "},
+ {"unproven", errors.Join(errReleaseUnproven, errors.New("cgroup")), true, true, SwapAbandoned, true, ""},
+ {"cancelled, ran", errReleaseVanished, true, false, SwapAbandoned, true, ""},
+ {"cancelled, the lease", fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost), true, false, SwapAbandoned, true, ""},
+ {"refused", errReleaseOpen, false, true, SwapAbandoned, false, ""},
+ {"refused by root", refuseRootfs(errors.New("root said no")), false, false, SwapAbandoned, false, ""},
+ {"refused, not published", errStagedBuildNotPublished, false, false, SwapAbandoned, false, ""},
+ } {
+ res := releaseSwapResult(tc.err, tc.executed, tc.open)
+ if res.Outcome != tc.outcome || res.Executed != tc.exec || !strings.HasPrefix(res.Reason, tc.prefix) {
+ t.Errorf("%s: %+v; want %s, executed %v, reason prefix %q", tc.name, res, tc.outcome, tc.exec, tc.prefix)
+ }
+ if res.Outcome == SwapDown {
+ t.Errorf("%s: a release before an overlap answered SwapDown", tc.name)
+ }
+ }
+ if got := rolloutwords.EventReleaseFailed; !strings.Contains("release: "+failed.Error(), strings.SplitN(got, "%", 2)[0]) {
+ t.Errorf("the failure's reason does not carry C05 (%q)", got)
+ }
+}
diff --git a/internal/activator/rootfsrelease.go b/internal/activator/rootfsrelease.go
index 8cb33b3bf..8a79b82b9 100644
--- a/internal/activator/rootfsrelease.go
+++ b/internal/activator/rootfsrelease.go
@@ -726,3 +726,142 @@ func (a *Service) reapReleaseOpsLocked() {
op.hold.retrySettle(true, actStopTimeout)
}
}
+
+// ---- R2: the release before an overlap swap ---------------------------
+
+// releasePass is an attempt-scoped, in-memory result: the attempt's
+// build's release succeeded and its unit is proven stopped. It lives only
+// on one Swap call's stack, so an agent restart forgets it and the next
+// attempt runs the release again (D3). It names the attempt (host,
+// SchedRev) and the build's full identity, and swapOverlap admits the
+// build only on a pass that matches both (INV-R5). (The plan calls it
+// releasePassed; that name is classifyRelease's outcome here.)
+type releasePass struct {
+ host string
+ schedRev uint64 // the attempt's SchedRev
+ build release.StagedIdentity // the attempt's full identity
+}
+
+// matches reports whether p is the pass of attempt at for generation g's
+// build: the same host and SchedRev, and g's whole staged identity
+// (version, path, digest, demand). A nil pass matches nothing.
+func (p *releasePass) matches(at Attempt, g Gen) bool {
+ if p == nil {
+ return false
+ }
+ id, err := stagedIdentityOf(g)
+ if err != nil {
+ return false
+ }
+ return p.host == at.Host && p.schedRev == at.SchedRev && id == p.build
+}
+
+var (
+ // errReleaseNotPassed: an overlap of a build that needs a release,
+ // without this attempt's proven pass for it (INV-R5). NoOwnership in
+ // verdictOf: a refusal before anything of the build ran.
+ errReleaseNotPassed = errors.New("activator: the attempt's build needs a release that has not passed for this attempt")
+ // errReleaseTurnedOff: the route's plan turned it off, so no release
+ // starts for it (the sweep stops it instead). NoOwnership in verdictOf.
+ errReleaseTurnedOff = errors.New("activator: the instance is turned off by its plan, so no release command starts")
+)
+
+// releaseAdmitsSwapLocked is the release's half of an overlap's admission
+// and of its exec gate: no release record of the host is open (INV-R4),
+// and when a release was due, pass is this attempt's for g's build
+// (INV-R5). The caller holds a.mu.
+func (a *Service) releaseAdmitsSwapLocked(at Attempt, g Gen, pass *releasePass, due bool) error {
+ if a.releaseOps[at.Host] != nil {
+ return errReleaseOpen
+ }
+ if due && !pass.matches(at, g) {
+ return errReleaseNotPassed
+ }
+ return nil
+}
+
+// releaseBeforeSwap runs the attempt's build's release, when one is due,
+// from the new image under the incumbent's lease, before the overlap swap
+// is admitted (Group R, R2; C8). ok && !due: no release is due (a binary
+// row, a build that declares none, the row's good build) and the swap
+// proceeds without a pass. ok && due: the release passed and its unit is
+// proven gone; the swap proceeds with pass. !ok: res is the release's
+// outcome as the swap's result, and the swap is never admitted. Only a
+// release that ran and failed, its unit proven gone, is SwapFailed; every
+// other outcome is an abandonment (INV-R3). Never call it with a.mu held.
+func (a *Service) releaseBeforeSwap(ctx context.Context, at Attempt, newest func(string) uint64) (pass *releasePass, due bool, res SwapResult, ok bool) {
+ a.mu.Lock()
+ e := a.entries[at.Host]
+ if e == nil || !e.route.Rootfs() {
+ // A binary row (or none: the swap's admission refuses it) reads
+ // nothing here, so a binary swap is exactly as it was (INV-6).
+ a.mu.Unlock()
+ return nil, false, SwapResult{}, true
+ }
+ rt, rep := e.route, e.rep
+ a.mu.Unlock()
+ // The gate, asked here, again by runRelease before the start, and at
+ // the exec [pf R2.3]: the swap's own checks (the entry, awake, its
+ // lease, no fence, no shutdown, the attempt newest), and a route its
+ // plan has not turned off.
+ gate := func() error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if err := a.swapChecksLocked(e, at, newest); err != nil {
+ return err
+ }
+ if a.disabled(e.route) {
+ return errReleaseTurnedOff
+ }
+ return nil
+ }
+ if err := gate(); err != nil {
+ return nil, false, abandon(err), false
+ }
+ id := release.StagedIdentity{Version: at.Build, StagedPath: at.StagedPath, Digest: at.Digest, Demand: at.Demand}
+ // The bytes first, as swapOverlap checks them again [pf R2.5].
+ if err := release.VerifyStaged(id); err != nil {
+ return nil, false, abandon(fmt.Errorf("staging: %w", err)), false
+ }
+ // The attempt's own lifetime, so Shutdown's lifeStop cancels the
+ // release [pf R2.6]. Only releaseTimeout bounds it otherwise.
+ mctx, cancel := a.attemptCtx(ctx)
+ defer cancel()
+ executed, err := a.runRelease(mctx, e, rt, id, watchOf(rep), gate)
+ if err == nil {
+ if !executed {
+ // runRelease answers (false, nil) only when no release is due;
+ // a passed release always started its unit.
+ return nil, false, SwapResult{}, true
+ }
+ return &releasePass{host: at.Host, schedRev: at.SchedRev, build: id}, true, SwapResult{}, true
+ }
+ return nil, true, releaseSwapResult(err, executed, a.releaseOpen(at.Host)), false
+}
+
+// releaseSwapResult is the overlap column of the release's classification
+// table: a release's result before an overlap swap as the swap's result.
+// failed (a *ReleaseError, its unit proven gone) is the build's failure,
+// SwapFailed with the release's reason, and the incumbent keeps serving
+// (C8). unproven is abandoned, executed, its record left blocking the host
+// (INV-R4). cancelled and refused are abandoned with executed as runRelease
+// gave it: false when no unit started, true when one did (it ran, or may
+// have). Never through classifyStep.
+func releaseSwapResult(err error, executed, recordOpen bool) SwapResult {
+ switch classifyRelease(err, recordOpen) {
+ case releaseFailed:
+ var rerr *ReleaseError
+ prefix := "release: "
+ if errors.As(err, &rerr) && rerr.TimedOut {
+ prefix = "release timed out: "
+ }
+ return SwapResult{Outcome: SwapFailed, Reason: prefix + err.Error(), Executed: true}
+ case releaseUnproven:
+ res := abandon(err)
+ res.Executed = true
+ return res
+ }
+ res := abandon(err)
+ res.Executed = executed
+ return res
+}
diff --git a/internal/activator/swap.go b/internal/activator/swap.go
index e8349bd15..7bd05aec5 100644
--- a/internal/activator/swap.go
+++ b/internal/activator/swap.go
@@ -222,6 +222,14 @@ const (
// the build it replaced at once (its veto switch names this sentinel
// before the NoOwnership case), since nothing of the attempt ran.
//
+// The release's gates (rootfs apps Plan 3, Group R, R2) are NoOwnership
+// too: an open release record of the host (errReleaseOpen, INV-R4), an
+// overlap whose build needs a release without this attempt's proven pass
+// (errReleaseNotPassed, INV-R5), and a release refused for a route its
+// plan turned off (errReleaseTurnedOff). Each refuses before anything of
+// the build runs, at the admission or at the exec, so a refusal that
+// surfaces from inside the spawn is abandonment, never the build's failure.
+//
// errSwapStopped (the barrier's cancel, from memberCurrentLocked) is
// NoOwnership too: the entry is stopping, so nothing may spawn for it.
// classifyStep reads it as stepCancelled before it asks this.
@@ -246,7 +254,8 @@ func verdictOf(err error) gateVerdict {
errors.Is(err, errUnitNoGens), errors.Is(err, errSwapNoGens), errors.Is(err, instancectl.ErrStagedExe),
errors.Is(err, instancectl.ErrStagedImage), errors.Is(err, errRootfsRefused),
errors.Is(err, errRootfsBinaryLaunch), errors.Is(err, errNoRootfsControl),
- errors.Is(err, errBuildStateUnwritten), errors.Is(err, errOwnershipRefused):
+ errors.Is(err, errBuildStateUnwritten), errors.Is(err, errOwnershipRefused),
+ errors.Is(err, errReleaseOpen), errors.Is(err, errReleaseNotPassed), errors.Is(err, errReleaseTurnedOff):
return gateNoOwnership
}
return gateProceed
@@ -305,6 +314,16 @@ func (a *Service) Swap(ctx context.Context, at Attempt, newest func(host string)
if newest == nil {
return abandon(errSwapSuperseded)
}
+ // INV-R4: an open release record (running, or its unit not proven
+ // stopped) blocks every transition of the host, whatever the mode and
+ // the cause, before anything reads the build or decides whether it
+ // needs a release [pf R2.1]. A binary row never has one.
+ a.mu.Lock()
+ open := a.releaseOps[at.Host] != nil
+ a.mu.Unlock()
+ if open {
+ return abandon(errReleaseOpen)
+ }
switch at.Mode {
case ModeOverlap:
if a.foreignRow(at.Host) {
@@ -317,7 +336,16 @@ func (a *Service) Swap(ctx context.Context, at Attempt, newest func(host string)
res.Mode = ModeHold
return res
}
- res := a.swapOverlap(ctx, gb, at, newest)
+ // A rootfs build that declares release runs it from the new image,
+ // under the incumbent's lease, before the swap is admitted (Group R,
+ // R2). The swap is admitted only on that attempt's proven pass.
+ pass, due, res, ok := a.releaseBeforeSwap(ctx, at, newest)
+ if ok {
+ res = a.swapOverlap(ctx, gb, at, newest, pass, due)
+ // A passed release is a process of the build that ran (against
+ // the instance's database), whatever ends the swap after it.
+ res.Executed = res.Executed || pass != nil
+ }
res.Mode = ModeOverlap
return res
case ModeHold:
@@ -414,7 +442,13 @@ func (a *Service) spawnSuccessor(ctx context.Context, gb SwapBackend, e *actEntr
// leaveSet restores a raised parent when the last member leaves. Nothing
// here blocks under a.mu except GenSwitched, which plan 1's lock contract
// puts in the same critical section as e.gen.
-func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, newest func(string) uint64) (out SwapResult) {
+//
+// pass and due are releaseBeforeSwap's: due is whether the attempt's build
+// needed a release, and pass is its proven pass. Both the admission and
+// the exec gate refuse while any release record of the host is open, and,
+// when a release was due, unless pass is this attempt's for this build
+// (INV-R4, INV-R5). No release runs here.
+func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, newest func(string) uint64, pass *releasePass, due bool) (out SwapResult) {
// The execution evidence (SwapResult.Executed): the backend returned a
// successor process, or its error says the build may have run
// (startMayHaveRun), whatever ends the attempt after that.
@@ -491,6 +525,9 @@ func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, n
if cmdStartInFlightLocked(e) {
return errSwapBusy
}
+ if err := a.releaseAdmitsSwapLocked(at, m.gen, pass, due); err != nil {
+ return err
+ }
a.addMemberLocked(e, m)
// The successor starts from the size column the size pass last
// read (sizedRouteLocked), so a deploy lands a new size's memory.
@@ -570,7 +607,10 @@ func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, n
gate := func() error {
a.mu.Lock()
defer a.mu.Unlock()
- return a.memberCurrentLocked(e, m, mctx, at, newest)
+ if err := a.memberCurrentLocked(e, m, mctx, at, newest); err != nil {
+ return err
+ }
+ return a.releaseAdmitsSwapLocked(at, m.gen, pass, due)
}
if err := a.admit(ctx, work, gate); err != nil {
a.dropMember(e, m) // restores the raised parent (leaveSet)
diff --git a/internal/activator/swaphold.go b/internal/activator/swaphold.go
index 93cc1092b..621b39a7b 100644
--- a/internal/activator/swaphold.go
+++ b/internal/activator/swaphold.go
@@ -206,11 +206,16 @@ func (a *Service) swapHold(ctx context.Context, at Attempt, newest func(string)
// checks on e, then the gates that refuse a row before anything stops (the
// kind, the layout, an operation already under way). swapHold asks it twice,
// before the build's publication and again after it, with a.mu re-taken.
-// The caller holds a.mu.
+// An open release record of the host refuses both (INV-R4) [pf R2.4]; the
+// check is here and not in attemptCurrentLocked, which a release's own
+// gate asks while its record exists. The caller holds a.mu.
func (a *Service) holdAdmitLocked(e *actEntry, at Attempt, newest func(string) uint64) error {
if err := a.swapChecksLocked(e, at, newest); err != nil {
return err
}
+ if a.releaseOps[at.Host] != nil {
+ return errReleaseOpen
+ }
if e.worker || e.route.Kind != "instance" || e.route.Backing == registry.BackingUnit {
return errSwapKind
}
diff --git a/internal/rollout/events.go b/internal/rollout/events.go
index d0b97dc80..88f78163b 100644
--- a/internal/rollout/events.go
+++ b/internal/rollout/events.go
@@ -36,6 +36,13 @@ const (
func reasonWord(text string) string {
t := strings.ToLower(text)
switch {
+ // A release command's failure (rootfs apps Plan 3, Group R) first:
+ // its text names the build's exit ("exited") and could name staging,
+ // and neither is why it failed [pf R2.7].
+ case strings.HasPrefix(t, "release timed out"):
+ return status.ReasonReleaseTimeout
+ case strings.HasPrefix(t, "release"):
+ return status.ReasonRelease
case strings.Contains(t, "reused"):
return status.ReasonReused
case strings.Contains(t, "staging"), strings.Contains(t, "staged"), strings.Contains(t, "digest"):
diff --git a/internal/rollout/rootfs_reason_test.go b/internal/rollout/rootfs_reason_test.go
new file mode 100644
index 000000000..9f1a37f98
--- /dev/null
+++ b/internal/rollout/rootfs_reason_test.go
@@ -0,0 +1,64 @@
+package rollout
+
+// Rootfs apps Plan 3, Group R, R2 [pf R2.7]: a release command's failure
+// before an overlap swap reaches the scheduler as SwapFailed with a reason
+// that starts "release: " (or "release timed out: "). reasonWord reads it
+// as the release's own word before its other arms, so the swap.failed
+// event and the REASON column say why (RFS-3-C01, C02) with no new code.
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/rolloutwords"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+func TestReasonWordRelease(t *testing.T) {
+ exit := &activator.ReleaseError{Build: "v2", Exit: 1}
+ signal := &activator.ReleaseError{Build: "v2", Signal: "9"}
+ timeout := &activator.ReleaseError{Build: "v2", TimedOut: true, Took: 10 * time.Minute}
+ for text, want := range map[string]string{
+ // The texts swap.go's releaseSwapResult builds from a ReleaseError.
+ "release: the release command of build v2 exited with status 1": status.ReasonRelease,
+ "release: " + exit.Error(): status.ReasonRelease,
+ "release: " + signal.Error(): status.ReasonRelease,
+ "release timed out: " + timeout.Error(): status.ReasonReleaseTimeout,
+ "Release: " + exit.Error(): status.ReasonRelease,
+ // The other arms are unchanged.
+ "health check failed": status.ReasonHealth,
+ "swap: successor exited during its settle": status.ReasonSettle,
+ "exited within 10s of becoming healthy": status.ReasonExit,
+ "staging: digest mismatch": status.ReasonStaging,
+ "staging: staged copy no longer matches the digest": status.ReasonStaging,
+ "version name reused with different content, ship under a new name": status.ReasonReused,
+ "GET / answered 500": status.ReasonHealth,
+ "": status.ReasonHealth,
+ // Only a reason that starts with the release's prefix is the
+ // release's: an exit that mentions a release elsewhere is an exit.
+ "spawn: exited before the release": status.ReasonExit,
+ } {
+ if got := reasonWord(text); got != want {
+ t.Errorf("reasonWord(%q) = %q, want %q", text, got, want)
+ }
+ }
+ // The member-facing phrases (RFS-3-C01, C02), read after "because" in
+ // the existing swap.failed event.
+ for word, phrase := range map[string]string{
+ status.ReasonRelease: "its release command failed",
+ status.ReasonReleaseTimeout: "its release command did not finish in time",
+ } {
+ if got := rolloutwords.Reason(word); got != phrase {
+ t.Errorf("Reason(%q) = %q, want %q", word, got, phrase)
+ }
+ ev := textSwapFailed("v2", "v1", word)
+ if !strings.Contains(ev, phrase) {
+ t.Errorf("swap.failed for %q = %q, missing %q", word, ev, phrase)
+ }
+ }
+ if got := textSwapFailed("v2", "v1", reasonWord("release timed out: "+timeout.Error())); !strings.Contains(got, "did not finish in time") {
+ t.Errorf("a timed-out release's swap.failed = %q", got)
+ }
+}
diff --git a/internal/rolloutwords/words.go b/internal/rolloutwords/words.go
index 89ba02839..50618d0b6 100644
--- a/internal/rolloutwords/words.go
+++ b/internal/rolloutwords/words.go
@@ -37,6 +37,10 @@ var reasons = map[string]string{
"exit": "it exited before it was ready",
"staging": "the copy on the box did not match the release",
"reused": "this version name was shipped twice with different content, so ship it under a new name",
+ // Rootfs apps Plan 3, Group R: a build whose release command failed,
+ // and one whose release command ran past its timeout.
+ "release": "its release command failed", // RFS-3-C01
+ "release-timeout": "its release command did not finish in time", // RFS-3-C02
}
const reasonUnknown = "it failed (%s)"
diff --git a/internal/rolloutwords/words_test.go b/internal/rolloutwords/words_test.go
index 423446387..44dbcd88f 100644
--- a/internal/rolloutwords/words_test.go
+++ b/internal/rolloutwords/words_test.go
@@ -82,7 +82,8 @@ func TestEveryCauseAndReasonHasAPhrase(t *testing.T) {
t.Errorf("cause %q has no phrase", c)
}
}
- for _, r := range []string{status.ReasonHealth, status.ReasonSettle, status.ReasonExit, status.ReasonStaging, status.ReasonReused} {
+ for _, r := range []string{status.ReasonHealth, status.ReasonSettle, status.ReasonExit, status.ReasonStaging, status.ReasonReused,
+ status.ReasonRelease, status.ReasonReleaseTimeout} {
if reasons[r] == "" {
t.Errorf("reason %q (plan 5's word) has no phrase", r)
}