carlos / platform Public

lease: a non-HA teardown is terminal before any sync (M1 review P2)

Close, CloseProven and SyncAndWait now claim a close's sync phase
before syncing and answer ErrSpent once a teardown has begun, so a
repeated close or a close after Abandon makes no request and reopens
nothing (litestream's DB.init reopens a closed database). The database
sync runs under syncGate's read lock and TryAbandon claims under its
write lock; the replica sync stays outside it, so an abandonment still
cancels a checkpoint in flight. Abandoned reports whether the teardown
was an abandonment.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 3ab3fb82558baffa4d23fb8a734a7fc8b0e8d729 parent a0de4b1
2 files changed, +215 −27
  • internal/lease/lease.go +125 −27
  • internal/lease/teardown_linux_test.go +90 −0
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index 4bab97a00..22ce699a0 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -518,14 +518,25 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
// acquired *before* replication starts and renewed on a ticker; Close stops
// replication and releases the lease.
type Replicator struct {
- leaser *lss3.Leaser
- store *litestream.Store
- db *litestream.DB
- rn *renewer
- mu sync.Mutex
- busy bool
- spent bool
- tornDown bool // a non-HA teardown has begun (claimTeardown); guarded by mu
+ leaser *lss3.Leaser
+ store *litestream.Store
+ db *litestream.DB
+ rn *renewer
+ mu sync.Mutex
+ busy bool
+ spent bool
+ tornDown bool // a non-HA teardown has begun (claimTeardown); guarded by mu
+ abandoned bool // that teardown was an abandonment (Abandoned); guarded by mu
+ closing bool // a non-HA Close or CloseProven is syncing (beginClose); guarded by mu
+ // syncGate orders a close's database sync against an abandonment
+ // (M1 review Astra P2-1): the sync runs under its read lock, and only
+ // while no teardown has begun; TryAbandon claims the teardown under
+ // its write lock. So no database sync starts once a teardown has
+ // (litestream's DB.init reopens a closed database, and nothing would
+ // close it again), while the replica sync, which can wait on the
+ // bucket, runs outside it, so an abandonment can still cancel a
+ // checkpoint in flight.
+ syncGate sync.RWMutex
poison error
replicaClient litestream.ReplicaClient // private local-replica test seam
// An HA replicator's (Held.Replicate carries them over): it releases
@@ -614,8 +625,10 @@ func (r *Replicator) SyncAndWait(ctx context.Context) error {
if r.finalized {
return ErrSpent
}
+ return r.db.SyncAndWait(ctx)
}
- return r.db.SyncAndWait(ctx)
+ // A non-HA replicator syncs nothing once torn down (ErrSpent).
+ return r.guardedSync(ctx, false)
}
// Err reports whether lease renewal has failed (leadership lost).
@@ -653,7 +666,10 @@ func (r *Replicator) TryAbandon(ctx context.Context) bool {
_, _ = r.finalize(ctx, false, false) // the one teardown; a later release never syncs
return true
}
- if !r.claimTeardown() {
+ r.syncGate.Lock()
+ claimed := r.claimTeardown(true)
+ r.syncGate.Unlock()
+ if !claimed {
return false
}
r.rn.stop() // deliberately no ReleaseLease — the TTL is the point
@@ -665,18 +681,59 @@ func (r *Replicator) TryAbandon(ctx context.Context) bool {
return true
}
+// Abandoned reports whether a non-HA replicator's teardown was an
+// abandonment (TryAbandon, or CloseProven's own over a lost lease), by
+// whichever call made it: the lease was not released and frees at its
+// TTL. False before any teardown, after a release, and for an HA
+// replicator. A caller whose TryAbandon answered false asks it to learn
+// whether the lease went to its TTL all the same.
+func (r *Replicator) Abandoned() bool {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.abandoned
+}
+
// claimTeardown reports whether the caller is the one to tear a non-HA
-// replicator down (Close or Abandon); false once another has.
-func (r *Replicator) claimTeardown() bool {
+// replicator down (Close or Abandon); false once another has. abandon
+// records which kind of teardown it is (Abandoned). It ends any close's
+// sync phase (closing).
+func (r *Replicator) claimTeardown(abandon bool) bool {
r.mu.Lock()
defer r.mu.Unlock()
if r.tornDown {
return false
}
- r.tornDown = true
+ r.tornDown, r.abandoned, r.closing = true, abandon, false
return true
}
+// beginClose claims a non-HA Close's or CloseProven's sync phase, before
+// any sync: false once a teardown has begun or another close is syncing,
+// and the caller then does nothing at all (ErrSpent). A close whose
+// checkpoint stays unproven ends the phase (endClose) so it can be tried
+// again; one that tears down ends it in claimTeardown.
+func (r *Replicator) beginClose() bool {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.tornDown || r.closing {
+ return false
+ }
+ r.closing = true
+ return true
+}
+
+func (r *Replicator) endClose() {
+ r.mu.Lock()
+ r.closing = false
+ r.mu.Unlock()
+}
+
+func (r *Replicator) isTornDown() bool {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.tornDown
+}
+
// 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).
@@ -684,16 +741,30 @@ func (r *Replicator) Close(ctx context.Context) error {
if r.ha {
return r.closeHA(ctx)
}
+ // A teardown is terminal: once one has begun (or another close is
+ // syncing), nothing is synced, reopened or released (M1 review Astra
+ // P2-1).
+ if !r.beginClose() {
+ return ErrSpent
+ }
// Force one full sync before teardown. litestream's DB.Close only
// final-syncs an *initialized* DB, and initialization happens on the
// monitor's first pass — so a checkpoint within ~a second of Replicate
// could silently ship nothing (a drain right after a wake, caught by the
- // mesh live test: the replica held no restorable snapshot). SyncAndWait
+ // mesh live test: the replica held no restorable snapshot). The sync
// forces init + a replica sync; its error is deliberately dropped — with
// 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() {
+ _ = r.guardedSync(ctx, false)
+ return r.teardownAndRelease(ctx)
+}
+
+// teardownAndRelease is a non-HA close's teardown once its sync phase is
+// over: the store closed (its own final sync included), then the lease
+// released under a budget of its own. ErrSpent, with nothing released,
+// when an abandonment tore the replicator down meanwhile.
+func (r *Replicator) teardownAndRelease(ctx context.Context) error {
+ if !r.claimTeardown(false) {
return ErrSpent // abandoned meanwhile: nothing is released
}
err := r.store.Close(ctx)
@@ -731,7 +802,7 @@ var ErrCheckpointAbandoned = errors.New("lease: final checkpoint not confirmed a
// CloseProven is Close for a stop whose release must prove its final
// 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
+// runs and ignores (guardedSync) 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,
@@ -745,14 +816,28 @@ var ErrCheckpointAbandoned = errors.New("lease: final checkpoint not confirmed a
// 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.
+//
+// Once a teardown has begun (a Close, an abandonment) CloseProven answers
+// ErrSpent before any sync, as Close does; an abandonment that lands while
+// its sync is in flight makes it answer ErrSpent too, with nothing
+// released.
func (r *Replicator) CloseProven(ctx context.Context) error {
if r.ha {
return r.closeHA(ctx)
}
- err := r.forcedSync(ctx)
+ if !r.beginClose() {
+ return ErrSpent // torn down, or another close is syncing: nothing more
+ }
+ err := r.guardedSync(ctx, true)
if err == nil {
- return r.Close(ctx)
+ return r.teardownAndRelease(ctx)
+ }
+ if r.isTornDown() {
+ // Abandoned while the checkpoint was in flight (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)
}
+ r.endClose()
if lost := r.rn.Err(); lost != nil {
done, cancel := context.WithCancel(context.Background())
cancel() // no further sync: the checkpoint just failed
@@ -766,19 +851,32 @@ func (r *Replicator) CloseProven(ctx context.Context) error {
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 {
+// guardedSync is litestream's DB.SyncAndWait, the database sync and then
+// the replica sync, for a non-HA replicator, guarded against its teardown
+// (syncGate): ErrSpent, with nothing synced, once a teardown has begun,
+// and the database sync starts only under syncGate's read lock. hook runs
+// closeProvenReplicaSync (a test seam, CloseProven's) between the two. The
+// replica sync waits for any replication already in flight whatever ctx
+// says: only closing the store (Abandon) cancels that.
+func (r *Replicator) guardedSync(ctx context.Context, hook bool) error {
if r.db.Replica == nil {
return fmt.Errorf("no replica configured")
}
- if err := r.db.Sync(ctx); err != nil {
+ r.syncGate.RLock()
+ if r.isTornDown() {
+ r.syncGate.RUnlock()
+ return ErrSpent
+ }
+ err := r.db.Sync(ctx)
+ r.syncGate.RUnlock()
+ if err != nil {
return fmt.Errorf("db sync: %w", err)
}
- if hook := closeProvenReplicaSync.Load(); hook != nil {
- (*hook)()
+ if h := closeProvenReplicaSync.Load(); hook && h != nil {
+ (*h)()
+ }
+ if r.isTornDown() {
+ return ErrSpent
}
if err := r.db.Replica.Sync(ctx); err != nil {
return fmt.Errorf("replica sync: %w", err)
diff --git a/internal/lease/teardown_linux_test.go b/internal/lease/teardown_linux_test.go
new file mode 100644
index 000000000..ea39c2469
--- /dev/null
+++ b/internal/lease/teardown_linux_test.go
@@ -0,0 +1,90 @@
+//go:build linux
+
+package lease_test
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/lease"
+ leasetest "github.com/carlosframework/platform/internal/lease/locktest"
+)
+
+// openDBFiles counts this process's open file descriptors on the database
+// at path and its -wal and -shm files: litestream's DB.init opens the
+// database (sql.DB and a long-running descriptor), its Close closes them.
+func openDBFiles(t *testing.T, path string) int {
+ t.Helper()
+ fds, err := os.ReadDir("/proc/self/fd")
+ if err != nil {
+ t.Fatal(err)
+ }
+ n := 0
+ for _, fd := range fds {
+ target, err := os.Readlink(filepath.Join("/proc/self/fd", fd.Name()))
+ if err != nil {
+ continue // closed since the listing
+ }
+ if target == path || target == path+"-wal" || target == path+"-shm" {
+ n++
+ }
+ }
+ return n
+}
+
+// replicating is a non-HA replicator of a fresh database on prefix, its
+// first sync shipped.
+func replicating(t *testing.T, fx *leasetest.LockFixture, prefix string) (*lease.Replicator, string) {
+ t.Helper()
+ 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)
+ }
+ t.Cleanup(func() { r.Abandon(ctx) })
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatalf("first sync: %v", err)
+ }
+ return r, dbPath
+}
+
+// M1 review Astra P2-1: a non-HA teardown is terminal. Once a Close or an
+// Abandon has torn the replicator down, a later Close or CloseProven
+// answers ErrSpent before any sync: it makes no request to the bucket and
+// reopens nothing (litestream's DB.init would reopen a closed database,
+// which no later Close would close).
+func TestTeardownIsTerminal(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ first func(*lease.Replicator) error
+ again func(*lease.Replicator) error
+ }{
+ {"close then close", func(r *lease.Replicator) error { return r.Close(ctx) }, func(r *lease.Replicator) error { return r.Close(ctx) }},
+ {"close then close proven", func(r *lease.Replicator) error { return r.Close(ctx) }, func(r *lease.Replicator) error { return r.CloseProven(ctx) }},
+ {"abandon then close", func(r *lease.Replicator) error { r.Abandon(ctx); return nil }, func(r *lease.Replicator) error { return r.Close(ctx) }},
+ {"abandon then close proven", func(r *lease.Replicator) error { r.Abandon(ctx); return nil }, func(r *lease.Replicator) error { return r.CloseProven(ctx) }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx := leasetest.NewLockFixture(t)
+ r, dbPath := replicating(t, fx, "instances/terminal.example.com")
+ if err := tc.first(r); err != nil {
+ t.Fatalf("first teardown: %v", err)
+ }
+ if n := openDBFiles(t, dbPath); n != 0 {
+ t.Fatalf("the first teardown left %d descriptors on the database open", n)
+ }
+ before := len(fx.Requests())
+ err := tc.again(r)
+ reqs, open := fx.Requests()[before:], openDBFiles(t, dbPath)
+ if !errors.Is(err, lease.ErrSpent) || len(reqs) != 0 || open != 0 {
+ t.Fatalf("a call after the teardown = %v, made requests %v, left %d descriptors on the database open; want ErrSpent, none and none", err, reqs, open)
+ }
+ })
+ }
+}