carlos / platform Public

ha: import departure wake state atomically

Persist duty revisions and adoption receipts with atomic wake replacement. Finalize through the existing restricted acquire and an unclean self marker; ordinary restore remains authoritative over local progress.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev f9f8e7df369b89494001202c0b7adf3f219609fc parent f3d050f
21 files changed, +1,677 −492
  • internal/activator/activator.go +3 −2
  • internal/activator/haadopt.go +332 −0
  • internal/activator/haadopt_test.go +195 −0
  • internal/activator/haduties.go +22 −7
  • internal/activator/hatakeover.go +4 −0
  • internal/activator/hawake.go +14 −0
  • internal/host/agent.go +1 −0
  • internal/hostfiles/wake.go +11 −30
  • internal/hostfiles/wake_test.go +3 −3
  • internal/registry/ha_departures.go +225 −0
  • internal/registry/ha_duties.go +152 −0
  • internal/registry/ha_duties_test.go +207 −0
  • internal/registry/registry.go +4 −1
  • internal/registry/remote.go +1 −1
  • internal/registry/remote_dispatch.go +120 −95
  • internal/schedule/cron.go +3 −165
  • internal/schedule/mingap.go +1 −64
  • internal/schedule/spec.go +10 −124
  • internal/timerspec/cron.go +169 −0
  • internal/timerspec/mingap.go +66 −0
  • internal/timerspec/spec.go +134 −0

Intent

Human

<task-notification> <task-id>becg5thd6</task-id> <tool-use-id>toolu_01NDm3DE9wxZyzVEvZNbCgRs</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/becg5thd6.output</output-file> <status>completed</status> <summary>Background command "Wait for B1 fix round 1" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a80e0af8bca8b19b5</task-id> <tool-use-id>toolu_01EyQsJsxfUVEkoLhUmxAnPK</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>- Important 1 (schedule wake failure skipped retry/backoff): ADDRESSED. `internal/schedule/runner.go:949-956`; test `TestHADutyWakeFailureBackoff`. - Important 2 (a refused exec stranded a picked run): ADDRESSED. `internal/host/runs.go:629-636`; tests `TestHADutyRunLeaseLossAfterPickup` (bucket) and `TestHADutyRelayLeaseLossAfterPickup` (relay). - Minor 3 (loser tests deferred for a trivial reason, no winner-ordering test): ADDRESSED. `internal/host/haduties_wiring_test.go:516-561` (real backend against a peer-held lock); `internal/activator/haduties_test.go:266-305` (token only after the wake). - Minor 4 (equality and reclassification tests bypassed the restricted acquire): ADDRESSED. `internal/activator/haduties_test.go:224-264`; `internal/lease/haduty_test.go:670-702`. - Minor 13 (old-tick advance also hit a fenced owner): ADDRESSED. `internal/activator/haduties.go:165-172` and `internal/schedule/runner.go:957` (advance now only on a known foreign holder); tests `TestHADutyLocalDeniedRetainsTick`, `TestHADutySelfExpiryRetainsTick` and the "local denied owner" row in `TestHADutyTickAge`. The fix diff adds no new Critical or Important issues (0 and 0). The report lists 4 out-of-scope Minors. One is the R1 Minor 7 doc-comment misplacement, still unfixed. 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-r2.md</result> <usage><subagent_tokens>154348</subagent_tokens><tool_uses>5</tool_uses><duration_ms>74273</duration_ms></usage> </task-notification>

