lease, activator: R2 review fixes (no release when lost, shutdown abandon)
Astra and Fable round 1, both Important items and the minor rulings. lease: CloseProven no longer releases when the lease's renewal has failed. rn.Err() latches on one failed renewal or a local pause and does not mean another box holds the lock, so releasing could hand over unproven state. A failed sync over such a lease now abandons (renewal and replication stopped, no further sync, lock.json left to its TTL) and returns the new ErrCheckpointAbandoned naming the prefix. A non-HA replicator is torn down once (claimTeardown), so an Abandon may run beside a CloseProven blocked in its sync. LoseLeaseForTest latches loss at a known point. SetShutdownSyncTimeoutForTest's doc says it is process-global. activator: closeFleetCheckpoint holds the fleet arm. ErrCheckpointAbandoned finishes the stop unclean with an ERROR naming the host (C45 draft). Shutdown's budget ending (shutdownExpired) abandons a checkpoint in flight beside it, since litestream's sync waits on replication already in flight and ignores its context; Shutdown then waits for it, abandons any stop still pending over an unproven checkpoint, and logs C45 for each before it returns. The shutdown ERROR is marked as C45. startrule: C43 also covers the set-aside branch, naming the set-aside copies newest first; both refusals wrap ErrNothingToRestore. Witnesses: TestCloseProvenAbandonsWhenTheLeaseIsLost, TestFleetStopWithLostLeaseFinishesUncleanWithoutRelease, TestShutdownAbandonsAPendingCheckpointBlockedInTheBucket (barriers on the checkpointStarted seam and a fixture write hook).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+188 −30internal/activator/pendingwake_linux_test.go+136 −1internal/activator/startrule.go+12 −11internal/activator/startrule_test.go+3 −2internal/lease/lease.go+60 −10internal/lease/release_test.go+61 −0
Intent
<task-notification> <task-id>a0c925fb35f246f63</task-id> <tool-use-id>toolu_01WpkUHG1TwEEtKp4kkBNvhK</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ac77363b-5830-422c-9f38-d7f2540dd398/tasks/a0c925fb35f246f63.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: R2 proven checkpoint" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS - **Commit:** `29fb2695 lease, activator: a fleet stop releases only after a proven checkpoint (R2)` (not pushed) - **Tests:** all six Step 2 tests and `TestCloseProven` pass, also under `-race`. They failed first for the expected reasons. The Step 4 activator tests pass and the darwin build compiles. The brief's `-run TestRelease` matches no test in `internal/lease`, so I ran the 10 tests in `release_test.go` instead; all pass. - **Concerns:** 1. `FailReplicaPuts` is on `locktest.LockFixture`, not in `internal/lease/leasetest`. `release_test.go` imports locktest under the alias `leasetest`, and litestream runs against that fixture. 2. The shutdown ERROR line is new log text with no row in the spec's copy table (§9). 3. When the lease is already lost, `CloseProven` releases as `Close` does instead of keeping the stop pending forever. That was my choice, it has no test of its own, and the brief does not cover it. 4. C43 is only on the `rt.Moved` refusal, so it always reads "set-aside copies: none". The first-label case keeps its old wording, which names the set-aside path. I updated the existing `TestMovedInstanceOnACleanBoxRefusesWithoutReplica` to check the C43 words. 5. I added a new exported test seam, `lease.SetShutdownSyncTimeoutForTest`. Without it, a failing final sync retries for litestream's default 30 s on every stop in the platform-region test. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-record-labels/.superpowers/sdd/2026-11-14-fleet-record-labels/task-2-report.md</result> <usage><subagent_tokens>220020</subagent_tokens><tool_uses>87</tool_uses><duration_ms>984222</duration_ms></usage> </task-notification>
<task-notification> <task-id>bzucczqmf</task-id> <tool-use-id>toolu_01Lq4ap3waQakfkTr1ysKZHK</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ac77363b-5830-422c-9f38-d7f2540dd398/tasks/bzucczqmf.output</output-file> <status>completed</status> <summary>Background command "Run Astra and Fable T2 reviews" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 14.8 g CO₂e (1,764,751 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-record-labels, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 9e19f2570..632801e02 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -675,6 +675,16 @@ type actEntry struct { |
| // proc.Exited() for every pendingStop entry and finishes the stop |
| // (finishPendingStop) the moment it's proven. |
| pendingStop bool |
| + // The fleet checkpoint's state (fleet record labels R2), under a.mu. |
| + // checkpointing is non-nil while finishStop's CloseProven is in flight |
| + // and closes when that arm has finished, abandonment included; |
| + // checkpointUnproven marks a stop kept pending over an unproven |
| + // checkpoint; checkpointAbandoned marks one Shutdown abandoned at its |
| + // deadline (abandonCheckpointsAtExit), which no later finishStop may |
| + // close again. |
| + checkpointing chan struct{} |
| + checkpointUnproven bool |
| + checkpointAbandoned 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 |
| @@ -1730,6 +1740,16 @@ type Service struct { |
| // proven (R2 of the fleet record labels spec). 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.checkpointing. It is a test seam; nil in production. |
| + checkpointStarted func(host string) |
| + // shutdownExpired closes when Shutdown's budget ends. A fleet final |
| + // checkpoint in flight (closeFleetCheckpoint) is cancelled then, so |
| + // Shutdown can abandon and name it before it returns. Made by New, or |
| + // by Shutdown for a Service built without it; read under a.mu. |
| + shutdownExpired chan struct{} |
| + expireOnce sync.Once |
| } |
| // New wires the state machine to its side-effect backend and due-time store. |
| @@ -1742,6 +1762,8 @@ func New(cfg Config, backend Backend, due DueStore) *Service { |
| now: time.Now, |
| entries: make(map[string]*actEntry), |
| gens: GenerationsEnabled(), |
| + |
| + shutdownExpired: make(chan struct{}), |
| } |
| a.initHALosses() |
| a.wakeSlots = make(chan struct{}, wakeSlotCount(cfg.WakeSlots)) |
| @@ -5433,33 +5455,11 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| // sync fails, so a successor's acquire would prove nothing. |
| // Unproven, the process stays stopped and the lease held and |
| // renewing, and the stop stays pending, as the HA arm's does: the |
| - // sweep finishes it once the checkpoint succeeds. At shutdown there |
| - // is no later sweep, so the lease is not released but left to its |
| - // TTL. |
| - repErr = pc.CloseProven(ctx) |
| - if errors.Is(repErr, lease.ErrCheckpointUnproven) { |
| - a.mu.Lock() |
| - shutting := a.shuttingDown |
| - if !shutting { |
| - a.keepPendingLocked(e, outcome) |
| - } |
| - kept := a.checkpointKept |
| - a.mu.Unlock() |
| - if !shutting { |
| - log.Printf("activator: final checkpoint %s: %v", e.host, repErr) |
| - // draft for copy review (C44) |
| - log.Printf("activator: final checkpoint for %s failed. keeping its lease until the checkpoint succeeds", e.host) |
| - if kept != nil { |
| - kept(e.host) |
| - } |
| - return |
| - } |
| - // A context already done: the checkpoint just failed, and an |
| - // abandon ships nothing more, as a crash would not. |
| - done, stop := context.WithCancel(context.Background()) |
| - stop() |
| - pc.Abandon(done) |
| - log.Printf("activator: ERROR: shutdown: %s: its final checkpoint failed, so its lease is not released and frees at its expiry", e.host) |
| + // sweep finishes it once the checkpoint succeeds. |
| + var kept bool |
| + kept, repErr = a.closeFleetCheckpoint(ctx, e, pc, outcome) |
| + if kept { |
| + return |
| } |
| } else if e.rep != nil { |
| repErr = e.rep.Close(ctx) |
| @@ -5557,6 +5557,158 @@ func (a *Service) fleetProvenCloser(e *actEntry) (provenCloser, bool) { |
| return pc, ok |
| } |
| +// 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: |
| +// |
| +// - 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 over a lease whose renewal had failed: CloseProven has |
| +// abandoned it (lease.ErrCheckpointAbandoned), and C45 is logged. |
| +// |
| +// When Shutdown's budget ends (shutdownExpired) the checkpoint in flight is |
| +// abandoned, so a retry blocked in the bucket is given up and named before |
| +// Shutdown returns; Shutdown waits on e.checkpointing for it. |
| +func (a *Service) closeFleetCheckpoint(ctx context.Context, e *actEntry, pc provenCloser, outcome *stopObservation) (kept bool, err error) { |
| + a.mu.Lock() |
| + if e.checkpointAbandoned { |
| + a.mu.Unlock() |
| + return true, nil |
| + } |
| + done := make(chan struct{}) |
| + e.checkpointing = done |
| + expired, started := a.shutdownExpired, a.checkpointStarted |
| + a.mu.Unlock() |
| + if started != nil { |
| + started(e.host) |
| + } |
| + defer func() { |
| + a.mu.Lock() |
| + e.checkpointing = nil |
| + a.mu.Unlock() |
| + close(done) |
| + }() |
| + // Shutdown's budget ending abandons the checkpoint in flight, beside |
| + // it: cancelling its context is not enough, since litestream's sync |
| + // waits for any replication already in flight, which only closing the |
| + // store cancels. CloseProven then answers at once; the replicator is |
| + // torn down once, whichever gets there first. |
| + cctx, cancel := context.WithCancel(ctx) |
| + var byShutdown atomic.Bool |
| + watched := make(chan struct{}) |
| + go func() { |
| + defer close(watched) |
| + select { |
| + case <-expired: |
| + byShutdown.Store(true) |
| + cancel() |
| + abandonCheckpoint(pc) |
| + case <-cctx.Done(): |
| + } |
| + }() |
| + err = pc.CloseProven(cctx) |
| + cancel() |
| + <-watched |
| + switch { |
| + case errors.Is(err, lease.ErrCheckpointAbandoned): |
| + if byShutdown.Load() { |
| + logCheckpointAbandoned("shutdown: ", e.host) |
| + } else { |
| + logCheckpointAbandoned("", e.host) |
| + } |
| + case errors.Is(err, lease.ErrCheckpointUnproven): |
| + a.mu.Lock() |
| + shutting := a.shuttingDown |
| + if !shutting { |
| + a.keepPendingLocked(e, outcome) |
| + e.checkpointUnproven = true |
| + } |
| + hook := a.checkpointKept |
| + a.mu.Unlock() |
| + if !shutting { |
| + log.Printf("activator: final checkpoint %s: %v", e.host, err) |
| + // draft for copy review (C44) |
| + log.Printf("activator: final checkpoint for %s failed. keeping its lease until the checkpoint succeeds", e.host) |
| + if hook != nil { |
| + hook(e.host) |
| + } |
| + return true, err |
| + } |
| + abandonCheckpoint(pc) |
| + logCheckpointAbandoned("shutdown: ", e.host) |
| + } |
| + return false, err |
| +} |
| + |
| +// 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). |
| +func abandonCheckpoint(pc provenCloser) { |
| + done, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + pc.Abandon(done) |
| +} |
| + |
| +// logCheckpointAbandoned is the ERROR an abandoned fleet checkpoint logs, |
| +// naming the host; prefix says where ("shutdown: " or ""). |
| +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, after |
| +// shutdownExpired has closed: no unproven fleet checkpoint is left renewing |
| +// or unnamed when Shutdown returns. It waits for every checkpoint in flight |
| +// (cancelled by shutdownExpired, each abandons and logs itself), and |
| +// abandons, and names, every stop kept pending over an unproven checkpoint |
| +// with none in flight, marking it so no later finishStop closes it again. |
| +func (a *Service) abandonCheckpointsAtExit() { |
| + a.mu.Lock() |
| + var inFlight []chan struct{} |
| + var left []*actEntry |
| + for _, e := range a.entries { |
| + switch { |
| + case e.checkpointing != nil: |
| + inFlight = append(inFlight, e.checkpointing) |
| + case e.checkpointUnproven && !e.checkpointAbandoned: |
| + e.checkpointAbandoned = true |
| + left = append(left, e) |
| + } |
| + } |
| + a.mu.Unlock() |
| + for _, done := range inFlight { |
| + <-done |
| + } |
| + for _, e := range left { |
| + if pc, ok := a.fleetProvenCloser(e); ok { |
| + abandonCheckpoint(pc) |
| + } |
| + logCheckpointAbandoned("shutdown: ", e.host) |
| + } |
| +} |
| + |
| +// expireShutdown closes shutdownExpired, once. |
| +func (a *Service) expireShutdown() { |
| + a.mu.Lock() |
| + ch := a.shutdownExpired |
| + a.mu.Unlock() |
| + a.expireOnce.Do(func() { close(ch) }) |
| +} |
| + |
| +// exitUnresolved is Shutdown's return once its budget has ended: unproven |
| +// fleet checkpoints abandoned and named, then the rest named. |
| +func (a *Service) exitUnresolved() { |
| + a.abandonCheckpointsAtExit() |
| + a.logUnresolvedAtExit() |
| +} |
| + |
| // Start launches the background sweeper that puts idle instances to sleep and |
| // stands down lost leases/dead children between requests. |
| func (a *Service) Start() { |
| @@ -6367,6 +6519,9 @@ func (a *Service) Shutdown(ctx context.Context) { |
| // Proofs that start or run from here end with this budget too |
| // (legacyRunGone, #292): none may outlive Shutdown. |
| a.shutdownCtx = ctx |
| + if a.shutdownExpired == nil { |
| + a.shutdownExpired = make(chan struct{}) |
| + } |
| var shutdownEntries []*actEntry |
| for _, e := range a.entries { |
| shutdownEntries = append(shutdownEntries, e) |
| @@ -6382,6 +6537,9 @@ func (a *Service) Shutdown(ctx context.Context) { |
| a.mu.Unlock() |
| // …and those already running end with it too (Astra, round 3). |
| context.AfterFunc(ctx, a.cancelProofs) |
| + // …and so do fleet final checkpoints (R2), which are then abandoned |
| + // and named before Shutdown returns (exitUnresolved). |
| + context.AfterFunc(ctx, a.expireShutdown) |
| // …and cancel the service lifetime, which TEARS DOWN any worker spawn |
| // already past that check rather than letting the stop below wait it out. |
| // The wait is right for a Bounce or an idle sleep — no deadline, and |
| @@ -6465,7 +6623,7 @@ func (a *Service) Shutdown(ctx context.Context) { |
| case <-poll.C: |
| pollPending() |
| case <-ctx.Done(): |
| - a.logUnresolvedAtExit() |
| + a.exitUnresolved() |
| return |
| } |
| } |
| @@ -6483,7 +6641,7 @@ func (a *Service) Shutdown(ctx context.Context) { |
| case <-poll.C: |
| pollPending() |
| case <-ctx.Done(): |
| - a.logUnresolvedAtExit() |
| + a.exitUnresolved() |
| return |
| } |
| } |
| @@ -6524,7 +6682,7 @@ func (a *Service) Shutdown(ctx context.Context) { |
| select { |
| case <-poll.C: |
| case <-ctx.Done(): |
| - a.logUnresolvedAtExit() |
| + a.exitUnresolved() |
| return |
| } |
| } |
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go| index 101d565f0..e8b76b25e 100644 |
| --- a/internal/activator/pendingwake_linux_test.go |
| +++ b/internal/activator/pendingwake_linux_test.go |
| @@ -1335,8 +1335,15 @@ func newCheckpointRig(t *testing.T, region string) *checkpointRig { |
| r := &checkpointRig{fx: fx, b: b, rt: rt, prefix: b.Cfg.hibernatePrefix(rt.Host), log: lockedLog(t), kept: make(chan string, 8)} |
| r.a = New(Config{Bucket: fx.Bucket, Idle: time.Hour}, b, reg) |
| r.a.checkpointKept = func(host string) { r.kept <- host } |
| - // Whatever a test leaves running stops before the fixture closes. |
| + // Whatever a test leaves running stops before the fixture closes, |
| + // unless the test shut the agent down itself. |
| t.Cleanup(func() { |
| + r.a.mu.Lock() |
| + down := r.a.shuttingDown |
| + r.a.mu.Unlock() |
| + if down { |
| + return |
| + } |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| r.a.Shutdown(ctx) |
| @@ -1496,3 +1503,131 @@ func TestPlatformRegionStopUnchanged(t *testing.T) { |
| t.Fatalf("a platform-region stop logged C44:\n%s", logged) |
| } |
| } |
| + |
| +// R2 review fix: a failed renewal latches the lease lost, but the lock |
| +// may still be ours and unexpired. A fleet stop whose final checkpoint |
| +// fails over such a lease must not release it: the replicator is |
| +// abandoned, lock.json is left to its TTL, an ERROR names the host, and |
| +// the stop finishes unclean rather than staying pending forever. |
| +func TestFleetStopWithLostLeaseFinishesUncleanWithoutRelease(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" |
| + // The bucket fault reaches the lock too: its next PUT or DELETE fails. |
| + r.fx.FailNextMatching("PUT", 403, func(k string, _ []byte) bool { return k == lockKey }) |
| + lease.LoseLeaseForTest(rep, errors.New("renewal: AccessDenied")) |
| + lock := r.fx.LockBody(r.prefix) |
| + before := len(r.fx.Requests()) |
| + |
| + stopped := r.stop(e) |
| + select { |
| + case <-stopped: |
| + case <-r.kept: |
| + t.Fatal("a stop over a lost lease was kept pending: it would wait forever") |
| + case <-time.After(30 * time.Second): |
| + t.Fatalf("the stop never finished:\n%s", r.log.String()) |
| + } |
| + if got := r.fx.LockBody(r.prefix); string(got) != string(lock) { |
| + t.Fatalf("lock.json changed to %s; an abandoned lease is left as it was", got) |
| + } |
| + for _, req := range r.fx.Requests()[before:] { |
| + if req == "DELETE "+lockKey { |
| + t.Fatal("the stop released the lock over an unproven checkpoint") |
| + } |
| + } |
| + r.a.mu.Lock() |
| + outcome := e.stopOutcome |
| + r.a.mu.Unlock() |
| + if outcome == nil || outcome.replicaClosed { |
| + t.Fatalf("the stop finished clean (%+v); want replicaClosed false", outcome) |
| + } |
| + logged := r.log.String() |
| + if !strings.Contains(logged, "activator: ERROR: "+r.rt.Host+": its final checkpoint failed, so its lease is not released and frees at its expiry") { |
| + t.Fatalf("no ERROR naming %s:\n%s", r.rt.Host, logged) |
| + } |
| + if strings.Contains(logged, c44Line) { |
| + t.Fatalf("C44 promised to keep a lease that was given up:\n%s", logged) |
| + } |
| +} |
| + |
| +// 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) |
| + } |
| +} |
diff --git a/internal/activator/startrule.go b/internal/activator/startrule.go| index 052947bab..37ebeff51 100644 |
| --- a/internal/activator/startrule.go |
| +++ b/internal/activator/startrule.go |
| @@ -58,14 +58,15 @@ const ( |
| // ErrNothingToRestore is the start rule's refusal: a labelled row with no |
| // kept copy and no replica, whose record has moved or of which a copy was |
| -// set aside on this box. The wrapping error names the set-aside path, or |
| -// is the C43 refusal (emptyStartRefusal) when nothing was set aside. |
| +// set aside on this box. The refusal is emptyStartRefusal (C43), naming |
| +// the set-aside copies or "none". |
| var ErrNothingToRestore = errors.New("nothing to restore") |
| -// emptyStartRefusal is the start rule's refusal for a moved, labelled row |
| -// with no local copy, no set-aside copy and no replica (fleet record |
| -// labels R2): the C43 words, wrapping ErrNothingToRestore. setAside is |
| -// what was set aside on this box, "none" here. |
| +// emptyStartRefusal is the start rule's refusal of an empty start for a |
| +// labelled row with no local copy and no replica (fleet record labels R2): |
| +// the C43 words, wrapping ErrNothingToRestore. setAside names what was set |
| +// aside on this box, newest first ("none" for a moved row with nothing set |
| +// aside), so the operator's recovery starts from the refusal. |
| type emptyStartRefusal struct{ host, setAside string } |
| func (r emptyStartRefusal) Error() string { |
| @@ -375,12 +376,12 @@ func (b *ExecBackend) startAllowed(rt registry.Route, haveLocal, restored bool) |
| return fmt.Errorf("%s: refusing to start: cannot tell whether a copy of it was set aside on this box: %w", host, err) |
| } |
| if n := len(entries); n > 0 { |
| - newest := filepath.Join(dir, entries[n-1]) |
| - more := "" |
| - if n > 1 { |
| - more = fmt.Sprintf(" (%d set-aside copies under %s)", n, dir) |
| + // Newest first, so the copy an operator restores leads the list. |
| + paths := make([]string, 0, n) |
| + for i := n - 1; i >= 0; i-- { |
| + paths = append(paths, filepath.Join(dir, entries[i])) |
| } |
| - return fmt.Errorf("%s: refusing to start empty: %w: no replica in the fleet bucket, and a copy of it was set aside on this box at %s%s", host, ErrNothingToRestore, newest, more) |
| + return emptyStartRefusal{host: host, setAside: strings.Join(paths, ", ")} |
| } |
| if rt.Moved { |
| return emptyStartRefusal{host: host, setAside: "none"} |
diff --git a/internal/activator/startrule_test.go b/internal/activator/startrule_test.go| index 169fdfc72..0bc1f8e01 100644 |
| --- a/internal/activator/startrule_test.go |
| +++ b/internal/activator/startrule_test.go |
| @@ -649,8 +649,9 @@ func TestFirstLabelOnServingBoxWithoutReplicaRefuses(t *testing.T) { |
| } |
| entry := assertSetAside(t, b, rt.Host, want) |
| assertGoneFromLive(t, rt.DBPath, want) |
| - if !strings.Contains(err.Error(), entry) { |
| - t.Fatalf("the refusal %q does not name the set-aside copy %s", err, entry) |
| + c43 := "refusing to start shop.example.com empty: it was tied to this box and there is no saved copy to restore. set-aside copies: " + entry |
| + if !strings.Contains(err.Error(), c43) { |
| + t.Fatalf("the refusal %q is not the C43 text naming the set-aside copy: %q", err, c43) |
| } |
| } |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index c65f75099..2658a47c2 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -525,6 +525,7 @@ type Replicator struct { |
| mu sync.Mutex |
| busy bool |
| spent bool |
| + tornDown bool // a non-HA teardown has begun (claimTeardown); guarded by mu |
| poison error |
| replicaClient litestream.ReplicaClient // private local-replica test seam |
| // An HA replicator's (Held.Replicate carries them over): it releases |
| @@ -634,19 +635,41 @@ func (r *Replicator) Lost() <-chan struct{} { return r.rn.lost } |
| // 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. |
| +// |
| +// 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. |
| func (r *Replicator) Abandon(ctx context.Context) { |
| - r.rn.stop() // deliberately no ReleaseLease — the TTL is the point |
| - // litestream's only teardown is Close, which includes a sync a real crash |
| - // would skip; it ships nothing as long as the caller killed the writer |
| - // first, and reclaims the replication goroutines either way. |
| 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 |
| } |
| + if !r.claimTeardown() { |
| + return |
| + } |
| + r.rn.stop() // deliberately no ReleaseLease — the TTL is the point |
| + // litestream's only teardown is Close, which includes a sync a real crash |
| + // would skip; it ships nothing as long as the caller killed the writer |
| + // first, and reclaims the replication goroutines either way. |
| _ = r.store.Close(ctx) |
| r.closeDone() |
| } |
| +// claimTeardown reports whether the caller is the one to tear a non-HA |
| +// replicator down (Close or Abandon); false once another has. |
| +func (r *Replicator) claimTeardown() bool { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if r.tornDown { |
| + return false |
| + } |
| + r.tornDown = true |
| + return true |
| +} |
| + |
| // Close stops replication (final sync included via litestream's DB.Close) |
| // and releases the lease so the next claimant can acquire immediately. An |
| // HA replicator releases through the unclean marker instead (closeHA). |
| @@ -663,6 +686,9 @@ func (r *Replicator) Close(ctx context.Context) error { |
| // the DB now initialized, store.Close's own final sync is the one that |
| // counts, and its error is returned. |
| _ = r.db.SyncAndWait(ctx) |
| + if !r.claimTeardown() { |
| + return ErrSpent // abandoned meanwhile: nothing is released |
| + } |
| err := r.store.Close(ctx) |
| r.closeDone() |
| @@ -689,6 +715,13 @@ func (r *Replicator) Close(ctx context.Context) error { |
| // renewing, so a later CloseProven can prove the checkpoint and release. |
| var ErrCheckpointUnproven = errors.New("lease: final checkpoint not confirmed") |
| +// ErrCheckpointAbandoned is CloseProven's answer when the forced final sync |
| +// failed and the lease's renewal had already failed (Err): the replicator |
| +// is torn down without releasing the lease, which frees at its expiry. The |
| +// stop can finish, unclean; a retry could neither renew the lease nor |
| +// prove anything a successor could rely on. |
| +var ErrCheckpointAbandoned = errors.New("lease: final checkpoint not confirmed and the lease no longer renews; left to expire") |
| + |
| // CloseProven is Close for a stop whose release must prove its final |
| // checkpoint first (fleet record labels R2): the forced SyncAndWait that |
| // Close runs and ignores is load-bearing here. When it fails, nothing is |
| @@ -697,11 +730,14 @@ var ErrCheckpointUnproven = errors.New("lease: final checkpoint not confirmed") |
| // renewing, so the caller can call CloseProven again. When it succeeds, |
| // CloseProven does exactly what Close does. |
| // |
| -// A lease already lost (Err) has nothing left to keep: a failed sync then |
| -// tears down and releases as Close does, and the answer carries the sync's |
| -// error, not ErrCheckpointUnproven, since no retry could release a lease |
| -// someone else may hold. An HA replicator releases through its marker |
| -// (closeHA) either way. |
| +// A failed sync over a lease whose renewal has already failed (Err) is |
| +// different: that error latches on one failed renewal or a local pause, |
| +// and does not mean another box holds the lock. lock.json may still be |
| +// ours and unexpired, so releasing it would hand over unproven state. The |
| +// replicator is abandoned instead (Abandon: renewal and replication |
| +// stopped, no further sync, no release), the lock runs to its TTL, and the |
| +// answer wraps ErrCheckpointAbandoned, the prefix and the cause. An HA |
| +// replicator releases through its marker (closeHA) either way. |
| func (r *Replicator) CloseProven(ctx context.Context) error { |
| if r.ha { |
| return r.closeHA(ctx) |
| @@ -711,11 +747,23 @@ func (r *Replicator) CloseProven(ctx context.Context) error { |
| return r.Close(ctx) |
| } |
| if lost := r.rn.Err(); lost != nil { |
| - return errors.Join(fmt.Errorf("lease: final checkpoint failed after the lease was lost (%v): %w", lost, err), r.Close(ctx)) |
| + done, cancel := context.WithCancel(context.Background()) |
| + cancel() // no further sync: the checkpoint just failed |
| + r.Abandon(done) |
| + return fmt.Errorf("%w: %s (renewal: %v): %w", ErrCheckpointAbandoned, r.leaser.Path, lost, err) |
| } |
| return fmt.Errorf("%w: %w", ErrCheckpointUnproven, err) |
| } |
| +// 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. |
| +func LoseLeaseForTest(r *Replicator, err error) { |
| + r.rn.mu.Lock() |
| + defer r.rn.mu.Unlock() |
| + r.rn.loseLocked(err) |
| +} |
| + |
| // shutdownSyncTimeout is how long a store's Close retries its final sync |
| // (litestream's ShutdownSyncTimeout), in nanoseconds. Production keeps |
| // litestream's default; SetShutdownSyncTimeoutForTest changes it. |
| @@ -727,6 +775,8 @@ func init() { shutdownSyncTimeout.Store(int64(litestream.DefaultShutdownSyncTime |
| // created from now on retry their final sync at Close; 0 tries once. It |
| // returns the restore. A test seam: a test whose final sync fails on |
| // purpose need not wait out litestream's default 30 seconds of retries. |
| +// The setting is process-global, so it is safe only while no t.Parallel |
| +// test in the calling package (or in package lease) creates replicators. |
| func SetShutdownSyncTimeoutForTest(d time.Duration) (restore func()) { |
| prev := shutdownSyncTimeout.Swap(int64(d)) |
| return func() { shutdownSyncTimeout.Store(prev) } |
diff --git a/internal/lease/release_test.go b/internal/lease/release_test.go| index 2feff9710..20ff7844f 100644 |
| --- a/internal/lease/release_test.go |
| +++ b/internal/lease/release_test.go |
| @@ -489,3 +489,64 @@ func TestCloseProvenKeepsTheLeaseWhenTheFinalSyncFails(t *testing.T) { |
| t.Fatalf("restored %d rows, want 15: the last write did not reach the bucket", n) |
| } |
| } |
| + |
| +// R2 review fix: a failed renewal latches the lease lost without meaning |
| +// another box holds the lock, and a bucket fault that fails the final sync |
| +// fails renewals too. CloseProven over a failed sync and a lease whose |
| +// renewal has failed must not release: lock.json is still ours and |
| +// unexpired. It abandons (no DELETE, renewal stopped, replicator ended) and |
| +// answers ErrCheckpointAbandoned naming the prefix, so the stop can finish |
| +// unclean rather than wait forever. |
| +func TestCloseProvenAbandonsWhenTheLeaseIsLost(t *testing.T) { |
| + fx := leasetest.NewLockFixture(t) |
| + prefix := "instances/lost.example.com" |
| + h, err := lease.Acquire(ctx, fx.Bucket, prefix, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dbPath := tempDB(t) |
| + r, err := h.Replicate(ctx, dbPath, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + closed := false |
| + t.Cleanup(func() { |
| + if !closed { |
| + r.Abandon(ctx) |
| + } |
| + }) |
| + if err := r.SyncAndWait(ctx); err != nil { |
| + t.Fatalf("first sync: %v", err) |
| + } |
| + t.Cleanup(fx.FailReplicaPuts(prefix)) |
| + addRows(t, dbPath, 5) // the last write, which the final sync cannot ship |
| + // The lock's own writes fail too from here, as the bucket fault that |
| + // fails the sync fails a renewal; the loss is latched at once. |
| + fx.FailNextMatching("PUT", 403, func(k string, _ []byte) bool { return k == prefix+"/lock.json" }) |
| + fx.FailNextMatching("DELETE", 403, func(k string, _ []byte) bool { return k == prefix+"/lock.json" }) |
| + lease.LoseLeaseForTest(r, errors.New("renewal: AccessDenied")) |
| + lock := fx.LockBody(prefix) |
| + before := len(fx.Requests()) |
| + |
| + err = r.CloseProven(ctx) |
| + closed = true |
| + if !errors.Is(err, lease.ErrCheckpointAbandoned) || errors.Is(err, lease.ErrCheckpointUnproven) { |
| + t.Fatalf("CloseProven over a failed sync and a lost lease = %v, want ErrCheckpointAbandoned only", err) |
| + } |
| + if !strings.Contains(err.Error(), prefix) { |
| + t.Fatalf("the answer %q does not name %s", err, prefix) |
| + } |
| + if got := fx.LockBody(prefix); !bytes.Equal(got, lock) { |
| + t.Fatalf("lock.json changed: %s, want it left as it was (%s) to run to its TTL", got, lock) |
| + } |
| + for _, req := range fx.Requests()[before:] { |
| + if strings.Contains(req, "lock.json") { |
| + t.Fatalf("CloseProven touched the lock (%s): an abandoned lease is never released", req) |
| + } |
| + } |
| + select { |
| + case <-r.Done(): |
| + default: |
| + t.Fatal("the replicator was not torn down") |
| + } |
| +} |