activator, lease: shutdown abandons an in-flight checkpoint directly (R2)
Fix round 2. The round-1 watcher that abandoned a fleet checkpoint at Shutdown's deadline exited when the checkpoint's own 30 s context ended, yet CloseProven can stay blocked: litestream's replica sync waits on its sync lock behind the background monitor's PUT, which runs under the monitor's own context. Shutdown then waited on the call with nothing left to tear it down. Shutdown teardown no longer depends on the call or its context. Each in-flight fleet CloseProven registers its cancel in e.checkpointCancel; when Shutdown's budget ends, abandonCheckpointsAtExit marks every in-flight or pending-unproven fleet stop abandoned, cancels its checkpoint and abandons its replicator itself (closing the store also cancels the monitor's PUT), and logs C45 when it was the teardown. It no longer waits on the calls: once abandoned they hold no lease. The watcher and shutdownExpired are gone. lease: TryAbandon reports whether the call was the teardown, so C45 is logged once by whoever tore down; CloseProven's lost-lease branch answers ErrSpent when another caller tore down first. CloseProven's forced sync is litestream's two steps with a test hook between them (SetCloseProvenReplicaSyncHookForTest). Witness: TestShutdownAbandonsACheckpointWhoseOwnBudgetEnded holds the monitor's PUT, ends the retry's own budget after it reaches its replica sync (checkpointContext seam and the lease hook), then runs Shutdown with its budget over.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+65 −95internal/activator/pendingwake_linux_test.go+95 −0internal/lease/lease.go+55 −8
CI failed — run details
Intent
<task-notification> <task-id>a0c925fb35f246f63</task-id> <tool-use-id>toolu_01MEcqePLyLwyJzUcspCUhhZ</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 - **Commits:** - `29fb2695 lease, activator: a fleet stop releases only after a proven checkpoint (R2)` - `1a32206f lease, activator: R2 review fixes (no release when lost, shutdown abandon)` - **Tests:** the 2 lease and 8 activator witnesses pass with `-count=3`, and again under `-race`. The related lease and activator runs, the locktest run and the darwin build all pass. Both new fixes failed before they were fixed. - **What the fixes do:** a failed checkpoint over a lost lease now abandons the replicator and leaves `lock.json` to its TTL; it never sends a DELETE. Shutdown now abandons and names an unproven checkpoint before it returns. - **Concerns:** 1. Cancelling the context was not enough. litestream's sync waits behind its own replication already in flight, so Shutdown abandons the replicator next to the blocked call. A non-HA replicator is now torn down only once, so `Close` after `Abandon` returns `ErrSpent` and releases nothing. I did not run the host e2e test that calls `Abandon`. 2. There are two new test seams: `lease.LoseLeaseForTest` (exported) and `checkpointStarted` (nil in production). 3. After its budget ends, Shutdown waits for in-flight checkpoints with no bound of its own. 4. While debugging I wrote one dump to `/home/paulca/.cache/tmp/dump.txt`, outside a `mktemp -d` folder. Another session has since overwritten it, so I left it alone. - **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 (fix round appended)</result> <usage><subagent_tokens>291903</subagent_tokens><tool_uses>36</tool_uses><duration_ms>818240</duration_ms></usage> </task-notification>
Attributed to this commit: 11.6 g CO₂e (1,303,309 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 632801e02..ea0b1b0df 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -676,13 +676,12 @@ type actEntry struct { |
| // (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{} |
| + // checkpointCancel is non-nil while finishStop's CloseProven is in |
| + // flight, and cancels its context; 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. |
| + checkpointCancel context.CancelFunc |
| checkpointUnproven bool |
| checkpointAbandoned bool |
| // stopRetrying is true while a retried proc.Stop call for a still-running |
| @@ -1742,14 +1741,13 @@ type Service struct { |
| 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. |
| + // e.checkpointCancel. 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 |
| + // 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) |
| } |
| // New wires the state machine to its side-effect backend and due-time store. |
| @@ -1762,8 +1760,6 @@ 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)) |
| @@ -5529,12 +5525,12 @@ 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; Abandon gives the lease up |
| -// to its TTL. A Rep without it (a local demo lease, which replicates |
| +// 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. |
| type provenCloser interface { |
| CloseProven(ctx context.Context) error |
| - Abandon(ctx context.Context) |
| + TryAbandon(ctx context.Context) bool |
| } |
| var _ provenCloser = (*lease.Replicator)(nil) |
| @@ -5572,59 +5568,46 @@ func (a *Service) fleetProvenCloser(e *actEntry) (provenCloser, bool) { |
| // - 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. |
| +// 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. |
| 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 |
| + mk := a.checkpointContext |
| + if mk == nil { |
| + mk = context.WithCancel |
| + } |
| + cctx, cancel := mk(ctx) |
| + e.checkpointCancel = cancel |
| + started := a.checkpointStarted |
| a.mu.Unlock() |
| + defer cancel() |
| 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 |
| + a.mu.Lock() |
| + e.checkpointCancel = nil |
| + shutting := a.shuttingDown |
| + a.mu.Unlock() |
| + prefix := "" |
| + if shutting { |
| + prefix = "shutdown: " |
| + } |
| switch { |
| case errors.Is(err, lease.ErrCheckpointAbandoned): |
| - if byShutdown.Load() { |
| - logCheckpointAbandoned("shutdown: ", e.host) |
| - } else { |
| - logCheckpointAbandoned("", e.host) |
| - } |
| + logCheckpointAbandoned(prefix, e.host) |
| case errors.Is(err, lease.ErrCheckpointUnproven): |
| a.mu.Lock() |
| - shutting := a.shuttingDown |
| + shutting = a.shuttingDown |
| if !shutting { |
| a.keepPendingLocked(e, outcome) |
| e.checkpointUnproven = true |
| @@ -5640,8 +5623,9 @@ func (a *Service) closeFleetCheckpoint(ctx context.Context, e *actEntry, pc prov |
| } |
| return true, err |
| } |
| - abandonCheckpoint(pc) |
| - logCheckpointAbandoned("shutdown: ", e.host) |
| + if abandonCheckpoint(pc) { |
| + logCheckpointAbandoned("shutdown: ", e.host) |
| + } |
| } |
| return false, err |
| } |
| @@ -5649,11 +5633,12 @@ func (a *Service) closeFleetCheckpoint(ctx context.Context, e *actEntry, pc prov |
| // 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) { |
| +// failed, as a crash would ship nothing more). It reports whether this |
| +// call tore the replicator down, and so must name it (C45). |
| +func abandonCheckpoint(pc provenCloser) bool { |
| done, cancel := context.WithCancel(context.Background()) |
| cancel() |
| - pc.Abandon(done) |
| + return pc.TryAbandon(done) |
| } |
| // logCheckpointAbandoned is the ERROR an abandoned fleet checkpoint logs, |
| @@ -5663,45 +5648,36 @@ func logCheckpointAbandoned(prefix, host string) { |
| 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. |
| +// 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 (e.checkpointCancel), 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, and named when this is the teardown. 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() { |
| 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) |
| + if e.checkpointAbandoned || (e.checkpointCancel == nil && !e.checkpointUnproven) { |
| + continue |
| + } |
| + e.checkpointAbandoned = true |
| + if e.checkpointCancel != nil { |
| + e.checkpointCancel() |
| } |
| + 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) |
| + if pc, ok := a.fleetProvenCloser(e); ok && abandonCheckpoint(pc) { |
| + logCheckpointAbandoned("shutdown: ", e.host) |
| } |
| - 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() { |
| @@ -6519,9 +6495,6 @@ 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) |
| @@ -6537,9 +6510,6 @@ 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 |
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go| index e8b76b25e..2084ab682 100644 |
| --- a/internal/activator/pendingwake_linux_test.go |
| +++ b/internal/activator/pendingwake_linux_test.go |
| @@ -1631,3 +1631,98 @@ func TestShutdownAbandonsAPendingCheckpointBlockedInTheBucket(t *testing.T) { |
| 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) |
| + } |
| +} |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 2658a47c2..4bab97a00 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -640,15 +640,21 @@ func (r *Replicator) Lost() <-chan struct{} { return r.rn.lost } |
| // 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) { |
| +// 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 { |
| 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 |
| + return true |
| } |
| if !r.claimTeardown() { |
| - return |
| + return false |
| } |
| r.rn.stop() // deliberately no ReleaseLease — the TTL is the point |
| // litestream's only teardown is Close, which includes a sync a real crash |
| @@ -656,6 +662,7 @@ func (r *Replicator) Abandon(ctx context.Context) { |
| // first, and reclaims the replication goroutines either way. |
| _ = r.store.Close(ctx) |
| r.closeDone() |
| + return true |
| } |
| // claimTeardown reports whether the caller is the one to tear a non-HA |
| @@ -723,8 +730,8 @@ var ErrCheckpointUnproven = errors.New("lease: final checkpoint not confirmed") |
| 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 |
| +// checkpoint first (fleet record labels R2): the forced sync that Close |
| +// runs and ignores (SyncAndWait; forcedSync here) is load-bearing. When it fails, nothing is |
| // torn down and nothing released: the answer wraps ErrCheckpointUnproven |
| // and the cause, replication keeps running and the lease stays held and |
| // renewing, so the caller can call CloseProven again. When it succeeds, |
| @@ -742,19 +749,59 @@ func (r *Replicator) CloseProven(ctx context.Context) error { |
| if r.ha { |
| return r.closeHA(ctx) |
| } |
| - err := r.db.SyncAndWait(ctx) |
| + err := r.forcedSync(ctx) |
| if err == nil { |
| return r.Close(ctx) |
| } |
| if lost := r.rn.Err(); lost != nil { |
| done, cancel := context.WithCancel(context.Background()) |
| cancel() // no further sync: the checkpoint just failed |
| - r.Abandon(done) |
| + if !r.TryAbandon(done) { |
| + // Torn down meanwhile by another caller (an abandonment at |
| + // shutdown), 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) |
| } |
| return fmt.Errorf("%w: %w", ErrCheckpointUnproven, err) |
| } |
| +// forcedSync is litestream's DB.SyncAndWait, the database sync and then |
| +// the replica sync, with closeProvenReplicaSync (a test seam) between |
| +// them. The replica sync waits for any replication already in flight |
| +// whatever ctx says: only closing the store (Abandon) cancels that. |
| +func (r *Replicator) forcedSync(ctx context.Context) error { |
| + if r.db.Replica == nil { |
| + return fmt.Errorf("no replica configured") |
| + } |
| + if err := r.db.Sync(ctx); err != nil { |
| + return fmt.Errorf("db sync: %w", err) |
| + } |
| + if hook := closeProvenReplicaSync.Load(); hook != nil { |
| + (*hook)() |
| + } |
| + if err := r.db.Replica.Sync(ctx); err != nil { |
| + return fmt.Errorf("replica sync: %w", err) |
| + } |
| + return nil |
| +} |
| + |
| +// closeProvenReplicaSync, when set, runs in CloseProven between its |
| +// database sync and its replica sync. A test seam; nil in production. |
| +var closeProvenReplicaSync atomic.Pointer[func()] |
| + |
| +// SetCloseProvenReplicaSyncHookForTest sets the hook CloseProven runs |
| +// between its database sync and its replica sync, and returns the |
| +// restore. Process-global, like SetShutdownSyncTimeoutForTest. |
| +func SetCloseProvenReplicaSyncHookForTest(hook func()) (restore func()) { |
| + var p *func() |
| + if hook != nil { |
| + p = &hook |
| + } |
| + prev := closeProvenReplicaSync.Swap(p) |
| + return func() { closeProvenReplicaSync.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. |