lease, activator: a fleet stop releases only after a proven checkpoint (R2)
Replicator.Close releases the lease even when its final sync fails, so a successor acquiring a released lease proved nothing about the predecessor's last writes. Fleet record labels R2 requires a proven final checkpoint before a fleet-placed row's lease is released. lease: CloseProven makes Close's forced SyncAndWait load-bearing. On failure it returns ErrCheckpointUnproven wrapping the cause, and leaves replication running and the lease held and renewing, so a later call can succeed. On success it does exactly what Close does. A lease already lost tears down as Close does (nothing left to keep). HA replicators keep closeHA. Abandon's doc now names its one production caller. SetShutdownSyncTimeoutForTest lets tests skip litestream's 30 s retry of a failing final sync. locktest: FailReplicaPuts(prefix) fails every PUT under a prefix except its lock.json with a 403 until heal() is called. activator: finishStop releases a non-HA fleet-placed row (FleetPlacement of the entry's route region) through CloseProven when its Rep offers it (narrow interface; demo leases and fakes keep Close). Unproven, it logs C44 and keeps the stop pending through keepPendingLocked; the sweep's existing reapCurrentGen -> finishPendingStop -> finishStop path retries. During Shutdown an unproven checkpoint abandons the replicator instead, so the lease runs to its TTL, and logs an ERROR naming the host. Platform-region rows still call Close unchanged. startrule: the empty-start refusal for a moved labelled row with nothing set aside now reads as C43 (draft for copy review), still wrapping ErrNothingToRestore. Tests: TestCloseProvenKeepsTheLeaseWhenTheFinalSyncFails, TestFleetStopWithFailedCheckpointStaysPending, TestShutdownWithUnprovenCheckpointLeavesLeaseToTTL, TestPlatformRegionStopUnchanged (real Service and ExecBackend against the lock fixture, barrier on a checkpointKept test seam), and the start rule pins TestFirstLabelOnServingBoxWithoutReplicaRefuses and TestLabelledInstanceWithNoDatabaseAnywhereRefuses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+69 −0internal/activator/pendingwake_linux_test.go+206 −0internal/activator/startrule.go+16 −3internal/activator/startrule_test.go+48 −2internal/lease/lease.go+59 −3internal/lease/locktest/fixture.go+40 −0internal/lease/release_test.go+73 −0
Intent
<task-notification> <task-id>ac1b40faeaa034e33</task-id> <tool-use-id>toolu_01SHFQ32zr8am9hEmjx3Hi4E</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ac77363b-5830-422c-9f38-d7f2540dd398/tasks/ac1b40faeaa034e33.output</output-file> <status>completed</status> <summary>Agent "Implement Task 1: R1 wake fence" 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 Commits: - c8b6eb49 activator: fence stale unlabelled fleet wakes under the lease (R1) - 6018c076 activator: R1 fence review fixes (sentinels, worker backoff, barriers) - e5a77903 activator: race-free worker tick barrier in the R1 witnesses Tests: the full covering set passed 5 times out of 5 with `-count=5`, and the two worker tests also passed 5 times under `-race`. Fix: the test helper that runs a tick no longer looks at `wk.starting`. It compares the worker's `startDone` channel before and after the tick, and waits on the new channel whenever there is one, even if it is already closed. Both worker tests use the new helper. `TestWorkerUnlabelledFenceBacksOff` now also checks that each worker start lands at the same time as a record read. Concerns: nothing new. Two from round 1 remain open: - The fence shares the worker's crash backoff, as the ruling asked. - `TestRootfsWorkerPendingNeedsNoProof` was already flaky on e27f469d, the commit before T1. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-record-labels/.superpowers/sdd/2026-11-14-fleet-record-labels/task-1-report.md</result> <usage><subagent_tokens>208505</subagent_tokens><tool_uses>7</tool_uses><duration_ms>177701</duration_ms></usage> </task-notification>
Attributed to this commit: 10.5 g CO₂e (1,155,510 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 a5f21e53a..9e19f2570 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1725,6 +1725,11 @@ type Service struct { |
| // has returned, before the critical section that ends the wake (wake). |
| // 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. |
| + checkpointKept func(host string) |
| } |
| // New wires the state machine to its side-effect backend and due-time store. |
| @@ -5422,6 +5427,40 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| a.mu.Unlock() |
| return |
| } |
| + } else if pc, ok := a.fleetProvenCloser(e); ok { |
| + // A fleet-placed row's release waits for a proven final checkpoint |
| + // (fleet record labels R2): Close releases even when its final |
| + // 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) |
| + } |
| } else if e.rep != nil { |
| repErr = e.rep.Close(ctx) |
| } |
| @@ -5488,6 +5527,36 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| log.Printf("activator: %s hibernated", e.host) |
| } |
| +// 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 |
| +// nothing, or a test fake) closes with Close as before. |
| +type provenCloser interface { |
| + CloseProven(ctx context.Context) error |
| + Abandon(ctx context.Context) |
| +} |
| + |
| +var _ provenCloser = (*lease.Replicator)(nil) |
| + |
| +// fleetProvenCloser is e's replica as a provenCloser when its stop must |
| +// prove its final checkpoint before the release: a non-HA replica of a |
| +// fleet-placed row (registry.FleetPlacement of the entry's route region). |
| +// Takes a.mu for the route; the caller does not hold it. |
| +func (a *Service) fleetProvenCloser(e *actEntry) (provenCloser, bool) { |
| + a.mu.Lock() |
| + region, rep := e.route.Region, e.rep |
| + a.mu.Unlock() |
| + if rep == nil { |
| + return nil, false |
| + } |
| + if _, fleet := registry.FleetPlacement(region); !fleet { |
| + return nil, false |
| + } |
| + pc, ok := rep.(provenCloser) |
| + return pc, ok |
| +} |
| + |
| // Start launches the background sweeper that puts idle instances to sleep and |
| // stands down lost leases/dead children between requests. |
| func (a *Service) Start() { |
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go| index 1cb617bad..101d565f0 100644 |
| --- a/internal/activator/pendingwake_linux_test.go |
| +++ b/internal/activator/pendingwake_linux_test.go |
| @@ -17,6 +17,8 @@ import ( |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -1290,3 +1292,207 @@ func TestWorkerUnlabelledFenceBacksOff(t *testing.T) { |
| t.Fatal("a fenced worker started") |
| } |
| } |
| + |
| +// R2 (fleet record labels): a fleet stop's final checkpoint must succeed |
| +// before its lease is released. checkpointRig is one box serving host |
| +// through the production wake and stop: a real Service over a real |
| +// ExecBackend, its lease and litestream replication against the lock |
| +// fixture, and a child that is the test binary's fake app. The database |
| +// holds one row before the wake. |
| +type checkpointRig struct { |
| + fx *locktest.LockFixture |
| + b *ExecBackend |
| + a *Service |
| + rt registry.Route |
| + prefix string |
| + log *lockedBuf |
| + // kept receives the host each time a stop is kept pending over an |
| + // unproven checkpoint (Service.checkpointKept). |
| + kept chan string |
| +} |
| + |
| +func newCheckpointRig(t *testing.T, region string) *checkpointRig { |
| + t.Helper() |
| + requireUnixSockets(t) |
| + // A final sync that fails is tried once, not retried for litestream's |
| + // default 30 seconds. |
| + t.Cleanup(lease.SetShutdownSyncTimeoutForTest(0)) |
| + fx := locktest.NewLockFixture(t) |
| + b := testExecBackend(t) |
| + b.Cfg.Bucket = fx.Bucket |
| + stageServingLive(t, b, ruleHost) |
| + rt := registry.Route{Host: ruleHost, Kind: "instance", Hibernate: true, Socket: tmpSock(t), |
| + DBPath: filepath.Join(b.DataDir, ruleHost+".db"), Region: region} |
| + writeUsableDB(t, rt.DBPath) |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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. |
| + t.Cleanup(func() { |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + r.a.Shutdown(ctx) |
| + }) |
| + return r |
| +} |
| + |
| +// wake wakes the host and returns its awake entry. |
| +func (r *checkpointRig) wake(t *testing.T) *actEntry { |
| + t.Helper() |
| + release, err := r.a.beginRequest(context.Background(), r.rt) |
| + if err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + release() |
| + r.a.mu.Lock() |
| + defer r.a.mu.Unlock() |
| + e := r.a.entries[r.rt.Host] |
| + if e == nil || e.state != actAwake || e.rep == nil { |
| + t.Fatalf("after the wake the entry is %+v", e) |
| + } |
| + return e |
| +} |
| + |
| +// stop begins e's idle stop and returns the channel that closes once the |
| +// stop has finished. |
| +func (r *checkpointRig) stop(e *actEntry) chan struct{} { |
| + r.a.mu.Lock() |
| + defer r.a.mu.Unlock() |
| + r.a.beginStopLocked(e, StopIdle) |
| + return e.stopped |
| +} |
| + |
| +// restoredRows restores the bucket's replica as another box would and |
| +// counts its rows. |
| +func (r *checkpointRig) restoredRows(t *testing.T) int { |
| + t.Helper() |
| + path := filepath.Join(t.TempDir(), "box-b.db") |
| + ok, err := lease.Restore(context.Background(), path, r.fx.Bucket, r.prefix, "") |
| + if err != nil || !ok { |
| + t.Fatalf("restore on box B: %v (restored %v)", err, ok) |
| + } |
| + return countRows(t, path) |
| +} |
| + |
| +const c44Line = "final checkpoint for shop.example.com failed. keeping its lease until the checkpoint succeeds" |
| + |
| +func TestFleetStopWithFailedCheckpointStaysPending(t *testing.T) { |
| + r := newCheckpointRig(t, registry.PlacementTarget("pi")) |
| + e := r.wake(t) |
| + heal := r.fx.FailReplicaPuts(r.prefix) |
| + appendRow(t, r.rt.DBPath) // the write the final checkpoint must carry |
| + stopped := r.stop(e) |
| + select { |
| + case host := <-r.kept: |
| + if host != r.rt.Host { |
| + t.Fatalf("kept pending: %s", host) |
| + } |
| + case <-stopped: |
| + t.Fatal("the stop finished over a failed final checkpoint") |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("the stop neither finished nor was kept pending") |
| + } |
| + r.a.mu.Lock() |
| + cur, pending, p, rep := r.a.entries[r.rt.Host], e.pendingStop, e.proc, e.rep |
| + r.a.mu.Unlock() |
| + if !p.Exited() { |
| + t.Fatal("the process is still running") |
| + } |
| + if cur != e || !pending { |
| + t.Fatalf("the entry is not pending (current %v, pending %v)", cur == e, pending) |
| + } |
| + if r.fx.LockBody(r.prefix) == nil { |
| + t.Fatal("the lease was released over an unproven checkpoint") |
| + } |
| + if err := rep.Err(); err != nil { |
| + t.Fatalf("the lease is no longer held: %v", err) |
| + } |
| + if !strings.Contains(r.log.String(), c44Line) { |
| + t.Fatalf("no C44 line in the log:\n%s", r.log.String()) |
| + } |
| + |
| + // Healed, the sweep finishes the stop: the checkpoint is proven, then |
| + // the lease released, and another box restores the write. |
| + heal() |
| + r.a.sweepOnce() |
| + select { |
| + case <-stopped: |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("the sweep did not finish the pending stop once the bucket healed") |
| + } |
| + if body := r.fx.LockBody(r.prefix); body != nil { |
| + t.Fatalf("the lease is still held after a proven checkpoint: %s", body) |
| + } |
| + if n := r.restoredRows(t); n != 2 { |
| + t.Fatalf("box B restored %d rows, want 2: the write after the wake is lost", n) |
| + } |
| +} |
| + |
| +// 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) { |
| + r := newCheckpointRig(t, "") |
| + e := r.wake(t) |
| + t.Cleanup(r.fx.FailReplicaPuts(r.prefix)) |
| + appendRow(t, r.rt.DBPath) |
| + stopped := r.stop(e) |
| + select { |
| + case <-stopped: |
| + case <-r.kept: |
| + t.Fatal("a platform-region stop was kept pending") |
| + case <-time.After(30 * time.Second): |
| + t.Fatalf("the stop never finished:\n%s", r.log.String()) |
| + } |
| + if body := r.fx.LockBody(r.prefix); body != nil { |
| + t.Fatalf("a platform-region stop kept its lease: %s", body) |
| + } |
| + logged := r.log.String() |
| + if !strings.Contains(logged, "activator: final checkpoint "+r.rt.Host+":") { |
| + t.Fatalf("the final sync did not fail, so this proves nothing:\n%s", logged) |
| + } |
| + if strings.Contains(logged, c44Line) { |
| + t.Fatalf("a platform-region stop logged C44:\n%s", logged) |
| + } |
| +} |
diff --git a/internal/activator/startrule.go b/internal/activator/startrule.go| index c6c807ca8..052947bab 100644 |
| --- a/internal/activator/startrule.go |
| +++ b/internal/activator/startrule.go |
| @@ -58,10 +58,23 @@ 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 |
| -// says the instance moved. |
| +// set aside on this box. The wrapping error names the set-aside path, or |
| +// is the C43 refusal (emptyStartRefusal) when nothing was set aside. |
| 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. |
| +type emptyStartRefusal struct{ host, setAside string } |
| + |
| +func (r emptyStartRefusal) Error() string { |
| + // draft for copy review (C43) |
| + return fmt.Sprintf("refusing to start %s empty: it was tied to this box and there is no saved copy to restore. set-aside copies: %s", r.host, r.setAside) |
| +} |
| + |
| +func (emptyStartRefusal) Unwrap() error { return ErrNothingToRestore } |
| + |
| // setAsideRename is the one move the set-aside makes, a seam for the |
| // interrupted-move test. It never replaces anything at the destination. |
| var setAsideRename = instancefs.RenameBetweenNoReplace |
| @@ -370,7 +383,7 @@ func (b *ExecBackend) startAllowed(rt registry.Route, haveLocal, restored bool) |
| 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) |
| } |
| if rt.Moved { |
| - return fmt.Errorf("%s: refusing to start empty: %w: the instance has moved between boxes and no replica was found in the fleet bucket", host, ErrNothingToRestore) |
| + return emptyStartRefusal{host: host, setAside: "none"} |
| } |
| return nil |
| } |
diff --git a/internal/activator/startrule_test.go b/internal/activator/startrule_test.go| index 1938effe8..169fdfc72 100644 |
| --- a/internal/activator/startrule_test.go |
| +++ b/internal/activator/startrule_test.go |
| @@ -614,8 +614,8 @@ func TestMovedInstanceOnACleanBoxRefusesWithoutReplica(t *testing.T) { |
| rt := fleetRoute(b, assignB, true) |
| replicaCalls(t, false) |
| rb, err := wakeOn(t, b, rt, nil) |
| - if !errors.Is(err, ErrNothingToRestore) || !strings.Contains(err.Error(), "moved") { |
| - t.Fatalf("err %v; want ErrNothingToRestore saying the instance moved", err) |
| + if !errors.Is(err, ErrNothingToRestore) || !strings.Contains(err.Error(), "it was tied to this box and there is no saved copy to restore") { |
| + t.Fatalf("err %v; want ErrNothingToRestore in the C43 words", err) |
| } |
| if rb.starts != 0 { |
| t.Fatalf("starts = %d", rb.starts) |
| @@ -630,6 +630,52 @@ func TestMovedInstanceOnACleanBoxRefusesWithoutReplica(t *testing.T) { |
| } |
| } |
| +// R2 (fleet record labels): the first label of an instance names the box |
| +// that was serving it, unlabelled. Its copy there carries no assignment |
| +// marker, so its next wake sets it aside; with no replica in the bucket to |
| +// restore, the start is refused rather than booted empty, and the refusal |
| +// names the set-aside copy for the operator. |
| +func TestFirstLabelOnServingBoxWithoutReplicaRefuses(t *testing.T) { |
| + b := testExecBackend(t) |
| + rt := fleetRoute(b, assignA, true) |
| + want := localCopy(t, rt.DBPath, "") // served unlabelled: no marker |
| + replicaCalls(t, false) |
| + rb, err := wakeOn(t, b, rt, nil) |
| + if !errors.Is(err, ErrNothingToRestore) { |
| + t.Fatalf("err %v; want ErrNothingToRestore", err) |
| + } |
| + if rb.starts != 0 { |
| + t.Fatalf("starts = %d; an unmarked copy with no replica must not boot", rb.starts) |
| + } |
| + 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) |
| + } |
| +} |
| + |
| +// R2: a labelled, moved instance with no local copy, no set-aside copy and |
| +// no replica refuses to start empty, in the C43 words. |
| +func TestLabelledInstanceWithNoDatabaseAnywhereRefuses(t *testing.T) { |
| + b := testExecBackend(t) |
| + rt := fleetRoute(b, assignB, true) |
| + replicaCalls(t, false) |
| + rb, err := wakeOn(t, b, rt, nil) |
| + if !errors.Is(err, ErrNothingToRestore) { |
| + t.Fatalf("err %v; want ErrNothingToRestore", err) |
| + } |
| + const 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: none" |
| + if !strings.Contains(err.Error(), c43) { |
| + t.Fatalf("err %q; want the C43 text %q", err, c43) |
| + } |
| + if rb.starts != 0 { |
| + t.Fatalf("starts = %d", rb.starts) |
| + } |
| + if names := supersededEntries(t, b, rt.Host); len(names) != 0 { |
| + t.Fatalf("nothing was there to set aside, but entries %q appeared", names) |
| + } |
| +} |
| + |
| func TestNewInstanceBootsFresh(t *testing.T) { |
| b := testExecBackend(t) |
| rt := fleetRoute(b, assignA, false) |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index b9513d207..c65f75099 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -19,6 +19,7 @@ import ( |
| "os" |
| "path/filepath" |
| "sync" |
| + "sync/atomic" |
| "time" |
| "github.com/benbjohnson/litestream" |
| @@ -482,6 +483,9 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream. |
| } |
| store := litestream.NewStore([]*litestream.DB{db}, compactionLevels) |
| quietStoreLogs(store, db) |
| + if d := time.Duration(shutdownSyncTimeout.Load()); d != litestream.DefaultShutdownSyncTimeout { |
| + store.SetShutdownSyncTimeout(d) |
| + } |
| store.SnapshotInterval = SnapshotInterval |
| store.SnapshotRetention = SnapshotRetention |
| if h.generationPrefix != "" { |
| @@ -624,9 +628,12 @@ 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. It |
| -// exists so tests can simulate hard box death in-process; production code has |
| -// no reason to call it (a real crash needs no help). |
| +// 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. |
| 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 |
| @@ -676,6 +683,55 @@ func (r *Replicator) Close(ctx context.Context) error { |
| return err |
| } |
| +// ErrCheckpointUnproven is CloseProven's answer when the forced final sync |
| +// failed: the replica may not hold the last writes, so the lease was not |
| +// released. Replication still runs and the lease is still held and |
| +// renewing, so a later CloseProven can prove the checkpoint and release. |
| +var ErrCheckpointUnproven = errors.New("lease: final checkpoint not confirmed") |
| + |
| +// 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 |
| +// 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, |
| +// 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. |
| +func (r *Replicator) CloseProven(ctx context.Context) error { |
| + if r.ha { |
| + return r.closeHA(ctx) |
| + } |
| + err := r.db.SyncAndWait(ctx) |
| + if err == nil { |
| + 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)) |
| + } |
| + return fmt.Errorf("%w: %w", ErrCheckpointUnproven, 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. |
| +var shutdownSyncTimeout atomic.Int64 |
| + |
| +func init() { shutdownSyncTimeout.Store(int64(litestream.DefaultShutdownSyncTimeout)) } |
| + |
| +// SetShutdownSyncTimeoutForTest sets how long the stores of replicators |
| +// 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. |
| +func SetShutdownSyncTimeoutForTest(d time.Duration) (restore func()) { |
| + prev := shutdownSyncTimeout.Swap(int64(d)) |
| + return func() { shutdownSyncTimeout.Store(prev) } |
| +} |
| + |
| // Restore pulls the newest replicated state of s3://bucket/prefix into |
| // dbPath via litestream's restore API — the cold-wake path when the local DB |
| // is missing. Returns restored=false with a nil error when the prefix holds |
diff --git a/internal/lease/locktest/fixture.go b/internal/lease/locktest/fixture.go| index 96b3d4094..6005233ee 100644 |
| --- a/internal/lease/locktest/fixture.go |
| +++ b/internal/lease/locktest/fixture.go |
| @@ -49,6 +49,10 @@ type LockFixture struct { |
| failWhen []matchFault |
| beforeWrite func(method, key string) |
| afterWrite func(method, key string) |
| + // replicaFaults is every FailReplicaPuts fault in force, by id, to |
| + // its prefix. |
| + replicaFaults map[int]string |
| + nextFault int |
| } |
| // matchFault fails the next request of verb whose key and body match. |
| @@ -171,6 +175,39 @@ func (f *LockFixture) AfterWrite(hook func(method, key string)) { |
| f.afterWrite = hook |
| } |
| +// FailReplicaPuts fails every PUT under prefix with 403 AccessDenied, |
| +// which the SDK does not retry, until heal is called: replication's |
| +// writes fail, as they do when the bucket refuses them. The prefix's own |
| +// lock.json is spared, so the lease is still taken, renewed and released. |
| +// Faults stack; each heal lifts only its own. |
| +func (f *LockFixture) FailReplicaPuts(prefix string) (heal func()) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.replicaFaults == nil { |
| + f.replicaFaults = map[int]string{} |
| + } |
| + f.nextFault++ |
| + id := f.nextFault |
| + f.replicaFaults[id] = prefix |
| + return func() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + delete(f.replicaFaults, id) |
| + } |
| +} |
| + |
| +// replicaFaultLocked reports whether a FailReplicaPuts fault covers a PUT |
| +// of key. The caller holds f.mu. |
| +func (f *LockFixture) replicaFaultLocked(key string) bool { |
| + for _, prefix := range f.replicaFaults { |
| + under := prefix == "" || strings.HasPrefix(key, prefix+"/") |
| + if under && key != lockKey(prefix) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| func (f *LockFixture) storeLocked(key string, body []byte) object { |
| sum := md5.Sum(body) |
| o := object{body: append([]byte(nil), body...), etag: `"` + hex.EncodeToString(sum[:]) + `"`, modified: time.Now().UTC()} |
| @@ -239,6 +276,9 @@ func (f *LockFixture) serve(w http.ResponseWriter, r *http.Request) { |
| } |
| } |
| } |
| + if !failing && verb == http.MethodPut && f.replicaFaultLocked(key) { |
| + status, failing = http.StatusForbidden, true |
| + } |
| hook, after := f.beforeWrite, f.afterWrite |
| f.mu.Unlock() |
| if failing { |
diff --git a/internal/lease/release_test.go b/internal/lease/release_test.go| index 6fcbc2a11..2feff9710 100644 |
| --- a/internal/lease/release_test.go |
| +++ b/internal/lease/release_test.go |
| @@ -416,3 +416,76 @@ func TestMarkerPutIsOneRequestPerAttempt(t *testing.T) { |
| return err |
| }) |
| } |
| + |
| +// rowsIn counts t's rows in the database at path. |
| +func rowsIn(t *testing.T, path string) int { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + var n int |
| + if err := db.QueryRow(`SELECT count(*) FROM t`).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// Fleet record labels R2: a fleet stop's final checkpoint must succeed |
| +// before its lease is released. CloseProven's forced sync is load-bearing: |
| +// while replica writes fail it answers ErrCheckpointUnproven and keeps the |
| +// lease held and renewing, replication still running, so a later |
| +// CloseProven over a healed bucket ships the last write and only then |
| +// releases. |
| +func TestCloseProvenKeepsTheLeaseWhenTheFinalSyncFails(t *testing.T) { |
| + fx := leasetest.NewLockFixture(t) |
| + prefix := "instances/proven.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) |
| + } |
| + |
| + heal := fx.FailReplicaPuts(prefix) |
| + addRows(t, dbPath, 5) // the last write, not yet in the bucket |
| + err = r.CloseProven(ctx) |
| + if !errors.Is(err, lease.ErrCheckpointUnproven) { |
| + t.Fatalf("CloseProven over failing replica writes = %v, want ErrCheckpointUnproven", err) |
| + } |
| + if fx.LockBody(prefix) == nil { |
| + t.Fatal("an unproven checkpoint released the lease: lock.json is gone") |
| + } |
| + if err := r.Err(); err != nil { |
| + t.Fatalf("an unproven checkpoint gave up the lease: %v", err) |
| + } |
| + |
| + heal() |
| + if err := r.CloseProven(ctx); err != nil { |
| + t.Fatalf("CloseProven once healed: %v", err) |
| + } |
| + closed = true |
| + if body := fx.LockBody(prefix); body != nil { |
| + t.Fatalf("a proven checkpoint kept the lease: lock.json is %s", body) |
| + } |
| + restored := filepath.Join(t.TempDir(), "restored.db") |
| + if ok, err := lease.Restore(ctx, restored, fx.Bucket, prefix, ""); err != nil || !ok { |
| + t.Fatalf("restore: %v (restored %v)", err, ok) |
| + } |
| + if n := rowsIn(t, restored); n != 15 { |
| + t.Fatalf("restored %d rows, want 15: the last write did not reach the bucket", n) |
| + } |
| +} |