carlos / platform Public

lease: bound renewal attempts by budget and safe deadline

Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev 8233804ded6fce789fbf0a98f226a7d5110b68cd parent 6f69bf1
3 files changed, +312 −3
  • internal/lease/health.go +42 −2
  • internal/lease/pause_test.go +1 −1
  • internal/lease/renew_attempt_test.go +269 −0
diff --git a/internal/lease/health.go b/internal/lease/health.go
index 64441bbfb..fd9895a07 100644
--- a/internal/lease/health.go
+++ b/internal/lease/health.go
@@ -77,6 +77,21 @@ func marginForTTL(ttl time.Duration) time.Duration {
return terminationMargin
}
+func renewAttemptDeadline(started, safeUntil time.Time, ttl time.Duration) time.Time {
+ budget := ttl / 3
+ if budget > 30*time.Second {
+ budget = 30 * time.Second
+ }
+ if budget <= 0 {
+ budget = time.Nanosecond
+ }
+ deadline := started.Add(budget)
+ if safeUntil.Before(deadline) {
+ return safeUntil
+ }
+ return deadline
+}
+
type renewer struct {
ctx context.Context
client lss3.S3API // the leaser's own client: renewals write through renewLease
@@ -220,24 +235,49 @@ func (rn *renewer) renew(ctx context.Context) {
// the lock a post-resume expiry, and the check after the write
// latches the loss.
started := rn.seen
+ until := rn.until
rn.mu.Unlock()
if err != nil {
rn.cancel()
return
}
+ deadline := renewAttemptDeadline(started, until, rn.leaser.TTL)
+ attemptCtx, cancel := context.WithDeadline(ctx, deadline)
if rn.beforeWrite != nil {
rn.beforeWrite()
}
- renewed, err := renewLease(ctx, rn.client, rn.leaser, cur, started.Add(rn.leaser.TTL))
rn.mu.Lock()
health := rn.checkLocked()
+ err = attemptCtx.Err()
+ if err == nil && !time.Now().Before(deadline) {
+ err = context.DeadlineExceeded
+ }
+ if health == nil && err != nil {
+ rn.loseLocked(err)
+ }
+ rn.mu.Unlock()
+ if health != nil || err != nil {
+ cancel()
+ rn.cancel()
+ return
+ }
+ renewed, err := renewLease(attemptCtx, rn.client, rn.leaser, cur, started.Add(rn.leaser.TTL))
+ attemptErr := attemptCtx.Err()
+ cancel()
+ rn.mu.Lock()
+ health = rn.checkLocked()
// Retain the newest ETag solely for conditional cleanup, including a late
// success. It never repairs a latched loss or extends a stopped handle.
if err == nil {
rn.lease = renewed
}
if health == nil {
- if err != nil {
+ if attemptErr == nil && !time.Now().Before(deadline) {
+ attemptErr = context.DeadlineExceeded
+ }
+ if attemptErr != nil {
+ rn.loseLocked(attemptErr)
+ } else if err != nil {
rn.loseLocked(err)
} else {
rn.until = started.Add(rn.leaser.TTL - rn.margin)
diff --git a/internal/lease/pause_test.go b/internal/lease/pause_test.go
index 07409bf8b..b3e802020 100644
--- a/internal/lease/pause_test.go
+++ b/internal/lease/pause_test.go
@@ -132,7 +132,7 @@ func TestRenewalExpiryStartsAtItsCheck(t *testing.T) {
}
var once sync.Once
entered := make(chan time.Time, 1)
- stall := 700 * time.Millisecond
+ stall := 200 * time.Millisecond
rn := startRenewerPause(backend, leaser, lock, time.Now(), ttl/10, 0, func() {
once.Do(func() {
entered <- time.Now()
diff --git a/internal/lease/renew_attempt_test.go b/internal/lease/renew_attempt_test.go
new file mode 100644
index 000000000..b9a76bd57
--- /dev/null
+++ b/internal/lease/renew_attempt_test.go
@@ -0,0 +1,269 @@
+package lease
+
+import (
+ "context"
+ "errors"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ s3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ lss3 "github.com/benbjohnson/litestream/s3"
+)
+
+func TestRenewAttemptDeadline(t *testing.T) {
+ started := time.Now()
+ for _, tc := range []struct {
+ name string
+ ttl, safe, want time.Duration
+ }{
+ {"production", 15 * time.Minute, 10 * time.Minute, 30 * time.Second},
+ {"short", 3 * time.Second, 2 * time.Second, time.Second},
+ {"safe_until", 15 * time.Minute, 5 * time.Second, 5 * time.Second},
+ {"equal_bounds", 15 * time.Minute, 30 * time.Second, 30 * time.Second},
+ {"exact_boundary", 15 * time.Minute, 0, 0},
+ {"spent", 15 * time.Minute, -time.Nanosecond, -time.Nanosecond},
+ {"tiny", 2 * time.Nanosecond, time.Second, time.Nanosecond},
+ {"zero", 0, time.Second, time.Nanosecond},
+ {"negative", -time.Second, time.Second, time.Nanosecond},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got := renewAttemptDeadline(started, started.Add(tc.safe), tc.ttl)
+ if want := started.Add(tc.want); !got.Equal(want) {
+ t.Fatalf("deadline = %s from start, want %s", got.Sub(started), tc.want)
+ }
+ })
+ }
+}
+
+func attemptRenewer(t *testing.T, backend *lockStore, ttl time.Duration, beforeWrite func()) *renewer {
+ t.Helper()
+ leaser := lss3.NewLeaser()
+ leaser.SetClient(backend)
+ leaser.TTL = ttl
+ started := time.Now()
+ lock, err := leaser.AcquireLease(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ rn := startRenewerPause(backend, leaser, lock, started, marginForTTL(ttl), 0, beforeWrite)
+ t.Cleanup(func() {
+ if err := leaser.ReleaseLease(context.Background(), rn.stop()); err != nil {
+ t.Error(err)
+ }
+ })
+ return rn
+}
+
+func TestRenewAttemptStall(t *testing.T) {
+ const ttl = 1500 * time.Millisecond
+ var calls atomic.Int32
+ requests := make(chan context.Context, 1)
+ backend := &lockStore{beforePut: func(ctx context.Context, p *s3.PutObjectInput) error {
+ if p.IfMatch == nil {
+ return nil
+ }
+ calls.Add(1)
+ select {
+ case requests <- ctx:
+ default:
+ }
+ <-ctx.Done()
+ return ctx.Err()
+ }}
+ rn := attemptRenewer(t, backend, ttl, nil)
+ until, err := rn.SafeUntil()
+ if err != nil {
+ t.Fatal(err)
+ }
+ lost := rn.lost
+ await(t, lost)
+ await(t, rn.done)
+ var ctx context.Context
+ select {
+ case ctx = <-requests:
+ default:
+ t.Fatal("lost ownership before sending a renewal")
+ }
+ deadline, ok := ctx.Deadline()
+ if !ok || !deadline.Before(until) {
+ t.Errorf("attempt deadline %v (present %t) must precede SafeUntil %v", deadline, ok, until)
+ }
+ if !errors.Is(rn.Err(), context.DeadlineExceeded) {
+ t.Errorf("stalled attempt health = %v, want deadline exceeded", rn.Err())
+ }
+ if !time.Now().Before(until) {
+ t.Error("attempt was only stopped at SafeUntil")
+ }
+ for i := 0; i < 3; i++ {
+ if _, err := rn.SafeUntil(); err == nil {
+ t.Fatal("lost lease still has a safe deadline")
+ }
+ if rn.lost != lost {
+ t.Fatal("Lost channel replaced")
+ }
+ await(t, lost)
+ }
+ time.Sleep(ttl/3 + 20*time.Millisecond)
+ if got := calls.Load(); got != 1 {
+ t.Errorf("sent %d renewals after a stalled attempt", got)
+ }
+ if puts, _ := backend.counts(); puts != 1 {
+ t.Errorf("stalled attempt changed the lock: %d PUTs", puts)
+ }
+}
+
+func TestRenewAttemptLateSuccessCannotRestoreHealth(t *testing.T) {
+ const ttl = 1500 * time.Millisecond
+ var calls atomic.Int32
+ backend := &lockStore{beforePut: func(ctx context.Context, p *s3.PutObjectInput) error {
+ if p.IfMatch != nil {
+ calls.Add(1)
+ <-ctx.Done()
+ }
+ return nil
+ }}
+ rn := attemptRenewer(t, backend, ttl, nil)
+ rn.mu.Lock()
+ oldETag, oldUntil := rn.lease.ETag, rn.until
+ rn.mu.Unlock()
+ await(t, rn.done)
+ await(t, rn.lost)
+ if !errors.Is(rn.Err(), context.DeadlineExceeded) {
+ t.Errorf("late success health = %v, want attempt deadline exceeded", rn.Err())
+ }
+ if _, err := rn.SafeUntil(); err == nil {
+ t.Error("late success restored SafeUntil")
+ }
+ rn.mu.Lock()
+ newest, until := rn.lease.ETag, rn.until
+ rn.mu.Unlock()
+ if newest == oldETag {
+ t.Error("late success discarded cleanup ETag")
+ }
+ backend.mu.Lock()
+ stored := backend.etag
+ backend.mu.Unlock()
+ if newest != stored {
+ t.Errorf("cleanup ETag = %q, stored %q", newest, stored)
+ }
+ if !until.Equal(oldUntil) {
+ t.Errorf("late success extended SafeUntil from %v to %v", oldUntil, until)
+ }
+ if calls.Load() != 1 {
+ t.Errorf("late success sent %d renewals", calls.Load())
+ }
+ // Cleanup uses the retained ETag; a stale ETag makes ReleaseLease fail.
+}
+
+func TestRenewAttemptDeadlineSpentBeforeWrite(t *testing.T) {
+ var calls atomic.Int32
+ backend := &lockStore{beforePut: func(ctx context.Context, p *s3.PutObjectInput) error {
+ if p.IfMatch != nil {
+ calls.Add(1)
+ }
+ return nil
+ }}
+ rn := attemptRenewer(t, backend, 900*time.Millisecond, func() { time.Sleep(350 * time.Millisecond) })
+ await(t, rn.done)
+ await(t, rn.lost)
+ if calls.Load() != 0 {
+ t.Errorf("sent %d writes after the attempt budget was spent", calls.Load())
+ }
+ if !errors.Is(rn.Err(), context.DeadlineExceeded) {
+ t.Errorf("spent attempt health = %v", rn.Err())
+ }
+}
+
+func TestRenewAttemptRechecksBeforeWrite(t *testing.T) {
+ for _, state := range []string{"lost", "stopped", "canceled"} {
+ t.Run(state, func(t *testing.T) {
+ var calls atomic.Int32
+ backend := &lockStore{beforePut: func(ctx context.Context, p *s3.PutObjectInput) error {
+ if p.IfMatch != nil {
+ calls.Add(1)
+ }
+ return nil
+ }}
+ current := make(chan *renewer, 1)
+ rn := attemptRenewer(t, backend, 900*time.Millisecond, func() {
+ r := <-current
+ r.mu.Lock()
+ switch state {
+ case "lost":
+ r.loseLocked(ErrPaused)
+ case "stopped":
+ r.stopped = true
+ case "canceled":
+ r.cancel()
+ }
+ r.mu.Unlock()
+ })
+ current <- rn
+ await(t, rn.done)
+ if calls.Load() != 0 {
+ t.Errorf("sent %d writes after %s before-write seam", calls.Load(), state)
+ }
+ if rn.Err() == nil {
+ t.Fatal("invalidated handle remained healthy")
+ }
+ })
+ }
+}
+
+func TestRenewAttemptCancelsSuccessfulChild(t *testing.T) {
+ requests := make(chan context.Context, 1)
+ backend := &lockStore{beforePut: func(ctx context.Context, p *s3.PutObjectInput) error {
+ if p.IfMatch != nil {
+ select {
+ case requests <- ctx:
+ default:
+ }
+ }
+ return nil
+ }}
+ rn := attemptRenewer(t, backend, 1500*time.Millisecond, nil)
+ select {
+ case ctx := <-requests:
+ await(t, ctx.Done())
+ if !errors.Is(ctx.Err(), context.Canceled) {
+ t.Fatalf("successful child not canceled promptly: %v", ctx.Err())
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("no renewal sent")
+ }
+ if err := rn.Err(); err != nil {
+ t.Fatalf("healthy success lost ownership: %v", err)
+ }
+}
+
+func TestRenewAttemptUsesEarlierSafeUntil(t *testing.T) {
+ requests := make(chan context.Context, 1)
+ backend := &lockStore{beforePut: func(ctx context.Context, p *s3.PutObjectInput) error {
+ if p.IfMatch == nil {
+ return nil
+ }
+ requests <- ctx
+ <-ctx.Done()
+ return ctx.Err()
+ }}
+ rn := attemptRenewer(t, backend, 1500*time.Millisecond, nil)
+ until := time.Now().Add(850 * time.Millisecond)
+ rn.mu.Lock()
+ rn.until = until
+ rn.mu.Unlock()
+ rn.changed <- struct{}{}
+ select {
+ case ctx := <-requests:
+ if deadline, ok := ctx.Deadline(); !ok || !deadline.Equal(until) {
+ t.Errorf("attempt deadline %v (present %t), want SafeUntil %v", deadline, ok, until)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("no renewal sent")
+ }
+ await(t, rn.done)
+ await(t, rn.lost)
+ if _, err := rn.SafeUntil(); err == nil {
+ t.Error("expired handle retained SafeUntil")
+ }
+}