carlos / platform Public

rootfs: release runs inside the wake's lease before web; an unproven release keeps the lease, the pin and the host latched

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4415f288951c8f04580e399a802840057b835918 parent c0075b3
18 files changed, +1,660 −58
  • docs/superpowers/notes/rootfs-first-boot-marker.md +4 −1
  • internal/activator/activator.go +39 −4
  • internal/activator/activator_test.go +19 −1
  • internal/activator/backend_rootfs.go +7 −10
  • internal/activator/maintenance.go +7 −0
  • internal/activator/rootfs_admission_test.go +9 −7
  • internal/activator/rootfs_gate_test.go +24 −3
  • internal/activator/rootfs_processes_test.go +40 −27
  • internal/activator/rootfs_resident_lease_test.go +1 −0
  • internal/activator/rootfs_resident_test.go +13 −0
  • internal/activator/rootfs_service.go +16 −0
  • internal/activator/rootfs_wake_release_test.go +1,122 −0
  • internal/activator/rootfsrelease.go +96 −1
  • internal/activator/rootfsrelease_test.go +35 −2
  • internal/activator/swaphold.go +31 −0
  • internal/activator/wakeidentity_test.go +15 −2
  • internal/activator/wakeplan.go +53 −0
  • internal/rollout/rootfs_release_outcomes_test.go +129 −0

CI failed — run details

