carlos / platform Public

activator: every consumer reads the release record; Shutdown drains it

Group R, R1c (INV-R1, INV-R2). Every question "is a release command
running or not proven stopped for this host" asks a.releaseOps[host]:
RunCmd's admission (ErrCmdBusy), the sweep's plan-disabled, idle and
awake-ceiling stops (deferred while a record is open), a stop of the
owner (op.cancel, so runRelease settles at once), releasable and
finishStop (the stop stays pending with the lease and replica held),
the doWake and claimed-wake latches (errWakeUnproven for a record
another entry left), FenceAndStop on an entry-less host, and the
resident tick (held). residentFailure reads a release's own result
through classifyRelease, so only a *ReleaseError counts; a vanished
unit, one with no exit and a lease end do not. Shutdown counts the
records in its drain, keeps running the one retry pass until each is
proven or its budget ends, and names each one left (host and build).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 17a55e8410ebe0d78b4a685124608e4e5dce3ea9 parent 5568738
8 files changed, +805 −18
  • internal/activator/activator.go +52 −8
  • internal/activator/claimwake.go +5 −0
  • internal/activator/cmd.go +4 −1
  • internal/activator/maintenance.go +4 −1
  • internal/activator/opset.go +5 −2
  • internal/activator/rootfs_service.go +14 −6
  • internal/activator/rootfsrelease.go +28 −0
  • internal/activator/rootfsrelease_test.go +693 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 0b18b9c5f..293ef9b4d 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -2395,9 +2395,15 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
