carlos / platform Public

ha: preserve duty retry policy and finish refused picked runs

Record failed duty wakes through schedule backoff, and finish and close runs refused after pickup. Advance old ticks only for a known peer owner. Exercise peer-lock producer admission, token ordering, expiry equality and CAS reclassification.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1cbdf6fdf9d2321212c954dfcf09528d59dc216d parent e41439a
8 files changed, +362 −9
  • internal/activator/haduties.go +17 −3
  • internal/activator/haduties_test.go +98 −0
  • internal/host/haduties_wiring_test.go +113 −2
  • internal/host/runrelay_linux_test.go +36 −0
  • internal/host/runs.go +8 −1
  • internal/lease/haduty_test.go +35 −0
  • internal/schedule/haduties_test.go +44 −1
  • internal/schedule/runner.go +11 −2

Intent

Human

Check Astra B1 progress for P1b-3b slice T: ledger at /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-duties/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/progress.md, log task-B1-astra-a.log mtime, output task-B1-astra-a.md; continue SDD.

Human

<task-notification> <task-id>a80e0af8bca8b19b5</task-id> <tool-use-id>toolu_014KTv6xYCcTdzrx9qvCbMGu</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/a80e0af8bca8b19b5.output</output-file> <status>completed</status> <summary>Agent "Opus review Task B1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Task quality:** Needs fixes. 0 Critical, 2 Important, 11 Minor. The two Important issues: 1. **Schedule tick wake loop:** `Runner.fire` now wakes the instance before it delivers the tick. If that wake fails for any reason other than a duty refusal, nothing is recorded: no attempt count, no backoff, no member-visible event. The timer stays due, so the next tick 15 seconds later wakes again. That is a lock read every 15 seconds for as long as the failure lasts. It affects all hibernating scheduled hosts, not only HA ones. 2. **Stranded runs:** if the duty gate refuses the run after it has been picked, the run never executes. Its sink is never closed (an open relay connection), its handle stays registered, and no result is written, so it sits in "picked" until it expires. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-duties/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/task-B1-review-r1.md</result> <usage><subagent_tokens>125107</subagent_tokens><tool_uses>24</tool_uses><duration_ms>357649</duration_ms></usage> </task-notification>

