lease: a holder paused past 30 s gives its lease up unrenewed
G2 drill 2 (dev, 2026-11-05): a SIGSTOPped HA holder, resumed by systemd's SIGTERM+SIGCONT at shutdown, ran its overdue renewal and moved lock.json's expiry 23:47:48Z -> 23:54:40Z; the takeover waited it out. The renewer samples its own liveness; any check that finds a gap over 30 s (the NLB exclusion bound; on at TTL >= 3 min) latches ErrPaused, an ErrLost, before a renewal can go out. Renewals write through renewLease with the check's sample plus the TTL, so a pause after the check cannot carry a post-resume expiry. Takeover rule unchanged. Tests: real SIGSTOP/SIGTERM+SIGCONT child (RED: renewed 1 ms after SIGCONT); check-to-write stall; root-runner witnesses at production TTL on real S3 under systemctl stop. Astra R2 READY AFTER FIXES; census (internal/lease envelope) approved on #280. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from fix-lease-renew-after-pause into main.
12 files changed,
+762
−24
docs/superpowers/notes/census-proposal-lease-renew-after-pause.md+11 −0internal/lease/checkpoint_test.go+2 −2internal/lease/createlease.go+43 −0internal/lease/ha.go+1 −1internal/lease/health.go+116 −19internal/lease/lease.go+1 −1internal/lease/pause_rootrunner_linux_test.go+241 −0internal/lease/pause_test.go+167 −0internal/lease/pause_unix_test.go+175 −0internal/lease/release_retry_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-lease-renew-after-pause.tsv+3 −0
CI passed — run details
diff --git a/docs/superpowers/notes/census-proposal-lease-renew-after-pause.md b/docs/superpowers/notes/census-proposal-lease-renew-after-pause.md| new file mode 100644 |
| index 000000000..44fde057c |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-lease-renew-after-pause.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: lease-renew-after-pause |
| + |
| +Ruling `census-ruling-lease-renew-after-pause`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/lease`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Seal: `ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939` → `ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-lease-renew-after-pause.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
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 4b3b9193a..64441bbfb 100644 |
| --- a/internal/lease/health.go |
| +++ b/internal/lease/health.go |
| @@ -3,6 +3,8 @@ package lease |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| + "log" |
| "sync" |
| "time" |
| @@ -14,8 +16,51 @@ var ( |
| ErrLost = errors.New("lease safety deadline elapsed") |
| ErrSpent = errors.New("lease handle is spent") |
| ErrBusy = errors.New("lease operation already running") |
| + // ErrPaused is ErrLost (errors.Is) reached early: the process went |
| + // longer than the pause limit without running, so it renews no more. |
| + ErrPaused = fmt.Errorf("lease given up, this process was paused for longer than the pause limit: %w", ErrLost) |
| ) |
| +// pauseLimit is how long a holder may go without running before it gives |
| +// its lease up instead of renewing it. G2 drill 2 (2026-11-05) is why: the |
| +// holder's edge was SIGSTOPped, missed its renewal, and the load balancer |
| +// and the group replaced the box. systemd's stop sends SIGTERM and then |
| +// SIGCONT, and the moment the process ran again its overdue renewal fired, |
| +// before the shutdown reached the lease. The lock's expiry moved a whole |
| +// TTL past the bound the takeover is planned around, and the replacement |
| +// waited it out. The conditional write kept a single writer; it was the |
| +// outage that grew. |
| +// |
| +// A renewal is a claim that the holder is alive. After a pause that claim |
| +// is stale: the box has been out of the load balancer for most of it (its |
| +// health checks fail within about 30 s) and is presumed to be being |
| +// replaced. So the renewer samples its own liveness (watch, below) and |
| +// latches ErrPaused when the gap since the last sample exceeds this limit. |
| +// The lock keeps the expiry its last live renewal wrote, so a takeover |
| +// (proof AND expiry, unchanged) waits no longer than it would for a hard |
| +// crash at the moment the pause began. |
| +// |
| +// 30 s is the load balancer's exclusion bound. A healthy process never |
| +// goes that long without a timer running; a holder that does is not |
| +// serving anyway, and standing down costs it a re-wake on its next |
| +// request. |
| +const pauseLimit = 30 * time.Second |
| + |
| +// pauseLimitForTTL is the pause limit for a lease of term ttl: pauseLimit |
| +// at production terms, off (0) below six of them, where only tests run |
| +// (their short TTLs would make a scheduling hiccup on a loaded CI worker |
| +// look like a pause). Tests that want pause detection set their own. |
| +func pauseLimitForTTL(ttl time.Duration) time.Duration { |
| + if ttl < 6*pauseLimit { |
| + return 0 |
| + } |
| + return pauseLimit |
| +} |
| + |
| +// pauseLimitFor is pauseLimitForTTL; a test seam for the child process |
| +// TestPausedHolderDoesNotRenewOnResume runs, which has a short TTL. |
| +var pauseLimitFor = pauseLimitForTTL |
| + |
| const terminationMargin = 5 * time.Second |
| // RenewMargin is the margin Held.SafeUntil subtracts from the lease's |
| @@ -33,24 +78,42 @@ func marginForTTL(ttl time.Duration) time.Duration { |
| } |
| type renewer struct { |
| - ctx context.Context |
| - leaser *lss3.Leaser |
| - mu sync.Mutex |
| - lease *litestream.Lease |
| - err error |
| - until time.Time |
| - margin time.Duration |
| - stopped bool |
| - cancel context.CancelFunc |
| - done chan struct{} |
| - watchDone chan struct{} |
| - changed chan struct{} |
| - lost chan 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 |
| + err error |
| + until time.Time |
| + margin time.Duration |
| + // 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 |
| + // 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{} |
| } |
| -func startRenewer(leaser *lss3.Leaser, lease *litestream.Lease, started time.Time, margin time.Duration) *renewer { |
| +// pauseSamples is how many liveness samples watch takes per pause limit. |
| +const pauseSamples = 6 |
| + |
| +// 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(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, 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 |
| @@ -72,11 +135,33 @@ func (rn *renewer) checkLocked() error { |
| if rn.stopped { |
| return ErrSpent |
| } |
| - if !time.Now().Before(rn.until) { |
| + now := time.Now() |
| + // The pause check comes first and every caller makes it, the renewal |
| + // included: after a resume, whichever goroutine runs first finds the |
| + // gap, so an overdue tick cannot renew ahead of the sampler. Only a |
| + // check that finds no gap counts as a new sample. |
| + if rn.pause > 0 && now.Sub(rn.seen) > rn.pause { |
| + log.Printf("lease: %s: this process did not run for %s (pause limit %s): giving the lease up unrenewed; it expires %s", rn.leaser.Path, |
| + now.Sub(rn.seen).Round(time.Millisecond), rn.pause, rn.expiresLocked()) |
| + rn.loseLocked(ErrPaused) |
| + return rn.err |
| + } |
| + if !now.Before(rn.until) { |
| rn.loseLocked(ErrLost) |
| } |
| + if rn.err == nil { |
| + rn.seen = now |
| + } |
| return rn.err |
| } |
| + |
| +// expiresLocked names the expiry the lock keeps, for the journal. |
| +func (rn *renewer) expiresLocked() string { |
| + if rn.lease == nil || rn.lease.ExpiresAt.IsZero() { |
| + return "at its last renewal's expiry" |
| + } |
| + return "at " + rn.lease.ExpiresAt.UTC().Format(time.RFC3339) |
| +} |
| func (rn *renewer) Err() error { |
| rn.mu.Lock() |
| defer rn.mu.Unlock() |
| @@ -98,7 +183,11 @@ func (rn *renewer) watch(ctx context.Context) { |
| rn.cancel() |
| return |
| } |
| - timer := time.NewTimer(time.Until(until)) |
| + wait := time.Until(until) |
| + if sample := rn.pause / pauseSamples; rn.pause > 0 && wait > sample { |
| + wait = sample |
| + } |
| + timer := time.NewTimer(wait) |
| select { |
| case <-ctx.Done(): |
| timer.Stop() |
| @@ -125,13 +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 |
| } |
| - 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| new file mode 100644 |
| index 000000000..6f48b540e |
| --- /dev/null |
| +++ b/internal/lease/pause_rootrunner_linux_test.go |
| @@ -0,0 +1,241 @@ |
| +//go:build linux && rootrunner |
| + |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/config" |
| + s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/benbjohnson/litestream" |
| +) |
| + |
| +// The root runner's role may Get and Put under this prefix and nothing |
| +// else, so the witness's lock object is left in place (one small object |
| +// per run, under the runner's own prefix). |
| +const ( |
| + witnessBucket = "carlos-dev-640012953448" |
| + witnessRegion = "eu-west-1" |
| + witnessChild = "CARLOS_LEASE_PAUSE_WITNESS_PREFIX" |
| +) |
| + |
| +// TestRootPausedHolderStopWitness replays G2 drill 2 with production |
| +// wiring: the production AcquireTTL at the production LeaseTTL and pause |
| +// limit, against real S3, in a real systemd unit. The holder is SIGSTOPped |
| +// right after it acquires, kept stopped past its first renewal (TTL/3) |
| +// but well inside its safe deadline, and then stopped by `systemctl stop`, |
| +// which sends SIGTERM and SIGCONT exactly as the box's shutdown did. The |
| +// holder must not renew on resume: the lock object in S3 keeps the ETag |
| +// and expiry its acquire wrote, and the holder's own journal says it gave |
| +// the lease up as paused. |
| +func TestRootPausedHolderStopWitness(t *testing.T) { |
| + if prefix := os.Getenv(witnessChild); prefix != "" { |
| + pausedWitnessChild(prefix) |
| + return |
| + } |
| + if os.Geteuid() != 0 { |
| + t.Fatal("the witness needs root (systemd-run)") |
| + } |
| + if pauseLimitFor(LeaseTTL) != pauseLimit || pauseLimit >= LeaseTTL/3 { |
| + t.Fatalf("production pause limit %s against renewal every %s: the witness assumes a limit shorter than the renewal interval", pauseLimitFor(LeaseTTL), LeaseTTL/3) |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var b [6]byte |
| + rand.Read(b[:]) |
| + run := hex.EncodeToString(b[:]) |
| + prefix := "root-runner/lease-pause-witness/" + run |
| + unit := "carlos-lease-pause-witness-" + run |
| + ctx := context.Background() |
| + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(witnessRegion)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + client := s3.NewFromConfig(cfg) |
| + readLock := 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.Fatalf("read the lock: %v", err) |
| + } |
| + defer out.Body.Close() |
| + raw, _ := io.ReadAll(out.Body) |
| + var l litestream.Lease |
| + if err := json.Unmarshal(raw, &l); err != nil { |
| + t.Fatalf("lock body %q: %v", raw, err) |
| + } |
| + return aws.ToString(out.ETag), l |
| + } |
| + |
| + start := exec.Command("systemd-run", "--unit="+unit, "--collect", "--quiet", |
| + "--setenv="+witnessChild+"="+prefix, |
| + self, "-test.run=^TestRootPausedHolderStopWitness$", "-test.v") |
| + if out, err := start.CombinedOutput(); err != nil { |
| + t.Fatalf("systemd-run: %v: %s", err, out) |
| + } |
| + defer exec.Command("systemctl", "kill", "--signal=SIGKILL", unit).Run() |
| + journal := func() string { |
| + out, _ := exec.Command("journalctl", "-u", unit, "-o", "cat", "--no-pager").CombinedOutput() |
| + return string(out) |
| + } |
| + waitFor := func(what string, limit time.Duration) { |
| + t.Helper() |
| + for deadline := time.Now().Add(limit); !strings.Contains(journal(), what); time.Sleep(200 * time.Millisecond) { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("no %q in the unit's journal:\n%s", what, journal()) |
| + } |
| + } |
| + } |
| + waitFor("witness held", time.Minute) |
| + // 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: 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 |
| + time.Sleep(hold) |
| + if e, _ := readLock(); e != etag0 { |
| + t.Fatal("the lock changed while the holder was stopped") |
| + } |
| + stop := exec.Command("systemctl", "stop", unit) |
| + resumedAt := time.Now() |
| + if out, err := stop.CombinedOutput(); err != nil { |
| + t.Fatalf("systemctl stop: %v: %s", err, out) |
| + } |
| + t.Logf("systemctl stop returned after %s", time.Since(resumedAt).Round(time.Millisecond)) |
| + j := journal() |
| + t.Logf("unit journal:\n%s", j) |
| + etag1, lock1 := readLock() |
| + if etag1 != etag0 || !lock1.ExpiresAt.Equal(lock0.ExpiresAt) { |
| + t.Fatalf("the resumed holder renewed: etag %s -> %s, expiry %s -> %s", etag0, etag1, |
| + lock0.ExpiresAt.UTC().Format(time.RFC3339Nano), lock1.ExpiresAt.UTC().Format(time.RFC3339Nano)) |
| + } |
| + for _, want := range []string{ |
| + "giving the lease up unrenewed", |
| + "witness SIGTERM", |
| + "witness verdict lost=true paused=true", |
| + } { |
| + if !strings.Contains(j, want) { |
| + t.Fatalf("the unit's journal has no %q", want) |
| + } |
| + } |
| + t.Logf("PASS: stopped %s (renewal due after %s, pause limit %s); no renewal after SIGTERM+SIGCONT; lock expiry unchanged at %s", |
| + resumedAt.Sub(stoppedAt).Round(time.Second), LeaseTTL/3, pauseLimit, lock1.ExpiresAt.UTC().Format(time.RFC3339Nano)) |
| +} |
| + |
| +// pausedWitnessChild holds the lease in the unit and reports, on SIGTERM, |
| +// what its handle says. It never releases: the parent reads the lock the |
| +// stop left behind. |
| +func pausedWitnessChild(prefix string) { |
| + term := make(chan os.Signal, 1) |
| + signal.Notify(term, syscall.SIGTERM) |
| + h, err := Acquire(context.Background(), witnessBucket, prefix, witnessRegion) |
| + if err != nil { |
| + fmt.Println("witness acquire failed:", err) |
| + os.Exit(1) |
| + } |
| + fmt.Println("witness held") |
| + <-term |
| + fmt.Println("witness SIGTERM") |
| + // The edge's shutdown takes this long and more before it reaches a |
| + // lease; the renewer must already have stood down. |
| + time.Sleep(2 * time.Second) |
| + err = h.Err() |
| + lost := false |
| + select { |
| + case <-h.Lost(): |
| + lost = true |
| + default: |
| + } |
| + 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) |
| + } |
| + // The renewer is stopped on every path (stop is idempotent): no |
| + // background writes outlive the test. |
| + t.Cleanup(func() { h.rn.stop() }) |
| + 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) |
| + } |
| + // Stop and join the renewer before the stale write, so no ordinary |
| + // renewal can change the lock under the assertion below; take the |
| + // baseline after it has stopped. |
| + h.rn.stop() |
| + etag1, _ = read() |
| + 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; with the |
| + // renewer stopped 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| new file mode 100644 |
| index 000000000..07409bf8b |
| --- /dev/null |
| +++ b/internal/lease/pause_test.go |
| @@ -0,0 +1,167 @@ |
| +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" |
| +) |
| + |
| +func TestPauseLimitForTTL(t *testing.T) { |
| + for _, c := range []struct { |
| + ttl, want time.Duration |
| + }{ |
| + {LeaseTTL, pauseLimit}, |
| + {45 * time.Minute, pauseLimit}, // the moves staging term |
| + {time.Hour, pauseLimit}, |
| + {3 * time.Minute, pauseLimit}, |
| + {3*time.Minute - time.Nanosecond, 0}, |
| + {3 * time.Second, 0}, |
| + } { |
| + if got := pauseLimitForTTL(c.ttl); got != c.want { |
| + t.Errorf("pauseLimitForTTL(%s) = %s, want %s", c.ttl, got, c.want) |
| + } |
| + } |
| + if pauseLimit != 30*time.Second { |
| + t.Fatalf("pause limit %s: the load balancer's 30 s exclusion bound is the reasoning; change both together", pauseLimit) |
| + } |
| +} |
| + |
| +func pauseRenewer(t *testing.T, backend *lockStore, ttl, pause time.Duration) *renewer { |
| + t.Helper() |
| + leaser := lss3.NewLeaser() |
| + leaser.SetClient(backend) |
| + leaser.TTL = ttl |
| + started := time.Now() |
| + lock, e := leaser.AcquireLease(context.Background()) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + rn := startRenewerPause(backend, leaser, lock, started, ttl/10, pause, nil) |
| + t.Cleanup(func() { leaser.ReleaseLease(context.Background(), rn.stop()) }) |
| + return rn |
| +} |
| + |
| +// A gap since the last liveness sample longer than the limit latches |
| +// ErrPaused (which is ErrLost) at the next check, whoever makes it, and |
| +// no renewal follows. The gap is made by moving the last sample back, |
| +// which is what a stopped process sees on resume. |
| +func TestPauseGapLatchesLossWithoutRenewing(t *testing.T) { |
| + backend := &lockStore{} |
| + rn := pauseRenewer(t, backend, 3*time.Second, 300*time.Millisecond) |
| + puts, _ := backend.counts() |
| + rn.mu.Lock() |
| + rn.seen = time.Now().Add(-time.Second) |
| + rn.mu.Unlock() |
| + err := rn.Err() |
| + if !errors.Is(err, ErrPaused) || !errors.Is(err, ErrLost) { |
| + t.Fatalf("a gap past the pause limit: %v, want ErrPaused (an ErrLost)", err) |
| + } |
| + await(t, rn.lost) |
| + await(t, rn.done) |
| + // A full renewal interval later, still nothing written. |
| + time.Sleep(time.Second + 100*time.Millisecond) |
| + if now, _ := backend.counts(); now != puts { |
| + t.Fatalf("%d renewal(s) after the pause latched", now-puts) |
| + } |
| + if _, e := rn.SafeUntil(); !errors.Is(e, ErrPaused) { |
| + t.Fatalf("SafeUntil after the pause: %v", e) |
| + } |
| +} |
| + |
| +// With the limit on, a holder that keeps running keeps renewing. The |
| +// limit here is shorter than the renewal interval, as in production (30 s |
| +// against 5 min), so the renewal's own checks cannot keep the holder |
| +// alive: only watch's sampling between renewals does. |
| +func TestPauseLimitKeepsAHealthyHolder(t *testing.T) { |
| + backend := &lockStore{} |
| + rn := pauseRenewer(t, backend, 3*time.Second, 600*time.Millisecond) |
| + start, _ := backend.counts() |
| + time.Sleep(2500 * time.Millisecond) // two and a half renewal intervals |
| + if e := rn.Err(); e != nil { |
| + t.Fatalf("healthy holder lost its lease: %v", e) |
| + } |
| + if now, _ := backend.counts(); now-start < 2 { |
| + 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| new file mode 100644 |
| index 000000000..3f2fa5413 |
| --- /dev/null |
| +++ b/internal/lease/pause_unix_test.go |
| @@ -0,0 +1,175 @@ |
| +//go:build unix |
| + |
| +package lease |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| +) |
| + |
| +// pauseHelperEnv carries the fake store's URL to the child process |
| +// TestPausedHolderDoesNotRenewOnResume re-executes this test binary as. |
| +const pauseHelperEnv = "CARLOS_LEASE_PAUSE_HELPER" |
| + |
| +// TestPausedHolderDoesNotRenewOnResume is G2 drill 2 in one test binary |
| +// (2026-11-05): a holder whose process is SIGSTOPped past its renewal |
| +// time, then sent SIGTERM and SIGCONT together (what systemd's stop does |
| +// to a stopped unit), must not renew on resume. Before the fix the |
| +// overdue ticker fired the moment the process ran again and the PUT |
| +// pushed the lock's expiry a whole TTL past the outage bound. |
| +// |
| +// The holder runs in a child process so the kernel really stops it: no |
| +// goroutine of the renewer can run while it is stopped, exactly as on the |
| +// box. The fake S3 store lives in this process and records every renewal |
| +// (If-Match PUT) with the time it landed. |
| +func TestPausedHolderDoesNotRenewOnResume(t *testing.T) { |
| + if url := os.Getenv(pauseHelperEnv); url != "" { |
| + pausedHolderChild(url) |
| + return |
| + } |
| + var mu sync.Mutex |
| + var renewals []time.Time |
| + backend := &lockStore{beforePut: func(ctx context.Context, p *s3.PutObjectInput) error { |
| + if p.IfMatch != nil { |
| + mu.Lock() |
| + renewals = append(renewals, time.Now()) |
| + mu.Unlock() |
| + } |
| + return nil |
| + }} |
| + srv := httptest.NewServer(backend) |
| + defer srv.Close() |
| + |
| + cmd := exec.Command(os.Args[0], "-test.run=^TestPausedHolderDoesNotRenewOnResume$") |
| + cmd.Env = append(os.Environ(), pauseHelperEnv+"="+srv.URL) |
| + cmd.Stderr = os.Stderr |
| + out, err := cmd.StdoutPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + _ = cmd.Process.Kill() |
| + _ = cmd.Wait() |
| + }) |
| + lines := make(chan string, 16) |
| + go func() { |
| + sc := bufio.NewScanner(out) |
| + for sc.Scan() { |
| + lines <- sc.Text() |
| + } |
| + close(lines) |
| + }() |
| + expect := func(prefix string) string { |
| + t.Helper() |
| + for { |
| + select { |
| + case l, ok := <-lines: |
| + if !ok { |
| + t.Fatalf("child exited before %q", prefix) |
| + } |
| + if strings.HasPrefix(l, prefix) { |
| + return l |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatalf("timed out waiting for %q", prefix) |
| + } |
| + } |
| + } |
| + expect("held") |
| + renewalCount := func() int { mu.Lock(); defer mu.Unlock(); return len(renewals) } |
| + // Stop the holder just after a renewal, so its next one falls due |
| + // while it is stopped. |
| + for deadline := time.Now().Add(5 * time.Second); renewalCount() == 0; { |
| + if time.Now().After(deadline) { |
| + t.Fatal("the holder never renewed before the pause") |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + if err := cmd.Process.Signal(syscall.SIGSTOP); err != nil { |
| + t.Fatal(err) |
| + } |
| + stoppedAt := time.Now() |
| + before := renewalCount() |
| + // pauseChildTTL/3 is the renewal interval: stopped for 1.5 of them, |
| + // the next renewal is overdue at resume while the lease is still valid |
| + // (well inside SafeUntil), which is drill 2's shape. |
| + time.Sleep(pauseChildTTL / 2) |
| + _ = cmd.Process.Signal(syscall.SIGTERM) |
| + if err := cmd.Process.Signal(syscall.SIGCONT); err != nil { |
| + t.Fatal(err) |
| + } |
| + resumedAt := time.Now() |
| + if renewalCount() != before { |
| + t.Fatal("a renewal landed while the holder was stopped") |
| + } |
| + verdict := expect("verdict") |
| + // One full renewal interval after resume: long enough for an overdue |
| + // tick and the next scheduled one. |
| + time.Sleep(pauseChildTTL/3 + 100*time.Millisecond) |
| + mu.Lock() |
| + after := append([]time.Time(nil), renewals[before:]...) |
| + mu.Unlock() |
| + t.Logf("stopped %s; %s", resumedAt.Sub(stoppedAt).Round(time.Millisecond), verdict) |
| + if len(after) != 0 { |
| + t.Fatalf("the resumed holder renewed %d time(s), first %s after SIGCONT: a paused holder extended its lease", len(after), after[0].Sub(resumedAt).Round(time.Millisecond)) |
| + } |
| + if !strings.Contains(verdict, "lost=true") || !strings.Contains(verdict, "paused=true") { |
| + t.Fatalf("the resumed holder did not stand down as paused: %s", verdict) |
| + } |
| +} |
| + |
| +// pauseChildTTL is short so the test runs in seconds; pauseChildLimit is |
| +// the pause the child tolerates, well under the 0.5 TTL stop above. |
| +const ( |
| + pauseChildTTL = 3 * time.Second |
| + pauseChildLimit = 400 * time.Millisecond |
| +) |
| + |
| +// pausedHolderChild is the child: it holds a lease through the production |
| +// AcquireTTL against the parent's store, then reports what its handle |
| +// says once SIGTERM arrives (delivered with the SIGCONT that resumes it). |
| +func pausedHolderChild(url string) { |
| + os.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + os.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + os.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + os.Setenv("CARLOS_S3_ENDPOINT", url) |
| + pauseLimitFor = func(time.Duration) time.Duration { return pauseChildLimit } |
| + term := make(chan os.Signal, 1) |
| + signal.Notify(term, syscall.SIGTERM) |
| + h, err := AcquireTTL(context.Background(), "test-bucket", "one.example", "test-region", pauseChildTTL) |
| + if err != nil { |
| + fmt.Println("error", err) |
| + os.Exit(1) |
| + } |
| + fmt.Println("held") |
| + <-term |
| + // A shutdown takes a moment before it reaches the lease; the renewer |
| + // must already have stood down by then, without help from the signal. |
| + time.Sleep(50 * time.Millisecond) |
| + err = h.Err() |
| + lost := false |
| + select { |
| + case <-h.Lost(): |
| + lost = true |
| + default: |
| + } |
| + fmt.Printf("verdict lost=%t paused=%t err=%v\n", lost, errors.Is(err, ErrPaused), err) |
| + // Stay up (as a draining edge would) until the parent kills us. |
| + time.Sleep(time.Minute) |
| +} |
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 |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 686bb53a1..afcc85ae7 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -105,3 +105,4 @@ plan14-root-reads-demo-api-site-route.tsv 9bfd77d30d8e3deb5f3863cb6c272c2cb46ce3 |
| plan14-root-reads-region-ha-p3b2-rolls.tsv c55b4a022b3d42f40a05b727f93e57dc9f76b6dc2251f7d3b777c34d7ffdee09 |
| plan14-root-reads-restart-new-box-gap.tsv 18e4df5f599a48a881526fc2f85a9b591e3ea8677bb297d5944c9d935771f5e6 |
| plan14-root-reads-agent-start-demo-3.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939 |
| +plan14-root-reads-lease-renew-after-pause.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939 |
diff --git a/internal/provision/testdata/plan14-root-reads-lease-renew-after-pause.tsv b/internal/provision/testdata/plan14-root-reads-lease-renew-after-pause.tsv| new file mode 100644 |
| index 000000000..4a1f15c5a |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-lease-renew-after-pause.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay lease-renew-after-pause, written by census-propose (#369). census-ruling-lease-renew-after-pause, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-lease-renew-after-pause.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/lease 08f6245f33c645540554926b965b3c3f0b7cf6c1ffd2e59f2fa1c3c965083e23 |