oficina / equipo Public

runner: retry a failed hosted renewal until 2 minutes before expiry

A failed bearer or proxy certificate renewal is tried again, 5 s
doubling to 60 s, across the bootstrap listeners each time, until 2
minutes before that credential expires; only a failure then stops the
work, reports once and returns ErrRenewal (revised Task 14 ruling).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e028652495c4e9eedcfbc5b4e19cb94a3e52df06 parent 4d35276
3 files changed, +196 −41
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +19 −0
  • internal/runner/hosted/renew.go +68 −33
  • internal/runner/hosted/renew_test.go +109 −8
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index a00c4bfd..f3a634eb 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1072,3 +1072,22 @@ Mutation checks (each an exact unique string in renew.go replaced by a script, `
138. Renew at the full lifetime, not half. `-run TestRenewAtHalfLife`: FAIL `renew_test.go:305: at 15m0s Run set no timer (returned true, ... answered 403 "cert_expired")`. Restored.
139. A certificate renewal that does not extend it is not the last (`certDue = certDue && c.Leaf.NotAfter.After(old)` replaced by `_ = old`). `-run TestNoRenewalPastDeadline`: FAIL `a_certification_launch: renew_test.go:447: Run set 201 timers, the last for 0s at 19m59.999999999s: renewing without end`. Restored.
140. The failure not reported (`if report != nil {` replaced by `if false {`). `-run TestRenewalFailureStopsWork`: FAIL `renew_test.go:411: reports [], want one "token_renewal_failed"` in both subtests. Restored.
+
+### Task 14 revised ruling: retry before failing
+
+The coordinator's revised ruling: a failed renewal (bearer or proxy certificate) is tried again with backoff, 5 s doubling to 60 s, across the bootstrap listeners each time, until 2 minutes before that credential expires; only a failure then stops the job (cancel work, report once, `ErrRenewal`). `Run` keeps a `renewal{due, at, wait}` per credential; `retry(now, expiry)` schedules the next try (`retryFirst` 5 s, `retryMax` 1 min, never later than `expiry - renewMargin`, 2 min) and says none from the margin on. A success resets the backoff. A renewal cut short because ctx ended is not a failure.
+
+Tests: `TestRenewalRetriesTransientFailure` (the certificate while the proxy is cut from the controller: 502 at 7m30s and 7m35s, 200 at 7m45s, the next renewal at 15m15s; the bearer with two 503s: asked at 30m, 30m5s, 30m15s, then bearer-2 installed; work, report and Run untouched, a step call passes). `TestRenewalFailureStopsWork` now fails only at the margin: still running at 12m59s and 57m59s, ended at 13m and 58m, and the bearer's tries match the 5 s doubling to 60 s schedule exactly. `TestNoRenewalPastDeadline`'s refused bearer ends at 58m.
+
+Red (the new tests against 4d352761's renew.go): `go test ./internal/runner/hosted -run 'TestRenew|TestStepPast|TestNoRenewal' -count=1` FAIL `renew_test.go:420: at 12m59s, before the 2-minute margin, Run has returned true with ... 403 "wrong_epoch"` (and 57m59s for the bearer); `renew_test.go:502: certificate renewals answered [502], want 502 at 7m30s and 7m35s, then 200 at 7m45s`; `renew_test.go:515: bearer renewals asked at [30m0s], want [30m0s 30m5s 30m15s]`.
+
+Green: the brief's command: ok, every test and subtest. `go test ./internal/runner/hosted ./internal/hostedproxy/... -count=1 -race`: ok. `make budget build vet`: exit 0. gofmt and `git diff --check`: clean.
+
+Mutation checks (as before: exact unique string replaced by a script, `-count=1 -timeout 120s`, restored from a copy and checked with `cmp`); each compiled and failed on an assertion.
+
+141. No retry (`retry` always says none: `if true || !now.Before(last)`). `-run 'TestRenewalRetries|TestRenewalFailure'`: FAIL `renew_test.go:420: at 12m59s, before the 2-minute margin, Run has returned true ...` (both subtests) and `renew_test.go:502: certificate renewals answered [502], want ...`. Restored.
+142. Retry to expiry, no margin (`last := expiry`). `-run TestRenewalFailure`: FAIL `renew_test.go:424: at 13m0s after the refusal Run has returned false with <nil>, want ErrRenewal` (and 58m0s). Restored.
+143. No backoff (`r.wait = retryFirst`). Same test: FAIL `renew_test.go:418: Run set 201 timers, the last for 5s at 46m20s: renewing without end`. Restored.
+144. Keep working after the final failure (the work contexts not cancelled). `-run TestRenewalFailureStopsWork`: FAIL `renew_test.go:429: the work context still runs after the failed renewal` (both). Restored.
+145. Keep running after the final bearer failure (`return s.fail(...)` replaced by `bearer.due = false`). Same test: FAIL `renew_test.go:424: at 58m0s after the refusal Run has returned false with <nil>, want ErrRenewal`. Restored.
+146. Renew past the deadline (the `renewAt` deadline check replaced by `if false`). `-run TestNoRenewalPastDeadline`: FAIL `renew_test.go:539: 2 certificate and 1 bearer renewals, want 1 and 0`. Restored.
diff --git a/internal/runner/hosted/renew.go b/internal/runner/hosted/renew.go
index 31af4b0f..c63a06c4 100644
--- a/internal/runner/hosted/renew.go
+++ b/internal/runner/hosted/renew.go
@@ -107,21 +107,22 @@ func (s *Session) fail(err error) error {
// (a certification launch has none) is renewed at half its remaining
// lifetime and installed at once, so the next connection and the next
// dial use it; one that already expires at the job's deadline is left to
-// expire with the job. Run returns nil when ctx ends or nothing is left
-// to renew. On a failed renewal it cancels the work (Work), sends the
-// report (OnRenewalFailed) and returns ErrRenewal.
+// expire with the job. A failed renewal is tried again (retry) until
+// renewMargin before that credential expires. Run returns nil when ctx
+// ends or nothing is left to renew. When a renewal has failed at the
+// margin it cancels the work (Work), sends the report (OnRenewalFailed)
+// and returns ErrRenewal.
func (s *Session) Run(ctx context.Context, clock func() time.Time) error {
now := clock()
- certAt, certDue := s.renewAt(s.cert.Load().Leaf.NotAfter, now)
- var bearerAt time.Time
- bearerDue := false
+ var cert, bearer renewal
+ cert.at, cert.due = s.renewAt(s.cert.Load().Leaf.NotAfter, now)
if c := s.bearer.Load(); c != nil {
- bearerAt, bearerDue = s.renewAt(c.ExpiresAt, now)
+ bearer.at, bearer.due = s.renewAt(c.ExpiresAt, now)
}
- for certDue || bearerDue {
- next := certAt
- if !certDue || bearerDue && bearerAt.Before(certAt) {
- next = bearerAt
+ for cert.due || bearer.due {
+ next := cert.at
+ if !cert.due || bearer.due && bearer.at.Before(cert.at) {
+ next = bearer.at
}
select {
case <-ctx.Done():
@@ -131,41 +132,75 @@ func (s *Session) Run(ctx context.Context, clock func() time.Time) error {
now = clock()
// The certificate first: the bearer's renewal goes through the
// proxy on it.
- if certDue && !now.Before(certAt) {
+ if cert.due && !now.Before(cert.at) {
old := s.cert.Load().Leaf.NotAfter
c, err := s.renewCert(ctx, now)
- if err != nil {
- return s.stopped(ctx, fmt.Errorf("proxy certificate: %w", err))
+ switch {
+ case ctx.Err() != nil:
+ return nil
+ case err != nil && !cert.retry(now, old):
+ return s.fail(fmt.Errorf("proxy certificate: %w", err))
+ case err == nil:
+ s.cert.Store(&c)
+ s.client.CloseIdleConnections() // they carry the old certificate
+ cert = renewal{}
+ cert.at, cert.due = s.renewAt(c.Leaf.NotAfter, now)
+ // Its issuer's cap reached (the job's deadline, which a
+ // certification launch's session does not know): a renewal
+ // that does not extend a credential is its last.
+ cert.due = cert.due && c.Leaf.NotAfter.After(old)
}
- s.cert.Store(&c)
- s.client.CloseIdleConnections() // they carry the old certificate
- certAt, certDue = s.renewAt(c.Leaf.NotAfter, now)
- // Its issuer's cap reached (the job's deadline, which a
- // certification launch's session does not know): a renewal
- // that does not extend a credential is its last.
- certDue = certDue && c.Leaf.NotAfter.After(old)
}
- if bearerDue && !now.Before(bearerAt) {
+ if bearer.due && !now.Before(bearer.at) {
old := s.bearer.Load().ExpiresAt
r, err := s.renewBearer(ctx, now)
- if err != nil {
- return s.stopped(ctx, fmt.Errorf("bearer: %w", err))
+ switch {
+ case ctx.Err() != nil:
+ return nil
+ case err != nil && !bearer.retry(now, old):
+ return s.fail(fmt.Errorf("bearer: %w", err))
+ case err == nil:
+ s.bearer.Store(&r.Credential)
+ bearer = renewal{}
+ bearer.at, bearer.due = s.renewAt(r.Credential.ExpiresAt, now)
+ bearer.due = bearer.due && r.Credential.ExpiresAt.After(old)
}
- s.bearer.Store(&r.Credential)
- bearerAt, bearerDue = s.renewAt(r.Credential.ExpiresAt, now)
- bearerDue = bearerDue && r.Credential.ExpiresAt.After(old)
}
}
return nil
}
-// stopped is a renewal's failure: none when ctx has ended (the job is
-// over), otherwise fail.
-func (s *Session) stopped(ctx context.Context, err error) error {
- if ctx.Err() != nil {
- return nil
+// A failed renewal is tried again after retryFirst, the wait doubling to
+// retryMax, until renewMargin before the credential expires: a last try
+// then, and the job fails if it fails too.
+const (
+ retryFirst = 5 * time.Second
+ retryMax = time.Minute
+ renewMargin = 2 * time.Minute
+)
+
+// renewal is one credential's next renewal: due at at, and the wait
+// before the next retry after a failure (0 before any).
+type renewal struct {
+ due bool
+ at time.Time
+ wait time.Duration
+}
+
+// retry schedules the next try after a failure at now of the renewal of
+// a credential expiring at expiry, and reports whether there is one: none
+// from renewMargin before its expiry.
+func (r *renewal) retry(now, expiry time.Time) bool {
+ last := expiry.Add(-renewMargin)
+ if !now.Before(last) {
+ return false
+ }
+ r.wait = min(max(2*r.wait, retryFirst), retryMax)
+ r.at = now.Add(r.wait)
+ if r.at.After(last) {
+ r.at = last
}
- return s.fail(err)
+ return true
}
// renewAt is when a credential expiring at expiry, seen at now, is
diff --git a/internal/runner/hosted/renew_test.go b/internal/runner/hosted/renew_test.go
index 3f91a2cc..7c4941d5 100644
--- a/internal/runner/hosted/renew_test.go
+++ b/internal/runner/hosted/renew_test.go
@@ -12,6 +12,7 @@ import (
"slices"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -41,6 +42,8 @@ type fakeInstance struct {
nonces map[string]bool // nonce -> used
renewals int
refuse bool // refuse every renewal
+ refuseN int // refuse the next refuseN renewals
+ tries []time.Time
lavish bool // issue renewed bearers for an hour, naming that as the deadline
stale []string
}
@@ -87,7 +90,13 @@ func instanceOn(h *proxytest.Harness, deadline time.Time) *fakeInstance {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
+ f.tries = append(f.tries, h.Clock.Wall())
used, known := f.nonces[string(q.Nonce)]
+ if f.refuseN > 0 {
+ f.refuseN--
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
if f.refuse || !known || used || q.RunnerID != "r-1" || q.Epoch != proxytest.Epoch ||
!ed25519.Verify(f.machine, wire.HostedRenewMessage(q.RunnerID, q.Epoch, q.Nonce), q.Signature) {
http.Error(w, "forbidden", http.StatusForbidden)
@@ -147,6 +156,17 @@ func (f *fakeInstance) counts() (renewals int, stale []string) {
return f.renewals, slices.Clone(f.stale)
}
+// tried is when each bearer renewal was asked for, from start.
+func (f *fakeInstance) tried(start time.Time) []time.Duration {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []time.Duration
+ for _, at := range f.tries {
+ out = append(out, at.Sub(start))
+ }
+ return out
+}
+
func (f *fakeInstance) set(fn func(*fakeInstance)) {
f.mu.Lock()
defer f.mu.Unlock()
@@ -169,7 +189,8 @@ type renewRig struct {
due time.Time // when Run's timer fires; zero when it set none
ended bool // Run returned err
err error
- wakes int // timers Run has set
+ wakes int // timers Run has set
+ cut bool // the proxy is cut from the controller: no polls
}
func newRenewRig(t *testing.T, life time.Duration) *renewRig {
@@ -261,6 +282,9 @@ func (r *renewRig) advanceTo(at time.Time) {
next = r.due
}
r.h.Clock.Advance(next.Sub(now))
+ if r.cut {
+ continue
+ }
if err := r.h.Proxy.Poll(context.Background()); err != nil {
r.t.Fatalf("Poll: %v", err)
}
@@ -360,20 +384,22 @@ func TestStepPastFifteenMinutesAndAnHour(t *testing.T) {
}
}
-// A renewal that fails stops the work: the work context is cancelled
-// with ErrRenewal as its cause (and one asked for later is born
-// cancelled), the failure is reported once, Run returns ErrRenewal, and
-// nothing more is renewed.
+// A renewal that keeps failing is tried again, 5 seconds on and doubling
+// to a minute, until 2 minutes before the credential expires; when that
+// last try fails the work stops: the work context is cancelled with
+// ErrRenewal as its cause (and one asked for later is born cancelled),
+// the failure is reported once, Run returns ErrRenewal, and nothing more
+// is renewed.
func TestRenewalFailureStopsWork(t *testing.T) {
cases := []struct {
name string
at time.Duration
fault func(r *renewRig)
}{
- {"the proxy certificate", 7*time.Minute + 30*time.Second, func(r *renewRig) {
+ {"the proxy certificate", 13 * time.Minute, func(r *renewRig) {
r.h.Controller.SetEpoch(proxytest.LaunchID, proxytest.Epoch+1)
}},
- {"the bearer", 30 * time.Minute, func(r *renewRig) { r.f.set(func(f *fakeInstance) { f.refuse = true }) }},
+ {"the bearer", 58 * time.Minute, func(r *renewRig) { r.f.set(func(f *fakeInstance) { f.refuse = true }) }},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -389,6 +415,10 @@ func TestRenewalFailureStopsWork(t *testing.T) {
})
r.run()
tc.fault(r)
+ r.advanceTo(r.start.Add(tc.at - time.Second))
+ if r.ended || work.Err() != nil {
+ t.Fatalf("at %v, before the 2-minute margin, Run has returned %v with %v; work %v", tc.at-time.Second, r.ended, r.err, work.Err())
+ }
r.advanceTo(r.start.Add(tc.at))
if !r.ended || !errors.Is(r.err, hosted.ErrRenewal) {
t.Fatalf("at %v after the refusal Run has returned %v with %v, want ErrRenewal", tc.at, r.ended, r.err)
@@ -411,6 +441,16 @@ func TestRenewalFailureStopsWork(t *testing.T) {
t.Errorf("reports %q, want one %q", reports, hosted.ReasonRenewalFailed)
}
mu.Unlock()
+ if tc.name == "the bearer" {
+ var want []time.Duration
+ for at, wait := 30*time.Minute, 5*time.Second; at < tc.at; at, wait = at+wait, min(2*wait, time.Minute) {
+ want = append(want, at)
+ }
+ want = append(want, tc.at)
+ if got := r.f.tried(r.start); !slices.Equal(got, want) {
+ t.Errorf("bearer renewals asked at %v, want %v", got, want)
+ }
+ }
certs, bearers := r.renewed()
r.advanceTo(r.start.Add(2 * time.Hour))
if c, b := r.renewed(); c != certs || b != bearers {
@@ -420,6 +460,67 @@ func TestRenewalFailureStopsWork(t *testing.T) {
}
}
+// A renewal that fails for a while and then succeeds keeps the job: the
+// certificate's while the proxy cannot reach the controller (502), the
+// bearer's while the instance is busy (503). Each is tried again 5 and
+// then 10 seconds on, and the work, the report and Run are untouched.
+func TestRenewalRetriesTransientFailure(t *testing.T) {
+ keeps := func(t *testing.T, r *renewRig, work context.Context, reports *atomic.Int64) {
+ t.Helper()
+ if r.ended || work.Err() != nil || reports.Load() != 0 {
+ t.Fatalf("after the recovery Run returned %v with %v; work %v; %d reports", r.ended, r.err, work.Err(), reports.Load())
+ }
+ if status, _, err := stepCall(r.s); err != nil || status != http.StatusOK {
+ t.Fatalf("the step's call after the recovery = %d, %v", status, err)
+ }
+ }
+ rig := func(t *testing.T) (*renewRig, context.Context, *atomic.Int64) {
+ r := newRenewRig(t, 3*time.Hour)
+ work, release := r.s.Work(context.Background())
+ t.Cleanup(release)
+ var reports atomic.Int64
+ r.s.OnRenewalFailed(func(string) { reports.Add(1) })
+ r.run()
+ return r, work, &reports
+ }
+ t.Run("the proxy certificate", func(t *testing.T) {
+ r, work, reports := rig(t)
+ r.advanceTo(r.start.Add(7*time.Minute + 29*time.Second))
+ r.h.Partition(true)
+ r.cut = true
+ r.advanceTo(r.start.Add(7*time.Minute + 40*time.Second))
+ r.h.Partition(false)
+ r.cut = false
+ r.advanceTo(r.start.Add(7*time.Minute + 45*time.Second))
+ var statuses []int
+ for _, l := range r.h.Log.Lines(t) {
+ if l.Route == "renew" {
+ statuses = append(statuses, l.Status)
+ }
+ }
+ if !slices.Equal(statuses, []int{http.StatusBadGateway, http.StatusBadGateway, http.StatusOK}) {
+ t.Errorf("certificate renewals answered %v, want 502 at 7m30s and 7m35s, then 200 at 7m45s", statuses)
+ }
+ keeps(t, r, work, reports)
+ if want := r.start.Add(15*time.Minute + 15*time.Second); !r.due.Equal(want) {
+ t.Errorf("the next renewal is at %v, want %v (half the renewed certificate's life)", r.due.Sub(r.start), want.Sub(r.start))
+ }
+ })
+ t.Run("the bearer", func(t *testing.T) {
+ r, work, reports := rig(t)
+ r.f.set(func(f *fakeInstance) { f.refuseN = 2 })
+ r.advanceTo(r.start.Add(31 * time.Minute))
+ want := []time.Duration{30 * time.Minute, 30*time.Minute + 5*time.Second, 30*time.Minute + 15*time.Second}
+ if got := r.f.tried(r.start); !slices.Equal(got, want) {
+ t.Errorf("bearer renewals asked at %v, want %v", got, want)
+ }
+ if r.s.Token() != "bearer-2" {
+ t.Errorf("the session's bearer is %q, want the renewed bearer-2", r.s.Token())
+ }
+ keeps(t, r, work, reports)
+ })
+}
+
// Nothing is renewed past the job's deadline. A bearer issued to the
// deadline is never renewed; the certificate is renewed once, to the
// deadline, and then left to expire with the job; with nothing left to
@@ -458,7 +559,7 @@ func TestNoRenewalPastDeadline(t *testing.T) {
work, release := r.s.Work(context.Background())
defer release()
r.run()
- r.advanceTo(r.start.Add(30 * time.Minute))
+ r.advanceTo(r.start.Add(58 * time.Minute))
if !r.ended || !errors.Is(r.err, hosted.ErrRenewal) {
t.Fatalf("a bearer renewed past the deadline: Run returned %v with %v, want ErrRenewal", r.ended, r.err)
}