region HA P1a Tasks 6-7: fix round 1 (one serialized finalization; marker PUTs without SDK retries)
Finish, Close and ReleaseMarker on an HA replicator now share one serialized, cached finalization (finalize, under finMu): the forced sync and the store's close run once, a release waits for one already running before it writes the marker, and nothing syncs afterwards (SyncAndWait answers ErrSpent; Abandon finalizes without a sync). Witness: TestNoReplicaWriteAfterTheMarker, a Close racing a Finish paused before its final sync. putMarker turns the SDK's automatic retries off, so each attempt of a release, RetryPending or AcquireHA's settle is one PUT and a 503 keeps the obligation. Witness: TestMarkerPutIsOneRequestPerAttempt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+215
−34
internal/lease/export_test.go+8 −0internal/lease/lease.go+20 −5internal/lease/release.go+58 −29internal/lease/release_test.go+129 −0
diff --git a/internal/lease/export_test.go b/internal/lease/export_test.go| index b164e2180..3afd92d03 100644 |
| --- a/internal/lease/export_test.go |
| +++ b/internal/lease/export_test.go |
| @@ -43,3 +43,11 @@ func SetOwedClockForTest(now func() time.Time) func() { |
| owedNow = now |
| return func() { owedNow = prev } |
| } |
| + |
| +// SetFinalSyncHookForTest runs hook inside the HA finalization, before its |
| +// forced sync, and returns the restore. |
| +func SetFinalSyncHookForTest(hook func()) func() { |
| + prev := finalSyncHook |
| + finalSyncHook = hook |
| + return func() { finalSyncHook = prev } |
| +} |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 6bd3e5f0c..3c786b0d3 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -465,15 +465,18 @@ type Replicator struct { |
| poison error |
| replicaClient litestream.ReplicaClient // private local-replica test seam |
| // An HA replicator's (Held.Replicate carries them over): it releases |
| - // through the marker only. finished, finishTXID and finishErr are |
| - // Finish's; released is set by the first release. Guarded by mu. |
| + // through the marker only. released is set by the first release |
| + // (guarded by mu). finMu serializes the one finalization (finalize) |
| + // and guards its cached answer. |
| ha bool |
| base hafresh.Marker |
| region string |
| - finished bool |
| + released bool |
| + finMu sync.Mutex |
| + finalized bool |
| finishTXID uint64 |
| finishErr error |
| - released bool |
| + closeErr error |
| } |
| // ReplicateWithLease acquires the single-writer lease at |
| @@ -497,8 +500,16 @@ func ReplicateWithLease(ctx context.Context, dbPath, bucket, prefix, region stri |
| // SyncAndWait forces a full sync of the database to the replica and blocks |
| // until the remote position catches up — used by tests to make replication |
| -// observable without waiting on monitor intervals. |
| +// observable without waiting on monitor intervals. On an HA replicator it |
| +// is serialized with the finalization and refused once that has run. |
| func (r *Replicator) SyncAndWait(ctx context.Context) error { |
| + if r.ha { |
| + r.finMu.Lock() |
| + defer r.finMu.Unlock() |
| + if r.finalized { |
| + return ErrSpent |
| + } |
| + } |
| return r.db.SyncAndWait(ctx) |
| } |
| @@ -521,6 +532,10 @@ func (r *Replicator) Abandon(ctx context.Context) { |
| // 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.finalize(ctx, false) // the one teardown; a later release never syncs |
| + return |
| + } |
| _ = r.store.Close(ctx) |
| } |
diff --git a/internal/lease/release.go b/internal/lease/release.go| index db72c8566..bd215e7dc 100644 |
| --- a/internal/lease/release.go |
| +++ b/internal/lease/release.go |
| @@ -51,7 +51,10 @@ func releaseWithMarker(ctx context.Context, leaser *lss3.Leaser, region string, |
| return owe(o, err) |
| } |
| -// putMarker is one conditional write of an obligation's marker. |
| +// putMarker is one conditional write of an obligation's marker: one PUT, |
| +// with the SDK's own retries off. The obligation queue owns the retries |
| +// (RetryPending's spacing, AcquireHA's settle), so a 503 costs one request |
| +// per attempt, not the SDK's three. |
| func putMarker(ctx context.Context, client lss3.S3API, o Obligation) error { |
| _, err := client.PutObject(ctx, &awss3.PutObjectInput{ |
| Bucket: aws.String(o.Bucket), |
| @@ -59,7 +62,7 @@ func putMarker(ctx context.Context, client lss3.S3API, o Obligation) error { |
| Body: bytes.NewReader(o.Body), |
| ContentType: aws.String("application/json"), |
| IfMatch: aws.String(o.ETag), |
| - }) |
| + }, noRetries) |
| if err == nil { |
| return nil |
| } |
| @@ -69,6 +72,9 @@ func putMarker(ctx context.Context, client lss3.S3API, o Obligation) error { |
| return fmt.Errorf("lease: write release marker: %w", err) |
| } |
| +// noRetries turns the SDK's automatic retries off for one call. |
| +func noRetries(o *awss3.Options) { o.Retryer = aws.NopRetryer{} } |
| + |
| // conditionFailed is a 412 only. A 409 (two conditional writes racing) |
| // says nothing about whose the lock is, so the marker is retried. |
| func conditionFailed(err error) bool { |
| @@ -135,28 +141,50 @@ func (r *Replicator) HA() bool { return r.ha } |
| // store's close (its own final sync), with the lease still held and |
| // renewing. txid is the replica's position after the close. err is |
| // non-nil if either sync failed or the lease's health did: such a |
| -// release is never clean. It runs once; later calls return its answer. |
| +// release is never clean. It is the replicator's one finalization |
| +// (finalize), shared with Close and ReleaseMarker: it runs once, and |
| +// later calls return its answer without syncing again. |
| func (r *Replicator) Finish(ctx context.Context) (txid uint64, err error) { |
| - r.mu.Lock() |
| - if r.finished { |
| - defer r.mu.Unlock() |
| + return r.finalize(ctx, true) |
| +} |
| + |
| +// errAbandoned is the finalization answer of a replicator Abandon tore |
| +// down: no final sync ran, so no marker it writes is clean. |
| +var errAbandoned = errors.New("lease: replication abandoned without a final sync") |
| + |
| +// finalSyncHook runs inside finalize, before the forced sync (a test seam |
| +// for the interleaving with a concurrent release). |
| +var finalSyncHook = func() {} |
| + |
| +// finalize is the HA replicator's one finalization, serialized and |
| +// cached: the forced sync (when sync is set) and the store's close, under |
| +// finMu. Every release calls it before it writes the marker, and waits |
| +// for one already running, so no replica write can follow the marker. |
| +// Once it has run, nothing syncs again: later calls, SyncAndWait |
| +// included, get its answer or ErrSpent. |
| +func (r *Replicator) finalize(ctx context.Context, sync bool) (uint64, error) { |
| + r.finMu.Lock() |
| + defer r.finMu.Unlock() |
| + if r.finalized { |
| return r.finishTXID, r.finishErr |
| } |
| - r.mu.Unlock() |
| - syncErr := r.db.SyncAndWait(ctx) |
| - closeErr := r.store.Close(ctx) |
| - txid = uint64(r.db.Replica.Pos().TXID) |
| - err = errors.Join(syncErr, closeErr, r.rn.Err()) |
| - r.mu.Lock() |
| - defer r.mu.Unlock() |
| - r.finished, r.finishTXID, r.finishErr = true, txid, err |
| - return txid, err |
| + r.finalized = true |
| + syncErr := errAbandoned |
| + if sync { |
| + finalSyncHook() |
| + syncErr = r.db.SyncAndWait(ctx) |
| + } |
| + r.closeErr = r.store.Close(ctx) |
| + r.finishTXID = uint64(r.db.Replica.Pos().TXID) |
| + r.finishErr = errors.Join(syncErr, r.closeErr, r.rn.Err()) |
| + return r.finishTXID, r.finishErr |
| } |
| // ReleaseMarker writes m as the release marker and spends the replicator. |
| -// The store is finished first if Finish has not run. The TXID is always |
| -// Finish's, and a marker is clean only if m says so and Finish succeeded. |
| -// A failure is a persisted *ObligationError. |
| +// It finalizes first (waiting for a Finish already running) if Finish has |
| +// not run. The TXID is always the finalization's, and a marker is clean |
| +// only if m says so and the finalization succeeded. A failure is a |
| +// persisted *ObligationError. |
| func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) error { |
| if !r.ha { |
| return ErrNotHA |
| @@ -168,7 +196,7 @@ func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) error |
| } |
| r.released = true |
| r.mu.Unlock() |
| - txid, err := r.Finish(ctx) |
| + txid, err := r.finalize(ctx, true) |
| m = withBase(r.base, m) |
| m.TXID = txid |
| if err != nil { |
| @@ -177,8 +205,9 @@ func (r *Replicator) ReleaseMarker(ctx context.Context, m hafresh.Marker) error |
| return releaseWithMarker(ctx, r.leaser, r.region, r.rn.stop(), m) |
| } |
| -// closeHA is Close for an HA replicator: the store closed as Close closes |
| -// it (unless Finish already did), then the unclean marker at the replica's |
| +// closeHA is Close for an HA replicator: the shared finalization (as |
| +// Close syncs: the forced sync initializes the DB, the store's close is |
| +// the sync that counts), then the unclean marker at the replica's |
| // position, on its own budget. A second release is a no-op. |
| func (r *Replicator) closeHA(ctx context.Context) error { |
| r.mu.Lock() |
| @@ -187,16 +216,16 @@ func (r *Replicator) closeHA(ctx context.Context) error { |
| return nil |
| } |
| r.released = true |
| - finished, txid := r.finished, r.finishTXID |
| r.mu.Unlock() |
| - var err error |
| - if !finished { |
| - _ = r.db.SyncAndWait(ctx) // as Close: it initializes the DB; the store's close is the sync that counts |
| - err = r.store.Close(ctx) |
| - txid = uint64(r.db.Replica.Pos().TXID) |
| - } |
| + txid, _ := r.finalize(ctx, true) |
| lease := r.rn.stop() |
| relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| defer cancel() |
| - return errors.Join(err, releaseWithMarker(relCtx, r.leaser, r.region, lease, uncleanMarker(r.base, txid))) |
| + return errors.Join(r.storeCloseErr(), releaseWithMarker(relCtx, r.leaser, r.region, lease, uncleanMarker(r.base, txid))) |
| +} |
| + |
| +func (r *Replicator) storeCloseErr() error { |
| + r.finMu.Lock() |
| + defer r.finMu.Unlock() |
| + return r.closeErr |
| } |
diff --git a/internal/lease/release_test.go b/internal/lease/release_test.go| index 81b7a976c..91b7678e2 100644 |
| --- a/internal/lease/release_test.go |
| +++ b/internal/lease/release_test.go |
| @@ -2,17 +2,22 @@ package lease_test |
| import ( |
| "bytes" |
| + "context" |
| "database/sql" |
| "errors" |
| "fmt" |
| + "io" |
| "net/http" |
| "path/filepath" |
| "slices" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| + "github.com/benbjohnson/litestream" |
| lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/superfly/ltx" |
| _ "modernc.org/sqlite" |
| "github.com/carlosframework/platform/internal/hafresh" |
| @@ -287,3 +292,127 @@ func TestStreamCaptureOneSecond(t *testing.T) { |
| t.Fatalf("default interval %s", got) |
| } |
| } |
| + |
| +// recordingReplica logs each replica write as it starts and as it ends. |
| +type recordingReplica struct { |
| + litestream.ReplicaClient |
| + rec func(string) |
| +} |
| + |
| +func (c *recordingReplica) WriteLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, r io.Reader) (*ltx.FileInfo, error) { |
| + c.rec("replica write") |
| + defer c.rec("replica write done") |
| + return c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, r) |
| +} |
| + |
| +func addRows(t *testing.T, path string, n int) { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + for i := 0; i < n; i++ { |
| + if _, err := db.Exec(`INSERT INTO t (body) VALUES ('late')`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// Review fix 1 (I1): Finish, Close and ReleaseMarker share one serialized |
| +// finalization. A Close racing a Finish paused before its final sync |
| +// waits for it, so no replica write starts or ends after the marker, and |
| +// nothing syncs once the finalization has run. |
| +func TestNoReplicaWriteAfterTheMarker(t *testing.T) { |
| + haBox(t) |
| + fx := leasetest.NewLockFixture(t) |
| + var mu sync.Mutex |
| + var events []string |
| + rec := func(e string) { mu.Lock(); events = append(events, e); mu.Unlock() } |
| + marker := func() bool { |
| + v, err := hafresh.DecodeLock(fx.LockBody("instances/h"), "") |
| + return err == nil && v.Lock.Release != nil |
| + } |
| + var once sync.Once |
| + fx.AfterWrite(func(m, _ string) { |
| + if m == http.MethodPut && marker() { |
| + once.Do(func() { rec("marker") }) |
| + } |
| + }) |
| + h := haHeld(t, fx, "instances/h") |
| + lease.SetReplicaClientForTest(h, &recordingReplica{ReplicaClient: lsfile.NewReplicaClient(t.TempDir()), rec: rec}) |
| + path := tempDB(t) |
| + r, err := h.Replicate(ctx, path, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + addRows(t, path, 20) // the final sync has something to ship |
| + |
| + entered, resume := make(chan struct{}), make(chan struct{}) |
| + t.Cleanup(lease.SetFinalSyncHookForTest(func() { close(entered); <-resume })) |
| + finished := make(chan error, 1) |
| + go func() { _, err := r.Finish(ctx); finished <- err }() |
| + <-entered // Finish holds the finalization, before its sync |
| + closed := make(chan error, 1) |
| + go func() { closed <- r.Close(ctx) }() |
| + for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { |
| + if marker() { |
| + close(resume) |
| + t.Fatal("the marker was written while the final sync was still to come") |
| + } |
| + } |
| + close(resume) |
| + if err := <-finished; err != nil { |
| + t.Fatalf("Finish: %v", err) |
| + } |
| + if err := <-closed; err != nil { |
| + t.Fatalf("Close: %v", err) |
| + } |
| + if err := r.SyncAndWait(ctx); !errors.Is(err, lease.ErrSpent) { |
| + t.Fatalf("SyncAndWait after the finalization: %v", err) |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| + i := slices.Index(events, "marker") |
| + if i < 0 || i != len(events)-1 || !slices.Contains(events, "replica write") { |
| + t.Fatalf("events %v: want replica writes, then the marker last", events) |
| + } |
| + if v := lockView(t, fx, "instances/h"); v.Lock.Release.Clean || v.Lock.Release.TXID == 0 { |
| + t.Fatalf("%+v", v.Lock.Release) |
| + } |
| +} |
| + |
| +// Review fix 2: a marker PUT is one request per attempt. The SDK would |
| +// retry a 503 by itself; the obligation queue owns the retries instead, |
| +// through the release, RetryPending and AcquireHA's settle alike. |
| +func TestMarkerPutIsOneRequestPerAttempt(t *testing.T) { |
| + dir := haBox(t) |
| + t0 := time.Now() |
| + now := t0 |
| + t.Cleanup(lease.SetOwedClockForTest(func() time.Time { return now })) |
| + fx := leasetest.NewLockFixture(t) |
| + h := haHeld(t, fx, "instances/h") |
| + attempt := func(what string, f func() error) { |
| + t.Helper() |
| + fx.FailNextMatching(http.MethodPut, http.StatusServiceUnavailable, isMarkerBody) |
| + before := len(fx.Requests()) |
| + err := f() |
| + var oe *lease.ObligationError |
| + if !errors.As(err, &oe) { |
| + t.Fatalf("%s: want an ObligationError, got %v", what, err) |
| + } |
| + if r := fx.Requests()[before:]; !slices.Equal(r, []string{"PUT instances/h/lock.json"}) { |
| + t.Fatalf("%s: requests %v, want one PUT", what, r) |
| + } |
| + if len(lease.PendingObligations()) != 1 || len(dirFiles(t, dir)) != 1 { |
| + t.Fatalf("%s: the obligation was not kept", what) |
| + } |
| + } |
| + attempt("release", func() error { return h.Release(ctx) }) |
| + now = t0.Add(time.Minute) |
| + attempt("RetryPending", func() error { return lease.RetryPending(ctx) }) |
| + attempt("AcquireHA's settle", func() error { |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + return err |
| + }) |
| +} |