carlos / platform Public

activator, lease: Shutdown only names unproven checkpoints (8a3d302 cut)

Release manager ruling 8a3d302 on M1 (Astra re-review items 4, 6, N1).
Shutdown no longer tears down an unproven fleet checkpoint. Its only act
is nameUnresolvedCheckpoints: a scan under a.mu alone that logs C45 once
per unresolved host (a stop's checkpoint in flight, kept pending or left;
a failed wake's first close in flight; a retained checkpoint wake) and
returns. No abandon, no store close, no cancel; the lease runs to its
TTL and renewal ends with the process. A checkpoint that answers
unproven during Shutdown is left: not retried, not waited for.

A failed fleet wake's first CloseProven is registered in
failedWakeCloses before it starts and moves to unprovenWakes in the same
critical section. C45 once-ness is a bool under a.mu (named).

lease: TryAbandon, Abandoned and syncGate are removed. No lock is held
across DB.Sync; a teardown stays terminal through mu (tornDown,
beginClose). CloseProven's outcomes (proven, unproven, lost-lease
abandon, proven-empty) are unchanged. New test seam
SetCloseProvenDBSyncHookForTest holds a checkpoint before DB.Sync.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b672e70e30623c1f4f6d736d1605edde7168309e parent 35dfd5a
6 files changed, +648 −610
  • internal/activator/activator.go +152 −193
  • internal/activator/checkpointshutdown_linux_test.go +364 −0
  • internal/activator/maintenance.go +32 −8
  • internal/activator/opset.go +24 −5
  • internal/activator/pendingwake_linux_test.go +0 −331
  • internal/lease/lease.go +76 −73

Intent

Human

<task-notification> <task-id>bx8ghly24</task-id> <tool-use-id>toolu_01VhAzEs7NXvXXCdRDVBhVdy</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ac77363b-5830-422c-9f38-d7f2540dd398/tasks/bx8ghly24.output</output-file> <status>completed</status> <summary>Background command "Run scoped M1 re-reviews by Astra and Fable" completed (exit code 0)</summary> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="52c70ccb-e62f-48bd-a736-ec374a44f54c"> Agent manager 8a3d302: A. Shutdown does a non-blocking scan, logs C45 once per unresolved host and returns; the lease runs to TTL; CloseProven stays the only release decision. It&apos;s the safe direction (no release over an unproven checkpoint) and it removes the family. One subagent fix, one Astra check of only that diff, then merge on green. Say in the spec/runbook that a shutdown during a wedged bucket leaves those hosts unavailable until the lease TTL. </paseo-system>

diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 53ecef036..2f586f16f 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -677,18 +677,16 @@ type actEntry struct {
pendingStop bool
// The fleet checkpoint's state (fleet record labels R2), under a.mu.
// checkpointBusy is true from finishStop's CloseProven until its
- // outcome has been handled (closeFleetCheckpoint), and
- // checkpointCancel cancels that call's context meanwhile;
- // checkpointUnproven marks a stop kept pending over an unproven
- // checkpoint; checkpointAbandoned marks one Shutdown abandoned when
- // its budget ended (abandonCheckpointsAtExit), which no later
- // finishStop tries again. checkpointNotice is its C45, logged once by
- // whichever call learns of the abandonment first (not under a.mu).
- checkpointBusy bool
- checkpointCancel context.CancelFunc
- checkpointUnproven bool
- checkpointAbandoned bool
- checkpointNotice abandonNotice
+ // outcome has been handled (closeFleetCheckpoint); checkpointUnproven
+ // marks a stop kept pending over an unproven checkpoint;
+ // checkpointLeft marks one whose checkpoint answered unproven during
+ // Shutdown: nothing retries it and Shutdown does not wait for it, its
+ // lease left to its TTL. checkpointNamed is set once C45 names the
+ // host (nameCheckpointLocked), so it is logged once.
+ checkpointBusy bool
+ checkpointUnproven bool
+ checkpointLeft bool
+ checkpointNamed bool
// stopRetrying is true while a retried proc.Stop call for a still-running
// pendingStop entry is in flight, so finishPendingStops does not launch a
// second one on top of it. stopRetriedAt is when the last retry was
@@ -1516,6 +1514,12 @@ type Service struct {
// the host's next wake until the sweep proves it
// (reapUnprovenWakesLocked). Under a.mu.
unprovenWakes map[string]*unprovenWake
+ // failedWakeCloses are the fleet failed wakes whose first CloseProven
+ // (cleanupFailedWake) is in flight, per host, registered before the
+ // close starts and moved to unprovenWakes, in one critical section,
+ // if it is kept. Shutdown names them (nameUnresolvedCheckpoints).
+ // Under a.mu.
+ failedWakeCloses map[string]*unprovenWake
// releaseOps are the rootfs release commands of this box (Plan 3
// Group R), one per host: each record owns its release from admission
// until its unit is proven gone, whatever happens to the entry, wake
@@ -1740,19 +1744,10 @@ type Service struct {
// It is a test seam; nil in production.
wakeReturned func(host string)
// checkpointKept, when set, is called (off a.mu) each time finishStop
- // keeps a fleet stop pending because its final checkpoint is not
- // proven (R2 of the fleet record labels spec). It is a test seam; nil
- // in production.
+ // keeps a fleet stop or failed wake over an unproven final checkpoint
+ // (R2 of the fleet record labels spec), pending or, during Shutdown,
+ // left. It is a test seam; nil in production.
checkpointKept func(host string)
- // checkpointStarted, when set, is called (off a.mu) as a fleet stop's
- // CloseProven begins (closeFleetCheckpoint), once it is registered in
- // e.checkpointCancel. It is a test seam; nil in production.
- checkpointStarted func(host string)
- // checkpointContext, when set, makes a fleet checkpoint's context from
- // finishStop's (closeFleetCheckpoint), so a test can end that budget
- // at a chosen point. It is a test seam; nil in production
- // (context.WithCancel).
- checkpointContext func(context.Context) (context.Context, context.CancelFunc)
// checkpointReturned, when set, is called (off a.mu) once a fleet
// stop's CloseProven has returned, before its outcome is handled
// (closeFleetCheckpoint). It is a test seam; nil in production.
@@ -5254,7 +5249,9 @@ func (a *Service) finishPendingStops() {
// A run whose stop was asked for and is not proven, pending stop
// or not (re-review 6).
a.retryCmdSettlesLocked(e)
- if !e.pendingStop || len(e.ops.members) > 0 || !a.respawnSettledLocked(e) {
+ // A stop left over its unproven fleet checkpoint at Shutdown is not
+ // tried again (checkpointLeft).
+ if !e.pendingStop || e.checkpointLeft || len(e.ops.members) > 0 || !a.respawnSettledLocked(e) {
continue
}
if e.proc == nil || e.proc.Exited() {
@@ -5534,15 +5531,11 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) {
// provenCloser is the optional half of Rep that a fleet stop releases
// through (fleet record labels R2): lease's *Replicator. CloseProven
-// releases only over a proven final checkpoint; TryAbandon gives the lease
-// up to its TTL and says whether it was the teardown. A Rep without it (a local demo lease, which replicates
-// nothing, or a test fake) closes with Close as before.
+// releases only over a proven final checkpoint. A Rep without it (a local
+// demo lease, which replicates nothing, or a test fake) closes with Close
+// as before.
type provenCloser interface {
CloseProven(ctx context.Context) error
- TryAbandon(ctx context.Context) bool
- // Abandoned reports whether the teardown, by whichever call, was an
- // abandonment: the lease frees at its TTL (lease.Replicator).
- Abandoned() bool
}
var _ provenCloser = (*lease.Replicator)(nil)
@@ -5587,129 +5580,100 @@ func failedWakeProvenCloser(rt registry.Route, l Lease, rep Rep) (provenCloser,
// (closeFleetCheckpoint):
//
// - proven: the lease is released, kept false and err nil;
-// - unproven, not shutting down: kept is true, C44 is logged, and the
-// caller retains the wake for the reaper, the lease held and renewing;
-// - unproven during Shutdown: the replicator is abandoned, so the lease
-// frees at its TTL, and C45 is logged through notice;
+// - unproven: kept is true, and the caller retains the wake, the lease
+// held and renewing. Outside a shutdown C44 is logged and the reaper
+// retries it; during one, u is left (u.left): nothing retries it,
+// Shutdown does not wait for it, and the lease runs to its TTL;
// - unproven over a lease whose renewal had failed: CloseProven has
-// abandoned it, and C45 is logged through notice.
+// abandoned it, and C45 names the host, once (u.named).
//
-// Any other replica closes with Close, as before.
-func (a *Service) closeFailedWakeRep(ctx context.Context, rt registry.Route, l Lease, rep Rep, notice *abandonNotice) (kept bool, err error) {
- pc, ok := failedWakeProvenCloser(rt, l, rep)
+// Any other replica closes with Close, as before. u is the wake's
+// retention, registered by the caller before this starts.
+func (a *Service) closeFailedWakeRep(ctx context.Context, u *unprovenWake) (kept bool, err error) {
+ pc, ok := failedWakeProvenCloser(u.rt, u.lease, u.rep)
if !ok {
- return false, rep.Close(ctx)
+ return false, u.rep.Close(ctx)
}
err = pc.CloseProven(ctx)
- a.mu.Lock()
- shutting := a.shuttingDown
- a.mu.Unlock()
- prefix := ""
- if shutting {
- prefix = "shutdown: "
- }
switch {
case errors.Is(err, lease.ErrCheckpointAbandoned):
- notice.name(prefix, rt.Host)
+ a.mu.Lock()
+ a.nameCheckpointLocked(&u.named, u.rt.Host)
+ a.mu.Unlock()
case errors.Is(err, lease.ErrCheckpointUnproven):
+ a.mu.Lock()
+ shutting := a.shuttingDown
+ u.left = shutting
+ a.mu.Unlock()
+ log.Printf("activator: final checkpoint %s: %v", u.rt.Host, err)
if !shutting {
- log.Printf("activator: final checkpoint %s: %v", rt.Host, err)
- logCheckpointKept(rt.Host)
- return true, err
- }
- abandonCheckpoint(pc)
- if pc.Abandoned() {
- notice.name("shutdown: ", rt.Host)
+ logCheckpointKept(u.rt.Host)
}
+ return true, err
}
return false, err
}
// closeFleetCheckpoint is finishStop's release of a fleet-placed row
// (fleet record labels R2), through CloseProven. kept reports that the
-// stop stays pending (or was already given up by Shutdown) and finishStop
-// must return; otherwise err is the release's outcome and the stop
-// finishes, unclean when err is not nil. outcome is the stop's, kept with
-// a pending stop:
+// stop stays pending (or was left at Shutdown) and finishStop must
+// return; otherwise err is the release's outcome and the stop finishes,
+// unclean when err is not nil. outcome is the stop's, kept with a pending
+// stop:
//
// - proven: the lease is released, err nil;
// - unproven, not shutting down: the stop is kept pending
// (keepPendingLocked), C44 is logged, and the sweep retries;
-// - unproven during Shutdown: the replicator is abandoned, so the lease
-// frees at its TTL, and C45 is logged;
+// - unproven during Shutdown: the stop is kept pending and left
+// (checkpointLeft): nothing retries it, Shutdown does not wait for it,
+// and the lease runs to its TTL. Shutdown names it (C45);
// - unproven over a lease whose renewal had failed: CloseProven has
-// abandoned it (lease.ErrCheckpointAbandoned), and C45 is logged.
+// abandoned it (lease.ErrCheckpointAbandoned), and C45 names the host.
//
-// C45 is logged by whichever call tore the replicator down (TryAbandon,
-// or CloseProven's own abandonment), once. While the call is in flight,
-// e.checkpointCancel registers it, so Shutdown can abandon and name it
-// when its budget ends whatever this call's own context has done
-// (abandonCheckpointsAtExit): litestream's replica sync waits for any
-// replication already in flight regardless of its context, and only
-// closing the store, which the abandonment does, cancels that.
+// While the call is in flight and until its outcome is handled,
+// e.checkpointBusy registers it, so Shutdown names it from memory if its
+// budget ends meanwhile (nameUnresolvedCheckpoints). Nothing cancels or
+// waits for the call (M1 cut, 8a3d302).
func (a *Service) closeFleetCheckpoint(ctx context.Context, e *actEntry, pc provenCloser, outcome *stopObservation) (kept bool, err error) {
a.mu.Lock()
- if e.checkpointAbandoned {
+ if e.checkpointLeft {
a.mu.Unlock()
return true, nil
}
- mk := a.checkpointContext
- if mk == nil {
- mk = context.WithCancel
- }
- cctx, cancel := mk(ctx)
- e.checkpointCancel, e.checkpointBusy = cancel, true
- started := a.checkpointStarted
+ e.checkpointBusy = true
a.mu.Unlock()
- defer cancel()
- // The checkpoint stays registered until its outcome has been handled
- // (M1 review Astra P2-2): Shutdown's exit (abandonCheckpointsAtExit)
- // then never misses it, between CloseProven's return and the pending
- // state or the abandonment below.
defer func() {
a.mu.Lock()
- e.checkpointCancel, e.checkpointBusy = nil, false
+ e.checkpointBusy = false
a.mu.Unlock()
}()
- if started != nil {
- started(e.host)
- }
- err = pc.CloseProven(cctx)
+ err = pc.CloseProven(ctx)
a.mu.Lock()
- shutting := a.shuttingDown
returned := a.checkpointReturned
a.mu.Unlock()
if returned != nil {
returned(e.host, err)
}
- prefix := ""
- if shutting {
- prefix = "shutdown: "
- }
switch {
case errors.Is(err, lease.ErrCheckpointAbandoned):
- e.checkpointNotice.name(prefix, e.host)
+ a.mu.Lock()
+ a.nameCheckpointLocked(&e.checkpointNamed, e.host)
+ a.mu.Unlock()
case errors.Is(err, lease.ErrCheckpointUnproven):
a.mu.Lock()
- shutting = a.shuttingDown
- if !shutting {
- a.keepPendingLocked(e, outcome)
- e.checkpointUnproven = true
- }
+ shutting := a.shuttingDown
+ a.keepPendingLocked(e, outcome)
+ e.checkpointUnproven, e.checkpointLeft = true, shutting
hook := a.checkpointKept
a.mu.Unlock()
+ log.Printf("activator: final checkpoint %s: %v", e.host, err)
if !shutting {
- log.Printf("activator: final checkpoint %s: %v", e.host, err)
logCheckpointKept(e.host)
- if hook != nil {
- hook(e.host)
- }
- return true, err
}
- abandonCheckpoint(pc)
- if pc.Abandoned() {
- e.checkpointNotice.name("shutdown: ", e.host)
+ if hook != nil {
+ hook(e.host)
}
+ return true, err
}
return false, err
}
@@ -5721,102 +5685,80 @@ func logCheckpointKept(host string) {
log.Printf("activator: final checkpoint for %s failed. keeping its lease until the checkpoint succeeds", host)
}
-// abandonCheckpoint gives an unproven fleet checkpoint's lease up to its
-// TTL: renewal and replication stop, nothing is released, and, under a
-// context already done, nothing more is synced (the checkpoint just
-// failed, as a crash would ship nothing more). It reports whether this
-// call tore the replicator down. Whoever names the abandonment (C45)
-// asks pc.Abandoned instead, which answers for any call's teardown.
-func abandonCheckpoint(pc provenCloser) bool {
- done, cancel := context.WithCancel(context.Background())
- cancel()
- return pc.TryAbandon(done)
-}
-
-// abandonNotice is the C45 of one abandoned fleet checkpoint (M1 review
-// Astra P2-2): every call that learns its replicator was abandoned names
-// it through the notice, which logs once. A call that comes second
-// returns only once the first has logged (sync.Once), so Shutdown, which
-// names each checkpoint it abandons or finds abandoned before it
-// returns, never returns before the line is out.
-type abandonNotice struct{ once sync.Once }
-
-// name logs C45 for host with prefix, the first time it is called.
-func (n *abandonNotice) name(prefix, host string) {
- n.once.Do(func() { logCheckpointAbandoned(prefix, host) })
+// nameCheckpointLocked logs C45 for host, unless named says it has been
+// already, and sets named: each fleet checkpoint is named once, by
+// Shutdown's scan or by the call that saw CloseProven abandon it. It logs
+// under a.mu, so Shutdown, whose scan takes a.mu, never returns before a
+// line another call has claimed is out. The caller holds a.mu.
+func (a *Service) nameCheckpointLocked(named *bool, host string) {
+ if *named {
+ return
+ }
+ *named = true
+ prefix := ""
+ if a.shuttingDown {
+ prefix = "shutdown: "
+ }
+ logCheckpointAbandoned(prefix, host)
}
-// logCheckpointAbandoned is the ERROR an abandoned fleet checkpoint logs,
-// naming the host; prefix says where ("shutdown: " or ""). It is logged
-// only through an abandonNotice.
+// logCheckpointAbandoned is the ERROR a fleet checkpoint whose lease is
+// left to its TTL logs, naming the host; prefix says where ("shutdown: "
+// or ""). It is logged only through nameCheckpointLocked.
func logCheckpointAbandoned(prefix, host string) {
// draft for copy review (C45)
log.Printf("activator: ERROR: %s%s: its final checkpoint failed, so its lease is not released and frees at its expiry", prefix, host)
}
-// abandonCheckpointsAtExit runs as Shutdown's budget ends: no unproven
-// fleet checkpoint is left renewing or unnamed when Shutdown returns.
-// Every fleet stop with a checkpoint in flight or not yet handled
-// (e.checkpointBusy), or kept pending over an unproven one, is marked
-// abandoned (so no later finishStop tries it again), its checkpoint's
-// context is cancelled, and its replicator abandoned here, whatever the
-// call in flight is waiting on. When its teardown was an abandonment, by
-// this call or any other, it is named (C45) before this returns, once in
-// all (abandonNotice). Nothing waits for the calls in flight: once
-// abandoned they hold no lease, and each finishes its entry when it
-// returns.
-func (a *Service) abandonCheckpointsAtExit() {
+// nameUnresolvedCheckpoints is Shutdown's only act on unproven fleet
+// checkpoints (fleet record labels R2; release manager ruling 8a3d302):
+// a scan of memory, under a.mu alone, that names (C45) each one still
+// unresolved, once per host. Nothing is released, abandoned, closed or
+// cancelled, and nothing here waits on litestream or the bucket; each
+// lease runs to its TTL, its renewal ending with the process, and a
+// CloseProven still in flight is left alone. Unresolved is:
+//
+// - a fleet stop whose checkpoint is in flight or not yet handled
+// (checkpointBusy), or kept pending, or left, over an unproven one
+// (checkpointUnproven);
+// - a fleet failed wake whose first close is in flight
+// (failedWakeCloses);
+// - a fleet failed wake retained over its unproven checkpoint, or whose
+// reaper close is in flight (unprovenWakes, checkpoint or closing).
+func (a *Service) nameUnresolvedCheckpoints() {
a.mu.Lock()
- var left []*actEntry
+ defer a.mu.Unlock()
for _, e := range a.entries {
- if e.checkpointAbandoned || (!e.checkpointBusy && !e.checkpointUnproven) {
- continue
- }
- e.checkpointAbandoned = true
- if e.checkpointCancel != nil {
- e.checkpointCancel()
+ if e.checkpointBusy || e.checkpointUnproven {
+ a.nameCheckpointLocked(&e.checkpointNamed, e.host)
}
- left = append(left, e)
}
- a.mu.Unlock()
- for _, e := range left {
- if pc, ok := a.fleetProvenCloser(e); ok {
- abandonCheckpoint(pc)
- if pc.Abandoned() {
- e.checkpointNotice.name("shutdown: ", e.host)
- }
- }
+ for host, u := range a.failedWakeCloses {
+ a.nameCheckpointLocked(&u.named, host)
}
- // A failed wake retained over its unproven fleet checkpoint, or whose
- // reaper is closing it, is abandoned and named the same way (M1
- // review Fable P2-1), and forgotten: nothing more is owed, and its
- // lease frees at its TTL.
- a.mu.Lock()
- var wakes []*unprovenWake
for host, u := range a.unprovenWakes {
- if !u.checkpoint && !u.closing {
- continue
- }
- if _, ok := failedWakeProvenCloser(u.rt, u.lease, u.rep); !ok {
- continue
+ if checkpointWake(u) {
+ a.nameCheckpointLocked(&u.named, host)
}
- delete(a.unprovenWakes, host)
- wakes = append(wakes, u)
}
- a.mu.Unlock()
- for _, u := range wakes {
- pc, _ := failedWakeProvenCloser(u.rt, u.lease, u.rep)
- abandonCheckpoint(pc)
- if pc.Abandoned() {
- u.notice.name("shutdown: ", u.rt.Host)
- }
+}
+
+// checkpointWake reports whether a retained failed wake owes only its
+// fleet replica's proven final checkpoint, or has a reaper close of it in
+// flight: Shutdown names it (C45), not as a failed wake not proven
+// stopped. The caller holds a.mu.
+func checkpointWake(u *unprovenWake) bool {
+ if !u.checkpoint && !u.closing {
+ return false
}
+ _, fleet := failedWakeProvenCloser(u.rt, u.lease, u.rep)
+ return fleet
}
// exitUnresolved is Shutdown's return once its budget has ended: unproven
-// fleet checkpoints abandoned and named, then the rest named.
+// fleet checkpoints named, then the rest.
func (a *Service) exitUnresolved() {
- a.abandonCheckpointsAtExit()
+ a.nameUnresolvedCheckpoints()
a.logUnresolvedAtExit()
}
@@ -6677,15 +6619,15 @@ func (a *Service) Shutdown(ctx context.Context) {
// process that finally exits during shutdown still gets its final
// checkpoint instead of being abandoned mid-drain.
a.finishPendingStops()
- var waits []chan struct{}
+ var waits []*actEntry
var waking []*actEntry
for _, e := range a.entries {
switch e.state {
case actAwake:
a.beginStopLocked(e, StopShutdown)
- waits = append(waits, e.stopped)
+ waits = append(waits, e)
case actStopping:
- waits = append(waits, e.stopped)
+ waits = append(waits, e)
case actWaking:
// Shutdown covers waking entries too (zero-downtime spec §7.4),
// whatever CARLOS_SWAP says. The wake is cancelled, and once it
@@ -6734,17 +6676,26 @@ func (a *Service) Shutdown(ctx context.Context) {
}
a.mu.Lock()
if a.entries[e.host] == e && e.state == actStopping {
- waits = append(waits, e.stopped)
+ waits = append(waits, e)
}
a.mu.Unlock()
}
- for _, w := range waits {
- for done := false; !done; {
+ // A stop left over its unproven fleet checkpoint (checkpointLeft) is
+ // not waited for: nothing more will happen to it before the process
+ // exits, and its lease runs to its TTL (M1 cut, 8a3d302).
+ left := func(e *actEntry) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return e.checkpointLeft
+ }
+ for _, e := range waits {
+ for done := left(e); !done; {
select {
- case <-w:
+ case <-e.stopped:
done = true
case <-poll.C:
pollPending()
+ done = left(e)
case <-ctx.Done():
a.exitUnresolved()
return
@@ -6774,14 +6725,19 @@ func (a *Service) Shutdown(ctx context.Context) {
// 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.
+ //
+ // A failed wake left over its unproven fleet checkpoint (u.left) is not
+ // waited for either. Whatever ends Shutdown, its last act on fleet
+ // checkpoints is to name the unresolved ones (nameUnresolvedCheckpoints).
for {
a.mu.Lock()
- left := len(a.unprovenWakes) + len(a.owedReleases) + len(a.releaseOps)
- if left > 0 {
+ owed := a.unprovenWakesOwedLocked() + len(a.owedReleases) + len(a.releaseOps)
+ if owed > 0 {
a.finishPendingStops()
}
a.mu.Unlock()
- if left == 0 {
+ if owed == 0 {
+ a.nameUnresolvedCheckpoints()
return
}
select {
@@ -6826,6 +6782,9 @@ func (a *Service) logUnresolvedAtExit() {
var held, owed, releasing []string
workers := a.workerStraysAtExitLocked()
for host, u := range a.unprovenWakes {
+ if checkpointWake(u) {
+ continue // named by C45 (nameUnresolvedCheckpoints)
+ }
held = append(held, fmt.Sprintf("%s (generation %d)", host, u.gen.N))
}
for o := range a.owedReleases {
diff --git a/internal/activator/checkpointshutdown_linux_test.go b/internal/activator/checkpointshutdown_linux_test.go
new file mode 100644
index 000000000..b3de9d9ef
--- /dev/null
+++ b/internal/activator/checkpointshutdown_linux_test.go
@@ -0,0 +1,364 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Fleet record labels R2 at shutdown (release manager ruling 8a3d302, the
+// M1 cut). Shutdown never tears down an unproven fleet checkpoint: no
+// abandonment, no store close, and nothing on its path that can wait on
+// litestream or the bucket. It names every checkpoint still unresolved
+// (C45, once per host) from memory and returns; the lease runs to its TTL,
+// and a CloseProven still in flight is left alone.
+
+// holdCloseProven holds the next CloseProven at the seam set installs
+// (lease.SetCloseProvenDBSyncHookForTest or
+// lease.SetCloseProvenReplicaSyncHookForTest): entered closes once a call
+// is held there, and it goes on once release is called, at the latest as
+// the test ends. Later calls pass.
+func holdCloseProven(t *testing.T, set func(func()) func()) (entered chan struct{}, release func()) {
+ t.Helper()
+ entered, gate := make(chan struct{}), make(chan struct{})
+ var once, closeOnce sync.Once
+ release = func() { closeOnce.Do(func() { close(gate) }) }
+ t.Cleanup(set(func() {
+ held := false
+ once.Do(func() { held = true })
+ if held {
+ close(entered)
+ <-gate
+ }
+ }))
+ t.Cleanup(release) // runs first: the held call goes on before the seam goes
+ return entered, release
+}
+
+// awaitCh waits for ch to close or receive; the timeout is only a
+// deadlock watchdog.
+func awaitCh[T any](t *testing.T, ch <-chan T, what string) {
+ t.Helper()
+ select {
+ case <-ch:
+ case <-time.After(30 * time.Second):
+ t.Fatal(what)
+ }
+}
+
+// exitAtEnd abandons rep when the test ends, as the agent's exit ends its
+// renewal: Shutdown leaves it running. Registered before any hold, so it
+// runs after the held call has gone on.
+func exitAtEnd(t *testing.T, rep Rep) {
+ t.Helper()
+ ab, ok := rep.(interface{ Abandon(context.Context) })
+ if !ok {
+ t.Fatalf("the replica is %T", rep)
+ }
+ t.Cleanup(func() {
+ done, cancel := context.WithCancel(context.Background())
+ cancel()
+ ab.Abandon(done)
+ })
+}
+
+// assertLockKept checks lock.json is still in the bucket and was never
+// DELETEd.
+func (r *checkpointRig) assertLockKept(t *testing.T) {
+ t.Helper()
+ if r.fx.LockBody(r.prefix) == nil {
+ t.Fatal("lock.json is gone: the lease was released over an unproven checkpoint")
+ }
+ lockKey := r.prefix + "/lock.json"
+ for _, req := range r.fx.Requests() {
+ if req == "DELETE "+lockKey {
+ t.Fatal("lock.json was DELETEd over an unproven checkpoint")
+ }
+ }
+}
+
+// assertLeftToTTL checks Shutdown left the checkpoint's lease to its TTL
+// without tearing anything down: lock.json kept and never DELETEd, and the
+// replicator still renewing (Shutdown neither abandoned nor closed it).
+func (r *checkpointRig) assertLeftToTTL(t *testing.T, rep Rep) {
+ t.Helper()
+ r.assertLockKept(t)
+ if err := rep.Err(); err != nil {
+ t.Fatalf("the replicator no longer renews after Shutdown (%v): Shutdown tore it down", err)
+ }
+}
+
+// assertC45Once checks C45 names the host at shutdown, once, and that no
+// other C45 was logged.
+func (r *checkpointRig) assertC45Once(t *testing.T) {
+ t.Helper()
+ logged := r.log.String()
+ if n := strings.Count(logged, "activator: ERROR: shutdown: "+r.rt.Host+": "+c45Text); n != 1 {
+ t.Fatalf("C45 naming %s at shutdown logged %d times, want once:\n%s", r.rt.Host, n, logged)
+ }
+ if n := strings.Count(logged, c45Text); n != 1 {
+ t.Fatalf("C45 logged %d times in all, want once:\n%s", n, logged)
+ }
+}
+
+// A stop's checkpoint is in flight (held before its replica sync) when
+// Shutdown's budget ends: Shutdown names it and returns while the call is
+// still held, the lease left as it is. Let go, the call carries on by
+// itself.
+func TestShutdownNamesAStopWhoseCheckpointIsInFlight(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ e := r.wake(t)
+ rep := e.rep
+ exitAtEnd(t, rep)
+ appendRow(t, r.rt.DBPath)
+ entered, release := holdCloseProven(t, lease.SetCloseProvenReplicaSyncHookForTest)
+ stopped := r.stop(e)
+ awaitCh(t, entered, "the stop's checkpoint never reached its replica sync")
+ r.shutdownSpent(t)
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ release()
+ awaitCh(t, stopped, "the stop never finished once its checkpoint went on")
+ r.assertC45Once(t)
+}
+
+// M1 review Astra N1: litestream's DB.Sync waits for the database's exec
+// lock, which the background monitor can hold while it waits on a bucket
+// LIST. A checkpoint held there (the seam stands in for that wait) must
+// not keep Shutdown: nothing on its path waits for the sync. Shutdown
+// returns before the hold is let go, and names the host.
+func TestShutdownReturnsWhileACheckpointsDatabaseSyncIsHeld(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ e := r.wake(t)
+ rep := e.rep
+ exitAtEnd(t, rep)
+ appendRow(t, r.rt.DBPath)
+ entered, release := holdCloseProven(t, lease.SetCloseProvenDBSyncHookForTest)
+ stopped := r.stop(e)
+ awaitCh(t, entered, "the stop's checkpoint never reached its database sync")
+ r.shutdownSpent(t)
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ release()
+ awaitCh(t, stopped, "the stop never finished once its database sync went on")
+ r.assertC45Once(t)
+}
+
+// A stop kept pending over an unproven checkpoint is retried, and the
+// retry is held, when Shutdown's budget ends: Shutdown names it once and
+// returns. The retry, let go, answers unproven again and is left (the
+// lease to its TTL), with no second C45 and no C44.
+func TestShutdownNamesAStopKeptPendingOverItsCheckpoint(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ e := r.wake(t)
+ rep := e.rep
+ exitAtEnd(t, rep)
+ t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
+ appendRow(t, r.rt.DBPath)
+ r.stop(e)
+ awaitCh(t, r.kept, "the stop was never kept pending")
+ entered, release := holdCloseProven(t, lease.SetCloseProvenReplicaSyncHookForTest)
+ r.a.sweepOnce() // the retry
+ awaitCh(t, entered, "the sweep never retried the checkpoint")
+ r.shutdownSpent(t)
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ release()
+ awaitCh(t, r.kept, "the retry was not left over its unproven checkpoint")
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ if n := strings.Count(r.log.String(), c44Line); n != 1 {
+ t.Fatalf("C44 logged %d times, want once (before Shutdown):\n%s", n, r.log.String())
+ }
+}
+
+// A failed fleet wake's first close (cleanupFailedWake) is in flight,
+// held, when Shutdown's budget ends (M1 review Astra item 4): it is
+// registered before it starts, so Shutdown names it and returns while it
+// is held.
+func TestShutdownNamesAFailedWakeWhoseFirstCloseIsInFlight(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ var rep signalRep
+ r.a.retainDB = func(ctx context.Context, rt registry.Route, l Lease) (Rep, error) {
+ got, err := retainDatabase(ctx, rt, l)
+ if err != nil {
+ return got, err
+ }
+ rep = signalRep{Replicator: got.(*lease.Replicator), closed: make(chan error, 8)}
+ appendRow(t, rt.DBPath) // the boot's write
+ return rep, errors.New("the wake failed after its replica started")
+ }
+ entered, release := holdCloseProven(t, lease.SetCloseProvenReplicaSyncHookForTest)
+ woke := make(chan error, 1)
+ go func() {
+ _, err := r.a.beginRequest(context.Background(), r.rt)
+ woke <- err
+ }()
+ awaitCh(t, entered, "the failed wake's close never reached its replica sync")
+ r.shutdownSpent(t)
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ release()
+ if err := closedWith(t, rep.closed, "failed wake"); err != nil {
+ t.Fatalf("the failed wake's close, let go over a healthy bucket = %v, want proven", err)
+ }
+ awaitCh(t, woke, "the failed wake never returned")
+ r.assertC45Once(t)
+}
+
+// A failed wake kept over its unproven checkpoint (reapUnprovenWake) is
+// retried, and the retry is held, when Shutdown's budget ends: Shutdown
+// names it once and returns. The retry, let go, answers unproven and is
+// left, the wake still retained.
+func TestShutdownNamesAReapedWakeKeptUnproven(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ rep, _ := r.retainedCheckpoint(t)
+ exitAtEnd(t, rep.Replicator)
+ r.a.sweepOnce()
+ if err := closedWith(t, rep.closed, "reaper"); !errors.Is(err, lease.ErrCheckpointUnproven) {
+ t.Fatalf("the reaper's close = %v, want an unproven checkpoint (CloseProven)", err)
+ }
+ r.assertCheckpointKept(t, rep)
+ entered, release := holdCloseProven(t, lease.SetCloseProvenReplicaSyncHookForTest)
+ r.a.sweepOnce() // the retry
+ awaitCh(t, entered, "the reaper never retried the checkpoint")
+ r.shutdownSpent(t)
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ release()
+ if err := closedWith(t, rep.closed, "reaper retry"); !errors.Is(err, lease.ErrCheckpointUnproven) {
+ t.Fatalf("the reaper's retry = %v, want an unproven checkpoint", err)
+ }
+ awaitCh(t, r.kept, "the retry was not left over its unproven checkpoint")
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ r.a.mu.Lock()
+ u := r.a.unprovenWakes[r.rt.Host]
+ r.a.mu.Unlock()
+ if u == nil {
+ t.Fatal("the failed wake is no longer retained")
+ }
+}
+
+// Shutdown begins a fleet stop whose checkpoint answers unproven: the stop
+// is left, not torn down, and Shutdown returns within its budget without
+// waiting on it, the host named (C45) and the lease left to its TTL.
+func TestShutdownLeavesAnUnprovenStopToItsTTL(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ e := r.wake(t)
+ rep := e.rep
+ exitAtEnd(t, rep)
+ t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
+ appendRow(t, r.rt.DBPath)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ r.a.Shutdown(ctx)
+ if ctx.Err() != nil {
+ t.Fatalf("Shutdown ran out of time waiting on an unproven checkpoint:\n%s", r.log.String())
+ }
+ r.a.mu.Lock()
+ p := e.proc
+ r.a.mu.Unlock()
+ if !p.Exited() {
+ t.Fatal("the process is still running")
+ }
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ if strings.Contains(r.log.String(), c44Line) {
+ t.Fatalf("Shutdown claimed to keep the lease until the checkpoint succeeds:\n%s", r.log.String())
+ }
+}
+
+// Shutdown with a failed wake kept over its unproven checkpoint: the
+// reaper's retry answers unproven and the wake is left, so Shutdown returns
+// within its budget, the host named and the lease left to its TTL.
+func TestShutdownLeavesAFailedWakesUnprovenCheckpoint(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ rep, _ := r.retainedCheckpoint(t)
+ exitAtEnd(t, rep.Replicator)
+ r.a.sweepOnce()
+ if err := closedWith(t, rep.closed, "reaper"); !errors.Is(err, lease.ErrCheckpointUnproven) {
+ t.Fatalf("the reaper's close = %v, want an unproven checkpoint (CloseProven)", err)
+ }
+ r.assertCheckpointKept(t, rep)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ r.a.Shutdown(ctx)
+ if ctx.Err() != nil {
+ t.Fatalf("Shutdown ran out of time waiting on an unproven checkpoint:\n%s", r.log.String())
+ }
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+}
+
+// A stop's CloseProven has answered unproven and its handling is held when
+// Shutdown's budget ends: Shutdown names it from memory and returns. The
+// handling, let go, leaves the stop without a second C45, and without C44.
+func TestShutdownNamesACheckpointBeforeItsOutcomeIsHandled(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ e := r.wake(t)
+ rep := e.rep
+ exitAtEnd(t, rep)
+ t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
+ appendRow(t, r.rt.DBPath)
+ returned, release := r.holdCheckpointReturn(t)
+ r.stop(e)
+ select {
+ case err := <-returned:
+ if !errors.Is(err, lease.ErrCheckpointUnproven) {
+ t.Fatalf("CloseProven = %v, want ErrCheckpointUnproven", err)
+ }
+ case <-time.After(30 * time.Second):
+ t.Fatalf("the stop's checkpoint never returned:\n%s", r.log.String())
+ }
+ r.shutdownSpent(t)
+ r.assertLeftToTTL(t, rep)
+ r.assertC45Once(t)
+ release()
+ awaitCh(t, r.kept, "the stop was not left once its handling went on")
+ r.assertC45Once(t)
+ if strings.Contains(r.log.String(), c44Line) {
+ t.Fatalf("C44 promised to keep a lease Shutdown left to its TTL:\n%s", r.log.String())
+ }
+}
+
+// CloseProven over a lost lease abandons the replicator itself (its
+// unchanged outcome), and its handling, which names it, is held when
+// Shutdown's budget ends: C45 is logged once in all, whichever names it,
+// and the lock is never released.
+func TestShutdownNamesALostLeaseAbandonmentOnce(t *testing.T) {
+ r := newCheckpointRig(t, registry.PlacementTarget("pi"))
+ e := r.wake(t)
+ t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
+ appendRow(t, r.rt.DBPath)
+ rep, ok := e.rep.(*lease.Replicator)
+ if !ok {
+ t.Fatalf("the entry's replica is %T", e.rep)
+ }
+ lockKey := r.prefix + "/lock.json"
+ r.fx.FailNextMatching("PUT", 403, func(k string, _ []byte) bool { return k == lockKey })
+ lease.LoseLeaseForTest(rep, errors.New("renewal: AccessDenied"))
+ returned, release := r.holdCheckpointReturn(t)
+ stopped := r.stop(e)
+ select {
+ case err := <-returned:
+ if !errors.Is(err, lease.ErrCheckpointAbandoned) {
+ t.Fatalf("CloseProven = %v, want ErrCheckpointAbandoned", err)
+ }
+ case <-time.After(30 * time.Second):
+ t.Fatalf("the stop's checkpoint never returned:\n%s", r.log.String())
+ }
+ r.shutdownSpent(t)
+ r.assertLockKept(t)
+ r.assertC45Once(t)
+ release()
+ awaitCh(t, stopped, "the stop never finished once its handling went on")
+ r.assertLockKept(t)
+ r.assertC45Once(t)
+}
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go
index 00431bb33..a475a7804 100644
--- a/internal/activator/maintenance.go
+++ b/internal/activator/maintenance.go
@@ -489,18 +489,42 @@ func (a *Service) cleanupFailedWake(ctx context.Context, e *actEntry, rt registr
defer closeCancel()
// A fleet replica's release proves its final checkpoint first
// (fleet record labels R2, M1 review Fable P2-1): the wake may
- // have written (boot migrations) before it failed. Unproven
- // outside a shutdown, the wake is retained as an unproven one,
- // its lease held and renewing, and the reaper retries the
- // checkpoint alone; at shutdown it is abandoned to its TTL.
+ // have written (boot migrations) before it failed. Unproven, the
+ // wake is retained as an unproven one, its lease held and
+ // renewing: outside a shutdown the reaper retries the checkpoint
+ // alone; during one it is left to its TTL. A fleet close is
+ // registered before it starts (failedWakeCloses, M1 review Astra
+ // item 4), so Shutdown names it (C45) if its budget ends while the
+ // close is in flight, and it moves to unprovenWakes in the same
+ // critical section that unregisters it.
u := &unprovenWake{rt: rt, gen: w.gen, proc: w.proc, lease: lease, rep: w.rep, build: w.spawnIdentity,
layout: w.launchLayout, checkpoint: true}
- kept, err := a.closeFailedWakeRep(closeCtx, rt, lease, w.rep, &u.notice)
- if kept {
- a.retainUnprovenWake(u)
+ _, fleet := failedWakeProvenCloser(rt, lease, w.rep)
+ if fleet {
a.mu.Lock()
- hook := a.checkpointKept
+ if a.failedWakeCloses == nil {
+ a.failedWakeCloses = make(map[string]*unprovenWake)
+ }
+ u.closing = true
+ a.failedWakeCloses[rt.Host] = u
a.mu.Unlock()
+ }
+ kept, err := a.closeFailedWakeRep(closeCtx, u)
+ a.mu.Lock()
+ if fleet && a.failedWakeCloses[rt.Host] == u {
+ delete(a.failedWakeCloses, rt.Host)
+ }
+ u.closing = false
+ var hook func(string)
+ if kept {
+ if a.unprovenWakes == nil {
+ a.unprovenWakes = make(map[string]*unprovenWake)
+ }
+ a.unprovenWakes[rt.Host] = u
+ hook = a.checkpointKept
+ }
+ a.mu.Unlock()
+ if kept {
if hook != nil {
hook(rt.Host)
}
diff --git a/internal/activator/opset.go b/internal/activator/opset.go
index efcc0bad0..420c749c3 100644
--- a/internal/activator/opset.go
+++ b/internal/activator/opset.go
@@ -798,11 +798,15 @@ type unprovenWake struct {
// checkpoint: the generation is proven stopped, and only the fleet
// replica's proven final checkpoint is owed (fleet record labels R2,
// M1 review Fable P2-1): the reaper retries its CloseProven alone.
- // closing marks a reaper's CloseProven in flight. Both under a.mu.
- // notice is its C45, logged once (abandonNotice).
+ // closing marks a CloseProven of it in flight (the reaper's, or the
+ // first, cleanupFailedWake's). left marks one kept during Shutdown:
+ // nothing retries it and Shutdown does not wait for it, its lease left
+ // to its TTL. named is set once C45 names the host
+ // (nameCheckpointLocked). All under a.mu.
checkpoint bool
closing bool
- notice abandonNotice
+ left bool
+ named bool
}
// errWakeUnproven refuses a wake while the host's last failed wake is not
@@ -863,11 +867,26 @@ func (a *Service) failedWakeStopped(rt registry.Route, g Gen, p Proc, launched L
return true
}
+// unprovenWakesOwedLocked counts the retained failed wakes Shutdown still
+// waits for: all but those left over an unproven fleet checkpoint
+// (u.left), which nothing retries. The caller holds a.mu.
+func (a *Service) unprovenWakesOwedLocked() int {
+ n := 0
+ for _, u := range a.unprovenWakes {
+ if !u.left {
+ n++
+ }
+ }
+ return n
+}
+
// reapUnprovenWakesLocked retries each unproven failed wake's proof and,
// once it holds, gives the lease back. The caller holds a.mu.
func (a *Service) reapUnprovenWakesLocked() {
for host, u := range a.unprovenWakes {
- if u.busy {
+ // A wake left over its unproven checkpoint at Shutdown is not
+ // tried again (u.left).
+ if u.busy || u.left {
continue
}
// A legacy start's failed wake records its outcome as its entry
@@ -944,7 +963,7 @@ func (a *Service) reapUnprovenWake(host string, u *unprovenWake) {
a.mu.Lock()
u.closing = true
a.mu.Unlock()
- kept, err = a.closeFailedWakeRep(ctx, u.rt, u.lease, u.rep, &u.notice)
+ kept, err = a.closeFailedWakeRep(ctx, u)
if kept {
cancel()
a.mu.Lock()
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go
index b61a37849..51dd43b73 100644
--- a/internal/activator/pendingwake_linux_test.go
+++ b/internal/activator/pendingwake_linux_test.go
@@ -1628,40 +1628,6 @@ func TestFleetStopOfAnUnsyncedDatabaseStaysPending(t *testing.T) {
}
}
-// At shutdown an unproven checkpoint is not released: the replicator is
-// abandoned, so the lease runs to its TTL, and an ERROR names the host.
-func TestShutdownWithUnprovenCheckpointLeavesLeaseToTTL(t *testing.T) {
- r := newCheckpointRig(t, registry.PlacementTarget("pi"))
- e := r.wake(t)
- t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
- appendRow(t, r.rt.DBPath)
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- r.a.Shutdown(ctx)
- if ctx.Err() != nil {
- t.Fatal("Shutdown ran out of time instead of leaving the lease to its TTL")
- }
- r.a.mu.Lock()
- left, p, rep := len(r.a.entries), e.proc, e.rep
- r.a.mu.Unlock()
- if left != 0 || !p.Exited() {
- t.Fatalf("Shutdown left %d entries (process exited %v)", left, p.Exited())
- }
- if r.fx.LockBody(r.prefix) == nil {
- t.Fatal("Shutdown released the lease over an unproven checkpoint")
- }
- if rep.Err() == nil {
- t.Fatal("the abandoned lease still reports itself held: its renewal did not stop")
- }
- logged := r.log.String()
- if !strings.Contains(logged, "ERROR") || !strings.Contains(logged, "shutdown: "+r.rt.Host) {
- t.Fatalf("no ERROR naming %s in the log:\n%s", r.rt.Host, logged)
- }
- if strings.Contains(logged, c44Line) {
- t.Fatalf("Shutdown claimed to keep the lease until the checkpoint succeeds:\n%s", logged)
- }
-}
-
// A platform-region row's stop is unchanged: its final sync failing still
// releases the lease, as Close always has.
func TestPlatformRegionStopUnchanged(t *testing.T) {
@@ -1741,177 +1707,6 @@ func TestFleetStopWithLostLeaseFinishesUncleanWithoutRelease(t *testing.T) {
}
}
-// R2 review fix: a stop already pending over an unproven checkpoint when
-// Shutdown begins is retried once more; that retry blocks in the bucket,
-// and Shutdown's budget ends. Shutdown cancels the checkpoint, abandons
-// the replicator (lock.json kept, renewal stopped) and logs the ERROR
-// before it returns.
-func TestShutdownAbandonsAPendingCheckpointBlockedInTheBucket(t *testing.T) {
- r := newCheckpointRig(t, registry.PlacementTarget("pi"))
- e := r.wake(t)
- heal := r.fx.FailReplicaPuts(r.prefix)
- appendRow(t, r.rt.DBPath)
- r.stop(e)
- select {
- case <-r.kept:
- case <-time.After(30 * time.Second):
- t.Fatalf("the stop was never kept pending:\n%s", r.log.String())
- }
-
- // The retry's replica PUT is held in the bucket until the test ends.
- lockKey := r.prefix + "/lock.json"
- entered, hold := make(chan struct{}), make(chan struct{})
- var once sync.Once
- t.Cleanup(func() { close(hold) }) // before the fixture's server closes
- r.fx.BeforeWrite(func(method, key string) {
- if method == "PUT" && strings.HasPrefix(key, r.prefix+"/") && key != lockKey {
- once.Do(func() { close(entered) })
- <-hold
- }
- })
- retrying := make(chan struct{}, 1)
- r.a.mu.Lock()
- r.a.checkpointStarted = func(string) {
- select {
- case retrying <- struct{}{}:
- default:
- }
- }
- r.a.mu.Unlock()
- heal()
-
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- returned := make(chan struct{})
- go func() {
- r.a.Shutdown(ctx)
- close(returned)
- }()
- // Both before the budget ends: Shutdown's retry is in flight
- // (checkpointStarted), and a replica PUT is held in the bucket, so the
- // retry's sync cannot finish (every replica PUT, its own or the one it
- // waits behind, is held).
- for _, ch := range []chan struct{}{retrying, entered} {
- select {
- case <-ch:
- case <-returned:
- t.Fatalf("Shutdown returned before the pending checkpoint was retried:\n%s", r.log.String())
- case <-time.After(30 * time.Second):
- t.Fatal("Shutdown never retried the pending checkpoint into the bucket")
- }
- }
- cancel() // the budget ends with the retry blocked
- select {
- case <-returned:
- case <-time.After(30 * time.Second):
- t.Fatal("Shutdown did not return once its budget ended")
- }
- if r.fx.LockBody(r.prefix) == nil {
- t.Fatal("Shutdown released the lease over an unproven checkpoint")
- }
- if err := e.rep.Err(); err == nil {
- t.Fatal("the lease still renews after Shutdown returned: it was not abandoned")
- }
- if logged := r.log.String(); !strings.Contains(logged, "activator: ERROR: shutdown: "+r.rt.Host+": its final checkpoint failed, so its lease is not released and frees at its expiry") {
- t.Fatalf("no ERROR naming %s before Shutdown returned:\n%s", r.rt.Host, logged)
- }
-}
-
-// R2 review fix round 2 (Astra): the checkpoint's own budget ends while
-// its sync is still blocked, and only then does Shutdown run, with its
-// budget already over. litestream's replica sync waits behind the
-// replication already in flight (here the background monitor's PUT, held
-// in the bucket under the monitor's own context) whatever the checkpoint's
-// context says, so the call stays in flight. Shutdown must still abandon
-// it (lock.json kept, renewal stopped) and log C45 before it returns.
-func TestShutdownAbandonsACheckpointWhoseOwnBudgetEnded(t *testing.T) {
- r := newCheckpointRig(t, registry.PlacementTarget("pi"))
- e := r.wake(t)
- heal := r.fx.FailReplicaPuts(r.prefix)
- appendRow(t, r.rt.DBPath)
- r.stop(e)
- select {
- case <-r.kept:
- case <-time.After(30 * time.Second):
- t.Fatalf("the stop was never kept pending:\n%s", r.log.String())
- }
-
- // Every replica PUT is held in the bucket until the test ends.
- lockKey := r.prefix + "/lock.json"
- entered, hold := make(chan struct{}), make(chan struct{})
- var once sync.Once
- t.Cleanup(func() { close(hold) }) // before the fixture's server closes
- r.fx.BeforeWrite(func(method, key string) {
- if method == "PUT" && strings.HasPrefix(key, r.prefix+"/") && key != lockKey {
- once.Do(func() { close(entered) })
- <-hold
- }
- })
- heal()
- // The background monitor ships the pending write next: its PUT is the
- // one held, under the replica's sync lock, before any retry starts.
- select {
- case <-entered:
- case <-time.After(30 * time.Second):
- t.Fatal("the replica monitor never retried the pending write")
- }
-
- // The retry: its budget is the test's to end, and it reports reaching
- // its replica sync, which waits behind the monitor's held PUT.
- budgets := make(chan context.CancelFunc, 1)
- atReplicaSync := make(chan struct{}, 1)
- r.a.mu.Lock()
- r.a.checkpointContext = func(p context.Context) (context.Context, context.CancelFunc) {
- c, cancel := context.WithCancel(p)
- budgets <- cancel
- return c, cancel
- }
- r.a.mu.Unlock()
- t.Cleanup(lease.SetCloseProvenReplicaSyncHookForTest(func() {
- select {
- case atReplicaSync <- struct{}{}:
- default:
- }
- }))
- r.a.sweepOnce()
- var endBudget context.CancelFunc
- select {
- case endBudget = <-budgets:
- case <-time.After(30 * time.Second):
- t.Fatal("the sweep never retried the checkpoint")
- }
- select {
- case <-atReplicaSync:
- case <-r.kept:
- t.Fatalf("the retry failed before its replica sync:\n%s", r.log.String())
- case <-time.After(30 * time.Second):
- t.Fatal("the retry never reached its replica sync")
- }
- endBudget() // the checkpoint's own budget ends; the call stays blocked
-
- ctx, cancel := context.WithCancel(context.Background())
- cancel() // Shutdown's budget is already over
- returned := make(chan struct{})
- go func() {
- r.a.Shutdown(ctx)
- close(returned)
- }()
- select {
- case <-returned:
- case <-time.After(30 * time.Second):
- t.Fatal("Shutdown did not return: the blocked checkpoint kept it waiting")
- }
- if r.fx.LockBody(r.prefix) == nil {
- t.Fatal("the lease was released over an unproven checkpoint")
- }
- if err := e.rep.Err(); err == nil {
- t.Fatal("the lease still renews after Shutdown returned: it was not abandoned")
- }
- if logged := r.log.String(); !strings.Contains(logged, "activator: ERROR: shutdown: "+r.rt.Host+": its final checkpoint failed, so its lease is not released and frees at its expiry") {
- t.Fatalf("no C45 ERROR naming %s before Shutdown returned:\n%s", r.rt.Host, logged)
- }
-}
-
// c45Text is the body of C45, the ERROR an abandoned fleet checkpoint
// logs, whatever its prefix.
const c45Text = "its final checkpoint failed, so its lease is not released and frees at its expiry"
@@ -1957,96 +1752,6 @@ func (r *checkpointRig) shutdownSpent(t *testing.T) {
}
}
-// M1 review Astra P2-2 (a): a fleet stop's checkpoint stays registered
-// until its outcome is handled. Its CloseProven has answered unproven and
-// its handling is held when Shutdown runs out of budget: Shutdown must
-// still abandon it (lock.json kept, renewal stopped) and name it (C45)
-// before it returns, and the handling, once let go, does not name it again.
-func TestShutdownAbandonsACheckpointBeforeItsOutcomeIsHandled(t *testing.T) {
- r := newCheckpointRig(t, registry.PlacementTarget("pi"))
- e := r.wake(t)
- t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
- appendRow(t, r.rt.DBPath)
- returned, release := r.holdCheckpointReturn(t)
- stopped := r.stop(e)
- select {
- case err := <-returned:
- if !errors.Is(err, lease.ErrCheckpointUnproven) {
- t.Fatalf("CloseProven = %v, want ErrCheckpointUnproven", err)
- }
- case <-time.After(30 * time.Second):
- t.Fatalf("the stop's checkpoint never returned:\n%s", r.log.String())
- }
- r.shutdownSpent(t)
- if r.fx.LockBody(r.prefix) == nil {
- t.Fatal("the lease was released over an unproven checkpoint")
- }
- r.a.mu.Lock()
- rep := e.rep
- r.a.mu.Unlock()
- if err := rep.Err(); err == nil {
- t.Fatal("the lease still renews after Shutdown returned: it was not abandoned")
- }
- if n := strings.Count(r.log.String(), c45Text); n != 1 {
- t.Fatalf("C45 logged %d times before Shutdown returned, want once:\n%s", n, r.log.String())
- }
- release()
- select {
- case <-stopped:
- case <-time.After(30 * time.Second):
- t.Fatal("the stop never finished once its handling went on")
- }
- logged := r.log.String()
- if n := strings.Count(logged, c45Text); n != 1 {
- t.Fatalf("C45 logged %d times, want once:\n%s", n, logged)
- }
- if strings.Contains(logged, c44Line) {
- t.Fatalf("C44 promised to keep a lease Shutdown gave up:\n%s", logged)
- }
-}
-
-// M1 review Astra P2-2 (b): C45 has one owner, and Shutdown completes it.
-// CloseProven over a lost lease abandons the replicator itself (the
-// teardown claimed) and its handling, which names it, is held: Shutdown,
-// whose own abandonment finds the teardown already claimed, must still
-// see C45 logged before it returns, and only once in all.
-func TestShutdownNamesAnAbandonmentClaimedElsewhere(t *testing.T) {
- r := newCheckpointRig(t, registry.PlacementTarget("pi"))
- e := r.wake(t)
- t.Cleanup(r.fx.FailReplicaPuts(r.prefix))
- appendRow(t, r.rt.DBPath)
- rep, ok := e.rep.(*lease.Replicator)
- if !ok {
- t.Fatalf("the entry's replica is %T", e.rep)
- }
- lockKey := r.prefix + "/lock.json"
- r.fx.FailNextMatching("PUT", 403, func(k string, _ []byte) bool { return k == lockKey })
- lease.LoseLeaseForTest(rep, errors.New("renewal: AccessDenied"))
- returned, release := r.holdCheckpointReturn(t)
- stopped := r.stop(e)
- select {
- case err := <-returned:
- if !errors.Is(err, lease.ErrCheckpointAbandoned) {
- t.Fatalf("CloseProven = %v, want ErrCheckpointAbandoned", err)
- }
- case <-time.After(30 * time.Second):
- t.Fatalf("the stop's checkpoint never returned:\n%s", r.log.String())
- }
- r.shutdownSpent(t)
- if n := strings.Count(r.log.String(), c45Text); n != 1 {
- t.Fatalf("C45 logged %d times before Shutdown returned, want once:\n%s", n, r.log.String())
- }
- release()
- select {
- case <-stopped:
- case <-time.After(30 * time.Second):
- t.Fatal("the stop never finished once its handling went on")
- }
- if n := strings.Count(r.log.String(), c45Text); n != 1 {
- t.Fatalf("C45 logged %d times, want once:\n%s", n, r.log.String())
- }
-}
-
// signalRep is a fleet replica whose Close and CloseProven send their
// answers on closed once they have returned.
type signalRep struct {
@@ -2184,39 +1889,3 @@ func TestReapedFleetWakeKeepsAnUnprovenCheckpoint(t *testing.T) {
r.assertCheckpointKept(t, rep)
r.assertHealedRelease(t, rep, heal)
}
-
-// At shutdown a failed wake kept over an unproven checkpoint is not
-// released: Shutdown's reaper pass abandons it (lock.json kept, renewal
-// stopped), names it (C45) and forgets it, so Shutdown returns within its
-// budget.
-func TestShutdownAbandonsAFailedWakesUnprovenCheckpoint(t *testing.T) {
- r := newCheckpointRig(t, registry.PlacementTarget("pi"))
- rep, _ := r.retainedCheckpoint(t)
- r.a.sweepOnce()
- if err := closedWith(t, rep.closed, "reaper"); !errors.Is(err, lease.ErrCheckpointUnproven) {
- t.Fatalf("the reaper's close = %v, want an unproven checkpoint (CloseProven)", err)
- }
- r.assertCheckpointKept(t, rep)
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- r.a.Shutdown(ctx)
- if ctx.Err() != nil {
- t.Fatalf("Shutdown ran out of time instead of abandoning the checkpoint:\n%s", r.log.String())
- }
- if r.fx.LockBody(r.prefix) == nil {
- t.Fatal("Shutdown released the lease over an unproven checkpoint")
- }
- if rep.Err() == nil {
- t.Fatal("the abandoned lease still renews: it was not abandoned")
- }
- logged := r.log.String()
- if n := strings.Count(logged, "activator: ERROR: shutdown: "+r.rt.Host+": "+c45Text); n != 1 {
- t.Fatalf("C45 naming %s at shutdown logged %d times, want once:\n%s", r.rt.Host, n, logged)
- }
- r.a.mu.Lock()
- left := len(r.a.unprovenWakes)
- r.a.mu.Unlock()
- if left != 0 {
- t.Fatalf("%d failed wakes still retained after Shutdown abandoned them", left)
- }
-}
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index 484e07ad8..71a0d0705 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -518,25 +518,23 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
// acquired *before* replication starts and renewed on a ticker; Close stops
// replication and releases the lease.
type Replicator struct {
- leaser *lss3.Leaser
- store *litestream.Store
- db *litestream.DB
- rn *renewer
- mu sync.Mutex
- busy bool
- spent bool
- tornDown bool // a non-HA teardown has begun (claimTeardown); guarded by mu
- abandoned bool // that teardown was an abandonment (Abandoned); guarded by mu
- closing bool // a non-HA Close or CloseProven is syncing (beginClose); guarded by mu
- // syncGate orders a close's database sync against an abandonment
- // (M1 review Astra P2-1): the sync runs under its read lock, and only
- // while no teardown has begun; TryAbandon claims the teardown under
- // its write lock. So no database sync starts once a teardown has
- // (litestream's DB.init reopens a closed database, and nothing would
- // close it again), while the replica sync, which can wait on the
- // bucket, runs outside it, so an abandonment can still cancel a
- // checkpoint in flight.
- syncGate sync.RWMutex
+ leaser *lss3.Leaser
+ store *litestream.Store
+ db *litestream.DB
+ rn *renewer
+ mu sync.Mutex
+ busy bool
+ spent bool
+ tornDown bool // a non-HA teardown has begun (claimTeardown); guarded by mu
+ closing bool // a non-HA Close or CloseProven is syncing (beginClose); guarded by mu
+ // No lock is held across a sync (M1 cut, 8a3d302; Astra N1):
+ // litestream's DB.Sync can wait on the bucket behind the monitor, and
+ // no other path may wait with it. A teardown is terminal through mu
+ // alone (tornDown, beginClose). Production never tears a replicator
+ // down while one of its syncs runs: Close and CloseProven tear down
+ // only after their own sync (beginClose serialises them), and nothing
+ // abandons one from outside. Only a test's Abandon (a box's crash)
+ // can race a sync in flight.
poison error
replicaClient litestream.ReplicaClient // private local-replica test seam
// An HA replicator's (Held.Replicate carries them over): it releases
@@ -643,33 +641,28 @@ func (r *Replicator) Lost() <-chan struct{} { return r.rn.lost }
// Abandon stops lease renewal and replication WITHOUT the final sync or the
// lease release — the wreckage a crashed box leaves behind: lock.json simply
// expires on its TTL, and the replica holds whatever was last synced. Tests
-// use it to simulate hard box death in-process. Production calls it in one
-// place: an agent shutting down over a fleet stop whose final checkpoint is
-// not proven (CloseProven), which must not release the lease, leaves it to
-// its TTL this way. Pass a context that is already done for no further
-// sync attempt at all.
+// use it to simulate hard box death in-process. In production only
+// CloseProven calls it, over a failed checkpoint whose lease no longer
+// renews (ErrCheckpointAbandoned). An agent's Shutdown never does: it
+// leaves an unproven fleet checkpoint as it is, and renewal ends with the
+// process (M1 cut, 8a3d302). Pass a context that is already done for no
+// further sync attempt at all.
//
// A non-HA replicator is torn down once: an Abandon after Close or another
-// Abandon, or racing one, does nothing (claimTeardown). So an Abandon may
-// run beside a CloseProven still waiting in its sync: closing the store
-// cancels the replication in flight, the sync fails, and CloseProven
-// answers without tearing down again (TryAbandon reports which call did).
-func (r *Replicator) Abandon(ctx context.Context) { r.TryAbandon(ctx) }
-
-// TryAbandon is Abandon, reporting whether this call is the one that tore
-// a non-HA replicator down: false when Close or another abandonment had
-// already begun (the lease then went whichever way that one took it). An
-// HA replicator always answers true.
-func (r *Replicator) TryAbandon(ctx context.Context) bool {
+// Abandon does nothing (claimTeardown), and a Close or CloseProven after it
+// answers ErrSpent with no I/O.
+func (r *Replicator) Abandon(ctx context.Context) { r.abandon(ctx) }
+
+// abandon is Abandon, reporting whether this call is the one that tore a
+// non-HA replicator down: false when a teardown had already begun. An HA
+// replicator always answers true.
+func (r *Replicator) abandon(ctx context.Context) bool {
if r.ha {
r.rn.stop() // deliberately no ReleaseLease — the TTL is the point
_, _ = r.finalize(ctx, false, false) // the one teardown; a later release never syncs
return true
}
- r.syncGate.Lock()
- claimed := r.claimTeardown(true)
- r.syncGate.Unlock()
- if !claimed {
+ if !r.claimTeardown() {
return false
}
r.rn.stop() // deliberately no ReleaseLease — the TTL is the point
@@ -681,29 +674,17 @@ func (r *Replicator) TryAbandon(ctx context.Context) bool {
return true
}
-// Abandoned reports whether a non-HA replicator's teardown was an
-// abandonment (TryAbandon, or CloseProven's own over a lost lease), by
-// whichever call made it: the lease was not released and frees at its
-// TTL. False before any teardown, after a release, and for an HA
-// replicator. A caller whose TryAbandon answered false asks it to learn
-// whether the lease went to its TTL all the same.
-func (r *Replicator) Abandoned() bool {
- r.mu.Lock()
- defer r.mu.Unlock()
- return r.abandoned
-}
-
// claimTeardown reports whether the caller is the one to tear a non-HA
-// replicator down (Close or Abandon); false once another has. abandon
-// records which kind of teardown it is (Abandoned). It ends any close's
-// sync phase (closing).
-func (r *Replicator) claimTeardown(abandon bool) bool {
+// replicator down (Close or Abandon); false once another has. It ends any
+// close's sync phase (closing). It takes mu only, never a lock a sync
+// holds.
+func (r *Replicator) claimTeardown() bool {
r.mu.Lock()
defer r.mu.Unlock()
if r.tornDown {
return false
}
- r.tornDown, r.abandoned, r.closing = true, abandon, false
+ r.tornDown, r.closing = true, false
return true
}
@@ -764,7 +745,7 @@ func (r *Replicator) Close(ctx context.Context) error {
// released under a budget of its own. ErrSpent, with nothing released,
// when an abandonment tore the replicator down meanwhile.
func (r *Replicator) teardownAndRelease(ctx context.Context) error {
- if !r.claimTeardown(false) {
+ if !r.claimTeardown() {
return ErrSpent // abandoned meanwhile: nothing is released
}
err := r.store.Close(ctx)
@@ -821,8 +802,8 @@ var ErrCheckpointAbandoned = errors.New("lease: final checkpoint not confirmed a
//
// Once a teardown has begun (a Close, an abandonment) CloseProven answers
// ErrSpent before any sync, as Close does; an abandonment that lands while
-// its sync is in flight makes it answer ErrSpent too, with nothing
-// released.
+// its sync is in flight (a test's Abandon; production has none) makes it
+// answer ErrSpent too, with nothing released.
func (r *Replicator) CloseProven(ctx context.Context) error {
if r.ha {
return r.closeHA(ctx)
@@ -835,8 +816,8 @@ func (r *Replicator) CloseProven(ctx context.Context) error {
return r.teardownAndRelease(ctx)
}
if r.isTornDown() {
- // Abandoned while the checkpoint was in flight (at shutdown),
- // which answers for the lease.
+ // Abandoned while the checkpoint was in flight, which answers for
+ // the lease.
return fmt.Errorf("%w: the final checkpoint failed and the replicator was torn down meanwhile: %w", ErrSpent, err)
}
if empty, eerr := r.provenEmpty(ctx); eerr == nil && empty {
@@ -848,9 +829,9 @@ func (r *Replicator) CloseProven(ctx context.Context) error {
if lost := r.rn.Err(); lost != nil {
done, cancel := context.WithCancel(context.Background())
cancel() // no further sync: the checkpoint just failed
- if !r.TryAbandon(done) {
- // Torn down meanwhile by another caller (an abandonment at
- // shutdown), which answers for the lease.
+ if !r.abandon(done) {
+ // Torn down meanwhile by another caller, which answers for
+ // the lease.
return fmt.Errorf("%w: the final checkpoint failed and the replicator was torn down meanwhile: %w", ErrSpent, err)
}
return fmt.Errorf("%w: %s (renewal: %v): %w", ErrCheckpointAbandoned, r.leaser.Path, lost, err)
@@ -901,23 +882,26 @@ func (r *Replicator) provenEmpty(ctx context.Context) (bool, error) {
}
// guardedSync is litestream's DB.SyncAndWait, the database sync and then
-// the replica sync, for a non-HA replicator, guarded against its teardown
-// (syncGate): ErrSpent, with nothing synced, once a teardown has begun,
-// and the database sync starts only under syncGate's read lock. hook runs
-// closeProvenReplicaSync (a test seam, CloseProven's) between the two. The
-// replica sync waits for any replication already in flight whatever ctx
-// says: only closing the store (Abandon) cancels that.
+// the replica sync, for a non-HA replicator, guarded against its teardown:
+// ErrSpent, with nothing synced, once a teardown has begun (a completed
+// teardown is terminal; litestream's DB.init would reopen a closed
+// database, and nothing would close it again). No lock is held across
+// either sync (M1 cut, Astra N1): DB.Sync waits for the database's exec
+// lock, which the monitor can hold while it waits on the bucket. hook runs
+// the test seams, CloseProven's: closeProvenDBSync just before the
+// database sync and closeProvenReplicaSync between the two. The replica
+// sync waits for any replication already in flight whatever ctx says.
func (r *Replicator) guardedSync(ctx context.Context, hook bool) error {
if r.db.Replica == nil {
return fmt.Errorf("no replica configured")
}
- r.syncGate.RLock()
if r.isTornDown() {
- r.syncGate.RUnlock()
return ErrSpent
}
+ if h := closeProvenDBSync.Load(); hook && h != nil {
+ (*h)()
+ }
err := r.db.Sync(ctx)
- r.syncGate.RUnlock()
if err != nil {
return fmt.Errorf("db sync: %w", err)
}
@@ -949,6 +933,25 @@ func SetCloseProvenReplicaSyncHookForTest(hook func()) (restore func()) {
return func() { closeProvenReplicaSync.Store(prev) }
}
+// closeProvenDBSync, when set, runs in CloseProven just before its
+// database sync: where litestream's DB.Sync waits for the database's
+// exec lock, which its background monitor can hold while it waits on the
+// bucket (M1 review Astra N1). A test seam; nil in production.
+var closeProvenDBSync atomic.Pointer[func()]
+
+// SetCloseProvenDBSyncHookForTest sets the hook CloseProven runs just
+// before its database sync, and returns the restore. A hook that blocks
+// stands in for a DB.Sync held behind a monitor waiting on the bucket.
+// Process-global, like SetCloseProvenReplicaSyncHookForTest.
+func SetCloseProvenDBSyncHookForTest(hook func()) (restore func()) {
+ var p *func()
+ if hook != nil {
+ p = &hook
+ }
+ prev := closeProvenDBSync.Swap(p)
+ return func() { closeProvenDBSync.Store(prev) }
+}
+
// LoseLeaseForTest latches r's lease as lost with err, as a failed renewal
// does, without touching lock.json. A test seam: a witness needs the loss
// at a known point, not at the next renewal tick.