lease: a renewal's expiry starts at its liveness check (review R1)
Astra round 1, P1: litestream's RenewLease stamps time.Now() as it writes, so a pause between the renewer's check and that stamp still sent a post-resume expiry. The renewer now writes through renewLease (createlease.go), whose expiry is the check's liveness sample plus the TTL, fixed through SDK retries; the deadline starts there too. TestRenewalExpiryStartsAtItsCheck stalls a renewal between check and write (fails with RenewLease). Witness: SIGSTOP through systemctl kill (never a PID read back: 0 would stop the runner's own group, P1); TestRootRenewalAgainstRealS3 checks renewLease against real S3. The Unix test reaps its child (P2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+223
−39
internal/lease/checkpoint_test.go+2 −2internal/lease/createlease.go+43 −0internal/lease/ha.go+1 −1internal/lease/health.go+27 −19internal/lease/lease.go+1 −1internal/lease/pause_rootrunner_linux_test.go+65 −13internal/lease/pause_test.go+79 −1internal/lease/pause_unix_test.go+4 −1internal/lease/release_retry_test.go+1 −1
diff --git a/internal/lease/checkpoint_test.go b/internal/lease/checkpoint_test.go| index 515d8c472..75df69167 100644 |
| --- a/internal/lease/checkpoint_test.go |
| +++ b/internal/lease/checkpoint_test.go |
| @@ -405,7 +405,7 @@ func TestLateRenewalCannotResurrect(t *testing.T) { |
| if e != nil { |
| t.Fatal(e) |
| } |
| - rn := startRenewer(leaser, lock, started, 30*time.Millisecond) |
| + rn := startRenewer(backend, leaser, lock, started, 30*time.Millisecond) |
| await(t, entered) |
| await(t, rn.ctx.Done()) |
| if !errors.Is(rn.Err(), ErrLost) { |
| @@ -550,7 +550,7 @@ func TestRenewDeadlineStartsBeforeRemoteRequest(t *testing.T) { |
| if e != nil { |
| t.Fatal(e) |
| } |
| - rn := startRenewer(leaser, lock, started, 100*time.Millisecond) |
| + rn := startRenewer(backend, leaser, lock, started, 100*time.Millisecond) |
| defer func() { leaser.ReleaseLease(context.Background(), rn.stop()) }() |
| initial, e := rn.SafeUntil() |
| if e != nil { |
diff --git a/internal/lease/createlease.go b/internal/lease/createlease.go| index a3759bf55..ed72b46ac 100644 |
| --- a/internal/lease/createlease.go |
| +++ b/internal/lease/createlease.go |
| @@ -57,6 +57,49 @@ func createLease(ctx context.Context, client *awss3.Client, l *lss3.Leaser) (*li |
| return lease, nil |
| } |
| +// renewLease is litestream's RenewLease with the expiry given rather than |
| +// stamped at the moment of the write: the same JSON, owner, generation and |
| +// If-Match on cur's ETag, and a lost condition is litestream.ErrLeaseNotHeld |
| +// as there. The renewer passes its last liveness sample plus the TTL, so a |
| +// pause anywhere between that sample and the PUT (or in an SDK retry, which |
| +// resends this same body) cannot carry a post-resume expiry to S3. G2 drill |
| +// 2 is the case: an overdue renewal resumed by SIGCONT must not move the |
| +// lock's expiry past the moment the holder stopped running. |
| +func renewLease(ctx context.Context, client lss3.S3API, l *lss3.Leaser, cur *litestream.Lease, expires time.Time) (*litestream.Lease, error) { |
| + if cur == nil { |
| + return nil, lss3.ErrLeaseRequired |
| + } |
| + if cur.ETag == "" { |
| + return nil, lss3.ErrLeaseETagRequired |
| + } |
| + next := &litestream.Lease{Generation: cur.Generation, ExpiresAt: expires, Owner: l.Owner} |
| + data, err := json.Marshal(next) |
| + if err != nil { |
| + return nil, fmt.Errorf("marshal lock file: %w", err) |
| + } |
| + key := lss3.DefaultLeasePath |
| + if l.Path != "" { |
| + key = l.Path + "/" + lss3.DefaultLeasePath |
| + } |
| + out, err := client.PutObject(ctx, &awss3.PutObjectInput{ |
| + Bucket: aws.String(l.Bucket), |
| + Key: aws.String(key), |
| + Body: bytes.NewReader(data), |
| + ContentType: aws.String("application/json"), |
| + IfMatch: aws.String(cur.ETag), |
| + }) |
| + if err != nil { |
| + if preconditionFailed(err) { |
| + return nil, litestream.ErrLeaseNotHeld |
| + } |
| + return nil, fmt.Errorf("put lock file: %w", err) |
| + } |
| + if out.ETag != nil { |
| + next.ETag = *out.ETag |
| + } |
| + return next, nil |
| +} |
| + |
| // preconditionFailed is litestream's isPreconditionFailed (unexported |
| // there), plus the 409 S3 answers when two conditional writes of one key |
| // race: either way a lock is, or is about to be, present. |
diff --git a/internal/lease/ha.go b/internal/lease/ha.go| index 0e5192910..20fa40046 100644 |
| --- a/internal/lease/ha.go |
| +++ b/internal/lease/ha.go |
| @@ -140,7 +140,7 @@ func acquireHARestricted(ctx context.Context, bucket, prefix, region string, bas |
| base.IID = me.IID |
| } |
| base.V = 1 |
| - rn := startRenewer(leaser, lease, started, marginForTTL(ttl)) |
| + rn := startRenewer(client, leaser, lease, started, marginForTTL(ttl)) |
| if err := rn.Err(); err != nil { |
| // A late acknowledgement: the lock is ours, the deadline is not. |
| // Let it go through the marker, on its own budget. |
diff --git a/internal/lease/health.go b/internal/lease/health.go| index 284252c96..64441bbfb 100644 |
| --- a/internal/lease/health.go |
| +++ b/internal/lease/health.go |
| @@ -79,6 +79,7 @@ func marginForTTL(ttl time.Duration) time.Duration { |
| type renewer struct { |
| ctx context.Context |
| + client lss3.S3API // the leaser's own client: renewals write through renewLease |
| leaser *lss3.Leaser |
| mu sync.Mutex |
| lease *litestream.Lease |
| @@ -88,27 +89,31 @@ type renewer struct { |
| // pause is the pause limit (0 = off) and seen the last time this |
| // process was observed running (checkLocked); watch samples at least |
| // every pause/pauseSamples while pause is on. |
| - pause time.Duration |
| - seen time.Time |
| - stopped bool |
| - cancel context.CancelFunc |
| - done chan struct{} |
| - watchDone chan struct{} |
| - changed chan struct{} |
| - lost chan struct{} |
| + pause time.Duration |
| + seen time.Time |
| + stopped bool |
| + // beforeWrite, when set, runs between a renewal's check and its write |
| + // (a test seam for a pause landing there; nil in production). |
| + beforeWrite func() |
| + cancel context.CancelFunc |
| + done chan struct{} |
| + watchDone chan struct{} |
| + changed chan struct{} |
| + lost chan struct{} |
| } |
| // pauseSamples is how many liveness samples watch takes per pause limit. |
| const pauseSamples = 6 |
| -func startRenewer(leaser *lss3.Leaser, lease *litestream.Lease, started time.Time, margin time.Duration) *renewer { |
| - return startRenewerPause(leaser, lease, started, margin, pauseLimitFor(leaser.TTL)) |
| +// startRenewer renews lease through client, the S3 client leaser was given. |
| +func startRenewer(client lss3.S3API, leaser *lss3.Leaser, lease *litestream.Lease, started time.Time, margin time.Duration) *renewer { |
| + return startRenewerPause(client, leaser, lease, started, margin, pauseLimitFor(leaser.TTL), nil) |
| } |
| // startRenewerPause is startRenewer with the pause limit given (0 = off). |
| -func startRenewerPause(leaser *lss3.Leaser, lease *litestream.Lease, started time.Time, margin, pause time.Duration) *renewer { |
| +func startRenewerPause(client lss3.S3API, leaser *lss3.Leaser, lease *litestream.Lease, started time.Time, margin, pause time.Duration, beforeWrite func()) *renewer { |
| ctx, cancel := context.WithCancel(context.Background()) |
| - rn := &renewer{ctx: ctx, leaser: leaser, lease: lease, until: started.Add(leaser.TTL - margin), margin: margin, pause: pause, seen: time.Now(), cancel: cancel, done: make(chan struct{}), watchDone: make(chan struct{}), changed: make(chan struct{}, 1), lost: make(chan struct{})} |
| + rn := &renewer{ctx: ctx, client: client, leaser: leaser, beforeWrite: beforeWrite, lease: lease, until: started.Add(leaser.TTL - margin), margin: margin, pause: pause, seen: time.Now(), cancel: cancel, done: make(chan struct{}), watchDone: make(chan struct{}), changed: make(chan struct{}, 1), lost: make(chan struct{})} |
| go rn.watch(ctx) |
| go rn.renew(ctx) |
| return rn |
| @@ -209,18 +214,21 @@ func (rn *renewer) renew(ctx context.Context) { |
| rn.mu.Lock() |
| err := rn.checkLocked() |
| cur := rn.lease |
| + // The check just sampled liveness (seen); the renewal's |
| + // expiry and deadline both start there, never later. A pause |
| + // after the check, before or during the write, so cannot give |
| + // the lock a post-resume expiry, and the check after the write |
| + // latches the loss. |
| + started := rn.seen |
| rn.mu.Unlock() |
| if err != nil { |
| rn.cancel() |
| return |
| } |
| - // The check above refused a paused process. A pause landing |
| - // between it and RenewLease does no harm: RenewLease stamps |
| - // ExpiresAt from time.Now() before it sends, so a renewal held |
| - // up by a pause carries a pre-pause expiry, and the check after |
| - // it latches the loss. |
| - started := time.Now() |
| - renewed, err := rn.leaser.RenewLease(ctx, cur) |
| + 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() |
| // Retain the newest ETag solely for conditional cleanup, including a late |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 4bb396f45..a12a84020 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -229,7 +229,7 @@ func AcquireAs(ctx context.Context, bucket, prefix, region string, ttl time.Dura |
| if err != nil { |
| return nil, fmt.Errorf("acquire lease: %w", err) |
| } |
| - rn := startRenewer(leaser, lease, started, marginForTTL(ttl)) |
| + rn := startRenewer(client, leaser, lease, started, marginForTTL(ttl)) |
| if err := rn.Err(); err != nil { |
| cur := rn.stop() |
| relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
diff --git a/internal/lease/pause_rootrunner_linux_test.go b/internal/lease/pause_rootrunner_linux_test.go| index ded42decf..e9510f908 100644 |
| --- a/internal/lease/pause_rootrunner_linux_test.go |
| +++ b/internal/lease/pause_rootrunner_linux_test.go |
| @@ -94,15 +94,6 @@ func TestRootPausedHolderStopWitness(t *testing.T) { |
| out, _ := exec.Command("journalctl", "-u", unit, "-o", "cat", "--no-pager").CombinedOutput() |
| return string(out) |
| } |
| - mainPID := func() int { |
| - out, err := exec.Command("systemctl", "show", "-P", "MainPID", unit).Output() |
| - if err != nil { |
| - t.Fatalf("MainPID: %v", err) |
| - } |
| - var pid int |
| - fmt.Sscanf(strings.TrimSpace(string(out)), "%d", &pid) |
| - return pid |
| - } |
| waitFor := func(what string, limit time.Duration) { |
| t.Helper() |
| for deadline := time.Now().Add(limit); !strings.Contains(journal(), what); time.Sleep(200 * time.Millisecond) { |
| @@ -112,13 +103,20 @@ func TestRootPausedHolderStopWitness(t *testing.T) { |
| } |
| } |
| waitFor("witness held", time.Minute) |
| - pid := mainPID() |
| - if err := syscall.Kill(pid, syscall.SIGSTOP); err != nil { |
| - t.Fatal(err) |
| + // Signal the unit's main process through systemd, never a PID read |
| + // back: a PID of 0 would stop this runner's own process group. |
| + if out, err := exec.Command("systemctl", "kill", "--kill-whom=main", "--signal=SIGSTOP", unit).CombinedOutput(); err != nil { |
| + t.Fatalf("SIGSTOP the unit: %v: %s", err, out) |
| + } |
| + if out, _ := exec.Command("systemctl", "show", "-P", "SubState", unit).Output(); strings.TrimSpace(string(out)) != "running" { |
| + t.Fatalf("the witness unit is %q, not running, after SIGSTOP", strings.TrimSpace(string(out))) |
| + } |
| + if st, _ := exec.Command("sh", "-c", "ps -o stat= -p \"$(systemctl show -P MainPID "+unit+")\"").Output(); !strings.HasPrefix(strings.TrimSpace(string(st)), "T") { |
| + t.Fatalf("the witness's main process is not stopped (ps stat %q)", strings.TrimSpace(string(st))) |
| } |
| stoppedAt := time.Now() |
| etag0, lock0 := readLock() |
| - t.Logf("held: pid %d, lock etag %s, expires %s; stopped at %s", pid, etag0, lock0.ExpiresAt.UTC().Format(time.RFC3339Nano), stoppedAt.UTC().Format(time.RFC3339)) |
| + t.Logf("held: lock etag %s, expires %s; stopped at %s", etag0, lock0.ExpiresAt.UTC().Format(time.RFC3339Nano), stoppedAt.UTC().Format(time.RFC3339)) |
| // Past the first renewal (TTL/3 after the acquire), well inside the |
| // safe deadline (TTL - margin): drill 2 was 112 s overdue. |
| hold := LeaseTTL/3 + 60*time.Second |
| @@ -179,3 +177,57 @@ func pausedWitnessChild(prefix string) { |
| fmt.Printf("witness verdict lost=%t paused=%t err=%v\n", lost, errors.Is(err, ErrPaused), err) |
| os.Exit(0) |
| } |
| + |
| +// TestRootRenewalAgainstRealS3 checks renewLease, the renewer's own |
| +// conditional write, against real S3: a short-TTL lease renews (the ETag |
| +// moves, the expiry moves forward by the renewals) and stays healthy, and |
| +// a renewal against a stale ETag is refused as not held. |
| +func TestRootRenewalAgainstRealS3(t *testing.T) { |
| + var b [6]byte |
| + rand.Read(b[:]) |
| + prefix := "root-runner/lease-renew-witness/" + hex.EncodeToString(b[:]) |
| + ctx := context.Background() |
| + ttl := 30 * time.Second |
| + h, err := AcquireTTL(ctx, witnessBucket, prefix, witnessRegion, ttl) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(witnessRegion)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + client := s3.NewFromConfig(cfg) |
| + read := func() (string, litestream.Lease) { |
| + t.Helper() |
| + out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(witnessBucket), Key: aws.String(prefix + "/lock.json")}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer out.Body.Close() |
| + raw, _ := io.ReadAll(out.Body) |
| + var l litestream.Lease |
| + if err := json.Unmarshal(raw, &l); err != nil { |
| + t.Fatal(err) |
| + } |
| + return aws.ToString(out.ETag), l |
| + } |
| + etag0, l0 := read() |
| + time.Sleep(ttl/3*2 + 3*time.Second) // two renewals |
| + if err := h.Err(); err != nil { |
| + t.Fatalf("renewing holder unhealthy: %v", err) |
| + } |
| + etag1, l1 := read() |
| + if etag1 == etag0 || !l1.ExpiresAt.After(l0.ExpiresAt.Add(ttl/2)) || l1.Generation != l0.Generation || l1.Owner != l0.Owner { |
| + t.Fatalf("no renewal landed: %s %+v -> %s %+v", etag0, l0, etag1, l1) |
| + } |
| + stale := &litestream.Lease{Generation: l0.Generation, ETag: etag0, Owner: l0.Owner} |
| + if _, err := renewLease(ctx, h.rn.client, h.leaser, stale, time.Now().Add(ttl)); !errors.Is(err, litestream.ErrLeaseNotHeld) { |
| + t.Fatalf("a renewal on a stale ETag: %v, want ErrLeaseNotHeld", err) |
| + } |
| + if e, _ := read(); e != etag1 { |
| + t.Fatal("the stale renewal changed the lock") |
| + } |
| + t.Logf("PASS: renewed %s -> %s, expiry %s -> %s; stale ETag refused", etag0, etag1, l0.ExpiresAt.UTC().Format(time.RFC3339Nano), l1.ExpiresAt.UTC().Format(time.RFC3339Nano)) |
| + // Release needs DeleteObject, which the runner's role lacks; the lock |
| + // lapses in 30 s under the runner's own prefix. |
| +} |
diff --git a/internal/lease/pause_test.go b/internal/lease/pause_test.go| index 383b65436..07409bf8b 100644 |
| --- a/internal/lease/pause_test.go |
| +++ b/internal/lease/pause_test.go |
| @@ -1,11 +1,17 @@ |
| package lease |
| import ( |
| + "bytes" |
| "context" |
| + "encoding/json" |
| "errors" |
| + "io" |
| + "sync" |
| "testing" |
| "time" |
| + s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/benbjohnson/litestream" |
| lss3 "github.com/benbjohnson/litestream/s3" |
| ) |
| @@ -39,7 +45,7 @@ func pauseRenewer(t *testing.T, backend *lockStore, ttl, pause time.Duration) *r |
| if e != nil { |
| t.Fatal(e) |
| } |
| - rn := startRenewerPause(leaser, lock, started, ttl/10, pause) |
| + rn := startRenewerPause(backend, leaser, lock, started, ttl/10, pause, nil) |
| t.Cleanup(func() { leaser.ReleaseLease(context.Background(), rn.stop()) }) |
| return rn |
| } |
| @@ -87,3 +93,75 @@ func TestPauseLimitKeepsAHealthyHolder(t *testing.T) { |
| t.Fatalf("only %d renewal(s) in two and a half intervals", now-start) |
| } |
| } |
| + |
| +// renewalBodies is a lockStore that keeps every renewal's body in order. |
| +type renewalBodies struct { |
| + *lockStore |
| + mu sync.Mutex |
| + bodies [][]byte |
| +} |
| + |
| +func (r *renewalBodies) PutObject(ctx context.Context, p *s3.PutObjectInput, o ...func(*s3.Options)) (*s3.PutObjectOutput, error) { |
| + raw, err := io.ReadAll(p.Body) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if p.IfMatch != nil { |
| + r.mu.Lock() |
| + r.bodies = append(r.bodies, raw) |
| + r.mu.Unlock() |
| + } |
| + p.Body = bytes.NewReader(raw) |
| + return r.lockStore.PutObject(ctx, p, o...) |
| +} |
| + |
| +// A pause landing after a renewal's check and before its write (Astra |
| +// review round 1, P1) must not give the lock a post-resume expiry: the |
| +// write carries the check's sample plus the TTL, however late it is sent. |
| +// The seam stands in for the pause; litestream's RenewLease, which stamps |
| +// time.Now() as it writes, fails this. |
| +func TestRenewalExpiryStartsAtItsCheck(t *testing.T) { |
| + backend := &renewalBodies{lockStore: &lockStore{}} |
| + leaser := lss3.NewLeaser() |
| + leaser.SetClient(backend) |
| + ttl := 1500 * time.Millisecond |
| + leaser.TTL = ttl |
| + lock, e := leaser.AcquireLease(context.Background()) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + var once sync.Once |
| + entered := make(chan time.Time, 1) |
| + stall := 700 * time.Millisecond |
| + rn := startRenewerPause(backend, leaser, lock, time.Now(), ttl/10, 0, func() { |
| + once.Do(func() { |
| + entered <- time.Now() |
| + time.Sleep(stall) |
| + }) |
| + }) |
| + defer func() { leaser.ReleaseLease(context.Background(), rn.stop()) }() |
| + var at time.Time |
| + select { |
| + case at = <-entered: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("no renewal") |
| + } |
| + var first []byte |
| + for deadline := time.Now().Add(3 * time.Second); first == nil; time.Sleep(5 * time.Millisecond) { |
| + backend.mu.Lock() |
| + if len(backend.bodies) > 0 { |
| + first = backend.bodies[0] |
| + } |
| + backend.mu.Unlock() |
| + if first == nil && time.Now().After(deadline) { |
| + t.Fatal("the stalled renewal never landed") |
| + } |
| + } |
| + var written litestream.Lease |
| + if err := json.Unmarshal(first, &written); err != nil { |
| + t.Fatal(err) |
| + } |
| + if limit := at.Add(ttl); written.ExpiresAt.After(limit) { |
| + t.Fatalf("the renewal written after a %s stall expires %s past its check's sample plus the TTL", stall, written.ExpiresAt.Sub(limit).Round(time.Millisecond)) |
| + } |
| +} |
diff --git a/internal/lease/pause_unix_test.go b/internal/lease/pause_unix_test.go| index c30ed9ed0..3f2fa5413 100644 |
| --- a/internal/lease/pause_unix_test.go |
| +++ b/internal/lease/pause_unix_test.go |
| @@ -63,7 +63,10 @@ func TestPausedHolderDoesNotRenewOnResume(t *testing.T) { |
| if err := cmd.Start(); err != nil { |
| t.Fatal(err) |
| } |
| - defer cmd.Process.Kill() |
| + t.Cleanup(func() { |
| + _ = cmd.Process.Kill() |
| + _ = cmd.Wait() |
| + }) |
| lines := make(chan string, 16) |
| go func() { |
| sc := bufio.NewScanner(out) |
diff --git a/internal/lease/release_retry_test.go b/internal/lease/release_retry_test.go| index 235628cc9..2f451cd69 100644 |
| --- a/internal/lease/release_retry_test.go |
| +++ b/internal/lease/release_retry_test.go |
| @@ -75,7 +75,7 @@ func heldAgainst(t *testing.T, srv *httptest.Server, etag string) *Held { |
| leaser.Path = "p" |
| leaser.TTL = time.Hour |
| rec := &litestream.Lease{Generation: 1, ETag: etag, Owner: "test", ExpiresAt: time.Now().Add(time.Hour)} |
| - return &Held{leaser: leaser, rn: startRenewer(leaser, rec, time.Now(), marginForTTL(time.Hour))} |
| + return &Held{leaser: leaser, rn: startRenewer(client, leaser, rec, time.Now(), marginForTTL(time.Hour))} |
| } |
| // A failed release leaves a conditional obligation that RetryRelease |