Attributed to this commit: 4.14 g CO₂e (535,007 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p1b3b-duties, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 70147e0ed..3ac5d7075 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1252,8 +1252,9 @@ var errShuttingDown = errors.New("activator: the agent is shutting down")
// edge.Cache and edge.ListenControl; serve calls edge.MarkAnswered), and the
// seam back is the interface the edge declares for itself.
type Service struct {
- DutyStore DutyStore
- duties localDuties
+ DutyStore DutyStore
+ AdoptionIdentity func(context.Context, string, string) (bool, error)
+ duties localDuties
// Set these before use. ObserveReplicaRelease reuses the wake/rollout
// record observation and supplies the canonical manifest digest, not
// the staged artifact digest. Missing observations refuse execution.
diff --git a/internal/activator/haadopt.go b/internal/activator/haadopt.go
new file mode 100644
index 000000000..0d57370bd
--- /dev/null
+++ b/internal/activator/haadopt.go
@@ -0,0 +1,332 @@
+package activator
+
+import (
+ "context"
+ "log"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type AdoptResult uint8
+
+const (
+ Deferred AdoptResult = iota
+ Adopted
+ AlreadyAdopted
+ Superseded
+)
+
+type Adoption struct {
+ Departure, Ref, IID, Lifetime string
+ Pair registry.Pair
+ Observed hafresh.View
+ Revision uint64
+}
+
+func adoptionBackend(b Backend, rt registry.Route) *ExecBackend {
+ if split, ok := b.(*SplitBackend); ok {
+ return adoptionBackend(split.pick(rt), rt)
+ }
+ eb, _ := b.(*ExecBackend)
+ return eb
+}
+func adoptionPair(rt registry.Route) registry.Pair {
+ return registry.Pair{Incarnation: rt.Incarnation, ServingSeq: rt.ServingSeq}
+}
+
+func (b *ExecBackend) adoptionCurrent(ctx context.Context, rt registry.Route, req Adoption) error {
+ cur, err := b.Registry.Get(rt.Host)
+ if err != nil {
+ return err
+ }
+ if cur == nil || adoptionPair(*cur) != req.Pair || cur.Account != rt.Account || cur.App != rt.App || cur.DBPath != rt.DBPath || cur.Kind != rt.Kind || cur.HoldOp != "" || cur.ImportGate != "" || cur.Replica || cur.Tunnel != "" || cur.Status != "ready" {
+ return registry.ErrHAChanged
+ }
+ e, ha, err := b.isHA(ctx, *cur)
+ if err != nil {
+ return err
+ }
+ if !ha || e.ID == "" || e.ID != req.Lifetime {
+ return registry.ErrHAChanged
+ }
+ return nil
+}
+func adoptionNames(v hafresh.View, ref, iid, life string) bool {
+ if v.Absent || v.ETag == "" || v.Lock.Generation < 0 || ref == "" || iid == "" {
+ return false
+ }
+ if m := v.Lock.Release; m != nil {
+ return m.V == 1 && m.Box == ref && m.IID == iid && m.Lifetime == life && v.Lock.Owner == hafresh.MarkerOwner(*m)
+ }
+ o, ok := hafresh.ParseOwner(v.Lock.Owner)
+ return ok && o.HA && o.Ref == ref && o.IID == iid
+}
+
+func (b *ExecBackend) adoptionWake(ctx context.Context, host string) (registry.HAWakeImport, error) {
+ if b.FilesStore == nil {
+ return registry.HAWakeImport{}, registry.ErrHAWake
+ }
+ prefix := b.filesPrefix(host)
+ m, found, err := hostfiles.Load(ctx, b.FilesStore, prefix)
+ if err != nil {
+ return registry.HAWakeImport{}, err
+ }
+ if !found {
+ return registry.HAWakeImport{}, registry.ErrHAWake
+ }
+ ws, found, err := hostfiles.LoadWake(ctx, b.FilesStore, prefix, m, nil)
+ if err != nil {
+ return registry.HAWakeImport{}, err
+ }
+ digest := "absent"
+ if !found {
+ ws = hostfiles.WakeState{V: 1, Host: host}
+ } else {
+ digest = m.Platform[hostfiles.WakeItem].SHA256
+ }
+ s, err := hostfiles.RegistryWake(host, ws)
+ if err != nil {
+ return s, err
+ }
+ s.Sequence = m.Seq
+ s.WakeDigest = digest
+ return s, nil
+}
+
+// AdoptHost owns both import and authority replay. Its temporary entry excludes
+// ordinary wakes; no activator mutex is held during registry or object I/O.
+func (a *Service) AdoptHost(ctx context.Context, rt registry.Route, req Adoption) (AdoptResult, error) {
+ b := adoptionBackend(a.backend, rt)
+ if b == nil || b.Registry == nil || haLegacyRoute(rt) || req.Departure == "" || req.Lifetime == "" || req.Ref == "" || req.IID == "" || !b.self().Complete() {
+ return Deferred, registry.ErrHAChanged
+ }
+ if err := b.haContained(rt); err != nil {
+ return Deferred, err
+ }
+ if err := b.adoptionCurrent(ctx, rt, req); err != nil {
+ return Deferred, err
+ }
+ if !adoptionNames(req.Observed, req.Ref, req.IID, req.Lifetime) {
+ return Deferred, registry.ErrHAChanged
+ }
+ in, _, err := a.dutyInput(ctx, rt)
+ if err != nil {
+ return Deferred, err
+ }
+ if in.LocalDenied {
+ return Deferred, nil
+ }
+ a.mu.Lock()
+ if a.shuttingDown || a.fences[rt.Host] != 0 || a.entries[rt.Host] != nil || a.disabled(rt) {
+ a.mu.Unlock()
+ return Deferred, nil
+ }
+ e := &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{}), duty: true}
+ a.entries[rt.Host] = e
+ a.mu.Unlock()
+ defer func() {
+ a.mu.Lock()
+ if a.entries[rt.Host] == e {
+ delete(a.entries, rt.Host)
+ }
+ e.err = ErrDutyDeferred
+ close(e.ready)
+ a.mu.Unlock()
+ }()
+
+ reg := b.Registry
+ progress, exists, err := reg.HAAdoption(ctx, rt.Host, req.Lifetime, req.Departure)
+ if err != nil {
+ return Deferred, err
+ }
+ if exists && (progress.LockETag != req.Observed.ETag || progress.LockGeneration != req.Observed.Lock.Generation) {
+ return Deferred, registry.ErrHAChanged
+ }
+ read := func() (hafresh.View, error) {
+ return lease.ReadLock(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(rt.Host), b.Cfg.Region)
+ }
+ view, err := read()
+ if err != nil {
+ return Deferred, err
+ }
+ self := b.self()
+ selfMarker := func(v hafresh.View) bool {
+ return adoptionNames(v, self.Ref, self.IID, req.Lifetime) && v.Lock.Release != nil && !v.Lock.Release.Clean && v.Lock.Generation == progress.AcquiredGeneration
+ }
+ phase := func(next string, generation int64, wake *registry.HAWakeImport) error {
+ if err := b.adoptionCurrent(ctx, rt, req); err != nil {
+ return err
+ }
+ d, ok, err := reg.HADuty(rt.Host, req.Lifetime)
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return registry.ErrHAChanged
+ }
+ old := progress.Phase
+ progress.Phase = next
+ progress.AcquiredGeneration = generation
+ if wake != nil {
+ progress.WakeDigest = wake.WakeDigest
+ progress.Sequence = wake.Sequence
+ }
+ ok, err = reg.CompareHAAdoption(ctx, rt.Host, req.Pair, d.Revision, old, progress)
+ if err == nil && !ok {
+ err = registry.ErrHAChanged
+ }
+ return err
+ }
+ if exists && (progress.Phase == "marker_pending" || progress.Phase == "adopted") && selfMarker(view) {
+ if progress.Phase == "adopted" {
+ return AlreadyAdopted, nil
+ }
+ if err := phase("adopted", progress.AcquiredGeneration, nil); err != nil {
+ return Deferred, err
+ }
+ return Adopted, nil
+ }
+ // A successor's identity must be bound by the departure controller. A changed
+ // lock without that binding remains pending, including a missing lock.
+ if view.Lock.Generation > req.Observed.Lock.Generation && a.AdoptionIdentity != nil {
+ ref, iid := "", ""
+ if m := view.Lock.Release; m != nil {
+ ref, iid = m.Box, m.IID
+ } else if o, ok := hafresh.ParseOwner(view.Lock.Owner); ok {
+ ref, iid = o.Ref, o.IID
+ }
+ ownPending := exists && ref == self.Ref && iid == self.IID && view.Lock.Generation == progress.AcquiredGeneration && progress.Phase != "adopted"
+ if !ownPending && !(ref == req.Ref && iid == req.IID) && adoptionNames(view, ref, iid, req.Lifetime) {
+ ok, err := a.AdoptionIdentity(ctx, ref, iid)
+ if err != nil {
+ return Deferred, err
+ }
+ if ok {
+ if err = b.adoptionCurrent(ctx, rt, req); err != nil {
+ return Deferred, err
+ }
+ return Superseded, nil
+ }
+ }
+ }
+ departed := view.ETag == req.Observed.ETag && view.Lock.Generation == req.Observed.Lock.Generation && adoptionNames(view, req.Ref, req.IID, req.Lifetime)
+ ownReplay := exists && progress.Phase != "adopted" && view.Lock.Generation == progress.AcquiredGeneration && adoptionNames(view, self.Ref, self.IID, req.Lifetime)
+ if !departed && !ownReplay {
+ return Deferred, nil
+ }
+ if view.Lock.Release == nil && !a.now().After(view.Lock.ExpiresAt) {
+ return Deferred, nil
+ }
+ if !exists {
+ s, err := b.adoptionWake(ctx, rt.Host)
+ if err != nil {
+ return Deferred, err
+ }
+ if err = b.adoptionCurrent(ctx, rt, req); err != nil {
+ return Deferred, err
+ }
+ s.Lifetime, s.Revision, s.Receipt, s.LockETag, s.LockGeneration = req.Lifetime, req.Revision, req.Departure, req.Observed.ETag, req.Observed.Lock.Generation
+ imported, err := reg.ImportHAWake(ctx, rt.Host, req.Pair, s)
+ if err != nil {
+ return Deferred, err
+ }
+ if imported == registry.ImportDeferred {
+ return Deferred, nil
+ }
+ progress, exists, err = reg.HAAdoption(ctx, rt.Host, req.Lifetime, req.Departure)
+ if err != nil {
+ return Deferred, err
+ }
+ if !exists {
+ return Deferred, registry.ErrHAChanged
+ }
+ }
+ // Persist the expected generation before the conditional write. Recovery of
+ // this process's held lock still waits for expiry and SameBoxEmpty.
+ expected := view.Lock.Generation + 1
+ if err = phase("acquiring", expected, nil); err != nil {
+ return Deferred, err
+ }
+ ctx = context.WithValue(ctx, adoptionCauseKey{}, true)
+ held, err := lease.AcquireHAForDuty(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(rt.Host), b.Cfg.Region, hafresh.Marker{Box: self.Ref, IID: self.IID, Lifetime: req.Lifetime}, hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)}, func(v hafresh.View) error {
+ if v.ETag != view.ETag || v.Lock.Generation != view.Lock.Generation {
+ return ErrDutyDeferred
+ }
+ if err := b.adoptionCurrent(ctx, rt, req); err != nil {
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ return Deferred, err
+ }
+ released := false
+ defer func() {
+ if !released {
+ releaseCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _ = held.Release(releaseCtx)
+ }
+ }()
+ if err = phase("acquired", expected, nil); err != nil {
+ return Deferred, err
+ }
+ // The newly acquired lease's manifest outranks all earlier local progress.
+ exact, err := b.adoptionWake(ctx, rt.Host)
+ if err != nil {
+ return Deferred, err
+ }
+ if err = b.adoptionCurrent(ctx, rt, req); err != nil {
+ return Deferred, err
+ }
+ if err = held.Err(); err != nil {
+ return Deferred, err
+ }
+ if err = reg.ReplaceHAWake(ctx, rt.Host, exact); err != nil {
+ return Deferred, err
+ }
+ if err = phase("marker_pending", expected, &exact); err != nil {
+ return Deferred, err
+ }
+ if err = held.Err(); err != nil {
+ return Deferred, err
+ }
+ released = true
+ if err = held.Release(ctx); err != nil {
+ return Deferred, err
+ }
+ view, err = read()
+ if err != nil {
+ return Deferred, err
+ }
+ if !selfMarker(view) {
+ return Deferred, nil
+ }
+ if err = phase("adopted", expected, nil); err != nil {
+ return Deferred, err
+ }
+ log.Printf("ha_adoption host=%s cause=departure-finalize generation=%d", rt.Host, expected)
+ return Adopted, nil
+}
+
+type adoptionCauseKey struct{}
+
+// bindDutyLifetime joins current record facts to the registry's monotonic revision.
+func (b *ExecBackend) bindDutyLifetime(ctx context.Context, rt registry.Route, life string) (registry.DutyState, error) {
+ d, ok, err := b.Registry.HADuty(rt.Host, life)
+ if err != nil || ok {
+ return d, err
+ }
+ changed, err := b.Registry.BindHADuty(ctx, rt.Host, adoptionPair(rt), life, d.Revision)
+ if err != nil {
+ return d, err
+ }
+ if !changed {
+ return d, registry.ErrHAChanged
+ }
+ return b.Registry.LoadDuty(ctx, rt.Host, life)
+}
diff --git a/internal/activator/haadopt_test.go b/internal/activator/haadopt_test.go
new file mode 100644
index 000000000..8c9df849c
--- /dev/null
+++ b/internal/activator/haadopt_test.go
@@ -0,0 +1,195 @@
+package activator
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func haAdoptionFixture(t *testing.T) (*haSvc, Adoption) {
+ t.Helper()
+ s := haService(t, "shop.example.com")
+ s.a.DutyStore = s.b.Registry
+ publishAdoptWake(t, s, hostfiles.WakeState{V: 1, Host: s.rt.Host, NextDue: time.Now().Add(48 * time.Hour).Unix(), Timers: []hostfiles.WakeTimer{{Name: "reminder", Kind: "once", Spec: "at 9999999999", Path: "/remind", NextAt: 9999999999, DueAt: 9999999999, Registration: "original"}}})
+ putLockFor(t, s.b, s.rt, markerBody(t, "b", "i-b", haFixOf(s.b).lifetime, 5, false))
+ v, err := lease.ReadLock(context.Background(), s.b.Cfg.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), s.b.Cfg.Region)
+ if err != nil {
+ t.Fatal(err)
+ }
+ d, err := s.b.Registry.LoadDuty(context.Background(), s.rt.Host, haFixOf(s.b).lifetime)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s, Adoption{Departure: "departure-b", Ref: "b", IID: "i-b", Lifetime: haFixOf(s.b).lifetime, Observed: v, Revision: d.Revision}
+}
+func publishAdoptWake(t *testing.T, s *haSvc, ws hostfiles.WakeState) {
+ t.Helper()
+ ctx := context.Background()
+ p, err := hostfiles.Open(ctx, s.b.FilesStore, s.b.filesPrefix(s.rt.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = hostfiles.StageWake(ctx, p, ws); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = p.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+}
+func TestHAAdoptAuthority(t *testing.T) {
+ for _, kind := range []string{"unclean", "clean", "held", "expiry equality", "expired", "marker failure", "marker 412"} {
+ t.Run(kind, func(t *testing.T) {
+ s, req := haAdoptionFixture(t)
+ ctx := context.Background()
+ switch kind {
+ case "clean":
+ putLockFor(t, s.b, s.rt, markerBody(t, "b", "i-b", req.Lifetime, 5, true))
+ case "held", "expiry equality", "expired":
+ expiry := time.Now().Add(time.Hour)
+ if kind == "expired" {
+ expiry = time.Now().Add(-time.Hour)
+ }
+ if kind == "expiry equality" {
+ s.a.now = func() time.Time { return expiry }
+ }
+ body, _ := json.Marshal(hafresh.Lock{Generation: 5, Owner: heldByB, ExpiresAt: expiry})
+ putLockFor(t, s.b, s.rt, body)
+ s.b.OwnerTerminated = func(context.Context, string) (bool, error) { return true, nil }
+ case "marker failure":
+ s.fx.FailNextMatching("PUT", 503, func(k string, b []byte) bool { return strings.Contains(string(b), "carlos_release") })
+ case "marker 412":
+ s.fx.FailNextMatching("PUT", 412, func(k string, b []byte) bool { return strings.Contains(string(b), "carlos_release") })
+ }
+ var err error
+ req.Observed, err = lease.ReadLock(ctx, s.b.Cfg.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), s.b.Cfg.Region)
+ if err != nil {
+ t.Fatal(err)
+ }
+ start := len(s.fx.Requests())
+ got, err := s.a.AdoptHost(ctx, s.rt, req)
+ denied := kind == "held" || kind == "expiry equality" || strings.HasPrefix(kind, "marker ")
+ if denied {
+ if got != Deferred {
+ t.Fatalf("refusal %v %v", got, err)
+ }
+ } else {
+ if err != nil || got != Adopted {
+ t.Fatalf("adopt %v %v", got, err)
+ }
+ v, e := lease.ReadLock(ctx, s.b.Cfg.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), s.b.Cfg.Region)
+ if e != nil || v.Lock.Release == nil || v.Lock.Release.Box != "a" || v.Lock.Release.Clean || v.Lock.Release.Lifetime != req.Lifetime {
+ t.Fatalf("marker %+v %v", v, e)
+ }
+ d, ok, e := s.b.Registry.HADuty(s.rt.Host, req.Lifetime)
+ if e != nil || !ok || d.Basis != DutyAdopted {
+ t.Fatalf("duty %+v %v %v", d, ok, e)
+ }
+ }
+ if s.wokeHere() || haFixOf(s.b).restores != 0 {
+ t.Fatal("adoption started or restored tenant")
+ }
+ for _, r := range s.fx.Requests()[start:] {
+ if strings.HasPrefix(r, "GET ") && !strings.Contains(r, "/lock.json") && !strings.Contains(r, "/manifest.json") && !strings.Contains(r, "/objects/") {
+ t.Fatalf("unexpected read %s", r)
+ }
+ }
+ })
+ }
+}
+func TestHAAdoptReplay(t *testing.T) {
+ s, req := haAdoptionFixture(t)
+ ctx := context.Background()
+ if got, err := s.a.AdoptHost(ctx, s.rt, req); err != nil || got != Adopted {
+ t.Fatalf("first %v %v", got, err)
+ }
+ if _, err := s.b.Registry.MarkTimerFired(s.rt.Host, "reminder", "original", 123, "ok", 0, 0, 0, 0); err != nil {
+ t.Fatal(err)
+ }
+ before := len(s.fx.Requests())
+ got, err := s.a.AdoptHost(ctx, s.rt, req)
+ if err != nil || got != AlreadyAdopted {
+ t.Fatalf("replay %v %v", got, err)
+ }
+ row, _ := s.b.Registry.GetTimer(s.rt.Host, "reminder")
+ if row.NextAt != 0 {
+ t.Fatal("resurrected")
+ }
+ for _, r := range s.fx.Requests()[before:] {
+ if strings.HasPrefix(r, "PUT ") {
+ t.Fatalf("replay wrote %s", r)
+ }
+ }
+}
+func TestHAAdoptManifestBoundary(t *testing.T) {
+ for _, kind := range []string{"missing manifest", "no wake", "missing object", "digest", "origin", "version", "host", "replication", "duplicate", "kind", "spec"} {
+ t.Run(kind, func(t *testing.T) {
+ s, req := haAdoptionFixture(t)
+ ctx := context.Background()
+ prefix := s.b.filesPrefix(s.rt.Host)
+ m, _, err := hostfiles.Load(ctx, s.b.FilesStore, prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ws := hostfiles.WakeState{V: 1, Host: s.rt.Host, Timers: []hostfiles.WakeTimer{{Name: "reminder", Kind: "once", Spec: "at 123", Path: "/remind", NextAt: 123, Registration: "r"}}}
+ switch kind {
+ case "missing manifest":
+ _ = s.b.FilesStore.Delete(ctx, hostfiles.ManifestKey(prefix))
+ case "missing object":
+ _ = s.b.FilesStore.Delete(ctx, m.Platform[hostfiles.WakeItem].Object)
+ case "no wake", "digest", "origin":
+ e := m.Platform[hostfiles.WakeItem]
+ if kind == "no wake" {
+ delete(m.Platform, hostfiles.WakeItem)
+ } else {
+ if kind == "digest" {
+ e.SHA256 = strings.Repeat("0", 64)
+ } else {
+ e.Object = "other/objects/foreign"
+ }
+ m.Platform[hostfiles.WakeItem] = e
+ }
+ body, _ := json.Marshal(m)
+ s.fx.PutObject(hostfiles.ManifestKey(prefix), body)
+ default:
+ switch kind {
+ case "version":
+ ws.V = 2
+ case "host":
+ ws.Host = "other.example.com"
+ case "replication":
+ ws.Replication = "bad"
+ case "duplicate":
+ ws.Timers = append(ws.Timers, ws.Timers[0])
+ case "kind":
+ ws.Timers[0].Kind = "bad"
+ case "spec":
+ ws.Timers[0].Spec = "cron bad"
+ }
+ publishAdoptWake(t, s, ws)
+ }
+ got, err := s.a.AdoptHost(ctx, s.rt, req)
+ if kind == "no wake" {
+ if err != nil || got != Adopted {
+ t.Fatalf("empty wake %v %v", got, err)
+ }
+ } else if err == nil || got != Deferred {
+ t.Fatalf("bad manifest %v %v", got, err)
+ }
+ if kind != "no wake" {
+ _, ok, _ := s.b.Registry.HAAdoption(ctx, s.rt.Host, req.Lifetime, req.Departure)
+ if ok {
+ t.Fatal("invalid import persisted")
+ }
+ }
+ })
+ }
+}
+
+var _ DutyStore = (*registry.Registry)(nil)
diff --git a/internal/activator/haduties.go b/internal/activator/haduties.go
index 2f062ebaa..f9e52c502 100644
--- a/internal/activator/haduties.go
+++ b/internal/activator/haduties.go
@@ -94,13 +94,7 @@ type DutyStore interface {
CompareDuty(context.Context, string, string, uint64, DutyState) (bool, error)
}
-type DutyState struct {
- Revision uint64
- Basis string
- HolderRef, HolderIID, ViewKey string
- HolderEpoch uint64
- NotBefore time.Time
-}
+type DutyState = registry.DutyState
type localDuties struct {
mu sync.Mutex
@@ -147,6 +141,27 @@ func dutyBackend(b Backend, rt registry.Route) interface {
func (a *Service) dutyState(ctx context.Context, host, life string) (DutyState, error) {
if a.DutyStore != nil {
+ if reg, ok := a.DutyStore.(*registry.Registry); ok {
+ rt, err := reg.Get(host)
+ if err != nil {
+ return DutyState{}, err
+ }
+ if rt == nil {
+ return DutyState{}, registry.ErrHAChanged
+ }
+ b := adoptionBackend(a.backend, *rt)
+ if b == nil {
+ return DutyState{}, registry.ErrHAChanged
+ }
+ current, ha, err := b.isHA(ctx, *rt)
+ if err != nil {
+ return DutyState{}, err
+ }
+ if !ha || current.ID != life {
+ return DutyState{}, registry.ErrHAChanged
+ }
+ return b.bindDutyLifetime(ctx, *rt, life)
+ }
return a.DutyStore.LoadDuty(ctx, host, life)
}
a.duties.mu.Lock()
diff --git a/internal/activator/hatakeover.go b/internal/activator/hatakeover.go
index b0e7842ec..4d81e201c 100644
--- a/internal/activator/hatakeover.go
+++ b/internal/activator/hatakeover.go
@@ -30,6 +30,10 @@ func (b *ExecBackend) ownerTerminated(ctx context.Context, rt registry.Route) fu
}
return func(iid string) (bool, error) {
gone, err := b.OwnerTerminated(ctx, iid)
+ if ctx.Value(adoptionCauseKey{}) == true {
+ log.Printf("ha_takeover host=%s iid=%s cause=departure-finalize confirmed=%t error=%t", rt.Host, iid, gone, err != nil)
+ return gone, err
+ }
if err != nil {
b.takeover.alarm(rt.Host, iid, err)
return false, err
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index 3f986922b..69383c24b 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -336,6 +336,20 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route)
if err := b.haContained(rt); err != nil {
return nil, refusedUncontained(err)
}
+ if b.Registry != nil && entry.ID != "" {
+ d, err := b.bindDutyLifetime(ctx, rt, entry.ID)
+ if err != nil {
+ return nil, err
+ }
+ d.Basis = ""
+ ok, err := b.Registry.CompareDuty(ctx, host, entry.ID, d.Revision, d)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ return nil, registry.ErrHAChanged
+ }
+ }
proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)}
var held *lease.Held
if duty, ok := ctx.Value(dutyContextKey{}).(dutyRestriction); ok {
diff --git a/internal/host/agent.go b/internal/host/agent.go
index b04653fc9..7aebf0ec5 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -580,6 +580,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
Exec: eb,
Unit: &activator.UnitBackend{OptDir: release.OptDir()},
}, reg) // the registry satisfies activator.DueStore directly
+ svc.DutyStore = reg
armHAPlacement(svc, PageOperator)
// Sizes (#329): the provisioning passes' PolicyChanged tells this
// Service a row's size column moved, and the status tick reads each
diff --git a/internal/hostfiles/wake.go b/internal/hostfiles/wake.go
index fe9bc5d1f..32c3019ec 100644
--- a/internal/hostfiles/wake.go
+++ b/internal/hostfiles/wake.go
@@ -77,43 +77,24 @@ func WakeStateOf(host string, rows []registry.Timer, nextDue int64, replication
return ws
}
-// ImportWake makes host's wake state exactly ws. It validates everything
-// and checks that host has a route before it writes anything. It is
-// retry-safe (a repeat is the same full replace) but not atomic across its
-// three writes.
func ImportWake(reg *registry.Registry, host string, ws WakeState) error {
- if ws.V != 1 {
- return fmt.Errorf("hostfiles: wake state version %d; this binary reads 1", ws.V)
- }
- if ws.Host != host {
- return fmt.Errorf("hostfiles: wake state is for %q, not %q", ws.Host, host)
- }
- if !registry.ValidReplication(ws.Replication) {
- return fmt.Errorf("hostfiles: wake state for %s names replication class %q", host, ws.Replication)
- }
- rt, err := reg.Get(host)
+ state, err := RegistryWake(host, ws)
if err != nil {
return err
}
- if rt == nil {
- return fmt.Errorf("hostfiles: wake state for %s: no route", host)
+ return reg.ReplaceHAWake(context.Background(), host, state)
+}
+
+// RegistryWake validates the wire state before a registry transaction begins.
+func RegistryWake(host string, ws WakeState) (registry.HAWakeImport, error) {
+ if ws.V != 1 || ws.Host != host {
+ return registry.HAWakeImport{}, registry.ErrHAWake
}
- rows := make([]registry.Timer, 0, len(ws.Timers))
+ state := registry.HAWakeImport{NextDue: ws.NextDue, Replication: ws.Replication}
for _, t := range ws.Timers {
- rows = append(rows, registry.Timer{Host: host, Name: t.Name, Kind: t.Kind, Spec: t.Spec, Path: t.Path,
- NextAt: t.NextAt, LastAt: t.LastAt, LastStatus: t.LastStatus, LastMs: t.LastMs, Attempts: t.Attempts,
- CreatedAt: t.CreatedAt, DueAt: t.DueAt, Registration: t.Registration})
- }
- if err := reg.ReplaceTimers(host, rows); err != nil {
- return err
- }
- if err := reg.SetNextDue(host, ws.NextDue); err != nil {
- return err
+ state.Timers = append(state.Timers, registry.Timer{Host: host, Name: t.Name, Kind: t.Kind, Spec: t.Spec, Path: t.Path, NextAt: t.NextAt, LastAt: t.LastAt, LastStatus: t.LastStatus, LastMs: t.LastMs, Attempts: t.Attempts, CreatedAt: t.CreatedAt, DueAt: t.DueAt, Registration: t.Registration})
}
- // Always, the empty class included: "" is the default rung, and a
- // destination left on its previous class would not be the state that
- // was exported.
- return reg.SetReplication(host, ws.Replication)
+ return state, registry.ValidateHAWake(host, state)
}
// StageWake stages the wake state as a platform item. Unchanged state
diff --git a/internal/hostfiles/wake_test.go b/internal/hostfiles/wake_test.go
index aef0a715a..72a44dd5d 100644
--- a/internal/hostfiles/wake_test.go
+++ b/internal/hostfiles/wake_test.go
@@ -32,10 +32,10 @@ func TestWakeStateRoundTripsThroughTheManifest(t *testing.T) {
seedHost(t, src, "shop.test")
seedHost(t, dst, "shop.test")
if err := src.ReplaceTimers("shop.test", []registry.Timer{
- {Host: "shop.test", Name: "nightly", Kind: "schedule", Spec: "0 3 * * *", Path: "/n", NextAt: 5000, LastAt: 4000,
+ {Host: "shop.test", Name: "nightly", Kind: "schedule", Spec: "cron 0 3 * * *", Path: "/n", NextAt: 5000, LastAt: 4000,
LastStatus: "ok", Attempts: 1, CreatedAt: 10, DueAt: 4900, Registration: "reg-n"},
- {Host: "shop.test", Name: "remind", Kind: "once", Spec: "2026-10-06T00:00:00Z", Path: "/r", NextAt: 6000, CreatedAt: 11, DueAt: 6000, Registration: "reg-r"},
- {Host: "shop.test", Name: "done", Kind: "once", Spec: "2026-10-01T00:00:00Z", Path: "/d", NextAt: 0, LastAt: 3000, CreatedAt: 9, Registration: "reg-d"},
+ {Host: "shop.test", Name: "remind", Kind: "once", Spec: "at 1791244800", Path: "/r", NextAt: 6000, CreatedAt: 11, DueAt: 6000, Registration: "reg-r"},
+ {Host: "shop.test", Name: "done", Kind: "once", Spec: "at 1790812800", Path: "/d", NextAt: 0, LastAt: 3000, CreatedAt: 9, Registration: "reg-d"},
}); err != nil {
t.Fatal(err)
}
diff --git a/internal/registry/ha_departures.go b/internal/registry/ha_departures.go
new file mode 100644
index 000000000..b4a21bc0c
--- /dev/null
+++ b/internal/registry/ha_departures.go
@@ -0,0 +1,225 @@
+package registry
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "net/url"
+ "regexp"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/timerspec"
+)
+
+var ErrHAWake = errors.New("ha_wake_invalid")
+
+type HAWakeImport struct {
+ Timers []Timer
+ NextDue int64
+ Replication string
+ Lifetime string
+ Revision uint64
+ Receipt, LockETag, WakeDigest string
+ LockGeneration int64
+ Sequence int64
+}
+type ImportResult uint8
+
+const (
+ ImportDeferred ImportResult = iota
+ Imported
+ ImportReplayed
+)
+
+type HAAdoption struct {
+ Receipt, Lifetime, LockETag, WakeDigest, Phase string
+ LockGeneration, AcquiredGeneration int64
+ Sequence int64
+}
+
+func (r *Registry) migrateHAAdoptions() error {
+ _, err := r.sql.Exec(`CREATE TABLE IF NOT EXISTS ha_departure_hosts (
+ departure_id TEXT NOT NULL,host TEXT NOT NULL,lifetime TEXT NOT NULL,
+ lock_etag TEXT NOT NULL,lock_generation INTEGER NOT NULL,wake_digest TEXT NOT NULL,sequence INTEGER NOT NULL,
+ phase TEXT NOT NULL,acquired_generation INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(departure_id,host,lifetime));`)
+ return err
+}
+
+var haTimerName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)
+
+func ValidateHAWake(host string, s HAWakeImport) error {
+ if host == "" || s.NextDue < 0 || !ValidReplication(s.Replication) {
+ return ErrHAWake
+ }
+ seen := map[string]bool{}
+ for _, t := range s.Timers {
+ spec, err := timerspec.ParseSpec(t.Spec)
+ if err != nil || spec.Kind != t.Kind || t.Host != host || !haTimerName.MatchString(t.Name) || seen[t.Name] || t.Registration == "" || t.ClaimOwnership.Valid() || t.NextAt < 0 || t.DueAt < 0 || t.LastAt < 0 || t.Attempts < 0 {
+ return ErrHAWake
+ }
+ seen[t.Name] = true
+ u, err := url.ParseRequestURI(t.Path)
+ if err != nil || len(t.Path) > 256 || !strings.HasPrefix(t.Path, "/") || strings.HasPrefix(t.Path, "//") || strings.ContainsAny(t.Path, " \t\r\n") || u.Host != "" || u.Scheme != "" || u.User != nil {
+ return ErrHAWake
+ }
+ for _, seg := range strings.Split(u.Path, "/") {
+ if seg == ".." {
+ return ErrHAWake
+ }
+ }
+ }
+ return nil
+}
+func replaceHAWake(ctx context.Context, tx *sql.Tx, host string, s HAWakeImport) error {
+ var kind string
+ if err := tx.QueryRowContext(ctx, `SELECT kind FROM routes WHERE host=?`, host).Scan(&kind); err != nil {
+ return err
+ }
+ if kind == "forward" {
+ return ErrHAChanged
+ }
+ if _, err := tx.ExecContext(ctx, `DELETE FROM timers WHERE host=?`, host); err != nil {
+ return err
+ }
+ for _, t := range s.Timers {
+ if _, err := tx.ExecContext(ctx, `INSERT INTO timers (`+legacyTimerCols+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`, host, t.Name, t.Kind, t.Spec, t.Path, t.NextAt, t.LastAt, t.LastStatus, t.LastMs, t.Attempts, t.CreatedAt, t.DueAt, t.Registration); err != nil {
+ return err
+ }
+ }
+ _, err := tx.ExecContext(ctx, `UPDATE routes SET next_due=?,replication=? WHERE host=?`, s.NextDue, s.Replication, host)
+ return err
+}
+func (r *Registry) ReplaceHAWake(ctx context.Context, host string, s HAWakeImport) error {
+ if r.remote != nil {
+ _, err := r.remote.call(ctx, remoteRequest{Method: "ReplaceHAWake", Host: host, Wake: s}, nil)
+ return err
+ }
+ if err := ValidateHAWake(host, s); err != nil {
+ return err
+ }
+ tx, err := r.sql.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if err = replaceHAWake(ctx, tx, host, s); err != nil {
+ return err
+ }
+ // Even an empty identical replacement invalidates adoption I/O.
+ if _, err = tx.ExecContext(ctx, `UPDATE ha_duties SET revision=revision+1 WHERE host=?`, host); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+func (r *Registry) ImportHAWake(ctx context.Context, host string, expected Pair, s HAWakeImport) (ImportResult, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(ctx, remoteRequest{Method: "ImportHAWake", Host: host, Pair: expected, Wake: s}, nil)
+ return out.Import, err
+ }
+ if err := ValidateHAWake(host, s); err != nil {
+ return ImportDeferred, err
+ }
+ if s.Lifetime == "" || s.Receipt == "" || s.LockETag == "" || s.WakeDigest == "" || s.LockGeneration < 0 {
+ return ImportDeferred, ErrHAWake
+ }
+ tx, err := r.sql.BeginTx(ctx, nil)
+ if err != nil {
+ return ImportDeferred, err
+ }
+ defer tx.Rollback()
+ var life string
+ var revision uint64
+ var active bool
+ var pair Pair
+ var hold, kind string
+ err = tx.QueryRowContext(ctx, `SELECT d.lifetime,d.revision,d.active,r.incarnation,r.serving_seq,r.hold_op,r.kind FROM ha_duties d JOIN routes r ON r.host=d.host WHERE d.host=?`, host).Scan(&life, &revision, &active, &pair.Incarnation, &pair.ServingSeq, &hold, &kind)
+ if errors.Is(err, sql.ErrNoRows) {
+ return ImportDeferred, nil
+ }
+ if err != nil {
+ return ImportDeferred, err
+ }
+ if !active || life != s.Lifetime || pair != expected || hold != "" || kind != "instance" {
+ return ImportDeferred, nil
+ }
+ var etag string
+ var generation int64
+ err = tx.QueryRowContext(ctx, `SELECT lock_etag,lock_generation FROM ha_departure_hosts WHERE departure_id=? AND host=? AND lifetime=?`, s.Receipt, host, s.Lifetime).Scan(&etag, &generation)
+ if err == nil {
+ if etag != s.LockETag || generation != s.LockGeneration {
+ return ImportDeferred, ErrHAChanged
+ }
+ return ImportReplayed, nil
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ return ImportDeferred, err
+ }
+ if revision != s.Revision {
+ return ImportDeferred, nil
+ }
+ if err = replaceHAWake(ctx, tx, host, s); err != nil {
+ return ImportDeferred, err
+ }
+ if _, err = tx.ExecContext(ctx, `INSERT INTO ha_departure_hosts(departure_id,host,lifetime,lock_etag,lock_generation,wake_digest,sequence,phase) VALUES(?,?,?,?,?,?,?,'imported_pending_authority')`, s.Receipt, host, s.Lifetime, s.LockETag, s.LockGeneration, s.WakeDigest, s.Sequence); err != nil {
+ return ImportDeferred, err
+ }
+ if _, err = tx.ExecContext(ctx, `UPDATE ha_duties SET revision=revision+1,basis='' WHERE host=?`, host); err != nil {
+ return ImportDeferred, err
+ }
+ if err = tx.Commit(); err != nil {
+ return ImportDeferred, err
+ }
+ return Imported, nil
+}
+func (r *Registry) HAAdoption(ctx context.Context, host, life, receipt string) (HAAdoption, bool, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(ctx, remoteRequest{Method: "HAAdoption", Host: host, Lifetime: life, Receipt: receipt}, nil)
+ return out.Adoption, out.Changed, err
+ }
+ a := HAAdoption{Receipt: receipt, Lifetime: life}
+ err := r.sql.QueryRowContext(ctx, `SELECT lock_etag,lock_generation,wake_digest,sequence,phase,acquired_generation FROM ha_departure_hosts WHERE host=? AND lifetime=? AND departure_id=?`, host, life, receipt).Scan(&a.LockETag, &a.LockGeneration, &a.WakeDigest, &a.Sequence, &a.Phase, &a.AcquiredGeneration)
+ if errors.Is(err, sql.ErrNoRows) {
+ return a, false, nil
+ }
+ return a, err == nil, err
+}
+
+// CompareHAAdoption records progress only for the same live route and receipt.
+func (r *Registry) CompareHAAdoption(ctx context.Context, host string, pair Pair, revision uint64, oldPhase string, a HAAdoption) (bool, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(ctx, remoteRequest{Method: "CompareHAAdoption", Host: host, Pair: pair, Revision: revision, Expected: oldPhase, Adoption: a}, nil)
+ return out.Changed, err
+ }
+ valid := a.Phase == "acquiring" || a.Phase == "acquired" || a.Phase == "marker_pending" || a.Phase == "adopted"
+ if !valid {
+ return false, ErrHAChanged
+ }
+ tx, err := r.sql.BeginTx(ctx, nil)
+ if err != nil {
+ return false, err
+ }
+ defer tx.Rollback()
+ res, err := tx.ExecContext(ctx, `UPDATE ha_duties SET revision=revision+1 WHERE host=? AND lifetime=? AND revision=? AND active=1 AND EXISTS(SELECT 1 FROM routes WHERE host=? AND incarnation=? AND serving_seq=? AND hold_op='')`, host, a.Lifetime, revision, host, pair.Incarnation, pair.ServingSeq)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil || n != 1 {
+ return false, err
+ }
+ res, err = tx.ExecContext(ctx, `UPDATE ha_departure_hosts SET phase=?,acquired_generation=?,wake_digest=?,sequence=? WHERE host=? AND lifetime=? AND departure_id=? AND phase=? AND lock_etag=? AND lock_generation=?`, a.Phase, a.AcquiredGeneration, a.WakeDigest, a.Sequence, host, a.Lifetime, a.Receipt, oldPhase, a.LockETag, a.LockGeneration)
+ if err != nil {
+ return false, err
+ }
+ n, err = res.RowsAffected()
+ if err != nil || n != 1 {
+ return false, err
+ }
+ if a.Phase == "adopted" {
+ if _, err = tx.ExecContext(ctx, `UPDATE ha_duties SET basis='adopted',holder_ref='',holder_iid='',view_key='',holder_epoch=0,not_before='' WHERE host=?`, host); err != nil {
+ return false, err
+ }
+ }
+ return true, tx.Commit()
+}
diff --git a/internal/registry/ha_duties.go b/internal/registry/ha_duties.go
new file mode 100644
index 000000000..0d31635b3
--- /dev/null
+++ b/internal/registry/ha_duties.go
@@ -0,0 +1,152 @@
+package registry
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "time"
+)
+
+var ErrHAChanged = errors.New("ha_state_changed")
+
+type DutyState struct {
+ Revision uint64
+ Basis string
+ HolderRef, HolderIID, ViewKey string
+ HolderEpoch uint64
+ NotBefore time.Time
+}
+
+func (r *Registry) migrateHADuties() error {
+ _, err := r.sql.Exec(`
+CREATE TABLE IF NOT EXISTS ha_duties (
+ host TEXT PRIMARY KEY, lifetime TEXT NOT NULL DEFAULT '', revision INTEGER NOT NULL DEFAULT 1,
+ active INTEGER NOT NULL DEFAULT 1, basis TEXT NOT NULL DEFAULT '',
+ holder_ref TEXT NOT NULL DEFAULT '', holder_iid TEXT NOT NULL DEFAULT '', view_key TEXT NOT NULL DEFAULT '',
+ holder_epoch INTEGER NOT NULL DEFAULT 0, not_before TEXT NOT NULL DEFAULT ''
+);
+INSERT OR IGNORE INTO ha_duties(host) SELECT host FROM routes;
+CREATE TRIGGER IF NOT EXISTS ha_route_insert AFTER INSERT ON routes BEGIN
+ INSERT INTO ha_duties(host) VALUES(NEW.host) ON CONFLICT(host) DO UPDATE SET
+ revision=revision+1,active=1,lifetime='',basis='',holder_ref='',holder_iid='',view_key='',holder_epoch=0,not_before='';
+END;
+CREATE TRIGGER IF NOT EXISTS ha_route_delete AFTER DELETE ON routes BEGIN
+ UPDATE ha_duties SET revision=revision+1,active=0,lifetime='',basis='',holder_ref='',holder_iid='',view_key='',holder_epoch=0,not_before='' WHERE host=OLD.host;
+END;
+CREATE TRIGGER IF NOT EXISTS ha_route_update AFTER UPDATE ON routes
+WHEN OLD.next_due IS NOT NEW.next_due OR OLD.replication IS NOT NEW.replication
+ OR OLD.incarnation IS NOT NEW.incarnation OR OLD.serving_seq IS NOT NEW.serving_seq
+ OR OLD.kind IS NOT NEW.kind OR OLD.account IS NOT NEW.account OR OLD.app IS NOT NEW.app
+ OR OLD.hold_op IS NOT NEW.hold_op OR OLD.status IS NOT NEW.status
+ OR OLD.hibernate IS NOT NEW.hibernate OR OLD.ha IS NOT NEW.ha
+ OR OLD.db_path IS NOT NEW.db_path OR OLD.backing IS NOT NEW.backing
+BEGIN
+ UPDATE ha_duties SET revision=revision+1 WHERE host=NEW.host;
+ UPDATE ha_duties SET lifetime='',basis='',holder_ref='',holder_iid='',view_key='',holder_epoch=0,not_before=''
+ WHERE host=NEW.host AND (OLD.incarnation IS NOT NEW.incarnation OR OLD.serving_seq IS NOT NEW.serving_seq
+ OR OLD.kind IS NOT NEW.kind OR OLD.account IS NOT NEW.account OR OLD.app IS NOT NEW.app OR OLD.db_path IS NOT NEW.db_path);
+END;
+CREATE TRIGGER IF NOT EXISTS ha_timer_insert AFTER INSERT ON timers BEGIN
+ UPDATE ha_duties SET revision=revision+1 WHERE host=NEW.host;
+END;
+CREATE TRIGGER IF NOT EXISTS ha_timer_update AFTER UPDATE ON timers BEGIN
+ UPDATE ha_duties SET revision=revision+1 WHERE host=NEW.host;
+END;
+CREATE TRIGGER IF NOT EXISTS ha_timer_delete AFTER DELETE ON timers BEGIN
+ UPDATE ha_duties SET revision=revision+1 WHERE host=OLD.host;
+END;
+`)
+ if err != nil {
+ return err
+ }
+ return r.migrateHAAdoptions()
+}
+
+func (r *Registry) HADuty(host, lifetime string) (DutyState, bool, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(nil, remoteRequest{Method: "HADuty", Host: host, Lifetime: lifetime}, nil)
+ return out.Duty, out.Changed, err
+ }
+ var d DutyState
+ var life, deadline string
+ var active bool
+ err := r.sql.QueryRow(`SELECT lifetime,revision,active,basis,holder_ref,holder_iid,view_key,holder_epoch,not_before FROM ha_duties WHERE host=?`, host).Scan(&life, &d.Revision, &active, &d.Basis, &d.HolderRef, &d.HolderIID, &d.ViewKey, &d.HolderEpoch, &deadline)
+ if errors.Is(err, sql.ErrNoRows) {
+ return DutyState{}, false, nil
+ }
+ if err != nil {
+ return d, false, err
+ }
+ if !active || life != lifetime {
+ return DutyState{Revision: d.Revision}, false, nil
+ }
+ if deadline != "" {
+ d.NotBefore, err = time.Parse(time.RFC3339Nano, deadline)
+ }
+ return d, true, err
+}
+
+// BindHADuty is called only with the current authoritative record's lifetime.
+func (r *Registry) BindHADuty(ctx context.Context, host string, pair Pair, lifetime string, revision uint64) (bool, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(ctx, remoteRequest{Method: "BindHADuty", Host: host, Pair: pair, Lifetime: lifetime, Revision: revision}, nil)
+ return out.Changed, err
+ }
+ if lifetime == "" {
+ return false, ErrHAChanged
+ }
+ res, err := r.sql.ExecContext(ctx, `UPDATE ha_duties SET lifetime=?,revision=revision+1,basis='',holder_ref='',holder_iid='',view_key='',holder_epoch=0,not_before=''
+ WHERE host=? AND active=1 AND revision=? AND lifetime<>? AND EXISTS(SELECT 1 FROM routes WHERE host=? AND incarnation=? AND serving_seq=? AND kind='instance' AND hold_op='')`, lifetime, host, revision, lifetime, host, pair.Incarnation, pair.ServingSeq)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n == 1, err
+}
+
+func (r *Registry) LoadDuty(ctx context.Context, host, life string) (DutyState, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(ctx, remoteRequest{Method: "LoadDuty", Host: host, Lifetime: life}, nil)
+ return out.Duty, err
+ }
+ d, ok, err := r.HADuty(host, life)
+ if err != nil || ok {
+ return d, err
+ }
+ // Only an unbound route can be initialized without a record comparison.
+ res, err := r.sql.ExecContext(ctx, `UPDATE ha_duties SET lifetime=?,revision=revision+1 WHERE host=? AND active=1 AND lifetime='' AND revision=? AND ?<>''`, life, host, d.Revision, life)
+ if err != nil {
+ return d, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return d, err
+ }
+ if n != 1 {
+ return d, ErrHAChanged
+ }
+ d, ok, err = r.HADuty(host, life)
+ if err == nil && !ok {
+ err = ErrHAChanged
+ }
+ return d, err
+}
+func (r *Registry) CompareDuty(ctx context.Context, host, life string, revision uint64, next DutyState) (bool, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(ctx, remoteRequest{Method: "CompareDuty", Host: host, Lifetime: life, Revision: revision, Duty: next}, nil)
+ return out.Changed, err
+ }
+ if next.Basis != "" && next.Basis != "local-holder" && next.Basis != "local-release" && next.Basis != "adopted" {
+ return false, ErrHAChanged
+ }
+ deadline := ""
+ if !next.NotBefore.IsZero() {
+ deadline = next.NotBefore.UTC().Format(time.RFC3339Nano)
+ }
+ res, err := r.sql.ExecContext(ctx, `UPDATE ha_duties SET revision=revision+1,basis=?,holder_ref=?,holder_iid=?,view_key=?,holder_epoch=?,not_before=? WHERE host=? AND lifetime=? AND revision=? AND active=1 AND (?<>'adopted' OR basis='adopted')`, next.Basis, next.HolderRef, next.HolderIID, next.ViewKey, next.HolderEpoch, deadline, host, life, revision, next.Basis)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n == 1, err
+}
diff --git a/internal/registry/ha_duties_test.go b/internal/registry/ha_duties_test.go
new file mode 100644
index 000000000..c89152620
--- /dev/null
+++ b/internal/registry/ha_duties_test.go
@@ -0,0 +1,207 @@
+package registry
+
+import (
+ "context"
+ "errors"
+ "path/filepath"
+ "testing"
+)
+
+func adoptRegistry(t *testing.T) (*Registry, string) {
+ t.Helper()
+ p := filepath.Join(t.TempDir(), "registry.db")
+ r, err := Open(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { r.Close() })
+ if err = r.Upsert(Route{Host: "shop.example.com", Kind: "instance", Status: "ready", Provisioned: true, HA: true}); err != nil {
+ t.Fatal(err)
+ }
+ return r, p
+}
+func adoptState(t *testing.T, r *Registry) HAWakeImport {
+ t.Helper()
+ d, err := r.LoadDuty(context.Background(), "shop.example.com", "life")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return HAWakeImport{Lifetime: "life", Revision: d.Revision, Receipt: "departure-1", LockETag: "dead-lock", LockGeneration: 5, WakeDigest: "digest", Sequence: 1, NextDue: 123, Replication: ReplicationStream, Timers: []Timer{{Host: "shop.example.com", Name: "reminder", Kind: "once", Spec: "at 123", Path: "/remind", NextAt: 123, DueAt: 123, Registration: "original"}}}
+}
+func TestHAAdoptReplay(t *testing.T) {
+ r, p := adoptRegistry(t)
+ ctx := context.Background()
+ s := adoptState(t, r)
+ got, err := r.ImportHAWake(ctx, "shop.example.com", Pair{}, s)
+ if err != nil || got != Imported {
+ t.Fatalf("import %v %v", got, err)
+ }
+ d, ok, err := r.HADuty("shop.example.com", "life")
+ if err != nil || !ok || d.Basis != "" {
+ t.Fatalf("pending authority %+v %v %v", d, ok, err)
+ }
+ if _, err = r.MarkTimerFired("shop.example.com", "reminder", "original", 123, "ok", 0, 0, 0, 0); err != nil {
+ t.Fatal(err)
+ }
+ if err = r.ClearNextDueIf("shop.example.com", 123); err != nil {
+ t.Fatal(err)
+ }
+ r.Close()
+ r, err = Open(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ got, err = r.ImportHAWake(ctx, "shop.example.com", Pair{}, s)
+ if err != nil || got != ImportReplayed {
+ t.Fatalf("replay %v %v", got, err)
+ }
+ row, _ := r.GetTimer("shop.example.com", "reminder")
+ rt, _ := r.Get("shop.example.com")
+ if row.NextAt != 0 || rt.NextDue != 0 {
+ t.Fatalf("resurrected %+v %+v", row, rt)
+ }
+}
+func TestHAAdoptRaces(t *testing.T) {
+ for _, kind := range []string{"registration", "next_due", "advance", "lifetime", "retirement", "acquire"} {
+ t.Run(kind, func(t *testing.T) {
+ r, _ := adoptRegistry(t)
+ s := adoptState(t, r)
+ switch kind {
+ case "registration":
+ _ = r.UpsertTimer(Timer{Host: "shop.example.com", Name: "reminder", Kind: "once", Spec: "at 999", NextAt: 999})
+ case "next_due":
+ _ = r.SetNextDue("shop.example.com", 999)
+ case "advance":
+ _ = r.UpsertTimer(Timer{Host: "shop.example.com", Name: "tick", Kind: "schedule", Spec: "every 1m", NextAt: 1})
+ case "lifetime":
+ _, _ = r.InstallLifetimeIf("shop.example.com", Pair{}, Pair{Incarnation: 2})
+ case "retirement":
+ _ = r.Delete("shop.example.com")
+ _ = r.Upsert(Route{Host: "shop.example.com", Kind: "instance", Status: "ready"})
+ case "acquire":
+ _, _ = r.CompareDuty(context.Background(), "shop.example.com", "life", s.Revision, DutyState{Basis: "local-holder"})
+ }
+ got, err := r.ImportHAWake(context.Background(), "shop.example.com", Pair{}, s)
+ if err != nil || got != ImportDeferred {
+ t.Fatalf("stale import %v %v", got, err)
+ }
+ })
+ }
+}
+func TestHAAdoptThenOrdinaryRestore(t *testing.T) {
+ r, _ := adoptRegistry(t)
+ s := adoptState(t, r)
+ ctx := context.Background()
+ if _, err := r.ImportHAWake(ctx, "shop.example.com", Pair{}, s); err != nil {
+ t.Fatal(err)
+ }
+ for range 3 {
+ _ = r.SetNextDue("shop.example.com", 456)
+ }
+ s.Timers[0].Registration = "interim"
+ s.Timers[0].NextAt = 999
+ s.NextDue = 999
+ if err := r.ReplaceHAWake(ctx, "shop.example.com", s); err != nil {
+ t.Fatal(err)
+ }
+ row, _ := r.GetTimer("shop.example.com", "reminder")
+ if row.Registration != "interim" || row.NextAt != 999 {
+ t.Fatalf("restore %+v", row)
+ }
+}
+func TestHAAdoptRemoteParity(t *testing.T) {
+ r, _ := remoteTestRegistry(t)
+ if err := r.Upsert(Route{Host: "shop.example.com", Kind: "instance", Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ s := adoptState(t, r)
+ got, err := r.ImportHAWake(context.Background(), "shop.example.com", Pair{}, s)
+ if err != nil || got != Imported {
+ t.Fatalf("import %v %v", got, err)
+ }
+ got, err = r.ImportHAWake(context.Background(), "shop.example.com", Pair{}, s)
+ if err != nil || got != ImportReplayed {
+ t.Fatalf("replay %v %v", got, err)
+ }
+ s.Timers[0].Kind = "bad"
+ if err = r.ReplaceHAWake(context.Background(), "shop.example.com", s); !errors.Is(err, ErrHAWake) {
+ t.Fatalf("error parity %v", err)
+ }
+}
+
+func TestHAAdoptAtomic(t *testing.T) {
+ for _, point := range []string{"delete", "insert", "route", "receipt", "duty", "commit"} {
+ t.Run(point, func(t *testing.T) {
+ r, p := adoptRegistry(t)
+ ctx := context.Background()
+ s := adoptState(t, r)
+ old := s
+ old.Timers = append([]Timer(nil), s.Timers...)
+ old.Timers[0].Name = "old"
+ old.NextDue = 99
+ if err := r.ReplaceHAWake(ctx, "shop.example.com", old); err != nil {
+ t.Fatal(err)
+ }
+ s = adoptState(t, r)
+ targets := map[string]string{"delete": "BEFORE DELETE ON timers", "insert": "BEFORE INSERT ON timers", "route": "BEFORE UPDATE ON routes", "receipt": "BEFORE INSERT ON ha_departure_hosts", "duty": "BEFORE UPDATE ON ha_duties"}
+ stmt := ""
+ if point == "commit" {
+ stmt = `PRAGMA foreign_keys=ON; CREATE TABLE crash_parent(id INTEGER PRIMARY KEY); CREATE TABLE crash_child(id INTEGER REFERENCES crash_parent(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER crash BEFORE INSERT ON ha_departure_hosts BEGIN INSERT INTO crash_child VALUES(1); END;`
+ } else {
+ stmt = "CREATE TRIGGER crash " + targets[point] + " BEGIN SELECT RAISE(ABORT,'crash'); END;"
+ }
+ if _, err := r.sql.Exec(stmt); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.ImportHAWake(ctx, "shop.example.com", Pair{}, s); err == nil {
+ t.Fatal("failure not injected")
+ }
+ r.Close()
+ var err error
+ r, err = Open(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ rows, _ := r.TimersFor("shop.example.com")
+ rt, _ := r.Get("shop.example.com")
+ if len(rows) != 1 || rows[0].Name != "old" || rt.NextDue != 99 {
+ t.Fatalf("partial transaction %+v %+v", rows, rt)
+ }
+ _, ok, err := r.HAAdoption(ctx, "shop.example.com", "life", s.Receipt)
+ if err != nil || ok {
+ t.Fatalf("receipt survived rollback %v %v", ok, err)
+ }
+ })
+ }
+}
+func TestHAAdoptDutyPersistence(t *testing.T) {
+ r, p := adoptRegistry(t)
+ ctx := context.Background()
+ s := adoptState(t, r)
+ ok, err := r.CompareDuty(ctx, "shop.example.com", "life", s.Revision, DutyState{Basis: "adopted"})
+ if ok {
+ t.Fatal("minted adoption without receipt")
+ }
+ ok, err = r.CompareDuty(ctx, "shop.example.com", "life", s.Revision, DutyState{Basis: "local-release", HolderRef: "peer", HolderIID: "i-peer"})
+ if err != nil || !ok {
+ t.Fatalf("save %v %v", ok, err)
+ }
+ r.Close()
+ r, err = Open(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ d, ok, err := r.HADuty("shop.example.com", "life")
+ if err != nil || !ok || d.Basis != "local-release" || d.HolderRef != "peer" {
+ t.Fatalf("persisted %+v %v %v", d, ok, err)
+ }
+ _ = r.Delete("shop.example.com")
+ _ = r.Upsert(Route{Host: "shop.example.com", Kind: "instance"})
+ ok, err = r.CompareDuty(ctx, "shop.example.com", "life", d.Revision, d)
+ if err != nil || ok {
+ t.Fatalf("retired CAS %v %v", ok, err)
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 3228385d3..12670ca4a 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -892,7 +892,10 @@ CREATE INDEX IF NOT EXISTS timers_due ON timers (next_at) WHERE next_at > 0;`);
if err := r.migrateClaimOwnership(); err != nil {
return err
}
- return r.migrateFleets()
+ if err := r.migrateFleets(); err != nil {
+ return err
+ }
+ return r.migrateHADuties()
}
// migrateAccounts brings the accounts table to its multi-account shape:
diff --git a/internal/registry/remote.go b/internal/registry/remote.go
index 481c1e2c8..e073f5156 100644
--- a/internal/registry/remote.go
+++ b/internal/registry/remote.go
@@ -14,7 +14,7 @@ import (
var errRemoteMethod = errors.New("registry: unsupported remote operation")
-var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrFleetKeyInUse, ErrForwardRow, ErrHostHeld, ErrNotForward}
+var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrFleetKeyInUse, ErrForwardRow, ErrHostHeld, ErrNotForward, ErrHAChanged, ErrHAWake}
func responseError(out remoteResponse) error {
if !out.Failed {
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 101613252..53ebd3e79 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -6,101 +6,106 @@ import (
)
type remoteRequest struct {
- Method string
- Deadline int64
- CallbackError string
- CallbackFailed bool
- Host string
- Owner ClaimOwnership
- Expected string
- Next string
- Observed Route
- Journal string
- Targets []ClaimRow
- ObservedValue Timer
- T Timer
- Name string
- Registration string
- Status string
- Now int64
- Id string
- Retirement string
- Old ColdRows
- NextValue ColdRows
- F Fleet
- B FleetBox
- Fleet string
- Label string
- TokenHash string
- Tags string
- Pub string
- KeyFP string
- By string
- IdValue int64
- Sqid string
- TValue Route
- Op string
- ExpectOp string
- Pair Pair
- ExpectPair Pair
- ToOp string
- FromOp string
- Account string
- Channel string
- From string
- To string
- FromDB string
- FromSock string
- ToDB string
- ToSock string
- Backing string
- Unit string
- Class string
- Addr string
- Addrs string
- Health string
- Steering string
- AssetsOff bool
- AssetGen string
- UpdateSettings string
- BuildState string
- Replicas string
- Replica bool
- Hash string
- RateLimit string
- Hosts []string
- Env string
- Tunnel string
- Target string
- CheckedAt int64
- At int64
- Ver string
- Prev string
- On bool
- Due int64
- Seed string
- Args string
- Idle int
- MaxRun int
- A RouteAlias
- Alias string
- W WildcardDomain
- RDs []RegionalDomain
- P RoutePath
- Prefix string
- Path string
- Rows []Timer
- Limit int
- ExcludeHosts []string
- Ms int64
- Attempts int
- NextAt int64
- Kind string
- Alive map[string]bool
- DoneBefore int64
- Keep map[string]bool
- ExpectGood GoodBuild
- NextGood GoodBuild
+ Lifetime, Receipt string
+ Revision uint64
+ Duty DutyState
+ Wake HAWakeImport
+ Adoption HAAdoption
+ Method string
+ Deadline int64
+ CallbackError string
+ CallbackFailed bool
+ Host string
+ Owner ClaimOwnership
+ Expected string
+ Next string
+ Observed Route
+ Journal string
+ Targets []ClaimRow
+ ObservedValue Timer
+ T Timer
+ Name string
+ Registration string
+ Status string
+ Now int64
+ Id string
+ Retirement string
+ Old ColdRows
+ NextValue ColdRows
+ F Fleet
+ B FleetBox
+ Fleet string
+ Label string
+ TokenHash string
+ Tags string
+ Pub string
+ KeyFP string
+ By string
+ IdValue int64
+ Sqid string
+ TValue Route
+ Op string
+ ExpectOp string
+ Pair Pair
+ ExpectPair Pair
+ ToOp string
+ FromOp string
+ Account string
+ Channel string
+ From string
+ To string
+ FromDB string
+ FromSock string
+ ToDB string
+ ToSock string
+ Backing string
+ Unit string
+ Class string
+ Addr string
+ Addrs string
+ Health string
+ Steering string
+ AssetsOff bool
+ AssetGen string
+ UpdateSettings string
+ BuildState string
+ Replicas string
+ Replica bool
+ Hash string
+ RateLimit string
+ Hosts []string
+ Env string
+ Tunnel string
+ Target string
+ CheckedAt int64
+ At int64
+ Ver string
+ Prev string
+ On bool
+ Due int64
+ Seed string
+ Args string
+ Idle int
+ MaxRun int
+ A RouteAlias
+ Alias string
+ W WildcardDomain
+ RDs []RegionalDomain
+ P RoutePath
+ Prefix string
+ Path string
+ Rows []Timer
+ Limit int
+ ExcludeHosts []string
+ Ms int64
+ Attempts int
+ NextAt int64
+ Kind string
+ Alive map[string]bool
+ DoneBefore int64
+ Keep map[string]bool
+ ExpectGood GoodBuild
+ NextGood GoodBuild
// SetPolicy's three columns (#328, #329).
EgressAllow string
@@ -113,6 +118,9 @@ type remoteRequest struct {
}
type remoteResponse struct {
+ Duty DutyState
+ Import ImportResult
+ Adoption HAAdoption
Failed bool
Error string
ErrorKind int
@@ -142,6 +150,23 @@ type remoteResponse struct {
func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback func(remoteResponse) error) (out remoteResponse, err error) {
switch q.Method {
+ case "HADuty":
+ out.Duty, out.Changed, err = r.HADuty(q.Host, q.Lifetime)
+ case "LoadDuty":
+ out.Duty, err = r.LoadDuty(ctx, q.Host, q.Lifetime)
+ case "BindHADuty":
+ out.Changed, err = r.BindHADuty(ctx, q.Host, q.Pair, q.Lifetime, q.Revision)
+ case "CompareDuty":
+ out.Changed, err = r.CompareDuty(ctx, q.Host, q.Lifetime, q.Revision, q.Duty)
+ case "ReplaceHAWake":
+ err = r.ReplaceHAWake(ctx, q.Host, q.Wake)
+ case "ImportHAWake":
+ out.Import, err = r.ImportHAWake(ctx, q.Host, q.Pair, q.Wake)
+ case "HAAdoption":
+ out.Adoption, out.Changed, err = r.HAAdoption(ctx, q.Host, q.Lifetime, q.Receipt)
+ case "CompareHAAdoption":
+ out.Changed, err = r.CompareHAAdoption(ctx, q.Host, q.Pair, q.Revision, q.Expected, q.Adoption)
+
case "ArtifactHosts":
out.Hosts, err = r.ArtifactHosts()
case "SetClaimHold":
diff --git a/internal/schedule/cron.go b/internal/schedule/cron.go
index 90f821832..24f6651bb 100644
--- a/internal/schedule/cron.go
+++ b/internal/schedule/cron.go
@@ -1,169 +1,7 @@
-// Package schedule is the platform's answer to "run this later": the WHEN of
-// scheduled work, so an app that hibernates does not have to keep a process
-// alive to keep a timer. Spec: docs/superpowers/specs/2026-08-23-scheduled-work-design.md.
-//
-// This file is the cron dialect. Deliberately small (five fields, UTC, no
-// names, no @aliases — spec §4.1) and deliberately ours: the box binary is
-// built with GOPROXY=off, and a parser this size is cheaper to own than to
-// vendor.
package schedule
-import (
- "errors"
- "fmt"
- "strconv"
- "strings"
- "time"
-)
+import "github.com/carlosframework/platform/internal/timerspec"
-// CronExpr is a parsed five-field expression. Each field is a bitset over
-// its legal range (minute 0-59, hour 0-23, day-of-month 1-31, month 1-12,
-// day-of-week 0-6 with 7 folded onto 0).
-type CronExpr struct {
- min, hour, dom, month, dow uint64
- raw string
- domStar, dowStar bool // "*" in a day field — the classic OR-vs-AND rule below
-}
+type CronExpr = timerspec.CronExpr
-func (c *CronExpr) String() string { return c.raw }
-
-// ParseCron accepts "min hour dom month dow" with *, n, a-b, */n, a-b/n and
-// comma lists. Anything else — names, six fields, @daily — is an error with
-// the field named, because the member typing it has no box to debug on.
-func ParseCron(expr string) (*CronExpr, error) {
- fields := strings.Fields(expr)
- if len(fields) != 5 {
- return nil, fmt.Errorf("cron: want 5 fields (min hour day month weekday), got %d", len(fields))
- }
- c := &CronExpr{raw: strings.Join(fields, " ")}
- var err error
- if c.min, _, err = parseField(fields[0], 0, 59, "minute"); err != nil {
- return nil, err
- }
- if c.hour, _, err = parseField(fields[1], 0, 23, "hour"); err != nil {
- return nil, err
- }
- if c.dom, c.domStar, err = parseField(fields[2], 1, 31, "day"); err != nil {
- return nil, err
- }
- if c.month, _, err = parseField(fields[3], 1, 12, "month"); err != nil {
- return nil, err
- }
- if c.dow, c.dowStar, err = parseField(fields[4], 0, 7, "weekday"); err != nil {
- return nil, err
- }
- if c.dow&(1<<7) != 0 { // 7 is Sunday too
- c.dow = (c.dow &^ (1 << 7)) | 1
- }
- return c, nil
-}
-
-// parseField returns the bitset and whether the field was a bare "*".
-func parseField(f string, lo, hi int, name string) (uint64, bool, error) {
- var bits uint64
- star := f == "*"
- for _, part := range strings.Split(f, ",") {
- rangePart, stepPart, hasStep := strings.Cut(part, "/")
- step := 1
- if hasStep {
- n, err := strconv.Atoi(stepPart)
- if err != nil || n <= 0 {
- return 0, false, fmt.Errorf("cron %s: bad step %q", name, part)
- }
- step = n
- }
- a, b := lo, hi
- switch {
- case rangePart == "*":
- case strings.Contains(rangePart, "-"):
- as, bs, _ := strings.Cut(rangePart, "-")
- var err error
- if a, err = atoiIn(as, lo, hi); err != nil {
- return 0, false, fmt.Errorf("cron %s: %w", name, err)
- }
- if b, err = atoiIn(bs, lo, hi); err != nil {
- return 0, false, fmt.Errorf("cron %s: %w", name, err)
- }
- if a > b {
- return 0, false, fmt.Errorf("cron %s: range %q runs backwards", name, rangePart)
- }
- default:
- n, err := atoiIn(rangePart, lo, hi)
- if err != nil {
- return 0, false, fmt.Errorf("cron %s: %w", name, err)
- }
- a, b = n, n
- if hasStep {
- b = hi // "5/10" means from 5 to the end, stepping
- }
- }
- for v := a; v <= b; v += step {
- bits |= 1 << uint(v)
- }
- }
- if bits == 0 {
- return 0, false, errors.New("cron " + name + ": empty")
- }
- return bits, star, nil
-}
-
-func atoiIn(s string, lo, hi int) (int, error) {
- n, err := strconv.Atoi(s)
- if err != nil {
- return 0, fmt.Errorf("%q is not a number", s)
- }
- if n < lo || n > hi {
- return 0, fmt.Errorf("%d is outside %d-%d", n, lo, hi)
- }
- return n, nil
-}
-
-// Next is the first matching minute strictly after `after`, in UTC, or the
-// zero time if none falls within the search window (a "0 0 30 2 *" never
-// matches, and terminates quickly since each mismatched day is a single
-// jump, not a minute-by-minute walk). The window is 5 years, not 366 days:
-// "0 0 29 2 *" (Feb 29) can be up to ~4 years out depending on where `after`
-// falls in the leap-year cycle, and a 366-day window would wrongly report
-// "never" for it.
-func (c *CronExpr) Next(after time.Time) time.Time {
- t := after.UTC().Truncate(time.Minute).Add(time.Minute)
- limit := t.AddDate(5, 0, 0)
- for t.Before(limit) {
- if c.month&(1<<uint(t.Month())) == 0 {
- // Skip to the first of next month.
- t = time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, time.UTC)
- continue
- }
- if !c.dayMatches(t) {
- t = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, time.UTC)
- continue
- }
- if c.hour&(1<<uint(t.Hour())) == 0 {
- t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+1, 0, 0, 0, time.UTC)
- continue
- }
- if c.min&(1<<uint(t.Minute())) == 0 {
- t = t.Add(time.Minute)
- continue
- }
- return t
- }
- return time.Time{}
-}
-
-// dayMatches applies Vixie cron's rule: when BOTH day fields are restricted
-// the day matches if EITHER does; when one is "*" the other decides.
-func (c *CronExpr) dayMatches(t time.Time) bool {
- dom := c.dom&(1<<uint(t.Day())) != 0
- dow := c.dow&(1<<uint(t.Weekday())) != 0
- switch {
- case c.domStar && c.dowStar:
- return true
- case c.domStar:
- return dow
- case c.dowStar:
- return dom
- default:
- return dom || dow
- }
-}
+func ParseCron(s string) (*CronExpr, error) { return timerspec.ParseCron(s) }
diff --git a/internal/schedule/mingap.go b/internal/schedule/mingap.go
index fb5385add..1f0df7536 100644
--- a/internal/schedule/mingap.go
+++ b/internal/schedule/mingap.go
@@ -24,70 +24,7 @@ func (s Schedule) ShortestInterval() (time.Duration, error) {
case sp.Every > 0:
return sp.Every, nil
case sp.Cron != nil:
- return sp.Cron.shortestGap(), nil
+ return sp.Cron.ShortestGap(), nil
}
return 0, errors.New("schedule has no interval")
}
-
-// gregorianCycleDays is the length of the Gregorian calendar's 400-year
-// cycle. It is a whole number of weeks, so dates, weekdays and leap days all
-// repeat after it.
-const gregorianCycleDays = 146097
-
-// shortestGap is the smallest gap between two firings: within a matching
-// day, or from one matching day's last firing to the next matching day's
-// first, with the days taken from a whole 400-year cycle.
-func (c *CronExpr) shortestGap() time.Duration {
- var times []int // minutes of the day, ascending
- for h := 0; h < 24; h++ {
- if c.hour&(1<<uint(h)) == 0 {
- continue
- }
- for m := 0; m < 60; m++ {
- if c.min&(1<<uint(m)) != 0 {
- times = append(times, h*60+m)
- }
- }
- }
- days := c.closestMatchingDays()
- if len(times) == 0 || days == 0 {
- return 24 * time.Hour // never fires
- }
- shortest := days*24*60 - times[len(times)-1] + times[0] // last firing to the next matching day's first
- for i := 1; i < len(times); i++ {
- if gap := times[i] - times[i-1]; gap < shortest {
- shortest = gap
- }
- }
- return time.Duration(shortest) * time.Minute
-}
-
-// closestMatchingDays is the fewest days between two days the line fires on
-// (1 for consecutive days), or 0 if it fires on no day at all. A line that
-// matches one day per cycle is that cycle's length apart from itself.
-func (c *CronExpr) closestMatchingDays() int {
- t := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
- first, prev, closest := -1, -1, 0
- for i := 0; i < gregorianCycleDays; i, t = i+1, t.Add(24*time.Hour) {
- if c.month&(1<<uint(t.Month())) == 0 || !c.dayMatches(t) {
- continue
- }
- if prev >= 0 && (closest == 0 || i-prev < closest) {
- closest = i - prev
- if closest == 1 {
- return 1
- }
- }
- if first < 0 {
- first = i
- }
- prev = i
- }
- if first < 0 {
- return 0
- }
- if wrap := gregorianCycleDays - prev + first; closest == 0 || wrap < closest {
- closest = wrap
- }
- return closest
-}
diff --git a/internal/schedule/spec.go b/internal/schedule/spec.go
index b6aa78938..9a539b542 100644
--- a/internal/schedule/spec.go
+++ b/internal/schedule/spec.go
@@ -1,134 +1,20 @@
-// This file is the timers.spec column's grammar: parse the three stored
-// shapes ("every <duration>", "cron <5 fields>", "at <unix>"), compute each
-// one's next fire from now (spec §6.1's coalescing — always from now, never
-// from the scheduled time), and render the canonical text back for
-// Converge and Runner to store and for `carlos schedule ls` to show.
-
package schedule
import (
- "errors"
- "fmt"
- "strconv"
- "strings"
+ "github.com/carlosframework/platform/internal/timerspec"
"time"
)
const (
- KindSchedule = "schedule"
- KindOnce = "once"
-
- MinEvery = time.Minute
- MaxEvery = 720 * time.Hour
- MaxOnceAhead = 400 * 24 * time.Hour
-
- // MaxOncePerHost bounds how many pending "at" jobs a single box may
- // hold at once — a later task's (the runner's) enforcement point, kept
- // here with the other schedule-wide limits.
- MaxOncePerHost = 1000
+ KindSchedule = timerspec.KindSchedule
+ KindOnce = timerspec.KindOnce
+ MinEvery = timerspec.MinEvery
+ MaxEvery = timerspec.MaxEvery
+ MaxOnceAhead = timerspec.MaxOnceAhead
+ MaxOncePerHost = timerspec.MaxOncePerHost
)
-// Spec is the parsed timers.spec column — one of three shapes, and the only
-// thing the runner needs to know to compute the next fire.
-type Spec struct {
- Kind string
- Every time.Duration
- Cron *CronExpr
- At time.Time
-}
-
-// ParseSpec reads the canonical column text: "every <duration>",
-// "cron <5 fields>", "at <unix>". String is its inverse.
-func ParseSpec(s string) (Spec, error) {
- kind, rest, _ := strings.Cut(strings.TrimSpace(s), " ")
- rest = strings.TrimSpace(rest)
- switch kind {
- case "every":
- d, err := time.ParseDuration(rest)
- if err != nil {
- return Spec{}, fmt.Errorf("every: %w", err)
- }
- if err := ValidEvery(d); err != nil {
- return Spec{}, err
- }
- return Spec{Kind: KindSchedule, Every: d}, nil
- case "cron":
- c, err := ParseCron(rest)
- if err != nil {
- return Spec{}, err
- }
- return Spec{Kind: KindSchedule, Cron: c}, nil
- case "at":
- n, err := strconv.ParseInt(rest, 10, 64)
- if err != nil {
- return Spec{}, fmt.Errorf("at: %q is not a unix time", rest)
- }
- return Spec{Kind: KindOnce, At: time.Unix(n, 0).UTC()}, nil
- }
- return Spec{}, fmt.Errorf("spec %q: want every|cron|at", s)
-}
-
-// ValidEvery is the member-facing bound: whole minutes, 1m to 30d.
-func ValidEvery(d time.Duration) error {
- switch {
- case d < MinEvery:
- return errors.New("every: shortest interval is 1m")
- case d > MaxEvery:
- return errors.New("every: longest interval is 720h (30 days)")
- case d%time.Minute != 0:
- return errors.New("every: whole minutes only")
- }
- return nil
-}
-
-func (s Spec) String() string {
- switch {
- case s.Every > 0:
- return "every " + shortEvery(s.Every)
- case s.Cron != nil:
- return "cron " + s.Cron.String()
- default:
- return "at " + strconv.FormatInt(s.At.Unix(), 10)
- }
-}
-
-// shortEvery renders d the way a member typed it, not the way
-// time.Duration.String does: stdlib always spells out hours, minutes AND
-// seconds ("6h" comes back "6h0m0s"), which is what a box would have stored
-// as the timers.spec column and what `carlos schedule ls` would have shown
-// verbatim. ValidEvery only ever lets a whole number of minutes through, so
-// d has no seconds component to render; this drops whichever of hours/
-// minutes is zero instead of printing it.
-func shortEvery(d time.Duration) string {
- h := d / time.Hour
- m := (d % time.Hour) / time.Minute
- switch {
- case h == 0:
- return fmt.Sprintf("%dm", m)
- case m == 0:
- return fmt.Sprintf("%dh", h)
- default:
- return fmt.Sprintf("%dh%dm", h, m)
- }
-}
+type Spec = timerspec.Spec
-// Next is the first fire strictly after now — epoch-aligned for every,
-// minute-stepped for cron, the instant itself for a pending once and the
-// zero time for a once that has passed. Always from now, never from the
-// scheduled time: that is what coalesces a missed run into one (spec §6.1).
-func (s Spec) Next(now time.Time) time.Time {
- now = now.UTC()
- switch {
- case s.Every > 0:
- n := now.Unix()
- e := int64(s.Every / time.Second)
- return time.Unix((n/e+1)*e, 0).UTC()
- case s.Cron != nil:
- return s.Cron.Next(now)
- default:
- if !s.At.After(now) {
- return time.Time{}
- }
- return s.At.UTC()
- }
-}
+func ParseSpec(s string) (Spec, error) { return timerspec.ParseSpec(s) }
+func ValidEvery(d time.Duration) error { return timerspec.ValidEvery(d) }
diff --git a/internal/timerspec/cron.go b/internal/timerspec/cron.go
new file mode 100644
index 000000000..1e153fd97
--- /dev/null
+++ b/internal/timerspec/cron.go
@@ -0,0 +1,169 @@
+// Package schedule is the platform's answer to "run this later": the WHEN of
+// scheduled work, so an app that hibernates does not have to keep a process
+// alive to keep a timer. Spec: docs/superpowers/specs/2026-08-23-scheduled-work-design.md.
+//
+// This file is the cron dialect. Deliberately small (five fields, UTC, no
+// names, no @aliases — spec §4.1) and deliberately ours: the box binary is
+// built with GOPROXY=off, and a parser this size is cheaper to own than to
+// vendor.
+package timerspec
+
+import (
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// CronExpr is a parsed five-field expression. Each field is a bitset over
+// its legal range (minute 0-59, hour 0-23, day-of-month 1-31, month 1-12,
+// day-of-week 0-6 with 7 folded onto 0).
+type CronExpr struct {
+ min, hour, dom, month, dow uint64
+ raw string
+ domStar, dowStar bool // "*" in a day field — the classic OR-vs-AND rule below
+}
+
+func (c *CronExpr) String() string { return c.raw }
+
+// ParseCron accepts "min hour dom month dow" with *, n, a-b, */n, a-b/n and
+// comma lists. Anything else — names, six fields, @daily — is an error with
+// the field named, because the member typing it has no box to debug on.
+func ParseCron(expr string) (*CronExpr, error) {
+ fields := strings.Fields(expr)
+ if len(fields) != 5 {
+ return nil, fmt.Errorf("cron: want 5 fields (min hour day month weekday), got %d", len(fields))
+ }
+ c := &CronExpr{raw: strings.Join(fields, " ")}
+ var err error
+ if c.min, _, err = parseField(fields[0], 0, 59, "minute"); err != nil {
+ return nil, err
+ }
+ if c.hour, _, err = parseField(fields[1], 0, 23, "hour"); err != nil {
+ return nil, err
+ }
+ if c.dom, c.domStar, err = parseField(fields[2], 1, 31, "day"); err != nil {
+ return nil, err
+ }
+ if c.month, _, err = parseField(fields[3], 1, 12, "month"); err != nil {
+ return nil, err
+ }
+ if c.dow, c.dowStar, err = parseField(fields[4], 0, 7, "weekday"); err != nil {
+ return nil, err
+ }
+ if c.dow&(1<<7) != 0 { // 7 is Sunday too
+ c.dow = (c.dow &^ (1 << 7)) | 1
+ }
+ return c, nil
+}
+
+// parseField returns the bitset and whether the field was a bare "*".
+func parseField(f string, lo, hi int, name string) (uint64, bool, error) {
+ var bits uint64
+ star := f == "*"
+ for _, part := range strings.Split(f, ",") {
+ rangePart, stepPart, hasStep := strings.Cut(part, "/")
+ step := 1
+ if hasStep {
+ n, err := strconv.Atoi(stepPart)
+ if err != nil || n <= 0 {
+ return 0, false, fmt.Errorf("cron %s: bad step %q", name, part)
+ }
+ step = n
+ }
+ a, b := lo, hi
+ switch {
+ case rangePart == "*":
+ case strings.Contains(rangePart, "-"):
+ as, bs, _ := strings.Cut(rangePart, "-")
+ var err error
+ if a, err = atoiIn(as, lo, hi); err != nil {
+ return 0, false, fmt.Errorf("cron %s: %w", name, err)
+ }
+ if b, err = atoiIn(bs, lo, hi); err != nil {
+ return 0, false, fmt.Errorf("cron %s: %w", name, err)
+ }
+ if a > b {
+ return 0, false, fmt.Errorf("cron %s: range %q runs backwards", name, rangePart)
+ }
+ default:
+ n, err := atoiIn(rangePart, lo, hi)
+ if err != nil {
+ return 0, false, fmt.Errorf("cron %s: %w", name, err)
+ }
+ a, b = n, n
+ if hasStep {
+ b = hi // "5/10" means from 5 to the end, stepping
+ }
+ }
+ for v := a; v <= b; v += step {
+ bits |= 1 << uint(v)
+ }
+ }
+ if bits == 0 {
+ return 0, false, errors.New("cron " + name + ": empty")
+ }
+ return bits, star, nil
+}
+
+func atoiIn(s string, lo, hi int) (int, error) {
+ n, err := strconv.Atoi(s)
+ if err != nil {
+ return 0, fmt.Errorf("%q is not a number", s)
+ }
+ if n < lo || n > hi {
+ return 0, fmt.Errorf("%d is outside %d-%d", n, lo, hi)
+ }
+ return n, nil
+}
+
+// Next is the first matching minute strictly after `after`, in UTC, or the
+// zero time if none falls within the search window (a "0 0 30 2 *" never
+// matches, and terminates quickly since each mismatched day is a single
+// jump, not a minute-by-minute walk). The window is 5 years, not 366 days:
+// "0 0 29 2 *" (Feb 29) can be up to ~4 years out depending on where `after`
+// falls in the leap-year cycle, and a 366-day window would wrongly report
+// "never" for it.
+func (c *CronExpr) Next(after time.Time) time.Time {
+ t := after.UTC().Truncate(time.Minute).Add(time.Minute)
+ limit := t.AddDate(5, 0, 0)
+ for t.Before(limit) {
+ if c.month&(1<<uint(t.Month())) == 0 {
+ // Skip to the first of next month.
+ t = time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, time.UTC)
+ continue
+ }
+ if !c.dayMatches(t) {
+ t = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, time.UTC)
+ continue
+ }
+ if c.hour&(1<<uint(t.Hour())) == 0 {
+ t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+1, 0, 0, 0, time.UTC)
+ continue
+ }
+ if c.min&(1<<uint(t.Minute())) == 0 {
+ t = t.Add(time.Minute)
+ continue
+ }
+ return t
+ }
+ return time.Time{}
+}
+
+// dayMatches applies Vixie cron's rule: when BOTH day fields are restricted
+// the day matches if EITHER does; when one is "*" the other decides.
+func (c *CronExpr) dayMatches(t time.Time) bool {
+ dom := c.dom&(1<<uint(t.Day())) != 0
+ dow := c.dow&(1<<uint(t.Weekday())) != 0
+ switch {
+ case c.domStar && c.dowStar:
+ return true
+ case c.domStar:
+ return dow
+ case c.dowStar:
+ return dom
+ default:
+ return dom || dow
+ }
+}
diff --git a/internal/timerspec/mingap.go b/internal/timerspec/mingap.go
new file mode 100644
index 000000000..8965f2868
--- /dev/null
+++ b/internal/timerspec/mingap.go
@@ -0,0 +1,66 @@
+package timerspec
+
+import "time"
+
+// gregorianCycleDays is the length of the Gregorian calendar's 400-year
+// cycle. It is a whole number of weeks, so dates, weekdays and leap days all
+// repeat after it.
+const gregorianCycleDays = 146097
+
+// shortestGap is the smallest gap between two firings: within a matching
+// day, or from one matching day's last firing to the next matching day's
+// first, with the days taken from a whole 400-year cycle.
+func (c *CronExpr) ShortestGap() time.Duration {
+ var times []int // minutes of the day, ascending
+ for h := 0; h < 24; h++ {
+ if c.hour&(1<<uint(h)) == 0 {
+ continue
+ }
+ for m := 0; m < 60; m++ {
+ if c.min&(1<<uint(m)) != 0 {
+ times = append(times, h*60+m)
+ }
+ }
+ }
+ days := c.closestMatchingDays()
+ if len(times) == 0 || days == 0 {
+ return 24 * time.Hour // never fires
+ }
+ shortest := days*24*60 - times[len(times)-1] + times[0] // last firing to the next matching day's first
+ for i := 1; i < len(times); i++ {
+ if gap := times[i] - times[i-1]; gap < shortest {
+ shortest = gap
+ }
+ }
+ return time.Duration(shortest) * time.Minute
+}
+
+// closestMatchingDays is the fewest days between two days the line fires on
+// (1 for consecutive days), or 0 if it fires on no day at all. A line that
+// matches one day per cycle is that cycle's length apart from itself.
+func (c *CronExpr) closestMatchingDays() int {
+ t := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
+ first, prev, closest := -1, -1, 0
+ for i := 0; i < gregorianCycleDays; i, t = i+1, t.Add(24*time.Hour) {
+ if c.month&(1<<uint(t.Month())) == 0 || !c.dayMatches(t) {
+ continue
+ }
+ if prev >= 0 && (closest == 0 || i-prev < closest) {
+ closest = i - prev
+ if closest == 1 {
+ return 1
+ }
+ }
+ if first < 0 {
+ first = i
+ }
+ prev = i
+ }
+ if first < 0 {
+ return 0
+ }
+ if wrap := gregorianCycleDays - prev + first; closest == 0 || wrap < closest {
+ closest = wrap
+ }
+ return closest
+}
diff --git a/internal/timerspec/spec.go b/internal/timerspec/spec.go
new file mode 100644
index 000000000..f1635b12e
--- /dev/null
+++ b/internal/timerspec/spec.go
@@ -0,0 +1,134 @@
+// This file is the timers.spec column's grammar: parse the three stored
+// shapes ("every <duration>", "cron <5 fields>", "at <unix>"), compute each
+// one's next fire from now (spec §6.1's coalescing — always from now, never
+// from the scheduled time), and render the canonical text back for
+// Converge and Runner to store and for `carlos schedule ls` to show.
+
+package timerspec
+
+import (
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+)
+
+const (
+ KindSchedule = "schedule"
+ KindOnce = "once"
+
+ MinEvery = time.Minute
+ MaxEvery = 720 * time.Hour
+ MaxOnceAhead = 400 * 24 * time.Hour
+
+ // MaxOncePerHost bounds how many pending "at" jobs a single box may
+ // hold at once — a later task's (the runner's) enforcement point, kept
+ // here with the other schedule-wide limits.
+ MaxOncePerHost = 1000
+)
+
+// Spec is the parsed timers.spec column — one of three shapes, and the only
+// thing the runner needs to know to compute the next fire.
+type Spec struct {
+ Kind string
+ Every time.Duration
+ Cron *CronExpr
+ At time.Time
+}
+
+// ParseSpec reads the canonical column text: "every <duration>",
+// "cron <5 fields>", "at <unix>". String is its inverse.
+func ParseSpec(s string) (Spec, error) {
+ kind, rest, _ := strings.Cut(strings.TrimSpace(s), " ")
+ rest = strings.TrimSpace(rest)
+ switch kind {
+ case "every":
+ d, err := time.ParseDuration(rest)
+ if err != nil {
+ return Spec{}, fmt.Errorf("every: %w", err)
+ }
+ if err := ValidEvery(d); err != nil {
+ return Spec{}, err
+ }
+ return Spec{Kind: KindSchedule, Every: d}, nil
+ case "cron":
+ c, err := ParseCron(rest)
+ if err != nil {
+ return Spec{}, err
+ }
+ return Spec{Kind: KindSchedule, Cron: c}, nil
+ case "at":
+ n, err := strconv.ParseInt(rest, 10, 64)
+ if err != nil {
+ return Spec{}, fmt.Errorf("at: %q is not a unix time", rest)
+ }
+ return Spec{Kind: KindOnce, At: time.Unix(n, 0).UTC()}, nil
+ }
+ return Spec{}, fmt.Errorf("spec %q: want every|cron|at", s)
+}
+
+// ValidEvery is the member-facing bound: whole minutes, 1m to 30d.
+func ValidEvery(d time.Duration) error {
+ switch {
+ case d < MinEvery:
+ return errors.New("every: shortest interval is 1m")
+ case d > MaxEvery:
+ return errors.New("every: longest interval is 720h (30 days)")
+ case d%time.Minute != 0:
+ return errors.New("every: whole minutes only")
+ }
+ return nil
+}
+
+func (s Spec) String() string {
+ switch {
+ case s.Every > 0:
+ return "every " + shortEvery(s.Every)
+ case s.Cron != nil:
+ return "cron " + s.Cron.String()
+ default:
+ return "at " + strconv.FormatInt(s.At.Unix(), 10)
+ }
+}
+
+// shortEvery renders d the way a member typed it, not the way
+// time.Duration.String does: stdlib always spells out hours, minutes AND
+// seconds ("6h" comes back "6h0m0s"), which is what a box would have stored
+// as the timers.spec column and what `carlos schedule ls` would have shown
+// verbatim. ValidEvery only ever lets a whole number of minutes through, so
+// d has no seconds component to render; this drops whichever of hours/
+// minutes is zero instead of printing it.
+func shortEvery(d time.Duration) string {
+ h := d / time.Hour
+ m := (d % time.Hour) / time.Minute
+ switch {
+ case h == 0:
+ return fmt.Sprintf("%dm", m)
+ case m == 0:
+ return fmt.Sprintf("%dh", h)
+ default:
+ return fmt.Sprintf("%dh%dm", h, m)
+ }
+}
+
+// Next is the first fire strictly after now — epoch-aligned for every,
+// minute-stepped for cron, the instant itself for a pending once and the
+// zero time for a once that has passed. Always from now, never from the
+// scheduled time: that is what coalesces a missed run into one (spec §6.1).
+func (s Spec) Next(now time.Time) time.Time {
+ now = now.UTC()
+ switch {
+ case s.Every > 0:
+ n := now.Unix()
+ e := int64(s.Every / time.Second)
+ return time.Unix((n/e+1)*e, 0).UTC()
+ case s.Cron != nil:
+ return s.Cron.Next(now)
+ default:
+ if !s.At.After(now) {
+ return time.Time{}
+ }
+ return s.At.UTC()
+ }
+}