diff --git a/internal/activator/haduties.go b/internal/activator/haduties.go
index 68dc2aa41..821ee0466 100644
--- a/internal/activator/haduties.go
+++ b/internal/activator/haduties.go
@@ -267,12 +267,12 @@ func (a *Service) Duty(ctx context.Context, rt registry.Route) (DutyDecision, er
}
func (a *Service) restrictDuty(ctx context.Context, rt registry.Route) (context.Context, error) {
- i, _, err := a.dutyInput(ctx, rt)
+ i, st, err := a.dutyInput(ctx, rt)
if err != nil {
return ctx, err
}
if DecideDuty(i) == Defer {
- return ctx, ErrDutyDeferred
+ return ctx, dutyRefusal(i, st)
}
return context.WithValue(ctx, dutyContextKey{}, dutyRestriction{allow: func(v hafresh.View) error { return a.allowDuty(ctx, rt, i.Lifetime, v) }}), nil
}
@@ -282,9 +282,12 @@ func (a *Service) allowDuty(ctx context.Context, rt registry.Route, lifetime str
if err != nil {
return err
}
- if !i.HA || (lifetime != "" && i.Lifetime != lifetime) || DecideDuty(i) == Defer {
+ if !i.HA || (lifetime != "" && i.Lifetime != lifetime) {
return ErrDutyDeferred
}
+ if DecideDuty(i) == Defer {
+ return dutyRefusal(i, st)
+ }
i.Observed = &v
if DecideDuty(i) == DutyAttempt {
if !v.Absent && v.Lock.Release == nil && !a.now().After(v.Lock.ExpiresAt) {
@@ -318,6 +321,17 @@ func (a *Service) allowDuty(ctx context.Context, rt registry.Route, lifetime str
if err := a.saveDuty(ctx, rt.Host, i.Lifetime, st, next); err != nil {
return err
}
+ i.Suppressed = true
+ return dutyRefusal(i, next)
+}
+
+func dutyRefusal(i DutyInput, st DutyState) error {
+ if i.LocalDenied || i.OwnedAwake || i.Lifetime == "" || i.Self.Ref == "" || i.Self.IID == "" || !i.Suppressed {
+ return ErrDutyDeferred
+ }
+ if st.HolderRef != "" && st.HolderRef != "@unknown" && (st.HolderRef != i.Self.Ref || st.HolderIID != i.Self.IID) {
+ return schedule.ErrDutyNotOwner
+ }
return ErrDutyDeferred
}
diff --git a/internal/activator/haduties_test.go b/internal/activator/haduties_test.go
index 74243a4c2..e972e3395 100644
--- a/internal/activator/haduties_test.go
+++ b/internal/activator/haduties_test.go
@@ -15,9 +15,11 @@ import (
"github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/schedule"
)
func TestHADutyOwnerTable(t *testing.T) {
@@ -372,3 +374,99 @@ func TestHADutyStaleLegacyClassification(t *testing.T) {
t.Fatalf("stale legacy bypass: err=%v woke=%v", err, s.wokeHere())
}
}
+
+func TestDutyAcquireRestrictionOnlyExpiryEquality(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ now := time.Now().UTC().Truncate(time.Second)
+ s.a.now = func() time.Time { return now }
+ life := haFixOf(s.b).lifetime
+ putLockFor(t, s.b, s.rt, leaseBody(t, hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a"}, 1, true), now))
+ proofs, calls := 0, 0
+ p := hafresh.Proofs{SameBoxEmpty: func() (bool, error) { proofs++; return true, nil }}
+ acquire := func() (*lease.Held, error) {
+ return lease.AcquireHAForDuty(context.Background(), s.fx.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), "", hafresh.Marker{Lifetime: life}, p, func(v hafresh.View) error {
+ calls++
+ return s.a.allowDuty(context.Background(), s.rt, life, v)
+ })
+ }
+ held, err := acquire()
+ if held != nil {
+ held.Release(context.Background())
+ }
+ if !errors.Is(err, ErrDutyDeferred) || proofs != 0 || calls != 1 {
+ t.Fatalf("equality: err=%v proofs=%d calls=%d", err, proofs, calls)
+ }
+ st, err := s.a.dutyState(context.Background(), s.rt.Host, life)
+ if err != nil || !st.NotBefore.Equal(now.Add(time.Nanosecond)) {
+ t.Fatalf("deadline=%+v err=%v", st, err)
+ }
+ for _, req := range s.fx.Requests() {
+ if strings.HasPrefix(req, "PUT ") {
+ t.Fatalf("equality wrote: %s", req)
+ }
+ }
+ now = now.Add(time.Nanosecond)
+ held, err = acquire()
+ if err != nil {
+ t.Fatal(err)
+ }
+ held.Release(context.Background())
+ if proofs != 1 || calls != 2 {
+ t.Fatalf("after equality: proofs=%d calls=%d", proofs, calls)
+ }
+}
+
+func TestHADutyScheduleTokenAfterWake(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ if err := s.b.Registry.Upsert(s.rt); err != nil {
+ t.Fatal(err)
+ }
+ s.a.SetDutyView(func(registry.Route) boxchoice.WakeSnapshot {
+ return boxchoice.WakeSnapshot{Usable: true, Self: "a", Serving: []boxchoice.Candidate{{BoxID: "a"}}}
+ })
+ now := time.Now().Truncate(time.Second)
+ timer := registry.Timer{Host: s.rt.Host, Name: "tick", Kind: "schedule", Spec: "every 1h", Path: "/job", NextAt: now.Unix()}
+ if err := s.b.Registry.UpsertTimer(timer); err != nil {
+ t.Fatal(err)
+ }
+ var tokens atomic.Int32
+ done := make(chan error, 1)
+ r := schedule.Runner{Reg: s.b.Registry, Now: func() time.Time { return now }, Token: func(string) (string, error) {
+ tokens.Add(1)
+ if !s.wokeHere() || !s.a.HoldsAwake(s.rt.Host) {
+ t.Error("token minted before restore and start completed")
+ }
+ return "", errors.New("stop after token ordering check")
+ }, WithDuty: func(ctx context.Context, rt registry.Route, work func(context.Context) error) error {
+ err := s.a.WithDuty(ctx, rt, work)
+ done <- err
+ return err
+ }}
+ r.Tick(context.Background())
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("schedule gate did not finish")
+ }
+ if tokens.Load() != 1 || lockGets(s.b, s.rt) != 1 {
+ t.Fatalf("tokens=%d lock reads=%d", tokens.Load(), lockGets(s.b, s.rt))
+ }
+}
+
+func TestHADutyLocalDeniedRetainsTick(t *testing.T) {
+ s := haHeldByB(t)
+ life := haFixOf(s.b).lifetime
+ if err := s.a.saveDuty(context.Background(), s.rt.Host, life, DutyState{}, DutyState{Basis: DutyLocalRelease}); err != nil {
+ t.Fatal(err)
+ }
+ s.a.SetDutyView(func(registry.Route) boxchoice.WakeSnapshot { return boxchoice.WakeSnapshot{LocalDenied: true} })
+ err := s.a.WithDuty(context.Background(), s.rt, func(context.Context) error { t.Error("denied owner ran"); return nil })
+ if !errors.Is(err, ErrDutyDeferred) || errors.Is(err, schedule.ErrDutyNotOwner) || lockGets(s.b, s.rt) != 0 {
+ t.Fatalf("err=%v lock reads=%d", err, lockGets(s.b, s.rt))
+ }
+}
diff --git a/internal/host/haduties_wiring_test.go b/internal/host/haduties_wiring_test.go
index a02ccbd8a..502548422 100644
--- a/internal/host/haduties_wiring_test.go
+++ b/internal/host/haduties_wiring_test.go
@@ -2,15 +2,21 @@ package host
import (
"context"
+ "encoding/json"
"path/filepath"
+ "strings"
"sync/atomic"
"testing"
"time"
"github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/runs"
)
func TestHADutyBeforeEveryProducer(t *testing.T) {
@@ -24,7 +30,7 @@ func TestHADutyBeforeEveryProducer(t *testing.T) {
if err := reg.Upsert(rt); err != nil {
t.Fatal(err)
}
- svc := activator.New(activator.Config{}, &fakeWakeBackend{inst: &fakeInstance{}}, reg)
+ svc, fx := peerHeldDutyService(t, reg, &rt)
defer svc.Shutdown(context.Background())
sd := newScheduleDeps(reg, nil, svc, nil, t.TempDir())
now := time.Now()
@@ -45,6 +51,7 @@ func TestHADutyBeforeEveryProducer(t *testing.T) {
case <-time.After(time.Second):
t.Fatal("gate not called")
}
+ assertPeerDutyRead(t, fx, rt.Host)
if tokens.Load() != 0 {
t.Fatal("loser minted token")
}
@@ -68,7 +75,7 @@ func TestHADutyBeforeEveryProducer(t *testing.T) {
if err := reg.Upsert(*rt); err != nil {
t.Fatal(err)
}
- svc := activator.New(activator.Config{}, &fakeWakeBackend{inst: &fakeInstance{}}, reg)
+ svc, fx := peerHeldDutyService(t, reg, rt)
defer svc.Shutdown(context.Background())
w := testWorker(store, reg.Get, "box-1", "boot-1", &calls)
w.launch = svc
@@ -76,6 +83,7 @@ func TestHADutyBeforeEveryProducer(t *testing.T) {
w.relay = &runRelay{}
}
w.consider(context.Background(), rec)
+ assertPeerDutyRead(t, fx, rt.Host)
if calls.count() != 0 || currentRun(t, store).State != provision.RunQueued {
t.Fatal("loser picked or launched run")
}
@@ -98,3 +106,106 @@ func (d runDutyFixture) WithDuty(ctx context.Context, rt registry.Route, work fu
}
func (d runDutyFixture) IsHA(_ context.Context, rt registry.Route) (bool, error) { return rt.HA, nil }
func (d runDutyFixture) HoldsAwake(host string) bool { return d.holds(host) }
+
+type dutyTrackedSink struct {
+ runSink
+ closed bool
+ finishes int
+}
+
+func (s *dutyTrackedSink) close() { s.closed = true; s.runSink.close() }
+func (s *dutyTrackedSink) Finish(ctx context.Context, rec provision.Record, req runs.Request, res runs.Result) error {
+ s.finishes++
+ return s.runSink.Finish(ctx, rec, req, res)
+}
+
+func TestHADutyRunLeaseLossAfterPickup(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ rec, id := queueRun(t, store, time.Now().Add(time.Minute))
+ var calls execLog
+ route := runOwnedRoute(runHost)
+ rt, _ := route(runHost)
+ rt.HA = true
+ w := testWorker(store, func(string) (*registry.Route, error) { return rt, nil }, "box-1", "boot-1", &calls)
+ w.dataDir = t.TempDir()
+ held := true
+ w.launch = runDutyFixture{holds: func(string) bool { return held }}
+ var sink *dutyTrackedSink
+ w.start = func(f func()) {
+ if currentRun(t, store).State != provision.RunPicked {
+ t.Fatal("run not picked before lease loss")
+ }
+ h := w.active[id]
+ sink = &dutyTrackedSink{runSink: h.sink}
+ h.sink = sink
+ held = false
+ f()
+ }
+ w.consider(context.Background(), rec)
+ if sink == nil {
+ t.Fatal("never picked")
+ }
+ defer sink.close()
+ if !sink.closed || sink.finishes != 1 || w.active[id] != nil || calls.count() != 0 {
+ t.Errorf("closed=%v finishes=%d active=%v execs=%d", sink.closed, sink.finishes, w.active[id] != nil, calls.count())
+ }
+ result, err := runs.ReadResult(context.Background(), store, rec.Account, rec.App, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result == nil {
+ t.Fatal("missing refusal result")
+ }
+ if result.Refused != runs.RefusedIncarnation || currentRun(t, store).State != provision.RunDone {
+ t.Fatalf("result=%+v state=%+v", result, currentRun(t, store))
+ }
+}
+
+type dutyNoControl struct{ activator.Control }
+
+func peerHeldDutyService(t *testing.T, reg *registry.Registry, rt *registry.Route) (*activator.Service, *locktest.LockFixture) {
+ t.Helper()
+ fx := locktest.NewLockFixture(t)
+ t.Cleanup(lease.ProcessStateForTest())
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"})
+ dir := t.TempDir()
+ dataDir := t.TempDir()
+ rt.DBPath = provision.NestedDBPath(dataDir, rt.Host)
+ rt.Socket = filepath.Join(dir, "instances", provision.InstanceID(rt.Host), "app.sock")
+ rt.Account, rt.App = "bab", "shop"
+ if err := reg.Upsert(*rt); err != nil {
+ t.Fatal(err)
+ }
+ rec := provision.Record{Schema: 1, Host: rt.Host, Account: rt.Account, App: rt.App, HA: true, CreatedAt: time.Now().UTC()}
+ index := &provision.LifetimeIndex{}
+ if _, err := provision.LifetimeEntryOf(rec); err != nil {
+ t.Fatal(err)
+ }
+ index.Merge(map[string]provision.Record{rt.Host: rec})
+ b := &activator.ExecBackend{Cfg: activator.Config{Bucket: fx.Bucket}, Registry: reg, Lifetimes: index, DataDir: dataDir, RunDirOverride: dir, Control: dutyNoControl{}, StartupSwept: func() bool { return true }}
+ body, err := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 1, true), ExpiresAt: time.Now().Add(time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.PutLock(activator.HibernatePrefix("", rt.Host), body)
+ return activator.New(activator.Config{Bucket: fx.Bucket}, b, reg), fx
+}
+
+func assertPeerDutyRead(t *testing.T, fx *locktest.LockFixture, host string) {
+ t.Helper()
+ gets := 0
+ for _, req := range fx.Requests() {
+ if req == "GET "+activator.HibernatePrefix("", host)+"/lock.json" {
+ gets++
+ }
+ if strings.HasPrefix(req, "PUT ") {
+ t.Errorf("loser wrote: %s", req)
+ }
+ }
+ if gets != 1 {
+ t.Fatalf("peer lock reads=%d requests=%v", gets, fx.Requests())
+ }
+}
diff --git a/internal/host/runrelay_linux_test.go b/internal/host/runrelay_linux_test.go
index 88614e8c8..6adc5c564 100644
--- a/internal/host/runrelay_linux_test.go
+++ b/internal/host/runrelay_linux_test.go
@@ -755,3 +755,39 @@ func TestFleetRunsWorkerRequestBudget(t *testing.T) {
t.Fatalf("a run let go, two passes: %q", got)
}
}
+
+func TestHADutyRelayLeaseLossAfterPickup(t *testing.T) {
+ rt := baseRelayRoute()
+ rt.HA = true
+ rw := newRelayWorld(t, rt)
+ var sink *dutyTrackedSink
+ rw.w.start = func(f func()) {
+ if rw.run(t).State != provision.RunPicked {
+ t.Fatal("not picked before lease loss")
+ }
+ h := rw.w.active[rw.id]
+ sink = &dutyTrackedSink{runSink: h.sink}
+ h.sink = sink
+ rw.w.relay.holds = func(string) bool { return false }
+ f()
+ }
+ rw.w.consider(context.Background(), rw.rec)
+ if sink == nil {
+ t.Fatal("not picked")
+ }
+ defer sink.close()
+ if !sink.closed || sink.finishes != 1 || rw.w.active[rw.id] != nil || rw.launcher.calls != 0 {
+ t.Fatalf("closed=%v finishes=%d active=%v launches=%d", sink.closed, sink.finishes, rw.w.active[rw.id] != nil, rw.launcher.calls)
+ }
+ select {
+ case <-rw.door.over:
+ case <-time.After(time.Second):
+ t.Fatal("relay connection stayed open")
+ }
+ if res := rw.result(t); res.Refused != runs.RefusedIncarnation || rw.run(t).State != provision.RunDone {
+ t.Fatalf("result=%+v run=%+v", res, rw.run(t))
+ }
+ if rw.box.writes.Load() != 0 {
+ t.Fatal("fleet wrote to bucket")
+ }
+}
diff --git a/internal/host/runs.go b/internal/host/runs.go
index 96b3c4df2..e2bd57c38 100644
--- a/internal/host/runs.go
+++ b/internal/host/runs.go
@@ -299,7 +299,14 @@ func (w *runsWorker) pickupOwned(ctx context.Context, rec provision.Record, rt r
if duty, ok := w.launch.(interface {
WithDuty(context.Context, registry.Route, func(context.Context) error) error
}); ok {
- _ = duty.WithDuty(call, rt, func(ctx context.Context) error { w.exec(ctx, *got, *req, rt, h); return nil })
+ ran := false
+ err := duty.WithDuty(call, rt, func(ctx context.Context) error { ran = true; w.exec(ctx, *got, *req, rt, h); return nil })
+ if err != nil && !ran {
+ defer w.forget(req.ID)
+ sink := w.sinkOf(h, *req)
+ defer sink.close()
+ w.finish(call, sink, *got, *req, runs.Result{Refused: runs.RefusedIncarnation}, nil, true)
+ }
} else {
w.exec(call, *got, *req, rt, h)
}
diff --git a/internal/lease/haduty_test.go b/internal/lease/haduty_test.go
index 4f7950c4f..ff4e07dc1 100644
--- a/internal/lease/haduty_test.go
+++ b/internal/lease/haduty_test.go
@@ -86,3 +86,38 @@ func TestDutyAcquireExpiryEquality(t *testing.T) {
t.Fatalf("equality: %+v proofs=%d", d, proofs)
}
}
+
+func TestDutyAcquireRestrictionOnlyReclassifiedPeer(t *testing.T) {
+ haBox(t)
+ fx := leasetest.NewLockFixture(t)
+ marker, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "a", IID: "i-a"})
+ fx.PutLock("instances/h", marker)
+ puts := 0
+ fx.BeforeWrite(func(method, key string) {
+ if method == http.MethodPut {
+ puts++
+ fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 1, true), time.Now().Add(-time.Hour)))
+ }
+ })
+ denied := errors.New("peer duty refused")
+ calls, proofs := 0, 0
+ h, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{OwnerTerminated: func(string) (bool, error) { proofs++; return true, nil }}, func(v hafresh.View) error {
+ calls++
+ if calls == 1 && v.Lock.Release != nil && v.Lock.Release.Box == "a" {
+ return nil
+ }
+ if calls == 2 && v.Lock.Release == nil {
+ if o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && o.Ref == "b" {
+ return denied
+ }
+ }
+ t.Errorf("unexpected round %d: %+v", calls, v)
+ return denied
+ })
+ if h != nil {
+ h.Release(ctx)
+ }
+ if !errors.Is(err, denied) || calls != 2 || puts != 1 || proofs != 0 {
+ t.Fatalf("err=%v calls=%d puts=%d proofs=%d", err, calls, puts, proofs)
+ }
+}
diff --git a/internal/schedule/haduties_test.go b/internal/schedule/haduties_test.go
index fc7685276..78833d3b4 100644
--- a/internal/schedule/haduties_test.go
+++ b/internal/schedule/haduties_test.go
@@ -2,7 +2,9 @@ package schedule
import (
"context"
+ "errors"
"strconv"
+ "strings"
"testing"
"time"
@@ -17,6 +19,7 @@ func TestHADutyTickAge(t *testing.T) {
}{
{"young", "schedule", 15*time.Minute - time.Second, false},
{"boundary", "schedule", 15 * time.Minute, true},
+ {"local denied owner", "schedule", time.Hour, false},
{"once", "once", time.Hour, false},
} {
t.Run(tc.name, func(t *testing.T) {
@@ -37,7 +40,12 @@ func TestHADutyTickAge(t *testing.T) {
}
tokens := 0
r.Token = func(string) (string, error) { tokens++; return "token", nil }
- r.WithDuty = func(context.Context, registry.Route, func(context.Context) error) error { return ErrDutyDeferred }
+ r.WithDuty = func(context.Context, registry.Route, func(context.Context) error) error {
+ if tc.name == "local denied owner" {
+ return ErrDutyDeferred
+ }
+ return ErrDutyNotOwner
+ }
r.Tick(context.Background())
r.wait()
after, err := reg.GetTimer(row.Host, row.Name)
@@ -82,3 +90,38 @@ func TestHADutyRegistrationGuard(t *testing.T) {
t.Fatalf("new occurrence overwritten: %v %v", changed, err)
}
}
+
+func TestHADutyWakeFailureBackoff(t *testing.T) {
+ reg, r := runnerFixture(t, &fakeDeliverer{})
+ now := time.Now().Truncate(time.Second)
+ r.Now = func() time.Time { return now }
+ row := registry.Timer{Host: "a.bab.oncarlos.com", Name: "tick", Kind: "schedule", Spec: "every 1h", Path: "/job", NextAt: now.Unix(), DueAt: now.Unix()}
+ if err := reg.UpsertTimer(row); err != nil {
+ t.Fatal(err)
+ }
+ tokens, events := 0, 0
+ r.Token = func(string) (string, error) { tokens++; return "token", nil }
+ r.Event = func(_ registry.Route, level, msg string) {
+ events++
+ if level != "warn" || !strings.Contains(msg, "restore failed") {
+ t.Errorf("event=%s %s", level, msg)
+ }
+ }
+ r.WithDuty = func(context.Context, registry.Route, func(context.Context) error) error {
+ return errors.New("restore failed")
+ }
+ r.Tick(context.Background())
+ r.wait()
+ got, err := reg.GetTimer(row.Host, row.Name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Attempts != 1 || got.NextAt != now.Add(backoffBase).Unix() || got.DueAt != row.DueAt || !strings.Contains(got.LastStatus, "restore failed") || events != 1 || tokens != 0 {
+ t.Fatalf("timer=%+v events=%d tokens=%d", got, events, tokens)
+ }
+ r.Tick(context.Background())
+ r.wait()
+ if events != 1 {
+ t.Fatal("retried before backoff")
+ }
+}
diff --git a/internal/schedule/runner.go b/internal/schedule/runner.go
index e60ceb488..d3a5e5d2b 100644
--- a/internal/schedule/runner.go
+++ b/internal/schedule/runner.go
@@ -33,6 +33,8 @@ const (
// may have finished, or still be running — a retry would double it.
var ErrDutyDeferred = errors.New("ha_duty_deferred")
+var ErrDutyNotOwner = fmt.Errorf("ha_duty_not_owner: %w", ErrDutyDeferred)
+
var ErrTimeout = errors.New("schedule: delivery timed out")
// Deliverer sends one tick and reports the handler's status, or an error.
@@ -542,8 +544,15 @@ func (r *Runner) fire(ctx context.Context, rt registry.Route, t registry.Timer)
r.fireOwned(ctx, rt, t)
return
}
- err := r.WithDuty(ctx, rt, func(call context.Context) error { r.fireOwned(call, rt, t); return nil })
- if errors.Is(err, ErrDutyDeferred) && OldDutyTick(t, r.now()) {
+ start := r.now()
+ ran := false
+ err := r.WithDuty(ctx, rt, func(call context.Context) error { ran = true; r.fireOwned(call, rt, t); return nil })
+ if err != nil && !errors.Is(err, ErrDutyDeferred) && !ran && r.timerStillDue(ctx, t) {
+ if sp, parseErr := ParseSpec(t.Spec); parseErr == nil {
+ r.record(ctx, rt, t, sp, start, classify(0, err, r.timeout()), r.now().Sub(start))
+ }
+ }
+ if !ran && errors.Is(err, ErrDutyNotOwner) && OldDutyTick(t, r.now()) {
sp, err := ParseSpec(t.Spec)
if err != nil {
return