// it (reapUnprovenWakesLocked). A legacy sidecar of the host whose
// termination is unproven refuses it the same way
// (reapStraySidecarsLocked).
+ // A release command of the host that another entry started, running
+ // or not proven stopped, refuses it too (Group R, INV-R1): its record
+ // outlives that entry, and only its proof frees the host.
a.mu.Lock()
_, unproven := a.unprovenWakes[host]
unproven = unproven || len(a.straySidecars[host]) > 0
+ if op := a.releaseOps[host]; op != nil && op.owner != e {
+ unproven = true
+ }
a.mu.Unlock()
if unproven {
return w, fmt.Errorf("%s: refusing to wake: %w", host, errWakeUnproven)
@@ -3011,6 +3017,12 @@ func (a *Service) beginStopLocked(e *actEntry, why string) {
if e.cmd != nil {
e.cmd.cancelPrepare() // a stop interrupts a run's download
}
+ // A release command this entry owns is cancelled, so runRelease stops
+ // and settles its unit at once (Group R, INV-R1). The stop keeps the
+ // lease until the record is proven gone (releasable, finishStop).
+ if op := a.releaseOps[e.host]; op != nil && op.owner == e {
+ op.cancel(fmt.Errorf("%w (%s)", errSwapStopped, why))
+ }
e.stopped = make(chan struct{})
go a.stop(e)
}
@@ -4741,6 +4753,18 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) {
a.mu.Unlock()
return
}
+ // A release command of the host is held to the same rule (Group R,
+ // [pf R1.11]): while its record exists, running or not proven
+ // stopped, replication and the lease stay, and the stop stays pending
+ // until the record's proof (reapReleaseOpsLocked). Here as well as in
+ // releasable, so no stop path can skip it.
+ if a.releaseOpen(e.host) {
+ log.Printf("activator: stop %s: a release command is not proven stopped; keeping replication and the lease until it is", e.host)
+ a.mu.Lock()
+ a.keepPendingLocked(e, outcome)
+ a.mu.Unlock()
+ return
+ }
// Close = final sync + lease release. After a lost lease the release part
// fails harmlessly (someone else owns the lock); the sync still preserves
// a local checkpoint.
@@ -5067,7 +5091,10 @@ func (a *Service) sweepOnce() {
// the activator.
// A route a lapse turned off (plans 4d) stops, worker or instance,
// whatever is in flight; never mid-command, and never a move's probe.
- if !activeProbe(e) && e.cmd == nil && a.disabled(e.route) {
+ // Nor while a release command of the host is open (Group R): the
+ // stop waits for the first sweep after its record goes.
+ releasing := a.releaseOps[e.host] != nil
+ if !activeProbe(e) && e.cmd == nil && !releasing && a.disabled(e.route) {
log.Printf("activator: %s was turned off by its plan — stopping", e.host)
a.beginStopLocked(e, StopIdle)
continue
@@ -5094,7 +5121,10 @@ func (a *Service) sweepOnce() {
idleWindow = d
}
}
- if hibernates && e.inflight == 0 && e.cmd == nil && now.Sub(e.lastActive) >= idleWindow {
+ // An instance whose release command is open is never idle (Group R,
+ // C8): a hibernating incumbent keeps serving through an overlap
+ // migration.
+ if hibernates && e.inflight == 0 && e.cmd == nil && !releasing && now.Sub(e.lastActive) >= idleWindow {
// Don't sleep into an imminent tick. A wake/sleep pair is a full
// checkpoint-and-restore round trip; spending one to be absent
// for less time than we would have idled anyway is a straight
@@ -5142,8 +5172,9 @@ func (a *Service) sweepOnce() {
// awake-throttled account's instance that is never idle (a steady
// pinger, a long stream) still sleeps after the ceiling, whatever is
// in flight, and wakes on its next request. Never a worker, and
- // never mid-command.
- if f := a.maxRunFor.Load(); f != nil && !e.worker && hibernates && e.cmd == nil {
+ // never mid-command or mid-release: it fires on the first sweep
+ // after the release's record goes.
+ if f := a.maxRunFor.Load(); f != nil && !e.worker && hibernates && e.cmd == nil && !releasing {
if d := (*f)(e.route); d > 0 && now.Sub(e.spawnedAt) >= d {
log.Printf("activator: %s awake %s, past its plan's ceiling of %s — stopping", e.host, now.Sub(e.spawnedAt).Truncate(time.Second), d)
a.beginStopLocked(e, StopIdle)
@@ -5716,9 +5747,14 @@ func (a *Service) Shutdown(ctx context.Context) {
// Lease releases that failed (#292, Astra P3) are retried here the same
// way, inside the same budget (retryOwedReleasesLocked, also inside
// finishPendingStops), and named at exit if they are still owed.
+ //
+ // So are release commands (Group R, INV-R2): a record outlives the
+ // entry that started it, so Shutdown waits on the records themselves
+ // until each is proven (reapReleaseOpsLocked, inside the same pass) or
+ // the budget ends, and names each one left at exit.
for {
a.mu.Lock()
- left := len(a.unprovenWakes) + len(a.owedReleases)
+ left := len(a.unprovenWakes) + len(a.owedReleases) + len(a.releaseOps)
if left > 0 {
a.finishPendingStops()
}
@@ -5736,18 +5772,26 @@ func (a *Service) Shutdown(ctx context.Context) {
}
// logUnresolvedAtExit names what Shutdown's budget ran out on: failed
-// wakes not proven stopped, whose leases are kept, and lease releases that
-// failed and were not resolved by a retry. The TTL frees either.
+// wakes not proven stopped, whose leases are kept, lease releases that
+// failed and were not resolved by a retry, and release commands not proven
+// stopped (each host with its build). The TTL frees each.
func (a *Service) logUnresolvedAtExit() {
a.mu.Lock()
- var held, owed []string
+ var held, owed, releasing []string
for host, u := range a.unprovenWakes {
held = append(held, fmt.Sprintf("%s (generation %d)", host, u.gen.N))
}
for o := range a.owedReleases {
owed = append(owed, o.host)
}
+ for host, op := range a.releaseOps {
+ releasing = append(releasing, fmt.Sprintf("%s (build %s)", host, op.build.Version))
+ }
a.mu.Unlock()
+ if len(releasing) > 0 {
+ slices.Sort(releasing)
+ log.Printf("activator: shutdown: out of time with %d release command(s) not proven stopped, their leases still held: %s", len(releasing), strings.Join(releasing, ", "))
+ }
if len(held) > 0 {
slices.Sort(held)
log.Printf("activator: shutdown: out of time with %d failed wake(s) not proven stopped, their leases still held: %s", len(held), strings.Join(held, ", "))
diff --git a/internal/activator/claimwake.go b/internal/activator/claimwake.go
index 414a71c00..0b58ad636 100644
--- a/internal/activator/claimwake.go
+++ b/internal/activator/claimwake.go
@@ -169,9 +169,14 @@ func (a *Service) doClaimWake(ctx context.Context, e *actEntry) (*wokenInstance,
// (zero-downtime spec §7.4). As doWake does, no new wake starts until
// the sweep proves it, and a stray legacy sidecar refuses it the same
// way.
+ // A release command's record another entry left (Group R, INV-R1)
+ // holds the host the same way.
a.mu.Lock()
_, unproven := a.unprovenWakes[e.host]
unproven = unproven || len(a.straySidecars[e.host]) > 0
+ if op := a.releaseOps[e.host]; op != nil && op.owner != e {
+ unproven = true
+ }
a.mu.Unlock()
if unproven {
return nil, fmt.Errorf("%s: refusing to wake: %w", e.host, errWakeUnproven)
diff --git a/internal/activator/cmd.go b/internal/activator/cmd.go
index b1a82a5f5..001940007 100644
--- a/internal/activator/cmd.go
+++ b/internal/activator/cmd.go
@@ -497,7 +497,10 @@ func (a *Service) RunCmd(ctx context.Context, rt registry.Route, spec CmdSpec) (
a.mu.Unlock()
release()
return nil, ErrCmdNotInstance
- case cmdBusyLocked(e):
+ case cmdBusyLocked(e), a.releaseOps[rt.Host] != nil:
+ // A release command of the host, running or not proven stopped,
+ // holds its cmd unit as a run does (Group R, INV-R1): the record is
+ // asked, never an entry field.
a.mu.Unlock()
release()
return nil, ErrCmdBusy
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go
index db48f399b..cd6e3bb22 100644
--- a/internal/activator/maintenance.go
+++ b/internal/activator/maintenance.go
@@ -178,11 +178,14 @@ func (a *Service) fenceAndStop(ctx context.Context, host string, generation uint
e := a.entries[host]
if e == nil {
outcome := a.stopHistory[host]
+ // A release command's record that outlived its entry (Group R,
+ // INV-R1): its unit may still write the database.
+ releasing := a.releaseOps[host] != nil
a.mu.Unlock()
if ctx.Err() != nil || !time.Now().Before(deadline) {
return nil, ErrStopUnproven
}
- if !outcome.complete() {
+ if releasing || !outcome.complete() {
return nil, ErrStopUnproven
}
return &StopEvidence{host: host, generation: generation, observation: outcome}, nil
diff --git a/internal/activator/opset.go b/internal/activator/opset.go
index b610d44a4..ed56bdf14 100644
--- a/internal/activator/opset.go
+++ b/internal/activator/opset.go
@@ -690,16 +690,19 @@ func (a *Service) reapExited(e *actEntry, m *genMember) {
// its child, or a worker's host cgroup, empty), and every run of the
// instance is proven stopped, its unit stopped and its cgroup empty
// (settleCmds; run spec §5.3, merge ruling M1). A run writes the database
-// as the serving process does, so it is held to the same rule. It runs
+// as the serving process does, so it is held to the same rule, and so is a
+// release command: no record of the host may be open, running or not
+// proven stopped (Group R, [pf R1.11]; finishStop asks it too). It runs
// without a.mu held; genTerminated may take DeadlineControl, and a run's
// settle up to cmdStopBound.
func (a *Service) releasable(e *actEntry) bool {
a.mu.Lock()
members, strays, restoring := len(e.ops.members), len(a.straySidecars[e.host]), e.ops.restoring
resizing := e.ops.resizing
+ releasing := a.releaseOps[e.host] != nil
rt, g, p := e.route, e.gen, e.proc
a.mu.Unlock()
- if members > 0 || strays > 0 || restoring || resizing {
+ if members > 0 || strays > 0 || restoring || resizing || releasing {
return false
}
return a.genTerminated(rt, g, p) && a.settleCmds(e)
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go
index 6c30ce970..f3127a768 100644
--- a/internal/activator/rootfs_service.go
+++ b/internal/activator/rootfs_service.go
@@ -440,15 +440,19 @@ func retryAfterSeconds(d time.Duration) int {
// has (errLeaseHeld) and refused config (errConfigRefused) are refusals
// through verdictOf once doWake has marked them for the row's runtime
// (markOwnershipRefusal); their retry pacing is residentOwnerWait's, never
-// a failure. A release command not proven stopped (errReleaseUnproven,
-// Group R R1b) holds the host as errWakeUnproven does, and is never a
-// failure either; R1c extends the rest through classifyRelease.
+// a failure. A release command's own result (Group R: a *ReleaseError or
+// one of the release's sentinels, isReleaseResult) counts only when
+// classifyRelease reads it as the build's failure (a *ReleaseError): an
+// unproven unit holds the host as errWakeUnproven does, and a lease end, a
+// vanished unit or one with no exit recorded is not the build's (INV-R3).
func residentFailure(err error) bool {
switch {
case err == nil:
return false
+ case isReleaseResult(err):
+ return classifyRelease(err, false) == releaseFailed
case errors.Is(err, ErrFenced), errors.Is(err, errShuttingDown), errors.Is(err, context.Canceled),
- errors.Is(err, errSwapBusy), errors.Is(err, errWakeUnproven), errors.Is(err, errReleaseUnproven):
+ errors.Is(err, errSwapBusy), errors.Is(err, errWakeUnproven):
return false
}
switch verdictOf(err) {
@@ -541,8 +545,9 @@ func (a *Service) residentJitterLocked() float64 {
// residentHeldLocked reports why host may not start now beside what the
// backoff says: a fence, a live entry, or an uncertainty latch (a failed
-// wake or a legacy sidecar not proven stopped; Group R adds its release
-// record), or its plan turned it off. The caller holds a.mu.
+// wake or a legacy sidecar not proven stopped, or a release command's
+// record in any state, Group R), or its plan turned it off. The caller
+// holds a.mu.
func (a *Service) residentHeldLocked(rt registry.Route) bool {
if a.fences[rt.Host] != 0 || a.entries[rt.Host] != nil {
return true
@@ -550,6 +555,9 @@ func (a *Service) residentHeldLocked(rt registry.Route) bool {
if _, latched := a.unprovenWakes[rt.Host]; latched || len(a.straySidecars[rt.Host]) > 0 {
return true
}
+ if a.releaseOps[rt.Host] != nil {
+ return true
+ }
return a.disabled(rt)
}
diff --git a/internal/activator/rootfsrelease.go b/internal/activator/rootfsrelease.go
index 1a930cc02..6dbc4e81f 100644
--- a/internal/activator/rootfsrelease.go
+++ b/internal/activator/rootfsrelease.go
@@ -279,6 +279,34 @@ func classifyRelease(err error, recordOpen bool) releaseOutcome {
return releaseRefused
}
+// isReleaseResult reports whether err carries a release command's own
+// result: a *ReleaseError or one of the release's sentinels. A consumer
+// handed one inside a wake's or a swap's error reads it through
+// classifyRelease (residentFailure). An error runRelease passes through
+// from elsewhere (a context, a refusal, a store error) is not one, and is
+// read as its own kind.
+func isReleaseResult(err error) bool {
+ var rerr *ReleaseError
+ if errors.As(err, &rerr) {
+ return true
+ }
+ for _, s := range []error{errReleaseOpen, errReleaseUnproven, errReleaseNoLease, errReleaseLeaseLost, errReleaseVanished, errReleaseNoExit} {
+ if errors.Is(err, s) {
+ return true
+ }
+ }
+ return false
+}
+
+// releaseOpen reports whether a release command's record exists for host,
+// running or not proven stopped (INV-R1): the one question every consumer
+// asks. Never call it with a.mu held.
+func (a *Service) releaseOpen(host string) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return a.releaseOps[host] != nil
+}
+
// releaseExit reads a done unit's status as `carlos run` does
// (host/runexec.go exitOf) [pf R1.15]: ExecMainCode 2, 3, killed or
// dumped is a signal, numbered by ExecMainStatus; ExecMainCode 1 or exited
diff --git a/internal/activator/rootfsrelease_test.go b/internal/activator/rootfsrelease_test.go
index 72deb2a8a..06c0f11eb 100644
--- a/internal/activator/rootfsrelease_test.go
+++ b/internal/activator/rootfsrelease_test.go
@@ -13,15 +13,21 @@ import (
"errors"
"fmt"
"io"
+ "log"
"net"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
+ "github.com/carlosframework/platform/internal/hostclaim"
+ "github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/provision"
@@ -1378,6 +1384,41 @@ func TestEveryReleaseResultIsClassified(t *testing.T) {
t.Errorf("%s: residentFailure = true", name)
}
}
+ // Resident accounting (R1c): a release's own result counts toward the
+ // resident's backoff only when classifyRelease reads it as failed,
+ // bare or inside a wake's error.
+ for _, c := range []struct {
+ name string
+ err error
+ want releaseOutcome
+ }{
+ {"a ReleaseError", rerr, releaseFailed},
+ {"a timed-out ReleaseError", &ReleaseError{Build: "v2", TimedOut: true, Took: time.Minute}, releaseFailed},
+ {"a signal's ReleaseError", &ReleaseError{Build: "v2", Signal: "9"}, releaseFailed},
+ {"errReleaseUnproven", errReleaseUnproven, releaseUnproven},
+ {"errReleaseUnproven after a lease trip", fmt.Errorf("%w: %w: %w (x)", errSwapLeaseLost, errReleaseLeaseLost, errReleaseUnproven), releaseUnproven},
+ {"errReleaseOpen", errReleaseOpen, releaseRefused},
+ {"errReleaseNoLease (marked)", refuseRootfs(errReleaseNoLease), releaseRefused},
+ {"errReleaseNoLease (bare)", errReleaseNoLease, releaseRefused},
+ {"the lease lost", fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost), releaseCancelled},
+ {"the vanished unit", errReleaseVanished, releaseCancelled},
+ {"no exit recorded", errReleaseNoExit, releaseCancelled},
+ } {
+ if !isReleaseResult(c.err) {
+ t.Errorf("%s: not read as a release's result", c.name)
+ }
+ for _, err := range []error{c.err, fmt.Errorf("start shop.example.com: %w", c.err)} {
+ if got := classifyRelease(err, false); got != c.want {
+ t.Errorf("%s: classifyRelease = %v, want %v", c.name, got, c.want)
+ }
+ if got, want := residentFailure(err), c.want == releaseFailed; got != want {
+ t.Errorf("%s (%v): residentFailure = %v, want %v", c.name, err, got, want)
+ }
+ }
+ }
+ if residentFailure(nil) {
+ t.Error("a passed release counts as a resident failure")
+ }
}
// What a member reads for a failed wake that carries a release result
@@ -1403,3 +1444,655 @@ func TestReleaseMemberWords(t *testing.T) {
}
}
}
+
+// --- R1c: every consumer reads the record; Shutdown drains it ----------------
+
+// releaseCmdFake is cmdFakeBackend (a nested layout and the run seam) with
+// releaseFake's release seam and process read on the same fakeBackend, so
+// one Service has an awake instance, its runs and its release.
+type releaseCmdFake struct {
+ *cmdFakeBackend
+ rel *releaseFake
+}
+
+func (b *releaseCmdFake) Processes(rt registry.Route, id release.StagedIdentity) (map[string]release.Process, error) {
+ return b.rel.Processes(rt, id)
+}
+
+func (b *releaseCmdFake) ReleaseEnv(ctx context.Context, rt registry.Route) (map[string]string, error) {
+ return b.rel.ReleaseEnv(ctx, rt)
+}
+
+func (b *releaseCmdFake) StartRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, env map[string]string, out io.Writer) (CmdUnit, error) {
+ return b.rel.StartRelease(ctx, rt, id, env, out)
+}
+
+var (
+ _ ReleaseBackend = (*releaseCmdFake)(nil)
+ _ ProcessReader = (*releaseCmdFake)(nil)
+ _ CmdBackend = (*releaseCmdFake)(nil)
+)
+
+// consumerRig is a Service over releaseCmdFake with shop.example.com woken
+// through the ordinary path (a process, a replica, the lease), so every
+// stop path, the sweep and RunCmd act on a real entry. rrt is the same row
+// as a release reads it: rootfs, good on v1, with v2 staged.
+type consumerRig struct {
+ a *Service
+ cb *cmdFakeBackend
+ rel *releaseFake
+ clk *fakeClock
+ sink *rootfsSink
+ rt registry.Route
+ rrt registry.Route
+ e *actEntry
+ id release.StagedIdentity
+ held *ownedLease
+}
+
+func newConsumerRig(t *testing.T, gens bool) *consumerRig {
+ t.Helper()
+ fb := &fakeBackend{layoutFn: func(registry.Route) (Layout, string) { return LayoutNested, "" }}
+ cb := &cmdFakeBackend{fakeBackend: fb}
+ cb.unit = &fakeCmdUnit{rep: fb.lastRep}
+ rel := &releaseFake{fakeBackend: fb, procs: releaseDeclared(), unit: newReleaseUnit(), started: make(chan struct{})}
+ clk := &fakeClock{t: time.Unix(1_700_000_000, 0)}
+ 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}, &releaseCmdFake{cmdFakeBackend: cb, rel: rel}, reg)
+ a.now = clk.now
+ a.gens = gens
+ sink := &rootfsSink{}
+ a.Logs = sink
+ a.GenerationsFile = filepath.Join(t.TempDir(), "generations.json")
+ rt := testRoute("shop.example.com")
+ arrangeAwake(t, a, rt)
+ a.mu.Lock()
+ e := a.entries[rt.Host]
+ a.mu.Unlock()
+ rrt := rt
+ rrt.Runtime, rrt.App, rrt.Account, rrt.Version = registry.RuntimeRootfsV1, "shop", "acme", "v1"
+ rrt.GoodVersion, rrt.GoodDigest = "v1", "aa11"
+ id := release.StagedIdentity{Version: "v2", StagedPath: filepath.Join(t.TempDir(), "v2", "rootfs.squashfs"), Digest: "bb22"}
+ return &consumerRig{a: a, cb: cb, rel: rel, clk: clk, sink: sink, rt: rt, rrt: rrt, e: e, id: id,
+ held: newOwnedLease(time.Now().Add(time.Hour), false)}
+}
+
+// gate is the site's ownership gate: the entry is still the host's and
+// awake.
+func (r *consumerRig) gate() error {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ if r.a.entries[r.rt.Host] != r.e || r.e.state != actAwake {
+ return errSwapSuperseded
+ }
+ return nil
+}
+
+// start runs a release for the entry in the background and waits for its
+// unit to start; its result arrives on the channel.
+func (r *consumerRig) start(t *testing.T, ctx context.Context) <-chan releaseResult {
+ t.Helper()
+ ch := make(chan releaseResult, 1)
+ go func() {
+ ex, err := r.a.runRelease(ctx, r.e, r.rrt, r.id, r.held, r.gate)
+ ch <- releaseResult{ex, err}
+ }()
+ select {
+ case <-r.rel.started:
+ case res := <-ch:
+ t.Fatalf("runRelease returned before its start: %v, %v", res.executed, res.err)
+ case <-time.After(10 * time.Second):
+ t.Fatal("StartRelease was never called")
+ }
+ return ch
+}
+
+// endRun stops and releases a run, its unit proven settled.
+func endRun(t *testing.T, h CmdHandle) {
+ t.Helper()
+ if err := h.Stop(context.Background()); err != nil {
+ t.Fatalf("the run's stop: %v", err)
+ }
+ h.Release()
+}
+
+// fresh gives the fake a new unit and start signal, for a second release.
+func (r *consumerRig) fresh() {
+ r.rel.rmu.Lock()
+ r.rel.unit, r.rel.started = newReleaseUnit(), make(chan struct{})
+ r.rel.rmu.Unlock()
+}
+
+func (r *consumerRig) record() *releaseOp {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ return r.a.releaseOps[r.rt.Host]
+}
+
+// awake reports whether the entry is still the host's, awake, and asked to
+// stop by nothing.
+func (r *consumerRig) awake() bool {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ return r.a.entries[r.rt.Host] == r.e && r.e.state == actAwake && r.e.stopWhy == ""
+}
+
+// pendingStop reports whether the entry is still the host's, stopping with
+// its stop pending.
+func (r *consumerRig) pendingStop() bool {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ return r.a.entries[r.rt.Host] == r.e && r.e.state == actStopping && r.e.pendingStop
+}
+
+// sweepUntilGone sweeps until the entry's pending stop has finished (a
+// sweep skips an entry whose last proof is still in flight).
+func (r *consumerRig) sweepUntilGone(t *testing.T) {
+ t.Helper()
+ for i := 0; i < 100 && r.a.entryCount() > 0; i++ {
+ r.a.sweepOnce()
+ time.Sleep(20 * time.Millisecond)
+ }
+ waitFor(t, "the stop to finish", func() bool { return r.a.entryCount() == 0 })
+}
+
+// sweepPass runs finishPendingStops as the sweep and Shutdown run it.
+func (r *consumerRig) sweepPass() {
+ r.a.mu.Lock()
+ r.a.finishPendingStops()
+ r.a.mu.Unlock()
+}
+
+// stuckUnit makes every settle of u fail until the returned func is called.
+func stuckUnit(u *releaseUnit) (unstick func()) {
+ var mu sync.Mutex
+ stuck := true
+ u.mu.Lock()
+ u.settle = func(int) error {
+ mu.Lock()
+ defer mu.Unlock()
+ if stuck {
+ return errors.New("processes remained in the unit's cgroup")
+ }
+ return nil
+ }
+ u.mu.Unlock()
+ return func() {
+ mu.Lock()
+ stuck = false
+ mu.Unlock()
+ }
+}
+
+// INV-R1: with a record for the host, every consumer of "is a release
+// running or unproven here" reads the record, and proceeds once it is
+// proven gone.
+func TestReleaseOpConsumersReadTheRecord(t *testing.T) {
+ t.Run("a run and a second release", func(t *testing.T) {
+ r := newConsumerRig(t, false)
+ ch := r.start(t, context.Background())
+ if _, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "run_a"}); !errors.Is(err, ErrCmdBusy) {
+ t.Fatalf("RunCmd during a release = %v, want ErrCmdBusy", err)
+ }
+ if r.cb.cmdStarts != 0 {
+ t.Fatal("a run started its unit beside a release")
+ }
+ if _, err := r.a.runRelease(context.Background(), r.e, r.rrt, r.id, r.held, r.gate); !errors.Is(err, errReleaseOpen) {
+ t.Fatalf("a second release = %v, want errReleaseOpen", err)
+ }
+ if n := r.rel.startCount(); n != 1 {
+ t.Fatalf("%d release starts, want 1", n)
+ }
+ if !pinned(t, r.a, r.rt.Host, "v2") {
+ t.Fatal("the generations file does not name the release's build")
+ }
+ r.rel.unit.done("1", "0", "success")
+ if res := wait(t, ch); res.err != nil {
+ t.Fatalf("the release = %v", res.err)
+ }
+ // Proven: each proceeds.
+ if pinned(t, r.a, r.rt.Host, "v2") {
+ t.Fatal("the pin outlived the record")
+ }
+ h, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "run_b"})
+ if err != nil {
+ t.Fatalf("RunCmd after the proof = %v", err)
+ }
+ endRun(t, h)
+ r.fresh()
+ ch = r.start(t, context.Background())
+ r.rel.unit.done("1", "0", "success")
+ if res := wait(t, ch); res.err != nil {
+ t.Fatalf("a release after the proof = %v", res.err)
+ }
+ })
+
+ // The sweep's three stops of an awake owner: deferred while the record
+ // is open, taken on the first sweep after it goes.
+ for _, arm := range []struct {
+ name string
+ install func(r *consumerRig)
+ }{
+ {"idle", func(r *consumerRig) { r.clk.advance(2 * time.Hour) }},
+ {"the awake ceiling", func(r *consumerRig) {
+ r.a.SetMaxRunFor(func(registry.Route) time.Duration { return time.Minute })
+ r.clk.advance(2 * time.Minute)
+ }},
+ {"plan-disabled", func(r *consumerRig) { r.a.SetDisabledFor(func(registry.Route) bool { return true }) }},
+ } {
+ t.Run("the sweep: "+arm.name, func(t *testing.T) {
+ r := newConsumerRig(t, false)
+ ch := r.start(t, context.Background())
+ arm.install(r)
+ r.a.sweepOnce()
+ if !r.awake() {
+ t.Fatalf("the sweep stopped the owner of an open release (stopWhy %q)", r.a.stopWhyOf(r.rt.Host))
+ }
+ r.rel.unit.done("1", "0", "success")
+ if res := wait(t, ch); res.err != nil {
+ t.Fatalf("the release = %v", res.err)
+ }
+ r.a.sweepOnce()
+ if r.awake() {
+ t.Fatal("the first sweep after the proof did not stop the owner")
+ }
+ waitFor(t, "the stop", func() bool { return r.a.entryCount() == 0 })
+ })
+ }
+
+ // A stop of the owner keeps its lease while the record is open:
+ // releasable is false and finishStop keeps the stop pending, with the
+ // replica open, under either generations setting.
+ for _, gens := range []bool{false, true} {
+ t.Run(fmt.Sprintf("a stop of the owner, gens %v", gens), func(t *testing.T) {
+ r := newConsumerRig(t, gens)
+ unstick := stuckUnit(r.rel.unit)
+ ch := r.start(t, context.Background())
+ rep := r.cb.lastRep()
+ r.a.Bounce(r.rt.Host)
+ res := wait(t, ch)
+ if !errors.Is(res.err, errReleaseUnproven) {
+ t.Fatalf("the release = %v, want errReleaseUnproven", res.err)
+ }
+ waitFor(t, "the stop to be kept pending", r.pendingStop)
+ if r.a.releasable(r.e) {
+ t.Fatal("releasable is true with the record open")
+ }
+ for i := 0; i < 3; i++ {
+ r.a.sweepOnce()
+ }
+ time.Sleep(50 * time.Millisecond)
+ if !r.pendingStop() || rep.isClosed() {
+ t.Fatalf("the stop finished over an open record (pending %v, replica closed %v)", r.pendingStop(), rep.isClosed())
+ }
+ unstick()
+ r.clk.advance(actStopTimeout)
+ r.a.sweepOnce()
+ waitFor(t, "the reaper's proof", func() bool { return r.record() == nil })
+ r.sweepUntilGone(t)
+ if !rep.isClosed() {
+ t.Fatal("the replica was not closed after the proof")
+ }
+ })
+ }
+
+ // The owner gone (R3's failed wake leaves owner nil): a wake of the
+ // host, the resident tick and a fence are refused while the record is
+ // open, before any lease; once it is proven the host wakes.
+ t.Run("the owner gone", func(t *testing.T) {
+ r := newConsumerRig(t, true)
+ unstick := stuckUnit(r.rel.unit)
+ ctx, cancel := context.WithCancel(context.Background())
+ ch := r.start(t, ctx)
+ cancel()
+ if res := wait(t, ch); !errors.Is(res.err, errReleaseUnproven) {
+ t.Fatalf("the release = %v, want errReleaseUnproven", res.err)
+ }
+ r.a.mu.Lock()
+ delete(r.a.entries, r.rt.Host)
+ r.a.releaseOps[r.rt.Host].owner = nil
+ r.a.rememberStopLocked(r.rt.Host, &stopObservation{mainStop: true, mainExited: true, sidecarStop: true, sidecarExited: true, replicaClosed: true, leaseReleased: true})
+ r.a.mu.Unlock()
+ acquires := r.cb.acquireCount()
+
+ w := httptest.NewRecorder()
+ r.a.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://"+r.rt.Host+"/", nil), r.rt, okHandler())
+ if w.Code == http.StatusOK {
+ t.Fatal("a request woke the host over an open release record")
+ }
+ if _, err := r.a.beginRequest(context.Background(), r.rt); !errors.Is(err, errWakeUnproven) {
+ t.Fatalf("a wake of the host = %v, want errWakeUnproven", err)
+ }
+ fctx, fcancel := context.WithTimeout(context.Background(), 5*time.Second)
+ if _, err := r.a.FenceAndStop(fctx, r.rt.Host, 1); !errors.Is(err, ErrStopUnproven) {
+ t.Errorf("a fence over an open release record = %v, want ErrStopUnproven", err)
+ }
+ fcancel()
+ r.a.LiftFence(r.rt.Host, 1)
+ armRootfsForTest(r.a)
+ r.a.residentJitter = func() float64 { return 0 }
+ res := residentRoute(r.rt.Host)
+ r.a.residentLister = &fakeResidents{routes: []registry.Route{res}}
+ var reserved atomic.Int32
+ r.a.residentGatesPassed = func(string) { reserved.Add(1) }
+ tickSettled(t, r.a)
+ if r.a.hasEntry(r.rt.Host) || reserved.Load() != 0 {
+ t.Fatalf("the resident tick reserved the host %d times over an open release record", reserved.Load())
+ }
+ if got := r.cb.acquireCount(); got != acquires {
+ t.Fatalf("%d lease acquires over an open release record", got-acquires)
+ }
+
+ unstick()
+ r.clk.advance(actStopTimeout)
+ r.sweepPass()
+ waitFor(t, "the reaper's proof", func() bool { return r.record() == nil })
+ 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")
+ }
+ if got := r.cb.acquireCount(); got != acquires+1 {
+ t.Fatalf("%d lease acquires after the proof, want 1", got-acquires)
+ }
+ })
+
+ // A claims-on wake asks the same record at its head.
+ t.Run("a claimed wake", func(t *testing.T) {
+ read := false
+ a := &Service{cfg: Config{HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box",
+ Read: func(context.Context, string) (hostclaim.Observed, error) {
+ read = true
+ return claimedObs("x.example"), nil
+ },
+ StopForeign: func(context.Context, string) error { return nil }}}}
+ a.releaseOps = map[string]*releaseOp{"x.example": {host: "x.example"}}
+ e := &actEntry{host: "x.example", route: registry.Route{Host: "x.example", Kind: "instance"}}
+ if _, err := a.doClaimWake(context.Background(), e); !errors.Is(err, errWakeUnproven) {
+ t.Fatalf("doClaimWake = %v, want errWakeUnproven", err)
+ }
+ if read {
+ t.Fatal("the claim was read for a host with an open release record")
+ }
+ })
+}
+
+// INV-R2: an unproven release of an awake incumbent, whose owner never
+// stops, is retried by the sweep's pass alone, and once proven its pin
+// goes and the host takes a release and a run again.
+func TestUnprovenReleaseOnAnAwakeIncumbentIsRetried(t *testing.T) {
+ r := newConsumerRig(t, true)
+ unstick := stuckUnit(r.rel.unit)
+ ch := r.start(t, context.Background())
+ r.rel.unit.done("1", "0", "success")
+ res := wait(t, ch)
+ if !errors.Is(res.err, errReleaseUnproven) || classifyRelease(res.err, true) != releaseUnproven {
+ t.Fatalf("the release = %v, want errReleaseUnproven", res.err)
+ }
+ op := r.record()
+ if op == nil {
+ t.Fatal("the record went with its unit unproven")
+ }
+ r.a.mu.Lock()
+ state := op.state
+ r.a.mu.Unlock()
+ if state != releaseNotProven || !r.awake() {
+ t.Fatalf("state %d, owner awake %v; want releaseNotProven beside an awake owner", state, r.awake())
+ }
+ // The sweep's pass is its one retrier, at most every actStopTimeout.
+ n := len(r.rel.unit.stopTimes())
+ r.a.sweepOnce()
+ time.Sleep(50 * time.Millisecond)
+ if got := len(r.rel.unit.stopTimes()); got != n {
+ t.Fatalf("the sweep's pass made %d settle attempts inside actStopTimeout", got-n)
+ }
+ r.clk.advance(actStopTimeout)
+ r.a.sweepOnce()
+ waitFor(t, "the sweep's retry", func() bool { return len(r.rel.unit.stopTimes()) == n+1 })
+ if !pinned(t, r.a, r.rt.Host, "v2") {
+ t.Fatal("the pin went with the unit unproven")
+ }
+ if _, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "run_a"}); !errors.Is(err, ErrCmdBusy) {
+ t.Fatalf("RunCmd over an unproven release = %v, want ErrCmdBusy", err)
+ }
+ unstick()
+ r.clk.advance(actStopTimeout)
+ r.a.sweepOnce()
+ waitFor(t, "the reaper's proof", func() bool { return r.record() == nil })
+ waitFor(t, "the pin to leave the file", func() bool { return !pinned(t, r.a, r.rt.Host, "v2") })
+ if !r.awake() {
+ t.Fatal("the owner was stopped")
+ }
+ r.a.mu.Lock()
+ history := r.a.stopHistory[r.rt.Host]
+ r.a.mu.Unlock()
+ if history != nil {
+ t.Errorf("the proof of an owned record wrote a stop history %+v over the live owner", history)
+ }
+ h, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "run_b"})
+ if err != nil {
+ t.Fatalf("RunCmd after the proof = %v", err)
+ }
+ endRun(t, h)
+ r.fresh()
+ ch = r.start(t, context.Background())
+ r.rel.unit.done("1", "0", "success")
+ if res := wait(t, ch); res.err != nil {
+ t.Fatalf("a release after the proof = %v", res.err)
+ }
+}
+
+// captureLockedLog sends the package log to a buffer goroutines may write
+// to, for one test. Not parallel.
+func captureLockedLog(t *testing.T) *lockedBuffer {
+ t.Helper()
+ buf := &lockedBuffer{}
+ log.SetOutput(buf)
+ t.Cleanup(func() { log.SetOutput(os.Stderr) })
+ return buf
+}
+
+type lockedBuffer struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (l *lockedBuffer) Write(p []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.Write(p)
+}
+
+func (l *lockedBuffer) String() string {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.b.String()
+}
+
+// shutdownIn runs Shutdown with budget in the background; the channel
+// closes when it returns.
+func shutdownIn(a *Service, budget time.Duration) <-chan struct{} {
+ done := make(chan struct{})
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), budget)
+ defer cancel()
+ a.Shutdown(ctx)
+ close(done)
+ }()
+ return done
+}
+
+func returned(ch <-chan struct{}) bool {
+ select {
+ case <-ch:
+ return true
+ default:
+ return false
+ }
+}
+
+// INV-R2: Shutdown runs the one retry path until every record is proven or
+// its budget ends, and names each record it leaves.
+func TestShutdownDrainsReleaseOps(t *testing.T) {
+ // orphan leaves the rig's record ownerless (R3's failed wake), its
+ // entry gone and its lease owed.
+ orphan := func(t *testing.T, r *consumerRig) (unstick func(), owed *fakeLease) {
+ t.Helper()
+ unstick = stuckUnit(r.rel.unit)
+ ctx, cancel := context.WithCancel(context.Background())
+ ch := r.start(t, ctx)
+ cancel()
+ if res := wait(t, ch); !errors.Is(res.err, errReleaseUnproven) {
+ t.Fatalf("the release = %v, want errReleaseUnproven", res.err)
+ }
+ owed = &fakeLease{b: r.cb.fakeBackend}
+ r.a.mu.Lock()
+ delete(r.a.entries, r.rt.Host)
+ op := r.a.releaseOps[r.rt.Host]
+ op.owner, op.owed = nil, owed
+ r.a.mu.Unlock()
+ return unstick, owed
+ }
+
+ t.Run("an ownerless record with an owed lease", func(t *testing.T) {
+ r := newConsumerRig(t, true)
+ unstick, _ := orphan(t, r)
+ releases := r.cb.releaseCount()
+ tries := len(r.rel.unit.stopTimes())
+ r.clk.advance(actStopTimeout)
+ done := shutdownIn(r.a, 10*time.Second)
+ waitFor(t, "Shutdown's pass to retry the settle", func() bool { return len(r.rel.unit.stopTimes()) > tries })
+ time.Sleep(300 * time.Millisecond)
+ if returned(done) {
+ t.Fatal("Shutdown returned with the record unproven inside its budget")
+ }
+ unstick()
+ r.clk.advance(actStopTimeout)
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("Shutdown did not return once the record could be proven")
+ }
+ if r.record() != nil {
+ t.Fatal("Shutdown returned with the record left")
+ }
+ if got := r.cb.releaseCount(); got != releases+1 {
+ t.Fatalf("%d lease releases, want the owed lease given back once", got-releases)
+ }
+ r.a.mu.Lock()
+ history := r.a.stopHistory[r.rt.Host]
+ r.a.mu.Unlock()
+ if history == nil || !history.uncertain {
+ t.Errorf("stop history %+v, want the uncertainty kept", history)
+ }
+ })
+
+ t.Run("a stopping incumbent", func(t *testing.T) {
+ r := newConsumerRig(t, true)
+ unstick := stuckUnit(r.rel.unit)
+ ch := r.start(t, context.Background())
+ rep := r.cb.lastRep()
+ var provenAtClose atomic.Bool
+ rep.setOnClose(func() { provenAtClose.Store(r.record() == nil && r.rel.unit.isProven()) })
+ done := shutdownIn(r.a, 10*time.Second)
+ if res := wait(t, ch); !errors.Is(res.err, errReleaseUnproven) || classifyRelease(res.err, true) != releaseUnproven {
+ t.Fatalf("the release = %v, want errReleaseUnproven", res.err)
+ }
+ time.Sleep(300 * time.Millisecond)
+ if returned(done) || rep.isClosed() {
+ t.Fatalf("Shutdown returned %v, replica closed %v, with the release unproven", returned(done), rep.isClosed())
+ }
+ unstick()
+ r.clk.advance(actStopTimeout)
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("Shutdown did not return once the release was proven")
+ }
+ if !rep.isClosed() || !provenAtClose.Load() {
+ t.Fatalf("replica closed %v, the release proven at its close %v", rep.isClosed(), provenAtClose.Load())
+ }
+ })
+
+ t.Run("still unproven at the deadline", func(t *testing.T) {
+ r := newConsumerRig(t, true)
+ orphan(t, r)
+ buf := captureLockedLog(t)
+ select {
+ case <-shutdownIn(r.a, 300*time.Millisecond):
+ case <-time.After(5 * time.Second):
+ t.Fatal("Shutdown outlived its budget")
+ }
+ if r.record() == nil {
+ t.Fatal("the record went unproven")
+ }
+ out := buf.String()
+ if !strings.Contains(out, "release command(s) not proven stopped") || !strings.Contains(out, "shop.example.com (build v2)") {
+ t.Fatalf("the exit log does not name the record:\n%s", out)
+ }
+ })
+}
+
+func (u *releaseUnit) isProven() bool {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ return u.proven
+}
+
+// A stop of the owner while the release polls cancels it: its unit is
+// stopped and proven before the replica closes, and a run asked for
+// meanwhile starts no unit. Run with -race.
+func TestStopSettlesARunningRelease(t *testing.T) {
+ for _, gens := range []bool{false, true} {
+ t.Run(fmt.Sprintf("gens %v", gens), func(t *testing.T) {
+ r := newConsumerRig(t, gens)
+ var omu sync.Mutex
+ var order []string
+ note := func(s string) {
+ omu.Lock()
+ order = append(order, s)
+ omu.Unlock()
+ }
+ // The settle is held until the run has had its say, so the
+ // record is open for the run's whole admission.
+ hold := make(chan struct{})
+ r.rel.unit.settle = func(int) error { <-hold; note("release settled"); return nil }
+ ch := r.start(t, context.Background())
+ rep := r.cb.lastRep()
+ rep.setOnClose(func() { note("replica closed") })
+ var wg sync.WaitGroup
+ var runErr error
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
+ defer cancel()
+ _, runErr = r.a.RunCmd(ctx, r.rt, CmdSpec{RunID: "run_a"})
+ }()
+ go func() { defer wg.Done(); r.a.Bounce(r.rt.Host) }()
+ wg.Wait()
+ close(hold)
+ res := wait(t, ch)
+ if !errors.Is(res.err, context.Canceled) || classifyRelease(res.err, false) != releaseCancelled {
+ t.Fatalf("the release = %v, want a cancellation", res.err)
+ }
+ if runErr == nil {
+ t.Fatal("a run was admitted during the release")
+ }
+ if r.cb.cmdStarts != 0 {
+ t.Fatal("a run started its unit during the release")
+ }
+ waitFor(t, "the record to go", func() bool { return r.record() == nil })
+ r.sweepUntilGone(t)
+ omu.Lock()
+ got := slices.Clone(order)
+ omu.Unlock()
+ if want := []string{"release settled", "replica closed"}; !slices.Equal(got, want) {
+ t.Fatalf("order %q, want %q", got, want)
+ }
+ })
+ }
+}