diff --git a/docs/superpowers/notes/rootfs-first-boot-marker.md b/docs/superpowers/notes/rootfs-first-boot-marker.md
index 90a850f4f..2f434944e 100644
--- a/docs/superpowers/notes/rootfs-first-boot-marker.md
+++ b/docs/superpowers/notes/rootfs-first-boot-marker.md
@@ -30,7 +30,10 @@ there): refusing an empty boot`. There are two causes:
- **The instance served and its data is gone.**
- **The first boot was interrupted** (the agent stopped after the marker
was confirmed). The instance may never have served. This refusal is by
- design (Paul's ruling, 2026-10-27, "refuse interrupted init").
+ design (Paul's ruling, 2026-10-27, "refuse interrupted init"). This
+ includes a first boot whose release command never passed and whose box
+ was then lost: the local, partly migrated placeholder database went
+ with the box, and nothing of it was replicated.
Nothing on the box or in the bucket tells these apart. An empty replica
prefix proves nothing: a first upload that fails only logs, and the
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 293ef9b4d..0ddc40e2b 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1939,7 +1939,9 @@ func (a *Service) wake(e *actEntry) {
// A probe's wake ends with its caller (ProbeWake).
parent = e.probe.parent
}
- ctx, cancel := context.WithTimeout(parent, 5*time.Minute)
+ // A rootfs row's ceiling has room for a release inside the wake
+ // (wakeCeilingFor; Group R, R3).
+ ctx, cancel := context.WithTimeout(parent, wakeCeilingFor(e.route))
defer cancel()
a.mu.Lock()
e.wakeCancel = cancel
@@ -2492,6 +2494,20 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
// refuses the wake here, before the lease: nothing is taken, nothing
// runs, and no build is blamed (errStagedBuildNotPublished).
if plan.planned() || e.pin != nil {
+ // A rootfs build about to boot has its declared processes read
+ // here, before the lease [pf R3.7]: a staged manifest that is not
+ // the image refuses before Acquire and Restore, once per change,
+ // and never as a resident's failure. runRelease reads them again
+ // under the lease.
+ if rt.Rootfs() {
+ g := genOf(plan.Boot)
+ if e.pin != nil {
+ g = *e.pin
+ }
+ if _, err := a.declaredProcesses(rt, g); err != nil {
+ return w, notAdmitted(refuseRootfs(err))
+ }
+ }
if err := a.publishBeforeExec(); err != nil {
return w, fmt.Errorf("%s: refusing to wake: %w", host, err)
}
@@ -2834,10 +2850,22 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
// The identity step 2b recorded, as the next generation, exactly
// where startGen would put it: the canonical socket (and, nested,
// the original run unit) with the flag off, generation n's own
- // socket and unit with it on (startGenExe).
+ // socket and unit with it on (startGenExe). A rootfs build's
+ // release runs first, on that identity, under this wake's lease
+ // (Group R, R3); a release that did not pass fails the wake.
var g Gen
- proc, g, err = a.startGenExe(ctx, ib, rt, id)
- spawnVer, w.gen = g.Build, g
+ if err = a.releaseInWake(ctx, e, rt, id, lease); err == nil {
+ proc, g, err = a.startGenExe(ctx, ib, rt, id)
+ spawnVer, w.gen = g.Build, g
+ }
+ } else if rt.Rootfs() {
+ // A rootfs row with no plan, no pin and no staged identity [pf
+ // R3.6]: nothing here can decide whether its release is due, so web
+ // does not start on a database its release may not have prepared.
+ // Nothing ran: a refusal, and the lease goes back.
+ w.stopOutcome.notStarted()
+ w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease)
+ return w, fmt.Errorf("start %s: %w", host, refuseRootfs(fmt.Errorf("%s: %w", host, errPartialStagedIdentity)))
} else {
var g Gen
proc, g, err = a.startGen(ctx, rt)
@@ -2847,6 +2875,13 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
w.steps.mark(a.now(), "spawn")
w.proc = proc
if err != nil {
+ // A release of this wake whose unit is not proven stopped keeps
+ // the wake's lease in its record (owed), never given back here
+ // while the release's unit may still write [pf R3.1]: the record
+ // outlives the entry and gives the lease back after its proof.
+ if a.oweWakeLeaseToRelease(e, w, lease) {
+ return w, fmt.Errorf("start %s: %w", host, err)
+ }
// A start whose kill was unproven may have left its generation
// running with no process handle (plan 2's startUnitAt). Its lease
// is kept, process or not (P2-13).
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go
index 32c0e5d65..ac26b0cf5 100644
--- a/internal/activator/activator_test.go
+++ b/internal/activator/activator_test.go
@@ -37,6 +37,7 @@ import (
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/seeds"
_ "modernc.org/sqlite"
@@ -528,6 +529,16 @@ type fakeBackend struct {
// repWrap, when set, wraps the replica each lease's Replicate hands
// back (Plan 3 Task 8: a replica with the lease's own loss signal).
repWrap func(*fakeRep) Rep
+
+ // Group R, R3 (rootfs_wake_release_test.go). processes answers the
+ // ProcessReader (nil: web alone) and processReads counts its reads.
+ // leaseWrap, when set, is the Lease each Acquire hands out in place of
+ // the plain fakeLease (a wake's lease with the lease's own signal), and
+ // acquireCtx, when set, sees each Acquire's context.
+ processes func(registry.Route, release.StagedIdentity) (map[string]release.Process, error)
+ processReads int
+ leaseWrap func(*fakeLease) Lease
+ acquireCtx func(context.Context)
}
// Layout is fakeBackend's Classifier implementation, always present so
@@ -551,16 +562,23 @@ func (b *fakeBackend) events() []string {
return append([]string(nil), b.order...)
}
-func (b *fakeBackend) Acquire(context.Context, registry.Route) (Lease, error) {
+func (b *fakeBackend) Acquire(ctx context.Context, _ registry.Route) (Lease, error) {
b.mu.Lock()
b.acquires++
err := b.acquireErr
rep := &fakeRep{b: b}
b.reps = append(b.reps, rep)
+ wrap, see := b.leaseWrap, b.acquireCtx
b.mu.Unlock()
+ if see != nil {
+ see(ctx)
+ }
if err != nil {
return nil, err
}
+ if wrap != nil {
+ return wrap(&fakeLease{rep: rep, b: b}), nil
+ }
return &fakeLease{rep: rep, b: b}, nil
}
diff --git a/internal/activator/backend_rootfs.go b/internal/activator/backend_rootfs.go
index 27ba1255e..221396b1b 100644
--- a/internal/activator/backend_rootfs.go
+++ b/internal/activator/backend_rootfs.go
@@ -85,13 +85,13 @@ func (b *ExecBackend) Processes(rt registry.Route, id release.StagedIdentity) (m
// rootfsProcessesHook is where a rootfs wake (doWake, after step 6) and
// an overlap swap (swapOverlap, step 8) meet the processes the serving
-// build declares beside web. In Group A this box runs web alone, so it
-// reads Processes(rt, stagedIdentityOf(g)) and logs, once per call, the
-// workers and the release process it does not run yet (D8); a refused
-// read logs once. It starts nothing and never fails a wake or a swap.
-// Group W's W1 makes the doWake call start the workers and W2 the swap's
-// hand them over (ctx and e are theirs); Group R's R1 drops the release
-// line. A binary row reads nothing. The caller does not hold a.mu: the
+// build declares beside web. This box runs web and, before it, the
+// release (Group R: every wake and swap site runs it), so it reads
+// Processes(rt, stagedIdentityOf(g)) and logs, once per call, the workers
+// it does not run yet (D8); a refused read logs once. It starts nothing
+// and never fails a wake or a swap. Group W's W1 makes the doWake call
+// start the workers and W2 the swap's hand them over (ctx and e are
+// theirs). A binary row reads nothing. The caller does not hold a.mu: the
// read is file I/O.
func (a *Service) rootfsProcessesHook(ctx context.Context, e *actEntry, rt registry.Route, g Gen) {
if !rt.Rootfs() {
@@ -112,9 +112,6 @@ func (a *Service) rootfsProcessesHook(ctx context.Context, e *actEntry, rt regis
if len(workers) > 0 {
log.Printf("activator: %s: build %s declares workers (%s); this box does not run workers yet", rt.Host, g.Build, strings.Join(workers, ", "))
}
- if _, ok := procs[release.ProcessRelease]; ok {
- log.Printf("activator: %s: build %s declares a release process; this box does not run it yet, so the app's web command must prepare its own database", rt.Host, g.Build)
- }
}
// declaredProcesses is g's declared processes through the Service's
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go
index cd6e3bb22..f28083592 100644
--- a/internal/activator/maintenance.go
+++ b/internal/activator/maintenance.go
@@ -367,6 +367,13 @@ func (a *Service) cleanupFailedWake(ctx context.Context, e *actEntry, rt registr
if e != nil {
a.stopFiles(e)
}
+ // A release of this wake whose unit is not proven stopped keeps the
+ // lease in its record (doWake hands it over first; this is the
+ // backstop) [pf R3.1]. Nothing of web starts after such a release, so
+ // there is nothing more here to prove or give back.
+ if a.oweWakeLeaseToRelease(e, w, lease) {
+ return
+ }
stopCtx, cancel := context.WithTimeout(context.Background(), actStopTimeout)
defer cancel()
// A wake that left a process is proven stopped before its lease goes,
diff --git a/internal/activator/rootfs_admission_test.go b/internal/activator/rootfs_admission_test.go
index a18d1be34..0d028eb8b 100644
--- a/internal/activator/rootfs_admission_test.go
+++ b/internal/activator/rootfs_admission_test.go
@@ -181,14 +181,16 @@ func TestRootfsAdmissionWaitsForTheStartupProof(t *testing.T) {
if release.BoxPlatform() != "linux-arm64" {
// Root stages rootfs images for linux-arm64 alone (a rootfs
// manifest carries only release.RootfsArtifactKey), so on this
- // box root refuses the image itself (ErrStagedImage): after the
- // admission, the lease and the restore, at root's /start of the
- // generation. On a linux-arm64 box the wake serves (below).
- if !errors.Is(err, instancectl.ErrStagedImage) {
- t.Fatalf("after a clean sweep on %s: %v, want root's staged-image refusal", release.BoxPlatform(), err)
+ // box the staged manifest names no image for it: after the
+ // admission, the lease and the restore, the wake's release
+ // decision reads the declared processes (Group R, R3) and refuses
+ // there, before root's /start. On a linux-arm64 box the wake
+ // serves (below).
+ if !errors.Is(err, errRootfsRefused) || !strings.Contains(err.Error(), "a rootfs release carries one artifact") {
+ t.Fatalf("after a clean sweep on %s: %v, want the staged manifest's refusal", release.BoxPlatform(), err)
}
- if acq, res := hb2.counts(); acq != 1 || res != 1 || h.requested("POST /start") != 1 {
- t.Fatalf("acquires %d, restores %d, /start asked %d times: the admission did not open", acq, res, h.requested("POST /start"))
+ if acq, res := hb2.counts(); acq != 1 || res != 1 || h.requested("POST /start") != 0 {
+ t.Fatalf("acquires %d, restores %d, /start asked %d times: the admission did not open, or the start ran", acq, res, h.requested("POST /start"))
}
return
}
diff --git a/internal/activator/rootfs_gate_test.go b/internal/activator/rootfs_gate_test.go
index b8f11f950..d11363473 100644
--- a/internal/activator/rootfs_gate_test.go
+++ b/internal/activator/rootfs_gate_test.go
@@ -21,6 +21,7 @@ import (
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/rolloutwords"
)
@@ -47,6 +48,27 @@ func (b *fakeBackend) rootfsStartable(ctx context.Context, rt registry.Route) er
return f(ctx, rt)
}
+// Processes is fakeBackend's ProcessReader, as every production backend
+// has one: processes' answer when set, else a build declaring web alone
+// (no release is due, so a rootfs wake starts web as it did before Group
+// R). Counted.
+func (b *fakeBackend) Processes(rt registry.Route, id release.StagedIdentity) (map[string]release.Process, error) {
+ b.mu.Lock()
+ b.processReads++
+ f := b.processes
+ b.mu.Unlock()
+ if f != nil {
+ return f(rt, id)
+ }
+ return map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}}, nil
+}
+
+func (b *fakeBackend) processReadCount() int {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.processReads
+}
+
func (b *fakeBackend) startableAsked(host string) int {
b.mu.Lock()
defer b.mu.Unlock()
@@ -537,10 +559,9 @@ func TestRootfsPlaceholderFailureStartsNothing(t *testing.T) {
// requests to A ask them once and coalesce on one wake; and Shutdown is
// not held up by A's gate, which ends with the service's lifetime.
func TestRootfsGatesRunOffTheLock(t *testing.T) {
+ // Every host starts from a staged identity (gateService's): a rootfs
+ // row with none refuses (Group R [pf R3.6]).
a, b, _, _ := gateService(t)
- b.mu.Lock()
- b.ident.on = false
- b.mu.Unlock()
hostA, hostB, hostC := "a.example.com", "blog.example.com", "c.example.com"
entered, release := make(chan struct{}), make(chan struct{})
var once sync.Once
diff --git a/internal/activator/rootfs_processes_test.go b/internal/activator/rootfs_processes_test.go
index 83a5ad3f6..ffa948e2d 100644
--- a/internal/activator/rootfs_processes_test.go
+++ b/internal/activator/rootfs_processes_test.go
@@ -276,6 +276,8 @@ func workersLine(host, build, names string) string {
return "activator: " + host + ": build " + build + " declares workers (" + names + "); this box does not run workers yet"
}
+// releaseLine is D8's release line, which Group R removed (R3): a test
+// asserts it is never logged.
func releaseLine(host, build string) string {
return "activator: " + host + ": build " + build + " declares a release process; this box does not run it yet, so the app's web command must prepare its own database"
}
@@ -296,7 +298,11 @@ func onlyWebAsked(t *testing.T, ctl *stagedRootfsCtl) {
}
}
-// D8. Not parallel: it captures the standard logger.
+// D8, as Group R leaves it: the workers a build declares are logged and
+// not run; its release process is run by every wake and swap site (R1 to
+// R3), so the hook no longer logs it [pf R1.17]. Here the release is the
+// row's good build's, not due, so nothing of it runs either. Not
+// parallel: it captures the standard logger.
func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
t.Run("wake", func(t *testing.T) {
logs := captureLogLines(t)
@@ -305,9 +311,9 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
release.ProcessWeb: {Command: []string{"/app/serve"}}, "jobs": {Command: []string{"/app/jobs"}},
"mailer": {Command: []string{"/app/mail"}}, release.ProcessRelease: {Command: []string{"/app/migrate"}},
}, nil)
- good := stagedRootfsIdentity(t, lb.eb, "v3")
ctl.setServe(serveVersions(t, lb.eb, lb.rt, 0, "v2"))
- a, rt, evs := rootfsPlanned(t, lb, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}, registry.RuntimeRootfsV1)
+ a, rt, evs := rootfsPlanned(t, lb, WakePlan{Boot: next, Mode: ModeOverlap}, registry.RuntimeRootfsV1)
+ rt.GoodVersion, rt.GoodDigest = next.Version, next.Digest
done, err := a.beginRequest(context.Background(), rt)
if err != nil {
t.Fatalf("the wake: %v; calls:\n%s", err, ctl.joined())
@@ -319,9 +325,7 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
if n := logs.count(workersLine(rt.Host, "v2", "jobs, mailer")); n != 1 {
t.Errorf("the workers line was logged %d times, want once; logs:\n%s", n, logs)
}
- if n := logs.count(releaseLine(rt.Host, "v2")); n != 1 {
- t.Errorf("the release line was logged %d times, want once; logs:\n%s", n, logs)
- }
+ noReleaseLine(t, logs, rt.Host)
if !entryAwake(a, rt.Host) {
t.Fatal("the instance is not awake after its wake")
}
@@ -330,8 +334,12 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
logs := captureLogLines(t)
f, lb, ctl, at := rootfsSwapFixture(t, ModeOverlap)
// v2's manifest, the image the attempt names, declares jobs and
- // release for this box.
+ // release for this box; v2 is the row's good build, so its release
+ // is not due.
writeDeclaredManifest(t, lb.eb, "v2", at.Digest, declaredProcs(), nil)
+ f.a.mu.Lock()
+ f.a.entries[f.host].route.GoodVersion, f.a.entries[f.host].route.GoodDigest = "v2", at.Digest
+ f.a.mu.Unlock()
ctl.setServe(serveVersions(t, lb.eb, lb.rt, 0, "v2"))
res := f.a.Swap(context.Background(), at, f.newest)
if res.Outcome != SwapDone {
@@ -345,9 +353,7 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
if n := logs.count(workersLine(f.host, "v2", "jobs")); n != 1 {
t.Errorf("the workers line was logged %d times, want once; logs:\n%s", n, logs)
}
- if n := logs.count(releaseLine(f.host, "v2")); n != 1 {
- t.Errorf("the release line was logged %d times, want once; logs:\n%s", n, logs)
- }
+ noReleaseLine(t, logs, f.host)
})
t.Run("web only", func(t *testing.T) {
logs := captureLogLines(t)
@@ -363,27 +369,27 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
})
t.Run("refused read", func(t *testing.T) {
logs := captureLogLines(t)
- lb, ctl := newRootfsLaunch(t, &fakeSwapBackend{fakeBackend: &fakeBackend{}})
- // v2's manifest names another image's digest: root's fake starts
- // web regardless, so the wake serves while the read is refused.
+ fb := &fakeSwapBackend{fakeBackend: &fakeBackend{}}
+ lb, ctl := newRootfsLaunch(t, fb)
+ // v2's manifest names another image's digest. Group R reads the
+ // declared processes of the build about to boot before the lease
+ // [pf R3.7]: the wake is refused there, and nothing is taken or
+ // started (it no longer serves with the read refused).
next := stageDeclared(t, lb.eb, "v2", declaredProcs(), func(m *release.Manifest) {
m.Artifacts[release.RootfsArtifactKey] = release.Artifact{File: release.RootfsArtifactFile, SHA256: strings.Repeat("ef", 32), Size: 1}
})
good := stagedRootfsIdentity(t, lb.eb, "v3")
ctl.setServe(serveVersions(t, lb.eb, lb.rt, 0, "v2"))
- a, rt, evs := rootfsPlanned(t, lb, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}, registry.RuntimeRootfsV1)
- done, err := a.beginRequest(context.Background(), rt)
- if err != nil {
- t.Fatalf("the wake: %v; calls:\n%s", err, ctl.joined())
+ a, rt, _ := rootfsPlanned(t, lb, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}, registry.RuntimeRootfsV1)
+ _, err := a.beginRequest(context.Background(), rt)
+ if !errors.Is(err, errRootfsNotAdmitted) || !strings.Contains(err.Error(), "the staged manifest names digest") {
+ t.Fatalf("the wake: %v, want the manifest's refusal before the lease; calls:\n%s", err, ctl.joined())
}
- done()
- evs.wait(t, GenHealthy)
- onlyWebAsked(t, ctl)
- if !entryAwake(a, rt.Host) {
- t.Fatal("the instance is not awake after its wake")
+ if n := fb.acquireCount(); n != 0 {
+ t.Errorf("%d lease acquires for a refused read, want none", n)
}
- if n := logs.matching("activator: "+rt.Host+": build v2", "declared processes"); n != 1 {
- t.Errorf("the refused read was logged %d times, want once; logs:\n%s", n, logs)
+ if starts := ctl.started(); len(starts) != 0 {
+ t.Errorf("root was asked for %+v", starts)
}
if n := logs.matching(rt.Host, "declares"); n != 0 {
t.Errorf("a refused read still logged %d declared-process lines; logs:\n%s", n, logs)
@@ -391,6 +397,15 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
})
}
+// noReleaseLine fails t if the hook logged anything of a release process
+// for host: Group R runs it, so D8's line is gone [pf R1.17].
+func noReleaseLine(t *testing.T, logs *logLines, host string) {
+ t.Helper()
+ if n := logs.count(releaseLine(host, "v2")) + logs.matching(host, "declares a release process"); n != 0 {
+ t.Errorf("the release line was logged %d times, want none; logs:\n%s", n, logs)
+ }
+}
+
// [Astra R1 4] Through the production composition: the Service's backend
// is a SplitBackend, whose ProcessReader forwards an exec-backed row to
// the ExecBackend and refuses a unit-backed one.
@@ -424,9 +439,7 @@ func TestProcessesThroughTheProductionBackend(t *testing.T) {
if n := logs.count(workersLine(rt.Host, "v2", "jobs")); n != 1 {
t.Errorf("the workers line through the production backend: %d, want 1; logs:\n%s", n, logs)
}
- if n := logs.count(releaseLine(rt.Host, "v2")); n != 1 {
- t.Errorf("the release line through the production backend: %d, want 1; logs:\n%s", n, logs)
- }
+ noReleaseLine(t, logs, rt.Host)
a.rootfsProcessesHook(context.Background(), nil, unit, g)
if n := logs.matching("activator: "+rt.Host+": build v2", "declared processes", "rootfs"); n != 1 {
t.Errorf("a unit-backed row's refused read: %d lines, want 1; logs:\n%s", n, logs)
diff --git a/internal/activator/rootfs_resident_lease_test.go b/internal/activator/rootfs_resident_lease_test.go
index 2f4c82dac..7fc599c45 100644
--- a/internal/activator/rootfs_resident_lease_test.go
+++ b/internal/activator/rootfs_resident_lease_test.go
@@ -105,6 +105,7 @@ func residentKillService(t *testing.T, routes ...registry.Route) (*Service, *kil
a.now = clk.now
a.gens = true
armRootfsForTest(a)
+ startsFromStagedIdentity(kb.fakeBackend)
a.residentJitter = func() float64 { return 0 }
l := &fakeResidents{routes: routes}
a.residentLister = l
diff --git a/internal/activator/rootfs_resident_test.go b/internal/activator/rootfs_resident_test.go
index 472f80905..cb4ab2d5e 100644
--- a/internal/activator/rootfs_resident_test.go
+++ b/internal/activator/rootfs_resident_test.go
@@ -79,6 +79,7 @@ func residentService(t *testing.T, idle time.Duration, routes ...registry.Route)
a, b, clk, _ = testActivator(t, idle)
a.gens = true
armRootfsForTest(a)
+ startsFromStagedIdentity(b)
a.residentJitter = func() float64 { return 0 }
l = &fakeResidents{routes: routes}
a.residentLister = l
@@ -90,6 +91,16 @@ func residentService(t *testing.T, idle time.Duration, routes ...registry.Route)
return a, b, clk, l, sink, shut
}
+// startsFromStagedIdentity has b start a rootfs row from a staged
+// identity (live/<host> resolving to v1's), as every production rootfs
+// image sits at its version's path: with none, a rootfs wake refuses
+// (Group R [pf R3.6]).
+func startsFromStagedIdentity(b *fakeBackend) {
+ b.mu.Lock()
+ b.ident.on, b.ident.materializeTo = true, "v1"
+ b.mu.Unlock()
+}
+
// shrinkResidentPoll sets residentPoll for one test. Start reads it once.
func shrinkResidentPoll(t *testing.T, d time.Duration) {
t.Helper()
@@ -179,6 +190,7 @@ func TestResidentStartsAtBootWithNoRequest(t *testing.T) {
}
a.gens = true
armRootfsForTest(a)
+ startsFromStagedIdentity(b)
rt := residentRoute("shop.example.com")
if err := reg.Upsert(rt); err != nil {
t.Fatal(err)
@@ -405,6 +417,7 @@ func TestResidentRestartsAfterAdoptionAtOnce(t *testing.T) {
cur.Store("v1")
b.mu.Lock()
b.execVerFn = func() string { return cur.Load().(string) }
+ b.ident.onLiveIdentity = func(f *identityFake) { f.live = cur.Load().(string) }
b.mu.Unlock()
a.liveVer = func(string) (string, error) { return cur.Load().(string), nil }
startResident(t, a, host)
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go
index f3127a768..e8d21bd9d 100644
--- a/internal/activator/rootfs_service.go
+++ b/internal/activator/rootfs_service.go
@@ -20,6 +20,7 @@ import (
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/rolloutwords"
+ "github.com/carlosframework/platform/internal/runs"
)
// errRuntimeUnknown refuses a row whose runtime this agent does not know
@@ -53,6 +54,21 @@ func firstWakeBudgetFor(rt registry.Route) time.Duration {
return firstWakeBudget
}
+// wakeBaseCeiling is a wake's ceiling for a binary row: wake() ends its
+// context after it, whatever is left to do.
+const wakeBaseCeiling = 5 * time.Minute
+
+// wakeCeilingFor is how long one wake of rt may take in all (wake()'s
+// context) [pf R3.5]: wakeBaseCeiling, and for a rootfs row the longest a
+// release may run (runs.MaxTimeout, which caps releaseTimeout) on top, so
+// a migration inside a wake ends at its own timeout, never at the wake's.
+func wakeCeilingFor(rt registry.Route) time.Duration {
+ if rt.Rootfs() {
+ return wakeBaseCeiling + runs.MaxTimeout
+ }
+ return wakeBaseCeiling
+}
+
// The admission refusals (Plan 3 Task 7, INV-3), each asked before the
// lease. errRootfsUnarmed: generations are off, or the overlap scheduler
// has not armed on this boot (deviation D2). errRootfsUnswept: the startup
diff --git a/internal/activator/rootfs_wake_release_test.go b/internal/activator/rootfs_wake_release_test.go
new file mode 100644
index 000000000..318287fb4
--- /dev/null
+++ b/internal/activator/rootfs_wake_release_test.go
@@ -0,0 +1,1122 @@
+package activator
+
+// Rootfs apps Plan 3, Group R, R3: the release inside a wake. A rootfs
+// build that declares `release` runs it under the wake's own lease and the
+// site's ownership gate, after the restore and before web, at the three
+// wake sites (a hold swap's pinned wake, a planned wake, an ordinary wake
+// with a staged identity). An unproven release keeps the failed wake's
+// lease in its record, which outlives the entry (INV-R1); only a proven
+// failure is the build's (INV-R3). Not parallel: some tests shrink the
+// release's package vars.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/runs"
+)
+
+// wakeRelBackend is planGenBackend (a planned wake's staged spawn and the
+// generation kill over fakeBackend) with the release seam and a wake's
+// watchable lease. Processes answers procs by build version (a build not
+// there declares web alone, procErr refuses it) and records
+// processes:<build>; StartRelease asks the exec gate, records
+// release:start:<build> and hands out a fresh releaseUnit on units, whose
+// settle fails while stuck and records release:proven:<build> once it
+// proves the unit gone. Every Acquire hands out an ownedLease (until from
+// leaseUntil) whose Release records release-lease. A web start records
+// start:<build>.
+type wakeRelBackend struct {
+ *planGenBackend
+ rmu sync.Mutex
+ procs map[string]map[string]release.Process
+ procErr map[string]error
+ onRead func(id release.StagedIdentity)
+ units chan *releaseUnit
+ relStarts []string
+ stuck bool
+ cmdStarts int
+ leases []*orderedLease
+ leaseUntil func() time.Time
+}
+
+// orderedLease is a wake's ownedLease whose Release is in the order log.
+type orderedLease struct {
+ *ownedLease
+}
+
+func (l *orderedLease) Release(ctx context.Context) error {
+ if l.fakeLease.b != nil {
+ l.fakeLease.b.record("release-lease")
+ }
+ return l.fakeLease.Release(ctx)
+}
+
+func newWakeRelBackend() *wakeRelBackend {
+ b := &wakeRelBackend{planGenBackend: newPlanGenBackend(), units: make(chan *releaseUnit, 16),
+ procs: map[string]map[string]release.Process{}, procErr: map[string]error{},
+ leaseUntil: func() time.Time { return time.Now().Add(time.Hour) }}
+ b.fakeBackend.layoutFn = func(registry.Route) (Layout, string) { return LayoutNested, "" }
+ b.fakeBackend.leaseWrap = func(fl *fakeLease) Lease {
+ b.rmu.Lock()
+ until := b.leaseUntil
+ b.rmu.Unlock()
+ o := newOwnedLease(until(), false)
+ o.fakeLease = fl
+ l := &orderedLease{ownedLease: o}
+ b.rmu.Lock()
+ b.leases = append(b.leases, l)
+ b.rmu.Unlock()
+ return l
+ }
+ return b
+}
+
+func (b *wakeRelBackend) Processes(_ registry.Route, id release.StagedIdentity) (map[string]release.Process, error) {
+ b.record("processes:" + id.Version)
+ b.rmu.Lock()
+ hook := b.onRead
+ p, ok := b.procs[id.Version]
+ err := b.procErr[id.Version]
+ b.rmu.Unlock()
+ if hook != nil {
+ hook(id)
+ }
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ return map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}}, nil
+ }
+ return p, nil
+}
+
+func (b *wakeRelBackend) ReleaseEnv(_ context.Context, rt registry.Route) (map[string]string, error) {
+ return map[string]string{"CARLOS_SOCKET": rt.Socket}, nil
+}
+
+func (b *wakeRelBackend) 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)
+ ver := id.Version
+ u := newReleaseUnit()
+ u.settle = func(int) error {
+ b.rmu.Lock()
+ stuck := b.stuck
+ b.rmu.Unlock()
+ if stuck {
+ return errors.New("processes remained in carlos-instance-rootfs-cmd@shop.example.com's cgroup")
+ }
+ b.record("release:proven:" + ver)
+ return nil
+ }
+ b.rmu.Lock()
+ b.relStarts = append(b.relStarts, ver)
+ b.rmu.Unlock()
+ b.units <- u
+ return u, nil
+}
+
+// StartStaged is the planned spawn, recorded once it started.
+func (b *wakeRelBackend) StartStaged(ctx context.Context, rt registry.Route, g Gen) (Gen, Proc, error) {
+ got, p, err := b.planGenBackend.StartStaged(ctx, rt, g)
+ if p != nil {
+ b.record("start:" + g.Build)
+ }
+ return got, p, err
+}
+
+// StartCmd counts a member's run; the fake runs none.
+func (b *wakeRelBackend) StartCmd(context.Context, registry.Route, CmdSpec) (CmdUnit, error) {
+ b.rmu.Lock()
+ b.cmdStarts++
+ b.rmu.Unlock()
+ return nil, errors.New("the fake runs no command")
+}
+
+func (b *wakeRelBackend) setStuck(stuck bool) {
+ b.rmu.Lock()
+ b.stuck = stuck
+ b.rmu.Unlock()
+}
+
+func (b *wakeRelBackend) releaseStarts() []string {
+ b.rmu.Lock()
+ defer b.rmu.Unlock()
+ return slices.Clone(b.relStarts)
+}
+
+func (b *wakeRelBackend) lastLease() *orderedLease {
+ b.rmu.Lock()
+ defer b.rmu.Unlock()
+ if len(b.leases) == 0 {
+ return nil
+ }
+ return b.leases[len(b.leases)-1]
+}
+
+func (b *wakeRelBackend) leaseReleases() int {
+ b.fakeBackend.mu.Lock()
+ defer b.fakeBackend.mu.Unlock()
+ return b.fakeBackend.releases
+}
+
+var (
+ _ ReleaseBackend = (*wakeRelBackend)(nil)
+ _ ProcessReader = (*wakeRelBackend)(nil)
+ _ SwapBackend = (*wakeRelBackend)(nil)
+ _ CmdBackend = (*wakeRelBackend)(nil)
+)
+
+// routeRows is a RouteLookup over rows the test sets: the registry's
+// committed row, which a wake re-reads at step 0.
+type routeRows struct {
+ mu sync.Mutex
+ rows map[string]registry.Route
+}
+
+func (r *routeRows) Get(host string) (*registry.Route, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ rt, ok := r.rows[host]
+ if !ok {
+ return nil, nil
+ }
+ return &rt, nil
+}
+
+func (r *routeRows) set(rt registry.Route) {
+ r.mu.Lock()
+ r.rows[rt.Host] = rt
+ r.mu.Unlock()
+}
+
+func (r *routeRows) get(host string) registry.Route {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.rows[host]
+}
+
+// wakeRelRig is a Service over wakeRelBackend whose every wake is plan:
+// shop.example.com, a hibernating rootfs row of acme/shop good on v1,
+// planned onto v2 (staged, declaring a release) as an overlap first wake
+// with v1 as its fallback. The registry's row is routes'; the generations
+// file is on disk; the clock is fake (the reaper's pace).
+type wakeRelRig struct {
+ b *wakeRelBackend
+ a *Service
+ clk *fakeClock
+ evs *genLog
+ sink *rootfsSink
+ routes *routeRows
+ rt registry.Route
+ good, next release.StagedIdentity
+ gensFile string
+ pmu sync.Mutex
+ plan WakePlan
+ planner bool
+}
+
+func newWakeRelRig(t *testing.T) *wakeRelRig {
+ t.Helper()
+ dir := t.TempDir()
+ good, next := stagedID(t, dir, "v1"), stagedID(t, dir, "v2")
+ b := newWakeRelBackend()
+ b.procs["v2"] = releaseDeclared()
+ rt := testRoute("shop.example.com")
+ rdir := t.TempDir()
+ rt.Socket, rt.DBPath = filepath.Join(rdir, "app.sock"), filepath.Join(rdir, "app.db")
+ rt.Runtime, rt.App, rt.Account = registry.RuntimeRootfsV1, "shop", "acme"
+ rt.GoodVersion, rt.GoodDigest = good.Version, good.Digest
+ r := &wakeRelRig{b: b, clk: &fakeClock{t: time.Unix(1_700_000_000, 0)}, evs: &genLog{}, sink: &rootfsSink{},
+ routes: &routeRows{rows: map[string]registry.Route{}}, rt: rt, good: good, next: next,
+ gensFile: filepath.Join(t.TempDir(), "generations.json"), planner: true,
+ plan: WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good, Token: 1}}
+ r.routes.set(rt)
+ r.a = r.service(t)
+ return r
+}
+
+// service is a new Service over the rig's backend, routes and generations
+// file (an agent restart is a second one). Its cleanup unsticks any
+// release unit and has the reaper's pace pass first, so Shutdown's drain
+// proves what is left.
+func (r *wakeRelRig) service(t *testing.T) *Service {
+ t.Helper()
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, r.b, reg)
+ a.now = r.clk.now
+ a.gens = true
+ armRootfsForTest(a)
+ a.OnGen = r.evs.add
+ if r.planner {
+ a.Planner = func(context.Context, registry.Route) WakePlan {
+ r.pmu.Lock()
+ defer r.pmu.Unlock()
+ return r.plan
+ }
+ }
+ a.genHealth = func(context.Context, Gen) error { return nil }
+ a.Logs = r.sink
+ a.GenerationsFile = r.gensFile
+ a.Routes = r.routes
+ t.Cleanup(func() {
+ r.b.setStuck(false)
+ r.clk.advance(actStopTimeout + time.Second)
+ a.Shutdown(context.Background())
+ })
+ return a
+}
+
+func (r *wakeRelRig) setPlan(p WakePlan) {
+ r.pmu.Lock()
+ r.plan = p
+ r.pmu.Unlock()
+}
+
+// wake begins a request for the host in the background; its error arrives
+// on the channel (nil once the wake served it).
+func (r *wakeRelRig) wake(a *Service) <-chan error {
+ ch := make(chan error, 1)
+ go func() {
+ done, err := a.beginRequest(context.Background(), r.rt)
+ if err == nil {
+ done()
+ }
+ ch <- err
+ }()
+ return ch
+}
+
+func waitErr(t *testing.T, ch <-chan error) error {
+ t.Helper()
+ select {
+ case err := <-ch:
+ return err
+ case <-time.After(30 * time.Second):
+ t.Fatal("the wake did not return")
+ }
+ return nil
+}
+
+func (r *wakeRelRig) nextUnit(t *testing.T) *releaseUnit {
+ t.Helper()
+ select {
+ case u := <-r.b.units:
+ return u
+ case <-time.After(10 * time.Second):
+ t.Fatal("no release started")
+ }
+ return nil
+}
+
+func (r *wakeRelRig) noUnit(t *testing.T, when string) {
+ t.Helper()
+ if s := r.b.releaseStarts(); len(s) != 0 {
+ t.Fatalf("%s: releases started %v", when, s)
+ }
+}
+
+func (r *wakeRelRig) record() *releaseOp {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ return r.a.releaseOps[r.rt.Host]
+}
+
+// index is ev's first position in the backend's order log, -1 if absent.
+func (r *wakeRelRig) index(ev string) int {
+ return slices.Index(r.b.events(), ev)
+}
+
+// webStarts is how many web generations started (planned or not).
+func (r *wakeRelRig) webStarts() int {
+ return len(r.b.started()) + r.b.fakeBackend.startCount()
+}
+
+// noBuildFailure fails t if any GenEvent recorded a failure of a build.
+func noBuildFailure(t *testing.T, evs *genLog) {
+ t.Helper()
+ for _, k := range evs.kinds() {
+ if k == GenFailed || k == GenFellBack {
+ t.Fatalf("a %s event was emitted: %v", k, evs.kinds())
+ }
+ }
+}
+
+// raiseFence fences host as a maintenance operation would.
+func raiseFence(a *Service, host string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.fences == nil {
+ a.fences = map[string]uint64{}
+ }
+ a.fences[host]++
+}
+
+// ---- the planned wake --------------------------------------------------
+
+func TestAsleepRowRunsReleaseBeforeServing(t *testing.T) {
+ r := newWakeRelRig(t)
+ var proxied []string
+ var pmu sync.Mutex
+ served := make(chan int, 1)
+ go func() {
+ w := httptest.NewRecorder()
+ r.a.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://"+r.rt.Host+"/", nil), r.rt,
+ http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ pmu.Lock()
+ proxied = slices.Clone(r.b.events())
+ pmu.Unlock()
+ w.WriteHeader(http.StatusOK)
+ }))
+ served <- w.Code
+ }()
+ u := r.nextUnit(t)
+ time.Sleep(100 * time.Millisecond)
+ if n := r.webStarts(); n != 0 {
+ t.Fatalf("%d web starts while the release runs", n)
+ }
+ select {
+ case code := <-served:
+ t.Fatalf("the request was answered %d while the release ran", code)
+ default:
+ }
+ u.done("exited", "0", "success")
+ select {
+ case code := <-served:
+ if code != http.StatusOK {
+ t.Fatalf("the waiting request answered %d", code)
+ }
+ case <-time.After(30 * time.Second):
+ t.Fatal("the waiting request was never served")
+ }
+ rs, rp, st := r.index("release:start:v2"), r.index("release:proven:v2"), r.index("start:v2")
+ if rs < 0 || rp < rs || st < rp {
+ t.Fatalf("order %v: want release:start:v2, release:proven:v2, then start:v2", r.b.events())
+ }
+ pmu.Lock()
+ defer pmu.Unlock()
+ if !slices.Contains(proxied, "start:v2") {
+ t.Fatalf("the request was proxied before web started: %v", proxied)
+ }
+ if g := r.b.started(); len(g) != 1 || g[0].Build != "v2" {
+ t.Fatalf("started %+v, want v2 alone", g)
+ }
+ r.evs.wait(t, GenHealthy)
+}
+
+// The third site: an ordinary wake of a rootfs row with a staged identity
+// (no plan, no pin) runs that identity's release under its lease, then
+// web on the same identity.
+func TestStagedIdentityWakeRunsReleaseFirst(t *testing.T) {
+ r := newWakeRelRig(t)
+ r.planner = false
+ a := r.service(t)
+ r.b.fakeBackend.mu.Lock()
+ r.b.fakeBackend.ident.on, r.b.fakeBackend.ident.live = true, "v2"
+ r.b.fakeBackend.mu.Unlock()
+ ch := r.wake(a)
+ u := r.nextUnit(t)
+ time.Sleep(50 * time.Millisecond)
+ if n := r.webStarts(); n != 0 {
+ t.Fatalf("%d web starts while the release runs", n)
+ }
+ u.done("exited", "0", "success")
+ if err := waitErr(t, ch); err != nil {
+ t.Fatalf("the wake: %v", err)
+ }
+ if rp, st := r.index("release:proven:v2"), r.index("start v2"); rp < 0 || st < rp {
+ t.Fatalf("order %v: want v2's release proven, then web on v2", r.b.events())
+ }
+}
+
+// [pf R3.4] A first wake's health window for B starts once B's release
+// has passed: a release longer than the whole window still leaves B its
+// verdict, rather than booting the good build untried.
+func TestFirstWakeWindowStartsAfterTheRelease(t *testing.T) {
+ shrinkHealthBounds(t, spawnHealthTimeout, 400*time.Millisecond, 200*time.Millisecond)
+ shrinkFirstWake(t, firstWakeBudget, 100*time.Millisecond, 10*time.Millisecond)
+ r := newWakeRelRig(t)
+ ch := r.wake(r.a)
+ u := r.nextUnit(t)
+ time.Sleep(700 * time.Millisecond) // past B's whole window, counted from the wake's start
+ u.done("exited", "0", "success")
+ if err := waitErr(t, ch); err != nil {
+ t.Fatalf("the wake: %v", err)
+ }
+ if g := r.b.started(); len(g) != 1 || g[0].Build != "v2" {
+ t.Fatalf("started %+v, want B (v2) judged, not the good build booted untried", g)
+ }
+ if ev := r.evs.wait(t, GenHealthy); ev.Gen.Build != "v2" || !ev.FirstWake {
+ t.Fatalf("the wake's verdict = %+v, want B's first wake healthy", ev)
+ }
+}
+
+// Release(B) fails, its unit proven gone: B is the failed build, and the
+// good build A boots in its place, with nothing of B's web ever started.
+func TestFirstWakeReleaseFailureFallsBack(t *testing.T) {
+ r := newWakeRelRig(t)
+ ch := r.wake(r.a)
+ r.nextUnit(t).done("exited", "1", "exit-code")
+ if err := waitErr(t, ch); err != nil {
+ t.Fatalf("the waiting request was not served by the good build: %v", err)
+ }
+ if g := r.b.started(); len(g) != 1 || g[0].Build != "v1" {
+ t.Fatalf("started %+v, want the good v1 alone (no web of v2)", g)
+ }
+ if k := r.b.kills(); len(k) != 0 {
+ t.Fatalf("killed %v: nothing of v2's web ran", k)
+ }
+ ev := r.evs.wait(t, GenFellBack)
+ want := (&ReleaseError{Build: "v2", Exit: 1}).Error()
+ if ev.Failed.Version != "v2" || ev.Gen.Build != "v1" || !strings.Contains(ev.Reason, want) {
+ t.Fatalf("fallback event = %+v, want v2 failed (%q) and v1 serving", ev, want)
+ }
+ if g, ok := r.a.Current(r.rt.Host); !ok || g.Build != "v1" {
+ t.Fatalf("Current = %+v %v, want the good build serving", g, ok)
+ }
+}
+
+// D3 [pf R3.11]: the build the row already counts as good is not migrated
+// again. The wake reads the row it refreshed (step 0), not the edge's
+// copy: here the scheduler recorded v2 good after the edge cached v1. And
+// a hold restart onto the good build re-runs it with no release. Neither
+// reads the declared processes between its lease and web's start.
+func TestRestartDoesNotRerunRelease(t *testing.T) {
+ t.Run("a planned wake onto the good build", func(t *testing.T) {
+ r := newWakeRelRig(t)
+ fresh := r.rt
+ fresh.GoodVersion, fresh.GoodDigest = r.next.Version, r.next.Digest
+ r.routes.set(fresh)
+ r.setPlan(WakePlan{Boot: r.next, Mode: ModeOverlap, Token: 1})
+ var underLease int
+ r.b.rmu.Lock()
+ r.b.onRead = func(release.StagedIdentity) {
+ if r.b.acquireCount() > 0 && r.webStarts() == 0 {
+ underLease++
+ }
+ }
+ r.b.rmu.Unlock()
+ if err := waitErr(t, r.wake(r.a)); err != nil {
+ t.Fatalf("the wake: %v", err)
+ }
+ r.noUnit(t, "a wake onto the good build")
+ r.b.rmu.Lock()
+ n := underLease
+ r.b.rmu.Unlock()
+ if n != 0 {
+ t.Fatalf("%d process reads under the lease before web", n)
+ }
+ if g := r.b.started(); len(g) != 1 || g[0].Build != "v2" {
+ t.Fatalf("started %+v, want v2", g)
+ }
+ })
+ t.Run("a hold restart", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ armRootfsForTest(f.a)
+ ownedWakeLeases(f.b.fakeBackend)
+ path, digest := stageTestBuild(t, "v1")
+ f.a.mu.Lock()
+ f.a.entries[f.host].route.GoodDigest = digest
+ f.a.mu.Unlock()
+ // The incumbent's own wake took a lease already: the pinned wake's
+ // is the next one.
+ base := f.b.acquireCount()
+ f.rb.rmu.Lock()
+ f.rb.procs["v1"] = releaseDeclared()
+ var underLease int
+ f.rb.onProcesses = func(release.StagedIdentity) {
+ if gens, _, _ := f.b.calls(); f.b.acquireCount() > base && gens == 0 {
+ underLease++
+ }
+ }
+ f.rb.rmu.Unlock()
+ at := Attempt{Host: f.host, Cause: CauseRestart, Build: "v1", StagedPath: path, Digest: digest, Mode: ModeHold, SchedRev: f.rev.Load()}
+ res := waitSwap(t, f.swapAsync(at))
+ if res.Outcome != SwapDone {
+ t.Fatalf("the hold restart = %+v, want done", res)
+ }
+ f.noUnit(t, "a hold restart onto the good build")
+ f.rb.rmu.Lock()
+ n := underLease
+ f.rb.rmu.Unlock()
+ if n != 0 {
+ t.Fatalf("%d process reads under the lease before web", n)
+ }
+ })
+}
+
+// ownedWakeLeases has b hand out a wake's lease with the lease's own
+// signal (an hour ahead) on every Acquire.
+func ownedWakeLeases(b *fakeBackend) {
+ b.mu.Lock()
+ b.leaseWrap = func(fl *fakeLease) Lease {
+ o := newOwnedLease(time.Now().Add(time.Hour), false)
+ o.fakeLease = fl
+ return o
+ }
+ b.mu.Unlock()
+}
+
+// The wake is cancelled (Shutdown) while its release polls: the unit is
+// settled and proven, nothing records v2 good, and after an agent restart
+// the next wake runs v2's release again before web.
+func TestReleaseRerunsAfterInterruptedWake(t *testing.T) {
+ r := newWakeRelRig(t)
+ ch := r.wake(r.a)
+ u := r.nextUnit(t)
+ shut := make(chan struct{})
+ go func() {
+ r.a.Shutdown(context.Background())
+ close(shut)
+ }()
+ if err := waitErr(t, ch); err == nil {
+ t.Fatal("a wake cancelled by Shutdown served")
+ }
+ select {
+ case <-shut:
+ case <-time.After(30 * time.Second):
+ t.Fatal("Shutdown did not return")
+ }
+ if len(u.stopTimes()) == 0 || !u.isProven() {
+ t.Fatal("the interrupted release's unit was not settled")
+ }
+ if op := r.record(); op != nil {
+ t.Fatal("the interrupted release's record outlived its proof")
+ }
+ if row := r.routes.get(r.rt.Host); row.GoodVersion != "v1" {
+ t.Fatalf("the row's good build is %q after an interrupted release, want v1", row.GoodVersion)
+ }
+ if n := r.webStarts(); n != 0 {
+ t.Fatalf("%d web starts after an interrupted release", n)
+ }
+ noBuildFailure(t, r.evs)
+
+ b := r.service(t)
+ ch = r.wake(b)
+ r.nextUnit(t).done("exited", "0", "success")
+ if err := waitErr(t, ch); err != nil {
+ t.Fatalf("the wake after the restart: %v", err)
+ }
+ if s := r.b.releaseStarts(); len(s) != 2 || s[0] != "v2" || s[1] != "v2" {
+ t.Fatalf("release starts %v, want v2's twice", s)
+ }
+ ev := r.b.events()
+ second := slices.Index(ev[r.index("release:start:v2")+1:], "release:start:v2") + r.index("release:start:v2") + 1
+ if st := r.index("start:v2"); st < second {
+ t.Fatalf("order %v: web started before the second release", ev)
+ }
+}
+
+// [pf R3.5] A rootfs wake's ceiling is room for a release inside it; a
+// binary wake keeps 5 minutes.
+func TestRootfsWakeCeiling(t *testing.T) {
+ t.Run("rootfs", func(t *testing.T) {
+ r := newWakeRelRig(t)
+ delete(r.b.procs, "v2") // web alone: the wake is quick
+ var mu sync.Mutex
+ var dl time.Time
+ var ok bool
+ r.b.fakeBackend.mu.Lock()
+ r.b.fakeBackend.acquireCtx = func(ctx context.Context) {
+ mu.Lock()
+ dl, ok = ctx.Deadline()
+ mu.Unlock()
+ }
+ r.b.fakeBackend.mu.Unlock()
+ began := time.Now()
+ if err := waitErr(t, r.wake(r.a)); err != nil {
+ t.Fatalf("the wake: %v", err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if !ok || dl.Before(began.Add(5*time.Minute+runs.MaxTimeout)) {
+ t.Fatalf("the rootfs wake's deadline is %v (set %v) after it began, want at least 5m + %v", dl.Sub(began), ok, runs.MaxTimeout)
+ }
+ })
+ t.Run("binary", func(t *testing.T) {
+ a, b, _, _ := testActivator(t, time.Hour)
+ var mu sync.Mutex
+ var dl time.Time
+ var ok bool
+ b.mu.Lock()
+ b.acquireCtx = func(ctx context.Context) {
+ mu.Lock()
+ dl, ok = ctx.Deadline()
+ mu.Unlock()
+ }
+ b.mu.Unlock()
+ done, err := a.beginRequest(context.Background(), testRoute("blog.example.com"))
+ if err != nil {
+ t.Fatalf("the wake: %v", err)
+ }
+ done()
+ mu.Lock()
+ defer mu.Unlock()
+ if !ok || dl.After(time.Now().Add(5*time.Minute+time.Second)) {
+ t.Fatalf("the binary wake's deadline is %v away (set %v), want at most 5m", time.Until(dl), ok)
+ }
+ })
+}
+
+// coldReleaseCancelled checks a cold wake whose release the lease ended:
+// the unit stopped and proven before until; the wake failed for the lease,
+// with no build failure; no web and no fallback; the lease went back only
+// after the unit's proof; the row's good build unchanged.
+func coldReleaseCancelled(t *testing.T, r *wakeRelRig, u *releaseUnit, until time.Time, err error) {
+ t.Helper()
+ if !errors.Is(err, errSwapLeaseLost) {
+ t.Fatalf("the wake = %v, want errSwapLeaseLost", err)
+ }
+ var rerr *ReleaseError
+ if errors.As(err, &rerr) {
+ t.Fatalf("a lease end read as the build's failure: %v", err)
+ }
+ stops := u.stopTimes()
+ if len(stops) == 0 || !u.isProven() || !stops[len(stops)-1].Before(until) {
+ t.Fatalf("the release's unit: stops %v, proven %v; want proven before %v", stops, u.isProven(), until)
+ }
+ if n := r.webStarts(); n != 0 {
+ t.Fatalf("%d web starts (B or the fallback A) after the lease ended", n)
+ }
+ r.evs.wait(t, GenCancelled)
+ noBuildFailure(t, r.evs)
+ if p, l := r.index("release:proven:v2"), r.index("release-lease"); p < 0 || l < p {
+ t.Fatalf("order %v: the lease went back before the release's proof", r.b.events())
+ }
+ if op := r.record(); op != nil {
+ t.Fatal("a proven release left its record")
+ }
+ if row := r.routes.get(r.rt.Host); row.GoodVersion != "v1" {
+ t.Fatalf("the row's good build is %q, want v1", row.GoodVersion)
+ }
+}
+
+// Review Focus 6. A cold wake's entry is actWaking, so the sweep's lease
+// check never visits it: the release's own supervisor is the only watch.
+// The lease's loss closes while release(B) polls.
+func TestColdWakeReleaseStopsOnLeaseLoss(t *testing.T) {
+ r := newWakeRelRig(t)
+ ch := r.wake(r.a)
+ u := r.nextUnit(t)
+ l := r.b.lastLease()
+ until, _ := l.SafeUntil()
+ l.lose(lease.ErrLost)
+ coldReleaseCancelled(t, r, u, until, waitErr(t, ch))
+}
+
+// The same row, the renewals stalled: until is frozen, Lost never closes,
+// and the supervisor stops the release releaseStopLead before until.
+func TestColdWakeReleaseStallsBeforeTheDeadline(t *testing.T) {
+ shrinkRelease(t, 500*time.Millisecond, 20*time.Millisecond)
+ r := newWakeRelRig(t)
+ until := time.Now().Add(1500 * time.Millisecond)
+ r.b.rmu.Lock()
+ r.b.leaseUntil = func() time.Time { return until }
+ r.b.rmu.Unlock()
+ ch := r.wake(r.a)
+ u := r.nextUnit(t)
+ coldReleaseCancelled(t, r, u, until, waitErr(t, ch))
+ select {
+ case <-r.b.lastLease().Lost():
+ t.Fatal("the lease's loss closed: this case is a stall")
+ default:
+ }
+}
+
+// Each wake site asks its ownership gate at the release's admission: a
+// fence raised after the lease, just before runRelease's gate, starts no
+// release, and the site answers its NoOwnership outcome.
+func TestReleaseRefusedWhenOwnershipEndsBeforeItStarts(t *testing.T) {
+ fenceUnderLease := func(r *wakeRelRig, a *Service) {
+ r.b.rmu.Lock()
+ r.b.onRead = func(release.StagedIdentity) {
+ if r.b.acquireCount() > 0 {
+ raiseFence(a, r.rt.Host)
+ }
+ }
+ r.b.rmu.Unlock()
+ }
+ t.Run("a planned wake", func(t *testing.T) {
+ r := newWakeRelRig(t)
+ fenceUnderLease(r, r.a)
+ err := waitErr(t, r.wake(r.a))
+ if err == nil || verdictOf(err) != gateNoOwnership {
+ t.Fatalf("the wake = %v, want a NoOwnership refusal", err)
+ }
+ r.noUnit(t, "a fenced planned wake")
+ if n := r.webStarts(); n != 0 {
+ t.Fatalf("%d web starts", n)
+ }
+ if ev := r.evs.wait(t, GenCancelled); ev.Executed {
+ t.Fatalf("the planned wake's end = %+v, want nothing executed", ev)
+ }
+ noBuildFailure(t, r.evs)
+ })
+ t.Run("an ordinary wake with a staged identity", func(t *testing.T) {
+ r := newWakeRelRig(t)
+ r.planner = false
+ r.a = r.service(t)
+ r.b.fakeBackend.mu.Lock()
+ r.b.fakeBackend.ident.on, r.b.fakeBackend.ident.live = true, "v2"
+ r.b.fakeBackend.mu.Unlock()
+ fenceUnderLease(r, r.a)
+ err := waitErr(t, r.wake(r.a))
+ if err == nil || verdictOf(err) != gateNoOwnership {
+ t.Fatalf("the wake = %v, want a NoOwnership refusal", err)
+ }
+ r.noUnit(t, "a fenced ordinary wake")
+ if n := r.webStarts(); n != 0 {
+ t.Fatalf("%d web starts", n)
+ }
+ })
+ t.Run("a hold's pinned wake", func(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ armRootfsForTest(f.a)
+ ownedWakeLeases(f.b.fakeBackend)
+ base := f.b.acquireCount() // the incumbent's own wake's lease
+ f.rb.rmu.Lock()
+ f.rb.onProcesses = func(release.StagedIdentity) {
+ if f.b.acquireCount() > base {
+ raiseFence(f.a, f.host)
+ }
+ }
+ f.rb.rmu.Unlock()
+ res := waitSwap(t, f.swapAsync(f.attempt(ModeHold)))
+ if res.Outcome != SwapAbandoned || res.Executed {
+ t.Fatalf("the hold = %+v, want abandoned with nothing executed", res)
+ }
+ f.noUnit(t, "a fenced hold")
+ if gens, _, _ := f.b.calls(); gens != 0 {
+ t.Fatalf("%d web starts", gens)
+ }
+ })
+}
+
+// ---- the hold's pinned wake --------------------------------------------
+
+// ModeHold: the incumbent is stopped, the pinned wake's release fails, its
+// unit proven gone: the hold is down, executed. Executed can only come
+// from the pinned wake's pinExec here (the error says nothing of a start
+// that may have run), so the release marked it.
+func TestHoldReleaseFailureIsDown(t *testing.T) {
+ f := newRelSwapFixture(t, true)
+ armRootfsForTest(f.a)
+ ownedWakeLeases(f.b.fakeBackend)
+ incumbent := f.b.lastProc()
+ ch := f.swapAsync(f.attempt(ModeHold))
+ f.nextUnit(t).done("1", "1", "exit-code")
+ res := waitSwap(t, ch)
+ want := (&ReleaseError{Build: "v2", Exit: 1}).Error()
+ if res.Outcome != SwapDown || !res.Executed || res.Mode != ModeHold || !strings.Contains(res.Reason, want) {
+ t.Fatalf("the hold = %+v; want down, executed, hold, reason carrying %q", res, want)
+ }
+ if !incumbent.isStopped() {
+ t.Fatal("the hold did not stop the incumbent first")
+ }
+ if gens, _, _ := f.b.calls(); gens != 0 {
+ t.Fatalf("%d web starts after the release failed", gens)
+ }
+ if startMayHaveRun(nil, errors.New(res.Reason)) {
+ t.Fatal("the reason alone reads as a start that may have run")
+ }
+}
+
+// For R2's overlap and R3's hold, each release outcome is exactly its
+// SwapResult (Outcome and Executed). Only a failure (a ReleaseError, its
+// unit proven gone) answers SwapFailed (overlap) or SwapDown (hold).
+func TestReleaseSwapResultsAreTheContract(t *testing.T) {
+ failed := &ReleaseError{Build: "v2", Exit: 3}
+ timedOut := &ReleaseError{Build: "v2", TimedOut: true, Took: time.Minute}
+ unknown := errors.New("start release: unexpected EOF")
+ for _, tc := range []struct {
+ name string
+ err error
+ executed bool
+ open bool
+ overlap SwapOutcome
+ hold SwapOutcome
+ exec bool
+ }{
+ {"failed", failed, true, false, SwapFailed, SwapDown, true},
+ {"timed out", timedOut, true, false, SwapFailed, SwapDown, true},
+ {"unproven", fmt.Errorf("%w: processes remained", errReleaseUnproven), true, true, SwapAbandoned, SwapAbandoned, true},
+ {"unproven after a lease trip", fmt.Errorf("%w: %w: %w (x)", errSwapLeaseLost, errReleaseLeaseLost, errReleaseUnproven), true, true, SwapAbandoned, SwapAbandoned, true},
+ {"cancelled, the lease", fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost), true, false, SwapAbandoned, SwapAbandoned, true},
+ {"cancelled, the caller's context", context.Canceled, true, false, SwapAbandoned, SwapAbandoned, true},
+ {"cancelled, a stop of the owner", fmt.Errorf("%w: %v", context.Canceled, errSwapStopped), true, false, SwapAbandoned, SwapAbandoned, true},
+ {"cancelled, a fence", ErrFenced, true, false, SwapAbandoned, SwapAbandoned, true},
+ {"cancelled, the unit vanished", errReleaseVanished, true, false, SwapAbandoned, SwapAbandoned, true},
+ {"cancelled, no exit recorded", errReleaseNoExit, true, false, SwapAbandoned, SwapAbandoned, true},
+ {"refused, a record open", errReleaseOpen, false, true, SwapAbandoned, SwapAbandoned, false},
+ {"refused, no watchable lease", refuseRootfs(errReleaseNoLease), false, false, SwapAbandoned, SwapAbandoned, false},
+ {"refused by root", refuseRootfs(fmt.Errorf("start release: %w", instancectl.ErrStagedImage)), false, false, SwapAbandoned, SwapAbandoned, false},
+ {"refused, the manifest", refuseRootfs(errNoStagedManifest), false, false, SwapAbandoned, SwapAbandoned, false},
+ {"refused, not published", errStagedBuildNotPublished, false, false, SwapAbandoned, SwapAbandoned, false},
+ {"refused, the exec gate", launchRefused{errSwapFenced}, false, false, SwapAbandoned, SwapAbandoned, false},
+ {"refused, the lease at admission", fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost), false, false, SwapAbandoned, SwapAbandoned, false},
+ {"a start error that came with a unit, proven", unknown, true, false, SwapAbandoned, SwapAbandoned, true},
+ {"a start error that came with a unit, unproven", unknown, true, true, SwapAbandoned, SwapAbandoned, true},
+ } {
+ ov := releaseSwapResult(tc.err, tc.executed, tc.open)
+ if ov.Outcome != tc.overlap || ov.Executed != tc.exec {
+ t.Errorf("%s, overlap: %+v; want %s, executed %v", tc.name, ov, tc.overlap, tc.exec)
+ }
+ ho := holdOf(tc.err, tc.executed, tc.open)
+ if ho.Outcome != tc.hold || ho.Executed != tc.exec {
+ t.Errorf("%s, hold: %+v; want %s, executed %v", tc.name, ho, tc.hold, tc.exec)
+ }
+ isFailure := classifyRelease(tc.err, tc.open) == releaseFailed
+ for col, out := range map[string]SwapOutcome{"overlap": ov.Outcome, "hold": ho.Outcome} {
+ if (out == SwapFailed || out == SwapDown) != isFailure {
+ t.Errorf("%s, %s: %s, but the release's class is %v", tc.name, col, out, classifyRelease(tc.err, tc.open))
+ }
+ }
+ }
+}
+
+// holdOf is holdResult for a hold's pinned wake whose release returned err
+// (executed: its unit started), as startPinnedChecked hands it back.
+func holdOf(err error, executed, open bool) SwapResult {
+ ready := make(chan struct{})
+ close(ready)
+ next := &actEntry{ready: ready, err: holdReleaseResult(err, open), pinExec: executed}
+ return (&Service{}).holdResult(context.Background(), Attempt{}, nil, holdWoke{next: next}, 0)
+}
+
+// ---- the failed wake's obligation (INV-R1) ------------------------------
+
+// unprovenColdWake runs a planned cold wake whose release(B) exits 1 and
+// whose unit's group stays populated: the wake fails unproven.
+func unprovenColdWake(t *testing.T) (*wakeRelRig, *releaseUnit) {
+ t.Helper()
+ r := newWakeRelRig(t)
+ r.b.setStuck(true)
+ ch := r.wake(r.a)
+ u := r.nextUnit(t)
+ u.done("exited", "1", "exit-code")
+ err := waitErr(t, ch)
+ if !errors.Is(err, errReleaseUnproven) {
+ t.Fatalf("the wake = %v, want errReleaseUnproven", err)
+ }
+ waitFor(t, "the failed wake's entry to go", func() bool { return !r.a.hasEntry(r.rt.Host) })
+ return r, u
+}
+
+func TestReleaseObligationOutlivesTheWake(t *testing.T) {
+ r, _ := unprovenColdWake(t)
+ host := r.rt.Host
+ op := r.record()
+ if op == nil {
+ t.Fatal("the unproven release's record went with the entry")
+ }
+ r.a.mu.Lock()
+ owner, owed := op.owner, op.owed
+ r.a.mu.Unlock()
+ if l := r.b.lastLease(); owner != nil || owed != Lease(l) {
+ t.Fatalf("the record's owner %p, owed %v; want ownerless, owing the wake's lease %p", owner, owed, l)
+ }
+ if n := r.b.leaseReleases(); n != 0 || r.index("release-lease") >= 0 {
+ t.Fatalf("the wake's lease was released (%d) while the release's unit may still write", n)
+ }
+ if !pinned(t, r.a, host, "v2") {
+ t.Fatal("the generations file no longer names v2 while its release is unproven")
+ }
+ if n := r.webStarts(); n != 0 {
+ t.Fatalf("%d web starts (no fallback beside an unproven unit)", n)
+ }
+ acquires := r.b.acquireCount()
+
+ w := httptest.NewRecorder()
+ r.a.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://"+host+"/", nil), r.rt, okHandler())
+ if w.Code == http.StatusOK {
+ t.Fatal("a second request woke the host over the open record")
+ }
+ if _, err := r.a.beginRequest(context.Background(), r.rt); !errors.Is(err, errWakeUnproven) {
+ t.Fatalf("a second wake = %v, want errWakeUnproven", err)
+ }
+ res := r.rt
+ res.Hibernate, res.Status = false, "ready"
+ r.a.residentJitter = func() float64 { return 0 }
+ r.a.residentLister = &fakeResidents{routes: []registry.Route{res}}
+ tickSettled(t, r.a)
+ if r.a.hasEntry(host) {
+ t.Fatal("the resident tick started the host over the open record")
+ }
+ _, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "r1", Args: []string{"true"}})
+ var we *CmdWakeError
+ if !errors.As(err, &we) || !errors.Is(err, errWakeUnproven) {
+ t.Fatalf("RunCmd = %v, want a wake error carrying errWakeUnproven", err)
+ }
+ r.b.rmu.Lock()
+ cmds := r.b.cmdStarts
+ r.b.rmu.Unlock()
+ if cmds != 0 {
+ t.Fatalf("%d runs started over the open record", cmds)
+ }
+ if got := r.b.acquireCount(); got != acquires {
+ t.Fatalf("%d lease acquires over the open record", got-acquires)
+ }
+ // INV-R3: the unproven release is not B's failure.
+ if ev := r.evs.wait(t, GenCancelled); !ev.Executed {
+ t.Fatalf("the wake's end = %+v, want executed (B's release ran)", ev)
+ }
+ noBuildFailure(t, r.evs)
+}
+
+func TestReleaseObligationRetriedUntilProven(t *testing.T) {
+ r, u := unprovenColdWake(t)
+ host := r.rt.Host
+ tries := len(u.stopTimes())
+ r.b.setStuck(false)
+ r.clk.advance(actStopTimeout + time.Second)
+ r.a.mu.Lock()
+ r.a.finishPendingStops()
+ r.a.mu.Unlock()
+ waitFor(t, "the reaper's proof", func() bool { return r.record() == nil })
+ if n := len(u.stopTimes()); n <= tries || !u.isProven() {
+ t.Fatalf("the release unit's settles: %d after %d, proven %v; want one more, proven", n, tries, u.isProven())
+ }
+ if k := r.b.kills(); len(k) != 0 {
+ t.Fatalf("a generation was killed (%v): the proof is the release's cmd unit's alone", k)
+ }
+ r.b.fakeBackend.mu.Lock()
+ legacy := r.b.fakeBackend.legacyStops
+ r.b.fakeBackend.mu.Unlock()
+ if legacy != 0 {
+ t.Fatalf("the binary run unit was asked to stop %d times", legacy)
+ }
+ waitFor(t, "the owed lease to go back", func() bool { return r.b.leaseReleases() == 1 })
+ if p, l := r.index("release:proven:v2"), r.index("release-lease"); p < 0 || l < p {
+ t.Fatalf("order %v: the lease went back before the proof", r.b.events())
+ }
+ if pinned(t, r.a, host, "v2") {
+ t.Fatal("the generations file still names v2 after the proof")
+ }
+ ch := r.wake(r.a)
+ r.nextUnit(t).done("exited", "0", "success")
+ if err := waitErr(t, ch); err != nil {
+ t.Fatalf("the next request's wake: %v", err)
+ }
+ if g := r.b.started(); len(g) != 1 || g[0].Build != "v2" {
+ t.Fatalf("started %+v, want v2 after its release passed", g)
+ }
+}
+
+// INV-R3. A planned first wake: release(B) exits 1 and its settle fails.
+// Unproven is never B's failure: nothing is recorded, nothing falls back
+// beside the unproven unit, and the wake reports that B ran.
+func TestUnprovenWakeReleaseIsNotABuildFailure(t *testing.T) {
+ r, _ := unprovenColdWake(t)
+ ev := r.evs.wait(t, GenCancelled)
+ if !ev.Executed || ev.Gen.Build != "v2" {
+ t.Fatalf("the wake's end = %+v, want B executed (w.bootRan)", ev)
+ }
+ noBuildFailure(t, r.evs)
+ if n := r.webStarts(); n != 0 {
+ t.Fatalf("%d web starts: the good build started beside an unproven release", n)
+ }
+ for _, m := range r.sink.msgs() {
+ if strings.Contains(m, "exited with status 1") {
+ t.Fatalf("an unproven release emitted its failure: %q", m)
+ }
+ }
+}
+
+// ---- refusals ----------------------------------------------------------
+
+// [pf R3.6] A rootfs wake that reaches the start with no plan, no pin and
+// no staged identity refuses: no web starts without the release decision.
+func TestRootfsWakeWithoutIdentityRefuses(t *testing.T) {
+ a, b, _, _ := gateService(t)
+ b.mu.Lock()
+ b.ident.on = false
+ b.mu.Unlock()
+ _, err := a.beginRequest(context.Background(), rootfsGateRoute("shop.example.com"))
+ if !errors.Is(err, errRootfsRefused) || !errors.Is(err, errPartialStagedIdentity) {
+ t.Fatalf("the wake = %v, want the partial identity's rootfs refusal", err)
+ }
+ if verdictOf(err) != gateNoOwnership {
+ t.Fatalf("the refusal reads as %d, want gateNoOwnership", verdictOf(err))
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.starts != 0 || b.acquires != 1 || b.releases != 1 {
+ t.Fatalf("starts %d, acquires %d, releases %d; want 0, 1, 1", b.starts, b.acquires, b.releases)
+ }
+}
+
+// [pf R3.7] A planned rootfs wake whose staged manifest is not the image
+// is refused before the lease, never as a resident's failure.
+func TestBrokenManifestRefusedBeforeTheLease(t *testing.T) {
+ r := newWakeRelRig(t)
+ r.b.rmu.Lock()
+ r.b.procErr["v2"] = refuseRootfs(fmt.Errorf("%s: build v2: the staged manifest names digest %s, the image is %s",
+ r.rt.Host, strings.Repeat("ef", 32), r.next.Digest))
+ r.b.rmu.Unlock()
+ err := waitErr(t, r.wake(r.a))
+ if !errors.Is(err, errRootfsNotAdmitted) || !strings.Contains(err.Error(), "the staged manifest names digest") {
+ t.Fatalf("the wake = %v, want the manifest's refusal, not admitted", err)
+ }
+ if n := r.b.acquireCount(); n != 0 {
+ t.Fatalf("%d lease acquires for a refused manifest", n)
+ }
+ if residentFailure(err) {
+ t.Fatal("the refusal counts as a resident's failure")
+ }
+ res := r.rt
+ res.Hibernate, res.Status = false, "ready"
+ r.a.residentJitter = func() float64 { return 0 }
+ r.a.residentLister = &fakeResidents{routes: []registry.Route{res}}
+ tickSettled(t, r.a)
+ if st, _ := r.a.residentOf(res.Host); st.failures != 0 {
+ t.Fatalf("the resident counted %d failures for a refused manifest", st.failures)
+ }
+ if n := r.b.acquireCount(); n != 0 {
+ t.Fatalf("%d lease acquires for the resident's refused manifest", n)
+ }
+ r.noUnit(t, "a refused manifest")
+}
+
+// [pf R3.10] The claim path runs no release: with HostWrites on, Plan 2's
+// gates refuse every rootfs row before the lease (the real gate, here
+// behind the fake's early ask), so no release and no web start.
+func TestNoReleaseOnTheClaimPath(t *testing.T) {
+ eb, _ := newRootfsBackend(t)
+ eb.Cfg.HostWrites.Enabled = true
+ ebRow := rootfsRoute(eb)
+ r := newWakeRelRig(t)
+ r.a.cfg.HostWrites.Enabled = true
+ r.b.fakeBackend.mu.Lock()
+ r.b.fakeBackend.startable = func(ctx context.Context, _ registry.Route) error { return eb.rootfsStartable(ctx, ebRow) }
+ r.b.fakeBackend.mu.Unlock()
+ err := waitErr(t, r.wake(r.a))
+ if !errors.Is(err, ErrClaimIsolationUnavailable) || !errors.Is(err, errRootfsRefused) {
+ t.Fatalf("the wake = %v, want Plan 2's claims refusal", err)
+ }
+ r.noUnit(t, "a rootfs row with claims on")
+ if n, acq := r.webStarts(), r.b.acquireCount(); n != 0 || acq != 0 {
+ t.Fatalf("web starts %d, acquires %d; want neither", n, acq)
+ }
+}
diff --git a/internal/activator/rootfsrelease.go b/internal/activator/rootfsrelease.go
index 8a79b82b9..2fd49b21f 100644
--- a/internal/activator/rootfsrelease.go
+++ b/internal/activator/rootfsrelease.go
@@ -65,7 +65,13 @@ func releaseDue(rt registry.Route, id release.StagedIdentity, procs map[string]r
if _, ok := procs[release.ProcessRelease]; !ok {
return false
}
- return !(id.Version == rt.GoodVersion && strings.EqualFold(id.Digest, rt.GoodDigest))
+ return !releaseRan(rt, id)
+}
+
+// releaseRan reports whether id is rt's good build, by version and digest:
+// the build whose release has already run here (D3).
+func releaseRan(rt registry.Route, id release.StagedIdentity) bool {
+ return id.Version == rt.GoodVersion && strings.EqualFold(id.Digest, rt.GoodDigest)
}
// releaseTimeout is how long p, a release process, may run [pf R1.6]: its
@@ -372,6 +378,12 @@ func (a *Service) runRelease(ctx context.Context, e *actEntry, rt registry.Route
if open {
return false, errReleaseOpen
}
+ // The row's good build is never migrated again (D3), and its processes
+ // are not read: a restart or a config attempt re-runs the serving
+ // build under the lease at no cost [pf R3.11].
+ if rt.Rootfs() && releaseRan(rt, id) {
+ return false, nil
+ }
// The declared processes, from the staged manifest root wrote. A read
// that fails is a refusal to start anything, never "no release
// process" [pf 1.9].
@@ -727,6 +739,89 @@ func (a *Service) reapReleaseOpsLocked() {
}
}
+// ---- R3: the release inside a wake ------------------------------------
+
+// releaseInWake runs id's release, when one is due, inside an ordinary
+// wake of rt with a pinned identity (doWake's staged-identity start),
+// under the wake's own lease, before web starts. Its gate is the wake's
+// lease (leaseLost; the entry has no replica yet) and the waking entry's
+// ownership (wakeOwned). A binary row runs nothing here. Any error fails
+// the wake; an unproven release leaves its record holding the host, and
+// doWake hands it the lease (oweWakeLeaseToRelease). Never call it with
+// a.mu held.
+func (a *Service) releaseInWake(ctx context.Context, e *actEntry, rt registry.Route, id release.StagedIdentity, lease Lease) error {
+ if !rt.Rootfs() {
+ return nil
+ }
+ gate := func() error {
+ if err := leaseLost(lease); err != nil {
+ return err
+ }
+ return a.wakeOwned(ctx, e)
+ }
+ _, err := a.runRelease(ctx, e, rt, id, watchOf(lease), gate)
+ return err
+}
+
+// oweWakeLeaseToRelease hands a failed wake's lease to the release record
+// e's wake left behind [pf R3.1]: when e's release ended with its unit not
+// proven stopped, the record (a.releaseOps[host], owned by e) keeps the
+// lease as owed, becomes ownerless, and gives the lease back only after
+// the reaper proves the unit gone (releaseProven). The wake's stop is
+// uncertain. It reports whether it took the lease: the caller then gives
+// nothing back, and the entry may go (wake()), the record outliving it.
+// A record already being proven (done closed) is not handed the lease:
+// its unit is gone, and the caller gives the lease back itself. It takes
+// a.mu.
+func (a *Service) oweWakeLeaseToRelease(e *actEntry, w *wokenInstance, lease Lease) bool {
+ if e == nil || lease == nil {
+ return false
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ op := a.releaseOps[e.host]
+ if op == nil || op.owner != e {
+ return false
+ }
+ select {
+ case <-op.done:
+ return false
+ default:
+ }
+ op.owed, op.owner = lease, nil
+ if w != nil {
+ if w.stopOutcome == nil {
+ w.stopOutcome = &stopObservation{}
+ }
+ w.stopOutcome.uncertain = true
+ }
+ log.Printf("activator: %s: the wake failed with the release command of build %s not proven stopped; its record keeps the lease until the sweep proves it", op.host, op.build.Version)
+ return true
+}
+
+// releaseKept marks a release result that is not the build's failure
+// (classifyRelease other than failed) as it leaves a hold's pinned spawn
+// (startPinnedChecked), so holdResult abandons the attempt for it rather
+// than reading it through classifyStep: a vanished unit, a result systemd
+// did not record, or a start error that came with a unit would otherwise
+// be the hold's SwapDown (INV-R3). The text and errors.Is are the
+// result's own.
+type releaseKept struct{ err error }
+
+func (e releaseKept) Error() string { return e.err.Error() }
+func (e releaseKept) Unwrap() error { return e.err }
+
+// holdReleaseResult is a release's error as a hold's pinned spawn returns
+// it: a failure (a *ReleaseError, its unit proven gone) as it is, which
+// holdResult answers SwapDown; anything else marked releaseKept.
+// recordOpen is whether a record exists for the host now.
+func holdReleaseResult(err error, recordOpen bool) error {
+ if err == nil || classifyRelease(err, recordOpen) == releaseFailed {
+ return err
+ }
+ return releaseKept{err: err}
+}
+
// ---- R2: the release before an overlap swap ---------------------------
// releasePass is an attempt-scoped, in-memory result: the attempt's
diff --git a/internal/activator/rootfsrelease_test.go b/internal/activator/rootfsrelease_test.go
index 8e5be15c3..7ade349e5 100644
--- a/internal/activator/rootfsrelease_test.go
+++ b/internal/activator/rootfsrelease_test.go
@@ -1324,7 +1324,7 @@ func TestReleaseCallerContextEndsIt(t *testing.T) {
func TestEveryReleaseResultIsClassified(t *testing.T) {
t.Parallel()
rerr := &ReleaseError{Build: "v2", Exit: 3}
- for _, c := range []struct {
+ rows := []struct {
name string
err error
record bool
@@ -1361,7 +1361,8 @@ func TestEveryReleaseResultIsClassified(t *testing.T) {
{"shutdown", errSwapShutdown, false, releaseRefused},
{"an unknown error with a record", errors.New("start release: unexpected EOF"), true, releaseUnproven},
{"an unknown error with no record", errors.New("start release: unexpected EOF"), false, releaseRefused},
- } {
+ }
+ for _, c := range rows {
got := classifyRelease(c.err, c.record)
if got != c.want {
t.Errorf("%s: classifyRelease = %v, want %v", c.name, got, c.want)
@@ -1419,6 +1420,31 @@ func TestEveryReleaseResultIsClassified(t *testing.T) {
if residentFailure(nil) {
t.Error("a passed release counts as a resident failure")
}
+ // The wake sites (R3): a hold's pinned wake and a planned first wake
+ // read every result the same way. Only a failure is the hold's
+ // SwapDown and B's recorded failure; every other result abandons the
+ // hold and records nothing of B, with execution as the release left it.
+ a := New(Config{Bucket: "test-bucket"}, &fakeBackend{}, nil)
+ boot := release.StagedIdentity{Version: "v2", StagedPath: "/opt/carlos/versions/v2/app", Digest: "bb22"}
+ rt := testRoute("shop.example.com")
+ rt.Runtime = registry.RuntimeRootfsV1
+ for _, c := range rows {
+ if c.err == nil {
+ continue
+ }
+ failed := c.want == releaseFailed
+ executed := c.want != releaseRefused
+ if ho := holdOf(c.err, executed, c.record); (ho.Outcome == SwapDown) != failed || ho.Outcome == SwapDone || ho.Executed != executed {
+ t.Errorf("%s, a hold: %+v; want down only for a failure, executed %v", c.name, ho, executed)
+ }
+ w := &wokenInstance{stopOutcome: &stopObservation{}}
+ plan := WakePlan{Boot: boot, Mode: ModeOverlap, FirstWake: true}
+ _, _, _, err := a.spawnPlannedRelease(context.Background(), &actEntry{host: rt.Host}, rt, plan, w, nil, false, executed, c.err)
+ if err == nil || (w.failed != nil) != failed || w.fellBack || w.bootRan != (executed || failed) {
+ t.Errorf("%s, a planned first wake: err %v, failed %v, fellBack %v, bootRan %v; want B failed only for a failure, ran %v",
+ c.name, err, w.failed != nil, w.fellBack, w.bootRan, executed || failed)
+ }
+ }
}
// What a member reads for a failed wake that carries a release result
@@ -1791,6 +1817,13 @@ func TestReleaseOpConsumersReadTheRecord(t *testing.T) {
r.clk.advance(actStopTimeout)
r.sweepPass()
waitFor(t, "the reaper's proof", func() bool { return r.record() == nil })
+ // The wake after the proof starts from a staged identity (a rootfs
+ // row with none refuses, R3 [pf R3.6]) of a build that declares no
+ // release, so it starts web at once.
+ startsFromStagedIdentity(r.cb.fakeBackend)
+ r.rel.rmu.Lock()
+ r.rel.procs = map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}}
+ r.rel.rmu.Unlock()
tickSettled(t, r.a)
if r.a.awakeEntry(r.rt.Host) == nil {
t.Fatal("the resident tick did not start the host after the proof")
diff --git a/internal/activator/swaphold.go b/internal/activator/swaphold.go
index 621b39a7b..753c9466b 100644
--- a/internal/activator/swaphold.go
+++ b/internal/activator/swaphold.go
@@ -267,7 +267,19 @@ func (a *Service) holdResult(sctx context.Context, at Attempt, newest func(strin
g, werr, proc, execed := hw.next.gen, hw.next.err, hw.next.proc, hw.next.pinExec
a.mu.Unlock()
defer func() { out.Executed = execed || werr == nil || startMayHaveRun(nil, werr) }()
+ var kept releaseKept
switch {
+ case werr != nil && errors.Is(werr, errReleaseUnproven):
+ // The build's release ran and its unit is not proven stopped [pf
+ // R3.3]: an uncertainty, never the build's failure (INV-R3). Its
+ // record holds the host; Executed is true (pinExec was set when the
+ // release started).
+ return abandon(werr)
+ case werr != nil && errors.As(werr, &kept):
+ // Any other release result but a failure (cancelled, refused, an
+ // unknown end): abandoned, Executed as the release left it
+ // (holdReleaseResult). Never SwapDown.
+ return abandon(werr)
case werr != nil && proc == nil && startMayHaveRun(nil, werr):
// A nested start root accepted whose outcome is uncertain (it
// exited before it was observed, root's start call failed, or its
@@ -368,6 +380,25 @@ func (a *Service) startPinnedChecked(ctx context.Context, e *actEntry, rt regist
if err := gate(); err != nil {
return nil, "", pin, err
}
+ // A rootfs build's release runs before its web, on the pin's whole
+ // identity, under this wake's lease and the same gate (Group R, R3).
+ // A release that ran is execution evidence whatever its end [pf
+ // R3.3]: it may have migrated the database. Only its failure comes
+ // back as it is (the hold's SwapDown); anything else is marked so
+ // holdResult abandons the attempt (holdReleaseResult).
+ if rt.Rootfs() {
+ id, ierr := stagedIdentityOf(pin)
+ if ierr != nil {
+ return nil, "", pin, refuseRootfs(ierr)
+ }
+ executed, rerr := a.runRelease(ctx, e, rt, id, watchOf(lease), gate)
+ if executed {
+ a.markPinExec(e)
+ }
+ if rerr != nil {
+ return nil, "", pin, holdReleaseResult(rerr, a.releaseOpen(rt.Host))
+ }
+ }
proc, ver, g, err := a.startPinnedAt(ctx, rt, pin, gate, time.Time{})
if proc != nil || genStartUnproven(err) {
a.markPinExec(e)
diff --git a/internal/activator/wakeidentity_test.go b/internal/activator/wakeidentity_test.go
index 3cc2fe9ae..78b940c48 100644
--- a/internal/activator/wakeidentity_test.go
+++ b/internal/activator/wakeidentity_test.go
@@ -133,6 +133,16 @@ func (b *fakeBackend) StartGenExe(ctx context.Context, rt registry.Route, n uint
b.mu.Lock()
defer b.mu.Unlock()
b.starts++
+ var held *fakeProc
+ if gate := b.startGate; gate != nil {
+ // Held on startGate as Start is (a resident's held start), its
+ // process already the last one, as Start's is.
+ held = &fakeProc{label: "instance", rec: b, stuck: b.procStuck}
+ b.procs = append(b.procs, held)
+ b.mu.Unlock()
+ <-gate
+ b.mu.Lock()
+ }
b.order = append(b.order, "start "+id.Version)
b.startedRoutes = append(b.startedRoutes, rt)
b.ident.exe = append(b.ident.exe, exeCall{n: n, perGen: perGen, id: id})
@@ -145,8 +155,11 @@ func (b *fakeBackend) StartGenExe(ctx context.Context, rt registry.Route, n uint
if b.startErr != nil {
return nil, g, b.startErr
}
- proc := &fakeProc{label: "instance", rec: b, stuck: b.procStuck}
- b.procs = append(b.procs, proc)
+ proc := held
+ if proc == nil {
+ proc = &fakeProc{label: "instance", rec: b, stuck: b.procStuck}
+ b.procs = append(b.procs, proc)
+ }
g.Build, g.StagedPath, g.Digest, g.Demand = id.Version, id.StagedPath, id.Digest, id.Demand
return proc, g, nil
}
diff --git a/internal/activator/wakeplan.go b/internal/activator/wakeplan.go
index 867958047..3c9393ab1 100644
--- a/internal/activator/wakeplan.go
+++ b/internal/activator/wakeplan.go
@@ -374,11 +374,26 @@ func (a *Service) spawnPlanned(ctx context.Context, e *actEntry, rt registry.Rou
}
canFall := plan.FirstWake && plan.Fallback != nil && plan.Mode == ModeOverlap
boot := plan.Boot
+ // A rootfs build's release runs before anything of B starts, under
+ // the wake's lease and the plan's gate (Group R, R3; spawnPlannedRelease).
+ released := false
+ if rt.Rootfs() {
+ executed, rerr := a.runRelease(ctx, e, rt, boot, watchOf(lease), a.planGate(ctx, e, lease, plan, boot.Version))
+ if rerr != nil {
+ return a.spawnPlannedRelease(ctx, e, rt, plan, w, lease, canFall, executed, rerr)
+ }
+ released = executed
+ }
gate := a.planGate(ctx, e, lease, plan, boot.Version)
var healthBy time.Time
var left time.Duration
if canFall {
healthBy = e.wakeStart.Add(firstWakeBudgetFor(rt) - firstWakeKillReserve)
+ if released {
+ // B's window starts once its release has passed [pf R3.4], so
+ // a migration does not spend B's health verdict.
+ healthBy = time.Now().Add(firstWakeBudgetFor(rt) - firstWakeKillReserve)
+ }
gate = verdictFloorGate(gate, healthBy, healthBoundFor(rt), &left)
}
// Every exec here that runs the good build in another build's place is
@@ -465,6 +480,44 @@ func (a *Service) spawnPlanned(ctx context.Context, e *actEntry, rt registry.Rou
return fproc, fver, withIdentity(fg, good), nil
}
+// spawnPlannedRelease is spawnPlanned's own branch for a release of B that
+// did not pass [pf R3.2], so the binary arms above read no release result
+// (INV-6). Only a failure (a *ReleaseError, its unit proven gone) is B's:
+// B ran (w.bootRan), a first wake records it (w.failed), and with canFall
+// the good build boots through its own planGate, beside nothing of B's
+// (no web of B ever started, so nothing is killed first). Every other
+// outcome (unproven, cancelled, refused) records nothing of B and falls
+// back to nothing: w.bootRan is whether the release's unit started, and
+// the error fails the wake. An unproven release keeps the lease in its
+// record (doWake's oweWakeLeaseToRelease), so the good build never starts
+// beside its unit. Never called with a.mu held.
+func (a *Service) spawnPlannedRelease(ctx context.Context, e *actEntry, rt registry.Route, plan WakePlan, w *wokenInstance, lease Lease,
+ canFall, executed bool, err error) (Proc, string, Gen, error) {
+ if classifyRelease(err, a.releaseOpen(rt.Host)) != releaseFailed {
+ w.bootRan = executed
+ return nil, "", Gen{}, err
+ }
+ boot := plan.Boot
+ w.bootRan = true
+ if plan.FirstWake {
+ w.failed, w.failReason = &boot, err.Error()
+ }
+ if !canFall {
+ return nil, "", Gen{}, err
+ }
+ good := *plan.Fallback
+ fctx := WithPlannedSelection(ctx, PlannedSelection{Build: good.Version, InPlaceOf: boot.Version})
+ fproc, fver, fg, ferr := a.startPinnedAt(fctx, rt, genOf(good), a.planGate(ctx, e, lease, plan, good.Version), time.Time{})
+ if ferr != nil {
+ if fproc == nil && !genStartUnproven(ferr) {
+ return nil, "", Gen{}, fmt.Errorf("%w; the good build was not started: %v", err, ferr)
+ }
+ return fproc, fver, fg, fmt.Errorf("%w; the good build %s failed too: %w", err, good.Version, ferr)
+ }
+ w.fellBack = true
+ return fproc, fver, withIdentity(fg, good), nil
+}
+
// errNoTimeForVerdict: at B's exec, less than firstWakeMinVerdict of its
// health window was left. B is not exec'd; it is never a failure of B.
var errNoTimeForVerdict = errors.New("too little of the first wake's health window is left for a verdict")
diff --git a/internal/rollout/rootfs_release_outcomes_test.go b/internal/rollout/rootfs_release_outcomes_test.go
new file mode 100644
index 000000000..740be15f9
--- /dev/null
+++ b/internal/rollout/rootfs_release_outcomes_test.go
@@ -0,0 +1,129 @@
+package rollout
+
+// Rootfs apps Plan 3, Group R, R3: the scheduler's half of the release's
+// classification. The activator answers a release that ran and failed
+// (its unit proven gone) as SwapFailed under overlap and SwapDown under a
+// hold; every other release outcome (unproven, cancelled, refused) is an
+// abandonment, Executed when the release's unit started. The scheduler
+// and the failure book, unchanged, turn those into exactly one record
+// (a failure only) and the hold-ran marker (a hold that ran and did not
+// pass), and a retried host's allowance is spent only by a release that
+// started.
+
+import (
+ "testing"
+
+ "github.com/carlosframework/platform/internal/activator"
+)
+
+// releaseRows is the activator's release contract as SwapResults, one row
+// per release outcome and mode (TestReleaseSwapResultsAreTheContract
+// pins the activator's side).
+var releaseRows = []struct {
+ name string
+ mode activator.SwapMode
+ res activator.SwapResult
+ record bool // a failure record is written
+ heldDown bool // the hold is held down on the host
+ marker bool // the hold-ran marker is set
+}{
+ {"overlap, failed", activator.ModeOverlap,
+ activator.SwapResult{Outcome: activator.SwapFailed, Reason: "release: " + (&activator.ReleaseError{Build: "v2", Exit: 1}).Error(), Executed: true},
+ true, false, false},
+ {"overlap, timed out", activator.ModeOverlap,
+ activator.SwapResult{Outcome: activator.SwapFailed, Reason: "release timed out: " + (&activator.ReleaseError{Build: "v2", TimedOut: true}).Error(), Executed: true},
+ true, false, false},
+ {"overlap, unproven", activator.ModeOverlap,
+ activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "activator: a release command's unit is not proven stopped", Executed: true},
+ false, false, false},
+ {"overlap, cancelled after it ran", activator.ModeOverlap,
+ activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "swap: the lease was lost", Executed: true},
+ false, false, false},
+ {"overlap, refused", activator.ModeOverlap,
+ activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "swap: another operation is in flight"},
+ false, false, false},
+ {"hold, failed", activator.ModeHold,
+ activator.SwapResult{Outcome: activator.SwapDown, Reason: "start a: " + (&activator.ReleaseError{Build: "v2", Exit: 1}).Error(), Executed: true},
+ true, true, false},
+ {"hold, unproven", activator.ModeHold,
+ activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "start a: activator: a release command's unit is not proven stopped", Executed: true},
+ false, false, true},
+ {"hold, cancelled after it ran", activator.ModeHold,
+ activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "start a: swap: the lease was lost", Executed: true},
+ false, false, true},
+ {"hold, cancelled before it ran", activator.ModeHold,
+ activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "start a: swap: the lease was lost"},
+ false, false, false},
+ {"hold, refused", activator.ModeHold,
+ activator.SwapResult{Outcome: activator.SwapAbandoned, Reason: "start a: rootfs refused"},
+ false, false, false},
+}
+
+func TestReleaseOutcomesThroughTheScheduler(t *testing.T) {
+ for _, tc := range releaseRows {
+ t.Run("the book, "+tc.name, func(t *testing.T) {
+ // The whole path: the scheduler admits the adoption of v2,
+ // hands it to the fake activator, which answers the row.
+ h := newHarness(t, "a")
+ b, err := OpenFailureBook(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.book, h.m.d.Book = b, b
+ h.stage("v2")
+ res := tc.res
+ h.act.mu.Lock()
+ h.act.outcome = func(a activator.Attempt) activator.SwapOutcome {
+ if a.Build == "v2" {
+ return res.Outcome
+ }
+ return activator.SwapDone
+ }
+ h.act.executed = func(activator.Attempt, activator.SwapOutcome) bool { return res.Executed }
+ h.act.reason, h.act.mode = res.Reason, tc.mode
+ h.act.mu.Unlock()
+ h.install("v2", "a")
+ h.pass()
+ waitFor(t, "the adoption", func() bool { calls, _, _ := h.act.snapshot(); return len(calls) >= 1 })
+ waitFor(t, "a's slot to free", func() bool { return !h.m.attemptRunning("a") })
+
+ rec, ok := h.book.Lookup("bab", "blog", "v2")
+ if ok != tc.record {
+ t.Fatalf("failure record %+v, %v; want written %v", rec, ok, tc.record)
+ }
+ if held := ok && len(rec.HeldDown) == 1 && rec.HeldDown[0] == "a"; held != tc.heldDown {
+ t.Fatalf("the record's hold-down %v; want held down %v", rec.HeldDown, tc.heldDown)
+ }
+ if _, marked := h.book.HoldRanOn("a"); marked != tc.marker {
+ t.Fatalf("the hold-ran marker is set %v; want %v", marked, tc.marker)
+ }
+ })
+ }
+ // A retried host's allowance is spent only by an attempt whose build
+ // ran: a release that started counts, abandoned or not; one refused
+ // before its unit started gives the allowance back.
+ for _, tc := range releaseRows {
+ if tc.res.Outcome != activator.SwapAbandoned {
+ continue
+ }
+ t.Run("the retry allowance, "+tc.name, func(t *testing.T) {
+ h := newHarness(t, "a")
+ s := h.m.scheduler(appKey{"bab", "blog"})
+ d := dispatch{ID: Identity{Host: "a", Cause: activator.CauseRetry, Build: "v2"}, SchedRev: 1, Class: classAdopt,
+ Cohort: cohortKey("v2", classAdopt), Canary: true, Forced: true}
+ s.mu.Lock()
+ slot := s.q.slot("a", t0)
+ slot.serving, slot.good = "v1", "v1"
+ slot.running = &d
+ s.q.running++
+ s.mu.Unlock()
+ s.done(d, tc.res, tc.mode)
+ s.mu.Lock()
+ rearmed := s.q.hosts["a"].forceBuilds["v2"]
+ s.mu.Unlock()
+ if rearmed != !tc.res.Executed {
+ t.Fatalf("the retry allowance came back %v; want %v (executed %v)", rearmed, !tc.res.Executed, tc.res.Executed)
+ }
+ })
+ }
+}