oficina / equipo Public

runner: admit every step attempt through schedule.Decide

Engineering, Review and Research attempts (failover included) are
admitted by the scheduler: readings refreshed first, the admission
written in one transaction that rereads the facts, a Run now consumed
there and kept as a grant for the step revision (a metered admission
commits in the guard's transaction). Holds are kept with their wake-up
and reported once; release and priority frames; the release order;
preference until. Leave to spend comes from urgent or a grant only: the
test-build seam and its release-check marker are gone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 5ca29750249f974dd140b4cc80cc7295d86985f2 parent 8540c36
20 files changed, +1,404 −160
  • cmd/equipo-runner/release_guard_test.go +2 −9
  • internal/runner/metered/meter.go +13 −1
  • internal/runner/thin/askmetered.go +3 −0
  • internal/runner/thin/conns.go +28 −3
  • internal/runner/thin/engineer.go +73 −30
  • internal/runner/thin/fixround_test.go +4 −1
  • internal/runner/thin/judge.go +38 −39
  • internal/runner/thin/link.go +26 −0
  • internal/runner/thin/pistep.go +20 −2
  • internal/runner/thin/pistep_test.go +33 −28
  • internal/runner/thin/research.go +20 −13
  • internal/runner/thin/run.go +2 −0
  • internal/runner/thin/schedule.go +617 −0
  • internal/runner/thin/schedule_test.go +475 −0
  • internal/runner/thin/spend.go +3 −13
  • internal/runner/thin/spend_testbuild.go +4 −6
  • internal/runner/thin/state.go +11 −1
  • internal/runner/thin/step.go +25 −5
  • internal/schedule/schedule.go +7 −5
  • scripts/no-fake-worker.sh +0 −4
diff --git a/cmd/equipo-runner/release_guard_test.go b/cmd/equipo-runner/release_guard_test.go
index 145e0789..5ea8f19a 100644
--- a/cmd/equipo-runner/release_guard_test.go
+++ b/cmd/equipo-runner/release_guard_test.go
@@ -52,9 +52,6 @@ func TestReleaseRunnerHasNoFakeWorker(t *testing.T) {
if bytes.Contains(raw, []byte(egressMarker)) {
t.Fatal("the release runner contains the test build's egress route")
}
- if bytes.Contains(raw, []byte(spendMarker)) {
- t.Fatal("the release runner contains the test build's leave to spend")
- }
if out, err := exec.Command("../../scripts/no-fake-worker.sh", bin).CombinedOutput(); err != nil {
t.Fatalf("the release check refused a clean binary: %s", out)
}
@@ -65,7 +62,7 @@ func TestReleaseRunnerHasNoFakeWorker(t *testing.T) {
if out, err := test.CombinedOutput(); err != nil {
t.Fatalf("test build: %v %s", err, out)
}
- if raw, _ := os.ReadFile(archive); !bytes.Contains(raw, []byte(marker)) || !bytes.Contains(raw, []byte(spendMarker)) {
+ if raw, _ := os.ReadFile(archive); !bytes.Contains(raw, []byte(marker)) {
t.Fatal("the test build has no marker: this guard sees nothing")
}
if out, err := exec.Command("../../scripts/no-fake-worker.sh", archive).CombinedOutput(); err == nil {
@@ -88,10 +85,6 @@ func TestReleaseRunnerHasNoFakeWorker(t *testing.T) {
}
}
-// spendMarker names the test build's leave to spend (internal/runner/thin
-// spend_testbuild.go): metered steps before S3, in tests only.
-const spendMarker = "EQUIPO_TEST_LEAVE_TO_SPEND"
-
// egressMarker names the test build's egress route (internal/runner/egress
// proxy_testbuild.go).
const egressMarker = "EQUIPO_TEST_EGRESS_UPSTREAM"
@@ -113,7 +106,7 @@ func TestReleaseCheckRefusesEachMarker(t *testing.T) {
if err := check("clean", "nothing of the test build"); err != nil {
t.Fatalf("a clean binary was refused: %v", err)
}
- for name, m := range map[string]string{"fake worker": marker, "egress route": egressMarker, "leave to spend": spendMarker} {
+ for name, m := range map[string]string{"fake worker": marker, "egress route": egressMarker} {
if err := check(strings.ReplaceAll(name, " ", "-"), m); err == nil {
t.Errorf("a binary with only the %s marker was accepted", name)
}
diff --git a/internal/runner/metered/meter.go b/internal/runner/metered/meter.go
index b19336d6..57a612bc 100644
--- a/internal/runner/metered/meter.go
+++ b/internal/runner/metered/meter.go
@@ -120,7 +120,11 @@ func (m *Meter) Admit(ctx context.Context, local string, h Holder, admit func(*s
return admit(t)
})
if err != nil || !a.Admitted {
+ // A failed admission (the caller's part refused it) admits nothing.
m.setRunning(local, h, false)
+ if err != nil {
+ a.Admitted = false
+ }
return a, err
}
if m.Fault != nil {
@@ -157,7 +161,15 @@ func (m *Meter) Notify() { m.changed() }
// frame). An attempt whose exit is not proven keeps its slot until
// Recover proves it.
func (m *Meter) Run(ctx context.Context, local string, h Holder, run func(context.Context, Launch) Result, report func(*sql.Tx, []wire.Usage) error) (Admission, Result, error) {
- a, err := m.Admit(ctx, local, h, nil)
+ return m.RunAdmitted(ctx, local, h, nil, run, report)
+}
+
+// RunAdmitted is Run with the caller's admission (the scheduler's: the
+// facts rechecked, a Run now consumed, the admission row) written in the
+// guard's transaction, so the slot's claim and the admission commit
+// together or not at all.
+func (m *Meter) RunAdmitted(ctx context.Context, local string, h Holder, admit func(*sql.Tx) error, run func(context.Context, Launch) Result, report func(*sql.Tx, []wire.Usage) error) (Admission, Result, error) {
+ a, err := m.Admit(ctx, local, h, admit)
if err != nil || !a.Admitted {
return a, Result{}, err
}
diff --git a/internal/runner/thin/askmetered.go b/internal/runner/thin/askmetered.go
index 06adc122..d5a01efb 100644
--- a/internal/runner/thin/askmetered.go
+++ b/internal/runner/thin/askmetered.go
@@ -166,5 +166,8 @@ func (e *StepEngine) MeteredChanged() {
if _, err := e.State.db.Exec("UPDATE asks SET not_before='' WHERE hold<>'' AND state=? AND started=0", runRunning); err != nil {
e.log("ask holds", err)
}
+ // Steps the scheduler holds look again too (connectors spec §7: on
+ // any reading, step end, budget change or preference change).
+ e.log("step holds", e.State.wakeHeld(context.Background()))
e.Wake()
}
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go
index bcea9200..8171b4cc 100644
--- a/internal/runner/thin/conns.go
+++ b/internal/runner/thin/conns.go
@@ -57,6 +57,15 @@ type Conns struct {
// Meter is the metered guard over the metered connections in
// thin.db (connectors spec S1); nil, none can be added.
Meter *metered.Meter
+ // Reading is a connection's reading probe (rev 3 §2.7: the harness's
+ // cheapest request, never a model turn), which the scheduler runs on
+ // a reading older than fifteen minutes before it decides; nil, none
+ // (no such request exists for Claude or Codex today), and a reading
+ // stays as it was last reported.
+ Reading func(context.Context, runner.AccountBinding) (*connect.Limit, error)
+ // Readings is told a connection's reported headroom changed: steps
+ // the scheduler holds look again.
+ Readings func()
mu sync.Mutex
live map[string]connState
@@ -65,6 +74,8 @@ type Conns struct {
// connection only from then; its CLI's local status never sets it.
validated map[string]time.Time
now func() time.Time
+ // probed is when each connection's reading probe last ran.
+ probed map[string]time.Time
}
func (c *Conns) clock() time.Time {
@@ -284,14 +295,21 @@ func (c *Conns) ChooseFor(ctx context.Context, person, role, current string, avo
return runner.AccountBinding{}, connect.Choice{}, ErrNoConnection
}
-// Preference is the person's preference as the instance last sent it.
+// Preference is the person's preference as the instance last sent it;
+// one whose end has passed is Automatic (connectors spec §7).
func (c *Conns) Preference(ctx context.Context, person string) (wire.Preferences, error) {
var p wire.Preferences
raw, err := c.State.meta(ctx, "prefer:"+person)
if err != nil || raw == "" {
return p, err
}
- return p, json.Unmarshal([]byte(raw), &p)
+ if err := json.Unmarshal([]byte(raw), &p); err != nil {
+ return p, err
+ }
+ if p.Until != nil && !c.clock().Before(*p.Until) {
+ p.Provider, p.Until = "", nil
+ }
+ return p, nil
}
// Prefer records the person's preference (a durable frame, once); an
@@ -317,7 +335,7 @@ func (c *Conns) Prefer(ctx context.Context, frameID string, cmd wire.PreferenceC
if cmd.Revision <= held.Revision {
return nil
}
- next, _ := json.Marshal(wire.Preferences{Provider: cmd.Provider, Revision: cmd.Revision})
+ next, _ := json.Marshal(wire.Preferences{Provider: cmd.Provider, Revision: cmd.Revision, Until: cmd.Until})
_, err = t.ExecContext(ctx, "INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", "prefer:"+cmd.Person, string(next))
return err
})
@@ -393,7 +411,11 @@ func (c *Conns) Observe(id string, l connect.Limit, plan string) {
c.mu.Lock()
cs := c.live[id]
was := cs.State
+ read := false
if l.Headroom != nil {
+ before, _ := json.Marshal(cs.Headroom)
+ after, _ := json.Marshal(l.Headroom)
+ read = string(before) != string(after)
cs.Headroom = l.Headroom
}
if plan != "" {
@@ -406,6 +428,9 @@ func (c *Conns) Observe(id string, l connect.Limit, plan string) {
c.mu.Unlock()
if was != cs.State {
c.changed()
+ } else if read && c.Readings != nil {
+ // A new reading: steps the scheduler holds look again.
+ c.Readings()
}
}
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go
index 47520563..d8889b0a 100644
--- a/internal/runner/thin/engineer.go
+++ b/internal/runner/thin/engineer.go
@@ -163,11 +163,13 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR
rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true
return rep
}
- // Nothing can run Engineering now: the step waits, queued, and goes on
- // its own when a connection returns (spec §3); the queue moves on.
- if _, err := e.engineerOn(ctx, r, nil, ""); errors.Is(err, ErrNoConnection) && !r.Republish {
- rep.State = stepDeferred
- return rep
+ // The scheduler holds it (connectors spec §7): the step waits,
+ // queued, and goes on its own at its wake-up or when a fact changes;
+ // the queue moves on.
+ if !r.Republish {
+ if h := e.precheck(ctx, r); h != nil {
+ return heldReport(rep, h)
+ }
}
if r.Republish {
// Retry of a failed push: the commit an earlier attempt recorded is
@@ -252,7 +254,9 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR
for {
var err error
var resume bool
- if b, resume, err = e.fixPlan(ctx, r, avoid, prior, resumable); err != nil {
+ var hold *wire.StepHold
+ var admit admitFunc
+ if b, resume, hold, admit, err = e.fixPlan(ctx, r, avoid, prior, resumable); err != nil {
if errors.Is(err, ErrNoConnection) {
// Nothing can take it (every connection that could is
// refused now): the attempt waits, queued, and goes on its
@@ -262,8 +266,13 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR
}
return fail("account_unavailable", true)
}
+ if hold != nil {
+ // Every attempt, failover included, is admitted through the
+ // scheduler: held, it waits as the first attempt does.
+ return heldReport(rep, hold)
+ }
rep.Family, rep.Account = b.Family, b.LocalID
- spec := specialistRun{action: "implement", binding: b, tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: claude.StepPermission, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: prompt, keep: e.keepDir(r), activity: e.stepActivity(r), research: handoff.dir}
+ spec := specialistRun{admit: admit, action: "implement", binding: b, tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: claude.StepPermission, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: prompt, keep: e.keepDir(r), activity: e.stepActivity(r), research: handoff.dir}
if resume {
// A resumed session reads only this message: the findings too.
spec.prompt, spec.resume, spec.from = handoff.with(e.fixPrompt(r), e.Note), prior.SessionID, prior.Dir
@@ -273,8 +282,7 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR
// The metered guard holds it (its slot, budget or spend): the
// attempt waits and goes again when the connection's standing
// changes.
- rep.State = stepDeferred
- return rep
+ return heldGuard(rep, res)
}
if resume && res.reason == "session_gone" && res.terminated {
// The kept transcript could not be put in place (nothing was
@@ -663,6 +671,9 @@ type specialistRun struct {
// research is the attempt's directory of kept Research images,
// bound read-only at /research ("": none).
research string
+ // admit is the scheduler's admission of a metered attempt, written in
+ // the metered guard's transaction (nil: admitted already, or none).
+ admit admitFunc
}
// stepResult is how the specialist's process ended. session is the
@@ -682,6 +693,9 @@ type stepResult struct {
// family is the family of the model that ran, where the harness
// reports it (Pi); Review's independence is judged on it.
family string
+ // hold is the metered guard's hold (reason reasonHeld): the step is
+ // held with it.
+ hold *wire.StepHold
}
// usage is the run's usage rows for the step attempt.
@@ -697,14 +711,52 @@ func (res stepResult) usage(b runner.AccountBinding, attempt int64) []wire.Usage
return usageRows(res.tokens, b, attempt, outcome)
}
-// engineerOn is the connection an Engineering attempt runs on; current
-// is a connection to keep when it can still run it ("" for none).
-func (e *Engineer) engineerOn(ctx context.Context, r stepRow, avoid []string, current string) (runner.AccountBinding, error) {
+// engineerOn admits an Engineering attempt through the scheduler; kept
+// is the connection of the session it resumes ("" for none). It returns
+// the connection, or the hold, and for a metered connection the
+// admission runPi writes in the guard's transaction.
+func (e *Engineer) engineerOn(ctx context.Context, r stepRow, avoid []string, kept string) (runner.AccountBinding, *wire.StepHold, admitFunc, error) {
+ if e.Conns == nil {
+ b, err := SelectAccount(e.O.Runner, r.Person)
+ return b, nil, nil, err
+ }
+ return e.Conns.admit(ctx, r, connect.RoleEngineering, kept, avoid, nil)
+}
+
+// precheck is the scheduler's look before a step prepares anything: the
+// hold, when Decide holds it now (nil when it would start, or without
+// connections). The attempt is admitted later, once prepared.
+func (e *Engineer) precheck(ctx context.Context, r stepRow) *wire.StepHold {
if e.Conns == nil {
- return SelectAccount(e.O.Runner, r.Person)
+ return nil
+ }
+ kept := ""
+ if prior, ok := e.fixSession(ctx, r, r.BaseSHA); ok {
+ kept = e.keptConnection(ctx, r.Person, prior)
+ }
+ d, err := e.Conns.decide(ctx, r, connect.RoleEngineering, kept, nil, nil)
+ if err != nil {
+ e.log("step schedule", err)
+ return nil
}
- b, _, err := e.Conns.ChooseFor(ctx, r.Person, connect.RoleEngineering, current, avoid, leaveToSpend(r))
- return b, err
+ return d.hold()
+}
+
+// keptConnection is the connection a kept session ran on: a Claude one,
+// or a metered one Pi ran ("" when neither is the person's now).
+func (e *Engineer) keptConnection(ctx context.Context, person string, kept keptSession) string {
+ current := ""
+ for _, c := range e.Conns.Mine(person) {
+ if c.Provider == "claude" && c.LocalID == kept.Account {
+ current = c.ID
+ }
+ }
+ for _, c := range e.Conns.MeteredMine(ctx, person) {
+ if c.LocalID == kept.Account {
+ current = c.ID
+ }
+ }
+ return current
}
// fixSession is the kept session a fix round may resume: Engineering's
@@ -738,26 +790,17 @@ func (e *Engineer) fixSession(ctx context.Context, r stepRow, base string) (kept
// the person's provider preference allows; connect.Choose keeps it
// then). Anything else, the attempt starts fresh wherever Choose puts
// it: failover always wins over the warm cache.
-func (e *Engineer) fixPlan(ctx context.Context, r stepRow, avoid []string, kept keptSession, resumable bool) (runner.AccountBinding, bool, error) {
+func (e *Engineer) fixPlan(ctx context.Context, r stepRow, avoid []string, kept keptSession, resumable bool) (runner.AccountBinding, bool, *wire.StepHold, admitFunc, error) {
current := ""
if resumable && e.Conns != nil {
- for _, c := range e.Conns.Mine(r.Person) {
- if c.Provider == "claude" && c.LocalID == kept.Account {
- current = c.ID
- }
- }
- for _, c := range e.Conns.MeteredMine(ctx, r.Person) {
- if c.LocalID == kept.Account {
- current = c.ID
- }
- }
+ current = e.keptConnection(ctx, r.Person, kept)
}
- b, err := e.engineerOn(ctx, r, avoid, current)
- if err != nil {
- return b, false, err
+ b, hold, admit, err := e.engineerOn(ctx, r, avoid, current)
+ if err != nil || hold != nil {
+ return b, false, hold, nil, err
}
resume := resumable && (b.Provider == "claude" || Metered(b)) && b.LocalID == kept.Account && (e.Healthy == nil || Metered(b) || e.Healthy(b.ID))
- return b, resume, nil
+ return b, resume, nil, admit, nil
}
// observe records the headroom a run's provider reported.
diff --git a/internal/runner/thin/fixround_test.go b/internal/runner/thin/fixround_test.go
index b3b0379b..06b030e7 100644
--- a/internal/runner/thin/fixround_test.go
+++ b/internal/runner/thin/fixround_test.go
@@ -82,10 +82,13 @@ func fixRound() stepRow {
func (r *fixRig) plan(row stepRow, avoid []string) (string, bool) {
r.t.Helper()
kept, ok := r.e.fixSession(context.Background(), row, row.Base)
- b, resume, err := r.e.fixPlan(context.Background(), row, avoid, kept, ok)
+ b, resume, hold, _, err := r.e.fixPlan(context.Background(), row, avoid, kept, ok)
if err != nil {
r.t.Fatal(err)
}
+ if hold != nil {
+ r.t.Fatalf("held: %+v", hold)
+ }
if resume && kept.SessionID != "sess-0" {
r.t.Fatalf("resumes %+v", kept)
}
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go
index e9d20d11..4e224a3d 100644
--- a/internal/runner/thin/judge.go
+++ b/internal/runner/thin/judge.go
@@ -624,16 +624,17 @@ func verdictOf(args json.RawMessage) (verdict, headline, summary string, finding
// (with connections; without them, Claude accounts only), else another
// account of the same family, else a fresh session on the same account
// (same family, same account).
-func (e *Engineer) reviewer(ctx context.Context, r stepRow) (runner.AccountBinding, string, error) {
+func (e *Engineer) reviewer(ctx context.Context, r stepRow, refused []string) (runner.AccountBinding, string, *wire.StepHold, admitFunc, error) {
person, avoid := r.Person, r.AvoidAccount
if e.Conns != nil {
- return e.reviewOn(ctx, person, avoid, leaveToSpend(r))
+ return e.reviewOn(ctx, r, refused)
}
bs, err := runner.LoadBindings(e.O.Runner.AccountBindingsPath)
if err != nil {
- return runner.AccountBinding{}, "", err
+ return runner.AccountBinding{}, "", nil, nil, err
}
- return pickReviewer(bs, person, avoid, e.Healthy)
+ b, label, err := pickReviewer(bs, person, avoid, e.Healthy)
+ return b, label, nil, nil, err
}
func pickReviewer(bs []runner.AccountBinding, person, avoid string, healthy func(string) bool) (runner.AccountBinding, string, error) {
@@ -660,33 +661,21 @@ func pickReviewer(bs []runner.AccountBinding, person, avoid string, healthy func
return engineer, wire.ReviewSameAccount, nil
}
-// reviewOn chooses Review's connection with the one choice function:
-// away from Engineering's connection when another can review (another
-// family, else another account of the same family), else a fresh session
-// on Engineering's own (same account). A limited connection is never
-// chosen.
-func (e *Engineer) reviewOn(ctx context.Context, person, avoid string, spend bool) (runner.AccountBinding, string, error) {
- engineer := e.engineerOf(ctx, person, avoid)
- // The family first: only when no connection of another family can
- // review does the choice (preference, headroom, order) look at the
- // engineer's family, then at its own account.
- var same []string
- for _, c := range append(e.Conns.Mine(person), e.Conns.MeteredMine(ctx, person)...) {
- if c.Family == engineer.Family {
- same = append(same, c.ID)
- }
- }
- b, _, err := e.Conns.ChooseFor(ctx, person, connect.RoleReview, "", same, spend)
- if errors.Is(err, ErrNoConnection) {
- b, _, err = e.Conns.ChooseFor(ctx, person, connect.RoleReview, "", []string{engineer.ID}, spend)
- }
- if errors.Is(err, ErrNoConnection) {
- b, _, err = e.Conns.ChooseFor(ctx, person, connect.RoleReview, "", nil, spend)
+// reviewOn admits Review through the scheduler (connectors spec §7),
+// with the family rule as Decide applies it: another family first, then
+// another account, then a fresh session on Engineering's own; refused
+// are connections this step's earlier attempts were refused on.
+func (e *Engineer) reviewOn(ctx context.Context, r stepRow, refused []string) (runner.AccountBinding, string, *wire.StepHold, admitFunc, error) {
+ engineer := e.engineerOf(ctx, r.Person, r.AvoidAccount)
+ var eng *runner.AccountBinding
+ if engineer.ID != "" {
+ eng = &engineer
}
- if err != nil {
- return b, "", err
+ b, hold, admit, err := e.Conns.admit(ctx, r, connect.RoleReview, "", refused, eng)
+ if err != nil || hold != nil {
+ return b, "", hold, nil, err
}
- return b, reviewLabel(engineer, b, b.Family), nil
+ return b, reviewLabel(engineer, b, b.Family), nil, admit, nil
}
// engineerOf is the connection Engineering ran on (avoid names it), else
@@ -730,10 +719,14 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste
}
defer os.RemoveAll(tree.GitDir)
defer os.RemoveAll(tree.Dir)
- b, label, err := e.reviewer(ctx, r)
+ var refused []string
+ b, label, hold, admit, err := e.reviewer(ctx, r, refused)
+ if hold != nil {
+ // The scheduler holds it: the step waits, queued, and goes on its
+ // own at its wake-up or when a fact changes; the queue moves on.
+ return heldReport(rep, hold)
+ }
if errors.Is(err, ErrNoConnection) {
- // Nothing can review now: the step waits, queued, and goes on its
- // own when a connection returns (spec §3); the queue moves on.
rep.State = stepDeferred
return rep
}
@@ -764,11 +757,10 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste
mu.Unlock()
return "Recorded. End with your summary.", false
}
- res := e.run(ctx, r, tree, specialistRun{action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: prompt, keep: e.keepDir(r), activity: e.stepActivity(r), research: handoff.dir})
+ res := e.run(ctx, r, tree, specialistRun{admit: admit, action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: prompt, keep: e.keepDir(r), activity: e.stepActivity(r), research: handoff.dir})
if res.reason == reasonHeld {
- // The metered guard holds it: Review waits, deferred.
- rep.State = stepDeferred
- return rep
+ // The metered guard holds it: Review waits, held there.
+ return heldGuard(rep, res)
}
e.observe(b.ID, res)
// Refused on quota or the credential before a verdict: once the exit
@@ -781,7 +773,14 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste
rep.State, rep.Reason, rep.Termination = wire.StepFailed, "provider_failed", true
return rep
}
- next, nextLabel, err := e.reviewer(ctx, r)
+ // The failover attempt is admitted through the scheduler too, the
+ // refused connection avoided; a grant for this step revision
+ // covers it.
+ refused = append(refused, b.ID)
+ next, nextLabel, hold, nextAdmit, err := e.reviewer(ctx, r, refused)
+ if hold != nil {
+ return heldReport(rep, hold)
+ }
if errors.Is(err, ErrNoConnection) {
rep.State = stepDeferred
return rep
@@ -789,11 +788,11 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste
if err != nil {
break
}
- b, label = next, nextLabel
+ b, label, admit = next, nextLabel, nextAdmit
rep.Family, rep.Account = b.Family, b.LocalID
rep.Switched.To = b.Provider
progress(rep)
- res = e.run(ctx, r, tree, specialistRun{action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: prompt, keep: e.keepDir(r), activity: e.stepActivity(r), research: handoff.dir})
+ res = e.run(ctx, r, tree, specialistRun{admit: admit, action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: prompt, keep: e.keepDir(r), activity: e.stepActivity(r), research: handoff.dir})
e.observe(b.ID, res)
}
if res.family != "" && res.family != b.Family {
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index 88216c3e..1f1c14f4 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -835,6 +835,20 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro
if err = l.Connector.Conns.Prefer(ctx, f.ID, *v); err != nil {
return 0, err
}
+ l.wakeHeld(ctx)
+ case *wire.ReleaseCommand:
+ // Run now: kept for its step revision, consumed with the
+ // admission it causes; a stale or replayed one is acked and
+ // ignored.
+ if _, err = l.State.Release(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
+ l.wakeHeld(ctx)
+ case *wire.PriorityCommand:
+ if _, err = l.State.SetPriority(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
+ l.wakeHeld(ctx)
case *wire.SecretCommand:
// Acked only once the secret is committed (or refused).
if l.Connector == nil {
@@ -962,3 +976,15 @@ func itoa(n int64) string {
b, _ := json.Marshal(n)
return string(b)
}
+
+// wakeHeld makes the steps the scheduler holds look again (a fact
+// changed: a release, a priority, a preference).
+func (l *Link) wakeHeld(ctx context.Context) {
+ if l.Steps == nil {
+ return
+ }
+ if err := l.State.wakeHeld(ctx); err != nil && l.Logger != nil {
+ l.Logger.Warn("step holds", "err", sanitize(err))
+ }
+ l.Steps.Wake()
+}
diff --git a/internal/runner/thin/pistep.go b/internal/runner/thin/pistep.go
index e5ec70d7..6af68bc8 100644
--- a/internal/runner/thin/pistep.go
+++ b/internal/runner/thin/pistep.go
@@ -64,7 +64,12 @@ func (e *Engineer) runPi(ctx context.Context, r stepRow, tree workspace.TaskTree
h := metered.Holder{Step: r.StepID, Attempt: r.Attempt, Role: meteredRole(spec.action)}
var res stepResult
var priced []wire.Usage
- adm, _, err := e.Conns.Meter.Run(ctx, b.LocalID, h, func(ctx context.Context, l metered.Launch) metered.Result {
+ var admit func(*sql.Tx) error
+ if spec.admit != nil {
+ // The scheduler's admission commits with the slot's claim.
+ admit = func(t *sql.Tx) error { return spec.admit(ctx, t) }
+ }
+ adm, _, err := e.Conns.Meter.RunAdmitted(ctx, b.LocalID, h, admit, func(ctx context.Context, l metered.Launch) metered.Result {
var ending metered.Ending
res, ending = e.piAttempt(ctx, r, tree, spec, l)
return metered.Result{Usage: usageRows(res.tokens, b, r.Attempt, outcomeOf(res, ctx)), Ending: ending}
@@ -72,6 +77,12 @@ func (e *Engineer) runPi(ctx context.Context, r stepRow, tree workspace.TaskTree
priced = rows
return nil
})
+ if errors.Is(err, errFactsMoved) {
+ // The facts moved before the admission committed: looked at again
+ // at once.
+ wake := time.Now().Add(heldRetry)
+ return stepResult{reason: reasonHeld, terminated: true, hold: &wire.StepHold{Reason: wire.HoldBusy, Connection: b.ID, Provider: b.Provider, WakeAt: &wake}}
+ }
if err != nil {
e.log("step metered", err)
if !adm.Admitted {
@@ -79,7 +90,14 @@ func (e *Engineer) runPi(ctx context.Context, r stepRow, tree workspace.TaskTree
}
}
if !adm.Admitted {
- return stepResult{reason: reasonHeld, terminated: true}
+ // The guard held it (its slot, budget or spend): held there, until
+ // the next budget period or a change of its standing.
+ h := &wire.StepHold{Reason: adm.Hold, Connection: b.ID, Provider: b.Provider}
+ if !adm.WakeAt.IsZero() {
+ at := adm.WakeAt
+ h.WakeAt = &at
+ }
+ return stepResult{reason: reasonHeld, terminated: true, hold: h}
}
if priced != nil {
res.tokens = priced
diff --git a/internal/runner/thin/pistep_test.go b/internal/runner/thin/pistep_test.go
index 07f9f843..5b4f886d 100644
--- a/internal/runner/thin/pistep_test.go
+++ b/internal/runner/thin/pistep_test.go
@@ -178,13 +178,9 @@ func newPiRig(t *testing.T, inst pi.Install, budget wire.Budget) *piRig {
return &piRig{t: t, ctx: ctx, e: e, state: state, conns: conns, review: review}
}
-// leave grants every step leave to spend while the test runs (S3 gives
-// steps their own: an urgent task or a released step).
-func leave(t *testing.T) {
- was := testLeaveToSpend
- testLeaveToSpend = func(stepRow) bool { return true }
- t.Cleanup(func() { testLeaveToSpend = was })
-}
+// urgent gives the rig's steps leave to spend the way S3 gives it: the
+// task is urgent (the person's tap).
+func (r *piRig) urgent() { r.review.Priority = wire.PriorityUrgent }
func (r *piRig) runReview(brief string, attempt int64) wire.StepReport {
r.t.Helper()
@@ -231,7 +227,7 @@ var bigBudget = wire.Budget{Day: 1_000_000, Month: 10_000_000, Revision: 1}
// proof, and its session kept so the person can ask it.
func TestPiReviewStep(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
rep := r.runReview("", 1)
if rep.State != wire.StepDone || rep.Verdict != wire.VerdictApprove || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || rep.Account != piLocal || !rep.Termination {
t.Fatalf("report %+v", rep)
@@ -245,6 +241,12 @@ func TestPiReviewStep(t *testing.T) {
if n := r.charges(); n != 1 || !r.slotFree() || r.conn().SpendUnknown {
t.Fatalf("charges %d, slot free %v, spend unknown %v", n, r.slotFree(), r.conn().SpendUnknown)
}
+ // Admitted through the scheduler, in the guard's transaction: the
+ // urgent task's leave.
+ var reason, conn string
+ if err := r.state.db.QueryRow("SELECT reason, connection FROM admissions WHERE step_id='rv1-1'").Scan(&reason, &conn); err != nil || reason != "metered_urgent" || conn != piLocal {
+ t.Fatalf("admission %q on %q: %v", reason, conn, err)
+ }
// A resent usage row charges once.
if err := r.conns.Meter.Finish(r.ctx, piLocal, metered.Holder{Step: "rv1-1", Attempt: 1, Role: metered.RoleReview}, metered.Result{Usage: rep.Usage}, nil); err != nil {
t.Fatal(err)
@@ -254,14 +256,14 @@ func TestPiReviewStep(t *testing.T) {
}
}
-// Without leave to spend (every step until S3), Review is never chosen
-// onto the metered connection: with Engineering's connection limited it
-// waits, deferred, and nothing runs.
+// Without leave to spend (a normal task, no Run now), Review is never
+// chosen onto the metered connection: with Engineering's connection
+// limited it is held for headroom on it, and nothing runs.
func TestPiReviewWithoutLeaveToSpend(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
rep := r.runReview("", 1)
- if rep.State != stepDeferred || r.charges() != 0 {
- t.Fatalf("report %+v, charges %d", rep, r.charges())
+ if rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldHeadroom || rep.Hold.Connection != "claude-a" || r.charges() != 0 {
+ t.Fatalf("report %+v, hold %+v, charges %d", rep, rep.Hold, r.charges())
}
}
@@ -269,7 +271,7 @@ func TestPiReviewWithoutLeaveToSpend(t *testing.T) {
// the next Review is held (deferred), not run.
func TestPiBudgetHoldsTheNextStep(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1})
- leave(t)
+ r.urgent()
if rep := r.runReview("", 1); rep.State != wire.StepDone {
t.Fatalf("first: %+v", rep)
}
@@ -283,7 +285,7 @@ func TestPiBudgetHoldsTheNextStep(t *testing.T) {
// the connection: spend unknown, and nothing more is admitted.
func TestPiNoUsagePausesTheConnection(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
rep := r.runReview("nousage", 1)
if rep.State != wire.StepFailed || !r.conn().SpendUnknown || !r.slotFree() {
t.Fatalf("report %s %s, spend unknown %v slot free %v", rep.State, rep.Reason, r.conn().SpendUnknown, r.slotFree())
@@ -297,7 +299,7 @@ func TestPiNoUsagePausesTheConnection(t *testing.T) {
// the connection refused: sign in again, never limited.
func TestPiKeyRefused(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
rep := r.runReview("keyrefused", 1)
if rep.State == wire.StepDone || !r.conn().Refused {
t.Fatalf("report %+v, refused %v", rep, r.conn().Refused)
@@ -316,7 +318,7 @@ func TestPiReviewStepRealPi(t *testing.T) {
testPiCA = func() string { return tensorx.CA }
t.Cleanup(func() { testPiCA = was })
r := newPiRig(t, inst, bigBudget)
- leave(t)
+ r.urgent()
rep := r.runReview("", 1)
if rep.State != wire.StepDone || rep.Verdict != wire.VerdictApprove || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || !strings.Contains(rep.Summary, "TensorX") {
t.Fatalf("report %+v", rep)
@@ -368,7 +370,7 @@ func (w testWriter) Write(p []byte) (int, error) {
// answer charged.
func TestPiAskKeptSession(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
rep := r.runReview("", 1)
if !rep.Askable {
t.Fatalf("not askable: %+v", rep)
@@ -430,7 +432,7 @@ func TestPiEngineeringRun(t *testing.T) {
// answered.
func TestPiReviewFamilyFromTheModelThatRan(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
r.review.AvoidAccount = piLocal
if rep := r.runReview("", 1); rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewSameAccount || rep.Family != "glm" {
t.Fatalf("same model: %+v", rep)
@@ -445,7 +447,7 @@ func TestPiReviewFamilyFromTheModelThatRan(t *testing.T) {
// about is refused, and the step goes on.
func TestPiStepRefusesAsks(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
rep := r.runReview("read:/etc/hostname", 1)
if rep.State != wire.StepDone || !strings.Contains(rep.LogTail, "Refused a call") || !strings.Contains(rep.LogTail, "read /etc/hostname refused") {
t.Fatalf("report %+v", rep)
@@ -456,11 +458,11 @@ func TestPiStepRefusesAsks(t *testing.T) {
// budget, which the Review before it reached.
func TestPiEngineeringHeldIsDeferred(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1})
- leave(t)
+ r.urgent()
if rep := r.runReview("", 1); rep.State != wire.StepDone {
t.Fatalf("review: %+v", rep)
}
- row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk5", StepID: "en5", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: r.review.Repo, Branch: "equipo/tk5-x", BaseSHA: r.review.BaseSHA, Title: "Do the thing", Findings: []wire.Finding{}}}
+ row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk5", StepID: "en5", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: r.review.Repo, Branch: "equipo/tk5-x", BaseSHA: r.review.BaseSHA, Title: "Do the thing", Findings: []wire.Finding{}, Priority: r.review.Priority}}
if err := r.state.AcceptDispatch(r.ctx, "f-en5", row.DispatchCommand); err != nil {
t.Fatal(err)
}
@@ -475,7 +477,7 @@ func TestPiEngineeringHeldIsDeferred(t *testing.T) {
// spend too, never a charge of zero.
func TestPiEndWithoutUsagePausesTheConnection(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
r.runReview("endnousage", 1)
if !r.conn().SpendUnknown || !r.slotFree() {
t.Fatalf("spend unknown %v, slot free %v", r.conn().SpendUnknown, r.slotFree())
@@ -490,7 +492,7 @@ func TestPiOversizedReply(t *testing.T) {
piTextLimit = 1000
t.Cleanup(func() { piTextLimit = was })
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
rep := r.runReview("flood:50000", 1)
if !strings.Contains(rep.LogTail, "The reply was too long") || !r.conn().SpendUnknown || len(rep.Summary) > 1000 {
t.Fatalf("report %s %s summary %d, spend unknown %v", rep.State, rep.Reason, len(rep.Summary), r.conn().SpendUnknown)
@@ -503,7 +505,7 @@ func TestPiOversizedReply(t *testing.T) {
// tail and the step's log.
func TestPiRedactsTheKey(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), bigBudget)
- leave(t)
+ r.urgent()
var logs strings.Builder
r.e.O.Logger = slog.New(slog.NewTextHandler(&logs, nil))
rep := r.runReview("echokey", 1)
@@ -533,7 +535,7 @@ func TestPiRedactsTheKey(t *testing.T) {
// budget), the round is held on it, never moved.
func TestPiKeptSessionStaysPut(t *testing.T) {
r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1})
- leave(t)
+ r.urgent()
// Round 0 ran on TensorX and kept its Pi session.
dir := filepath.Join(t.TempDir(), "kept")
os.MkdirAll(dir, 0700)
@@ -551,17 +553,20 @@ func TestPiKeptSessionStaysPut(t *testing.T) {
if _, _, err := r.conns.Choose(r.ctx, connPerson, connect.RoleEngineering, "", nil); err != nil {
t.Fatalf("Claude is not usable: %v", err)
}
- row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk7", StepID: "e1", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: r.review.Repo, Branch: "equipo/tk7-x", BaseSHA: base, Round: 1, Feedback: "Fix round 1 of 2. Review asked for changes.", Findings: []wire.Finding{}}, Base: base}
+ row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk7", StepID: "e1", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: r.review.Repo, Branch: "equipo/tk7-x", BaseSHA: base, Round: 1, Feedback: "Fix round 1 of 2. Review asked for changes.", Findings: []wire.Finding{}, Priority: r.review.Priority}, Base: base}
plan := func() (string, bool) {
t.Helper()
kept, ok := r.e.fixSession(r.ctx, row, base)
if !ok {
t.Fatal("the kept Pi session was not found")
}
- b, resume, err := r.e.fixPlan(r.ctx, row, nil, kept, ok)
+ b, resume, hold, _, err := r.e.fixPlan(r.ctx, row, nil, kept, ok)
if err != nil {
t.Fatal(err)
}
+ if hold != nil {
+ return hold.Connection, false
+ }
return b.ID, resume
}
if id, resume := plan(); id != piLocal || !resume {
diff --git a/internal/runner/thin/research.go b/internal/runner/thin/research.go
index 076731ca..b27fe573 100644
--- a/internal/runner/thin/research.go
+++ b/internal/runner/thin/research.go
@@ -293,7 +293,12 @@ func (e *Engineer) research(ctx context.Context, r stepRow, progress func(wire.S
return fail("policy_rejected")
}
plan.Instance, plan.Forge = instanceHost(e.O.Runner.Origin), researchForgeHost
- b, err := e.researcher(ctx, r.Person)
+ b, hold, err := e.researcher(ctx, r)
+ if hold != nil {
+ // The scheduler holds it: queued and never authorized, it goes on
+ // its own at its wake-up or when a fact changes.
+ return heldReport(rep, hold)
+ }
if errors.Is(err, ErrNoConnection) {
// Nothing can read the pages now: the step waits, queued and never
// authorized (the instance can still cancel it as queued), and goes
@@ -392,33 +397,35 @@ func (e *Engineer) research(ctx context.Context, r stepRow, progress func(wire.S
return rep
}
-// researcher is the connection the Research model runs on: any healthy
-// one, the coordinator's family first.
-func (e *Engineer) researcher(ctx context.Context, person string) (runner.AccountBinding, error) {
+// researcher admits the Research model through the scheduler: the
+// coordinator's family first (only its connections), then any. Research
+// runs on subscriptions only (never metered).
+func (e *Engineer) researcher(ctx context.Context, r stepRow) (runner.AccountBinding, *wire.StepHold, error) {
if e.Conns == nil {
- return SelectAccount(e.O.Runner, person)
+ b, err := SelectAccount(e.O.Runner, r.Person)
+ return b, nil, err
}
- current, _ := e.O.State.meta(ctx, "conn:"+person)
+ current, _ := e.O.State.meta(ctx, "conn:"+r.Person)
family := ""
- for _, c := range e.Conns.Mine(person) {
+ for _, c := range e.Conns.Mine(r.Person) {
if c.ID == current {
family = c.Family
}
}
if family != "" {
var others []string
- for _, c := range e.Conns.Mine(person) {
+ for _, c := range e.Conns.Mine(r.Person) {
if c.Family != family {
others = append(others, c.ID)
}
}
- b, _, err := e.Conns.Choose(ctx, person, connect.RoleResearch, "", others)
- if !errors.Is(err, ErrNoConnection) {
- return b, err
+ b, hold, _, err := e.Conns.admit(ctx, r, connect.RoleResearch, "", others, nil)
+ if err != nil || hold == nil {
+ return b, nil, err
}
}
- b, _, err := e.Conns.Choose(ctx, person, connect.RoleResearch, "", nil)
- return b, err
+ b, hold, _, err := e.Conns.admit(ctx, r, connect.RoleResearch, "", nil, nil)
+ return b, hold, err
}
// researchAttemptDir is a fresh private directory for the attempt's
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index e58f3ee2..55f64bcc 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -346,6 +346,8 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
steps.MeteredAsk = engineer.askPi
wake := steps.MeteredChanged
wakeSteps.Store(&wake)
+ // A new reading wakes the steps the scheduler holds.
+ conns.Readings = steps.MeteredChanged
if err = steps.Start(ctx); err != nil {
return err
}
diff --git a/internal/runner/thin/schedule.go b/internal/runner/thin/schedule.go
new file mode 100644
index 00000000..f8c43848
--- /dev/null
+++ b/internal/runner/thin/schedule.go
@@ -0,0 +1,617 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "reflect"
+ "slices"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/connect"
+ "amadan.net/oficina/equipo/internal/runner/metered"
+ "amadan.net/oficina/equipo/internal/schedule"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The scheduler on the runner (connectors spec 2026-11-12 rev 3.1, §7
+// and §8, slice S3). Every Engineering, Review and Research attempt,
+// failover included, is admitted through schedule.Decide: its readings
+// refreshed first (outside the call), the admission written in one
+// thin.db transaction that reads the facts again and calls Decide again
+// when they changed, a pending Run now consumed in that same transaction
+// and kept as a grant for the step revision. A held step keeps its hold
+// with its wake-up, is reported once per hold, and is looked at again at
+// the wake-up and on any fact change. A question never comes here: it
+// stays on its step's session and passes S1's metered guard.
+
+const scheduleSchema = `
+CREATE TABLE IF NOT EXISTS releases (id TEXT PRIMARY KEY, person TEXT NOT NULL, task_id TEXT NOT NULL, step_id TEXT NOT NULL, step_revision INTEGER NOT NULL, state TEXT NOT NULL, at TEXT NOT NULL);
+CREATE TABLE IF NOT EXISTS grants (step_id TEXT NOT NULL, step_revision INTEGER NOT NULL, release_id TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (step_id, step_revision));
+CREATE TABLE IF NOT EXISTS admissions (step_id TEXT NOT NULL, attempt INTEGER NOT NULL, step_revision INTEGER NOT NULL, connection TEXT NOT NULL, reason TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (step_id, attempt));
+CREATE TABLE IF NOT EXISTS task_priority (task_id TEXT PRIMARY KEY, person TEXT NOT NULL, priority TEXT NOT NULL, by_at TEXT NOT NULL, revision INTEGER NOT NULL);
+`
+
+// Release states: written by the release frame, consumed by the
+// admission it causes, or ignored (stale, or its step revision already
+// holds a grant).
+const (
+ releasePending = "pending"
+ releaseConsumed = "consumed"
+ releaseIgnored = "ignored"
+)
+
+// staleAfter is how old a reading may be before it is refreshed (§6).
+const staleAfter = 15 * time.Minute
+
+// admitRetries bounds how often an admission whose facts moved under it
+// decides again before the step is held briefly.
+const admitRetries = 4
+
+// errFactsMoved: the facts Decide read changed before the admission
+// committed; it decides again.
+var errFactsMoved = errors.New("the scheduler's facts changed")
+
+// priorityRank orders the steps a runner holds (§7, release order):
+// urgent, then a deadline (earliest first), then normal, then low.
+func priorityRank(priority string, by *time.Time) int {
+ switch {
+ case priority == wire.PriorityUrgent:
+ return 0
+ case by != nil:
+ return 1
+ case priority == wire.PriorityLow:
+ return 3
+ }
+ return 2
+}
+
+func byStamp(by *time.Time) string {
+ if by == nil {
+ return ""
+ }
+ return by.UTC().Format(time.RFC3339)
+}
+
+func parseBy(v string) *time.Time {
+ if v == "" {
+ return nil
+ }
+ t, err := time.Parse(time.RFC3339, v)
+ if err != nil {
+ return nil
+ }
+ return &t
+}
+
+// stepFacts are the step's own scheduler facts as the runner holds them.
+type stepFacts struct {
+ priority string
+ by *time.Time
+ deadlineNotified bool
+ revision int64
+ // release is the grant or pending release this step revision has
+ // ("" none); pending: not consumed yet.
+ release string
+ pending bool
+}
+
+type querier interface {
+ QueryContext(context.Context, string, ...any) (*sql.Rows, error)
+ QueryRowContext(context.Context, string, ...any) *sql.Row
+}
+
+// readStepFacts reads a step's priority, deadline, revision and leave.
+func readStepFacts(ctx context.Context, q querier, r stepRow) (stepFacts, error) {
+ var f stepFacts
+ var by string
+ var notified int
+ err := q.QueryRowContext(ctx, "SELECT priority, by_at, deadline_notified, revision FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&f.priority, &by, &notified, &f.revision)
+ if errors.Is(err, sql.ErrNoRows) {
+ // Not held in the table (a test calling a step function directly):
+ // the dispatch's own facts.
+ f.priority, f.by, f.revision = r.Priority, r.By, r.Attempt
+ err = nil
+ }
+ if err != nil {
+ return f, err
+ }
+ if f.by == nil {
+ f.by = parseBy(by)
+ }
+ f.deadlineNotified = notified == 1
+ if f.revision == 0 {
+ f.revision = r.Attempt
+ }
+ err = q.QueryRowContext(ctx, "SELECT release_id FROM grants WHERE step_id=? AND step_revision=?", r.StepID, f.revision).Scan(&f.release)
+ if errors.Is(err, sql.ErrNoRows) {
+ err = q.QueryRowContext(ctx, "SELECT id FROM releases WHERE step_id=? AND step_revision=? AND state=? ORDER BY at, id LIMIT 1", r.StepID, f.revision, releasePending).Scan(&f.release)
+ f.pending = err == nil
+ if errors.Is(err, sql.ErrNoRows) {
+ err = nil
+ }
+ }
+ return f, err
+}
+
+// readings are one subscription connection's facts from thin.db.
+type reading struct {
+ state, resets, headroom string
+ updated string
+ validated bool
+}
+
+// scheduleFacts are the person's connections on this runner as Decide
+// reads them, from q (thin.db, or the admission's transaction), with the
+// bindings they stand for. Bindings come from the bindings file and the
+// metered table, facts from thin.db only.
+func (c *Conns) scheduleFacts(ctx context.Context, q querier, person, role string, now time.Time) ([]schedule.Conn, map[string]runner.AccountBinding, error) {
+ out := []schedule.Conn{}
+ by := map[string]runner.AccountBinding{}
+ for _, b := range c.Mine(person) {
+ var rd reading
+ err := q.QueryRowContext(ctx, "SELECT state, resets_at, headroom, updated_at FROM conn_state WHERE id=?", b.ID).Scan(&rd.state, &rd.resets, &rd.headroom, &rd.updated)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return nil, nil, err
+ }
+ var at string
+ err = q.QueryRowContext(ctx, "SELECT at FROM conn_validated WHERE id=?", b.ID).Scan(&at)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return nil, nil, err
+ }
+ rd.validated = at != ""
+ sc := schedule.Conn{ID: b.ID, Provider: b.Provider, Family: b.Family, Account: b.AccountID, Billing: schedule.Subscription, Capable: connect.Capable(b.Provider, role), State: rd.state}
+ if b.Kind == wire.KindToken && !rd.validated {
+ // Never answered a real request: not a connection yet.
+ sc.State = ""
+ }
+ if t, err := time.Parse(time.RFC3339Nano, rd.resets); err == nil && sc.State == wire.ConnLimited {
+ sc.LimitedUntil = t
+ }
+ if rd.headroom != "" {
+ var h wire.Headroom
+ if json.Unmarshal([]byte(rd.headroom), &h) == nil {
+ sc.Windows = windowsOf(&h)
+ }
+ }
+ out = append(out, sc)
+ by[b.ID] = b
+ }
+ if c.Meter != nil {
+ conns, err := metered.List(ctx, q)
+ if err != nil {
+ return nil, nil, err
+ }
+ for _, m := range conns {
+ if m.Person != person || !m.Validated || m.Retiring || m.Harness != wire.HarnessPi {
+ continue
+ }
+ b := meteredBinding(m)
+ spend, err := metered.SpendOf(ctx, q, m, now)
+ if err != nil {
+ return nil, nil, err
+ }
+ sc := schedule.Conn{ID: b.ID, Provider: b.Provider, Family: b.Family, Account: b.AccountID, Billing: schedule.Metered, Capable: connect.Capable(wire.HarnessPi, role), State: wire.ConnHealthy, Busy: spend.Running, SpendUnknown: spend.Unknown, SpendDay: spend.Day, SpendMonth: spend.Month, BudgetDay: m.Budget.Day, BudgetMonth: m.Budget.Month}
+ if m.Refused {
+ sc.State = wire.ConnSignInAgain
+ }
+ var state, resets string
+ if err := q.QueryRowContext(ctx, "SELECT state, resets_at FROM conn_state WHERE id=?", b.ID).Scan(&state, &resets); err == nil && (state == wire.ConnLimited || state == wire.ConnSignInAgain) {
+ sc.State = state
+ if t, err := time.Parse(time.RFC3339Nano, resets); err == nil {
+ sc.LimitedUntil = t
+ }
+ } else if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return nil, nil, err
+ }
+ out = append(out, sc)
+ by[b.ID] = b
+ }
+ }
+ return out, by, nil
+}
+
+// windowsOf are a reading's windows, used from 0 to 1. Claude's one
+// figure, when it gave no windows, is one window.
+func windowsOf(h *wire.Headroom) []schedule.Window {
+ var out []schedule.Window
+ for _, w := range h.Windows {
+ out = append(out, schedule.Window{Name: w.Name, Used: w.UsedPercent / 100, Minutes: w.Minutes, ResetsAt: w.ResetsAt})
+ }
+ if len(out) == 0 && h.Utilization != nil {
+ out = append(out, schedule.Window{Name: "utilization", Used: *h.Utilization, ResetsAt: h.ResetsAt})
+ }
+ return out
+}
+
+// refreshReadings checks the person's connections before a decision
+// (outside it): one never checked is checked now, as the choice always
+// did, and a reading older than fifteen minutes is refreshed by the
+// connection's reading probe when it has one (at most once per fifteen
+// minutes each). A reading that cannot be refreshed stays as it was
+// read; a window past its reset counts as not reported in Decide.
+func (c *Conns) refreshReadings(ctx context.Context, person, role string) {
+ if err := c.load(ctx); err != nil {
+ return
+ }
+ now := c.clock()
+ for _, b := range c.Mine(person) {
+ if !connect.Capable(b.Provider, role) {
+ continue
+ }
+ c.mu.Lock()
+ cs, known := c.live[b.ID]
+ unknown := cs.State == ""
+ c.mu.Unlock()
+ if unknown {
+ c.checkOne(ctx, b)
+ continue
+ }
+ if c.Reading == nil || !known {
+ continue
+ }
+ var updated string
+ _ = c.State.db.QueryRowContext(ctx, "SELECT updated_at FROM conn_state WHERE id=?", b.ID).Scan(&updated)
+ at, err := time.Parse(time.RFC3339Nano, updated)
+ if err == nil && now.Sub(at) < staleAfter {
+ continue
+ }
+ c.mu.Lock()
+ if c.probed == nil {
+ c.probed = map[string]time.Time{}
+ }
+ last := c.probed[b.ID]
+ due := last.IsZero() || now.Sub(last) >= staleAfter
+ if due {
+ c.probed[b.ID] = now
+ }
+ c.mu.Unlock()
+ if !due {
+ continue
+ }
+ l, err := c.Reading(ctx, b)
+ if err != nil || l == nil {
+ continue
+ }
+ c.Observe(b.ID, *l, "")
+ }
+}
+
+// decision is one scheduling decision: what Decide read and said, and
+// the binding it chose (a run) or names (a hold).
+type decision struct {
+ in schedule.Input
+ d schedule.Decision
+ step stepFacts
+ binding runner.AccountBinding
+ by map[string]runner.AccountBinding
+}
+
+// hold is the decision's hold as the step reports it.
+func (d decision) hold() *wire.StepHold {
+ if d.d.Run {
+ return nil
+ }
+ h := &wire.StepHold{Reason: d.d.Reason, Connection: d.d.Connection, ResetsAt: d.d.ResetsAt, WakeAt: d.d.WakeAt, NeedsPerson: d.d.NeedsPerson, StepRevision: d.step.revision}
+ if b, ok := d.by[d.d.Connection]; ok {
+ h.Provider = b.Provider
+ }
+ return h
+}
+
+// stepInput is a step's Decide input from the facts.
+func (c *Conns) stepInput(ctx context.Context, q querier, r stepRow, role, kept string, avoid []string, eng *runner.AccountBinding, now time.Time) (decision, error) {
+ f, err := readStepFacts(ctx, q, r)
+ if err != nil {
+ return decision{}, err
+ }
+ cs, by, err := c.scheduleFacts(ctx, q, r.Person, role, now)
+ if err != nil {
+ return decision{}, err
+ }
+ pref, err := c.preferenceIn(ctx, q, r.Person)
+ if err != nil {
+ return decision{}, err
+ }
+ in := schedule.Input{Version: schedule.Version, Now: now, Conns: cs, Preference: schedule.Preference{Provider: pref.Provider, Until: pref.Until}, Step: schedule.Step{Role: role, Priority: f.priority, By: f.by, DeadlineNotified: f.deadlineNotified, Kept: kept, Avoid: slices.Clone(avoid), Release: f.release}}
+ if eng != nil {
+ in.Step.Engineer = &schedule.Engineer{ID: eng.ID, Family: eng.Family, Account: eng.AccountID}
+ }
+ return decision{in: in, step: f, by: by}, nil
+}
+
+// decide refreshes the person's readings, then decides the step.
+func (c *Conns) decide(ctx context.Context, r stepRow, role, kept string, avoid []string, eng *runner.AccountBinding) (decision, error) {
+ if err := c.load(ctx); err != nil {
+ return decision{}, err
+ }
+ c.refreshReadings(ctx, r.Person, role)
+ d, err := c.stepInput(ctx, c.State.db, r, role, kept, avoid, eng, c.clock())
+ if err != nil {
+ return d, err
+ }
+ d.d = schedule.Decide(d.in)
+ if d.d.Run {
+ d.binding = d.by[d.d.Connection]
+ }
+ return d, nil
+}
+
+// admitTx writes the admission in t (the caller's transaction: thin.db's
+// for a subscription, the metered guard's for a metered connection): the
+// facts read again and compared with what Decide read, the step's
+// pending release consumed and kept as a grant for its revision, the
+// admission row, and the step's hold cleared. errFactsMoved: decide
+// again.
+func (c *Conns) admitTx(ctx context.Context, t *sql.Tx, r stepRow, d decision) error {
+ again, err := c.stepInput(ctx, t, r, d.in.Step.Role, d.in.Step.Kept, d.in.Step.Avoid, nil, d.in.Now)
+ if err != nil {
+ return err
+ }
+ if !sameFacts(again.in.Conns, d.in.Conns, d.d.Connection) || again.step.release != d.step.release || again.step.priority != d.step.priority || !reflect.DeepEqual(again.in.Preference, d.in.Preference) {
+ return errFactsMoved
+ }
+ if d.step.release != "" && d.step.pending {
+ res, err := t.ExecContext(ctx, "UPDATE releases SET state=? WHERE id=? AND state=?", releaseConsumed, d.step.release, releasePending)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n != 1 {
+ return errFactsMoved
+ }
+ // The grant: one per step revision, so a replayed release finds it
+ // and starts nothing.
+ if _, err := t.ExecContext(ctx, "INSERT INTO grants(step_id, step_revision, release_id, at) VALUES(?,?,?,?)", r.StepID, d.step.revision, d.step.release, now()); err != nil {
+ return err
+ }
+ }
+ if _, err := t.ExecContext(ctx, "INSERT INTO admissions(step_id, attempt, step_revision, connection, reason, at) VALUES(?,?,?,?,?,?) ON CONFLICT(step_id, attempt) DO UPDATE SET connection=excluded.connection, reason=excluded.reason, at=excluded.at", r.StepID, r.Attempt, d.step.revision, d.d.Connection, d.d.Reason, now()); err != nil {
+ return err
+ }
+ _, err = t.ExecContext(ctx, "UPDATE steps SET hold='', not_before='' WHERE step_id=? AND attempt=? AND state=?", r.StepID, r.Attempt, runRunning)
+ return err
+}
+
+// sameFacts compares two readings of the connections. A metered
+// connection's slot is the guard's to recheck (the admitting attempt's
+// own claim is in it by then), so Busy is not compared.
+func sameFacts(a, b []schedule.Conn, _ string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ x, y := a[i], b[i]
+ x.Busy, y.Busy = false, false
+ if !reflect.DeepEqual(x, y) {
+ return false
+ }
+ }
+ return true
+}
+
+// admitFunc is an admission to write in the metered guard's
+// transaction (nil: nothing to write).
+type admitFunc func(context.Context, *sql.Tx) error
+
+// admit decides the step and, for a subscription, writes its admission;
+// for a metered connection it returns the admission for runPi to write in
+// the guard's transaction. A held step returns its hold. Decided again
+// while the facts move under it, at most admitRetries times.
+func (c *Conns) admit(ctx context.Context, r stepRow, role, kept string, avoid []string, eng *runner.AccountBinding) (runner.AccountBinding, *wire.StepHold, admitFunc, error) {
+ for range admitRetries {
+ d, err := c.decide(ctx, r, role, kept, avoid, eng)
+ if err != nil {
+ return runner.AccountBinding{}, nil, nil, err
+ }
+ if !d.d.Run {
+ return runner.AccountBinding{}, d.hold(), nil, nil
+ }
+ if Metered(d.binding) {
+ return d.binding, nil, func(ctx context.Context, t *sql.Tx) error { return c.admitTx(ctx, t, r, d) }, nil
+ }
+ err = c.State.tx(ctx, func(t *sql.Tx) error { return c.admitTx(ctx, t, r, d) })
+ if errors.Is(err, errFactsMoved) {
+ continue
+ }
+ return d.binding, nil, nil, err
+ }
+ // The facts kept moving: held briefly, then looked at again.
+ wake := c.clock().Add(heldRetry)
+ return runner.AccountBinding{}, &wire.StepHold{Reason: wire.HoldBusy, WakeAt: &wake}, nil, nil
+}
+
+// heldReport is a step's held report: running (the instance keeps it
+// queued until it starts), with its hold, and the state that tells
+// runOne to keep it held.
+func heldReport(rep wire.StepReport, h *wire.StepHold) wire.StepReport {
+ rep.State, rep.Hold = stepDeferred, h
+ return rep
+}
+
+// heldGuard is a step the metered guard held at its admission: held
+// with the guard's reason on that connection (deferred, as before, when
+// it gave none).
+func heldGuard(rep wire.StepReport, res stepResult) wire.StepReport {
+ if res.hold == nil {
+ rep.State = stepDeferred
+ return rep
+ }
+ h := *res.hold
+ return heldReport(rep, &h)
+}
+
+// holdStep keeps a held step's hold and its wake-up (until a fact
+// changes when it has none), recording that the deadline check fired.
+// It reports whether the hold is not the one the step had (said once per
+// hold, not at every look).
+func (s *State) holdStep(ctx context.Context, r stepRow, h *wire.StepHold) (bool, error) {
+ at := heldUntilChange
+ if h.WakeAt != nil {
+ at = stamp(*h.WakeAt)
+ }
+ changed := false
+ err := s.tx(ctx, func(t *sql.Tx) error {
+ if h.StepRevision == 0 {
+ // The guard's hold: the step revision a Run now names.
+ if err := t.QueryRowContext(ctx, "SELECT revision FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&h.StepRevision); err != nil {
+ return err
+ }
+ }
+ raw, err := json.Marshal(h)
+ if err != nil {
+ return err
+ }
+ var was string
+ if err := t.QueryRowContext(ctx, "SELECT hold FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&was); err != nil {
+ return err
+ }
+ // Said again only when what it says moved: its wake-up alone is
+ // the runner's to keep.
+ var prev wire.StepHold
+ _ = json.Unmarshal([]byte(was), &prev)
+ prev.WakeAt, h.WakeAt = nil, nil
+ a, _ := json.Marshal(prev)
+ b, _ := json.Marshal(h)
+ changed = was == "" || string(a) != string(b)
+ h.WakeAt = parseWake(at)
+ notified := 0
+ if h.NeedsPerson == wire.HoldNeedsDeadline {
+ notified = 1
+ }
+ _, err = t.ExecContext(ctx, "UPDATE steps SET hold=?, not_before=?, deadline_notified=MAX(deadline_notified, ?), deferred_since=CASE WHEN deferred_since='' THEN ? ELSE deferred_since END WHERE step_id=? AND attempt=? AND state=?", string(raw), at, notified, stamp(time.Now()), r.StepID, r.Attempt, runRunning)
+ return err
+ })
+ return changed, err
+}
+
+// parseWake is a not_before stamp as a time (nil: until a change).
+func parseWake(at string) *time.Time {
+ if at == heldUntilChange {
+ return nil
+ }
+ var ms int64
+ if _, err := fmt.Sscanf(at, "%d", &ms); err != nil {
+ return nil
+ }
+ t := time.UnixMilli(ms).UTC()
+ return &t
+}
+
+// Release applies a Run now (the durable release frame, once): kept as a
+// pending release for a step this runner holds at that step revision,
+// for that person; acked and ignored when the step is not held at that
+// revision any more, or its revision already holds a grant (a replay).
+func (s *State) Release(ctx context.Context, frameID string, cmd wire.ReleaseCommand) (bool, error) {
+ kept := false
+ err := s.tx(ctx, func(t *sql.Tx) error {
+ fresh, err := seen(t, frameID)
+ if err != nil || !fresh {
+ return err
+ }
+ state := releaseIgnored
+ var n int
+ if err := t.QueryRowContext(ctx, "SELECT count(*) FROM steps WHERE step_id=? AND task_id=? AND person=? AND revision=? AND state=?", cmd.StepID, cmd.TaskID, cmd.Person, cmd.StepRevision, runRunning).Scan(&n); err != nil {
+ return err
+ }
+ var granted int
+ if err := t.QueryRowContext(ctx, "SELECT count(*) FROM grants WHERE step_id=? AND step_revision=?", cmd.StepID, cmd.StepRevision).Scan(&granted); err != nil {
+ return err
+ }
+ if n > 0 && granted == 0 {
+ state, kept = releasePending, true
+ }
+ _, err = t.ExecContext(ctx, "INSERT INTO releases(id, person, task_id, step_id, step_revision, state, at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING", cmd.ID, cmd.Person, cmd.TaskID, cmd.StepID, cmd.StepRevision, state, now())
+ return err
+ })
+ return kept, err
+}
+
+// SetPriority applies a task's priority change (the durable priority
+// frame, once) to the steps of the task this runner holds, above the
+// revision held.
+func (s *State) SetPriority(ctx context.Context, frameID string, cmd wire.PriorityCommand) (bool, error) {
+ if !wire.ValidPriority(cmd.Priority) {
+ return false, nil
+ }
+ applied := false
+ err := s.tx(ctx, func(t *sql.Tx) error {
+ fresh, err := seen(t, frameID)
+ if err != nil || !fresh {
+ return err
+ }
+ var held int64
+ err = t.QueryRowContext(ctx, "SELECT revision FROM task_priority WHERE task_id=? AND person=?", cmd.TaskID, cmd.Person).Scan(&held)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
+ if cmd.Revision <= held {
+ return nil
+ }
+ if _, err = t.ExecContext(ctx, "INSERT INTO task_priority(task_id, person, priority, by_at, revision) VALUES(?,?,?,?,?) ON CONFLICT(task_id) DO UPDATE SET priority=excluded.priority, by_at=excluded.by_at, revision=excluded.revision", cmd.TaskID, cmd.Person, cmd.Priority, byStamp(cmd.By), cmd.Revision); err != nil {
+ return err
+ }
+ _, err = t.ExecContext(ctx, "UPDATE steps SET priority=?, by_at=?, rank=?, deadline_notified=CASE WHEN by_at=? THEN deadline_notified ELSE 0 END, not_before=CASE WHEN hold<>'' THEN '' ELSE not_before END WHERE task_id=? AND person=? AND state=?", cmd.Priority, byStamp(cmd.By), priorityRank(cmd.Priority, cmd.By), byStamp(cmd.By), cmd.TaskID, cmd.Person, runRunning)
+ applied = err == nil
+ return err
+ })
+ return applied, err
+}
+
+// acceptScheduled records a dispatch's scheduler facts in t: its step
+// revision (the attempt the instance sent), priority, deadline and rank,
+// a later priority change the runner already holds for the task, and a
+// release it carries.
+func acceptScheduled(t *sql.Tx, d wire.DispatchCommand) error {
+ priority, by := d.Priority, d.By
+ var held, heldBy string
+ err := t.QueryRow("SELECT priority, by_at FROM task_priority WHERE task_id=? AND person=?", d.TaskID, d.Person).Scan(&held, &heldBy)
+ switch {
+ case err == nil:
+ priority, by = held, parseBy(heldBy)
+ case !errors.Is(err, sql.ErrNoRows):
+ return err
+ }
+ if _, err := t.Exec("UPDATE steps SET revision=?, priority=?, by_at=?, rank=? WHERE step_id=? AND attempt=? AND revision=0", d.Attempt, priority, byStamp(by), priorityRank(priority, by), d.StepID, d.Attempt); err != nil {
+ return err
+ }
+ if d.Release == "" {
+ return nil
+ }
+ var granted int
+ if err := t.QueryRow("SELECT count(*) FROM grants WHERE step_id=? AND step_revision=?", d.StepID, d.Attempt).Scan(&granted); err != nil {
+ return err
+ }
+ state := releasePending
+ if granted > 0 {
+ state = releaseIgnored
+ }
+ _, err = t.Exec("INSERT INTO releases(id, person, task_id, step_id, step_revision, state, at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING", d.Release, d.Person, d.TaskID, d.StepID, d.Attempt, state, now())
+ return err
+}
+
+// wakeHeld makes every held step due now (a fact changed).
+func (s *State) wakeHeld(ctx context.Context) error {
+ _, err := s.db.ExecContext(ctx, "UPDATE steps SET not_before='' WHERE hold<>'' AND state=?", runRunning)
+ return err
+}
+
+// preferenceIn is the person's preference read from q; one whose end
+// has passed is Automatic.
+func (c *Conns) preferenceIn(ctx context.Context, q querier, person string) (wire.Preferences, error) {
+ var p wire.Preferences
+ var raw string
+ err := q.QueryRowContext(ctx, "SELECT value FROM meta WHERE key=?", "prefer:"+person).Scan(&raw)
+ if errors.Is(err, sql.ErrNoRows) || err == nil && raw == "" {
+ return p, nil
+ }
+ if err != nil {
+ return p, err
+ }
+ if err := json.Unmarshal([]byte(raw), &p); err != nil {
+ return p, fmt.Errorf("preference: %w", err)
+ }
+ return p, nil
+}
diff --git a/internal/runner/thin/schedule_test.go b/internal/runner/thin/schedule_test.go
new file mode 100644
index 00000000..da9e03b5
--- /dev/null
+++ b/internal/runner/thin/schedule_test.go
@@ -0,0 +1,475 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/connect"
+ "amadan.net/oficina/equipo/internal/runner/metered"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// schedRig is a runner's state with the person's connections (Claude
+// and Codex subscriptions, and a metered TensorX) and a step engine
+// whose step function admits through the scheduler the way Engineering,
+// Review and Research do: held, it reports its hold; admitted on a
+// metered connection, the admission commits with the guard's claim.
+type schedRig struct {
+ t *testing.T
+ ctx context.Context
+ state *State
+ conns *Conns
+ steps *StepEngine
+ mu sync.Mutex
+ // ran are the admitted attempts: step/attempt -> connection.
+ ran map[string]string
+ // fail makes an attempt on a connection refuse on quota once.
+ fail map[string]bool
+}
+
+func newSchedRig(t *testing.T, subs ...string) *schedRig {
+ t.Helper()
+ root := t.TempDir()
+ os.MkdirAll(filepath.Join(root, "state"), 0700)
+ state, err := OpenState(context.Background(), filepath.Join(root, "state"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { state.Close() })
+ var bs []map[string]any
+ for _, id := range subs {
+ provider := id[:len(id)-2]
+ bs = append(bs, map[string]any{"id": id, "local_id": id, "label": id, "person_id": connPerson, "provider": provider, "family": provider, "model": "m", "account_id": id + "@example.com", "provider_home": filepath.Join(root, id), "kind": "subscription", "expected_identity": map[string]string{"account_id": id + "@example.com", "home_id": "h", "provider_version": "1"}})
+ }
+ raw, _ := json.Marshal(bs)
+ bindings := filepath.Join(root, "bindings.json")
+ if err := os.WriteFile(bindings, raw, 0600); err != nil {
+ t.Fatal(err)
+ }
+ conns := &Conns{Runner: runner.Config{AccountBindingsPath: bindings, ClaudePath: "/bin/true", CodexPath: "/bin/true"}, State: state}
+ conns.Meter = &metered.Meter{DB: state.db}
+ ctx, cancel := context.WithCancel(context.Background())
+ r := &schedRig{t: t, ctx: ctx, state: state, conns: conns, ran: map[string]string{}, fail: map[string]bool{}}
+ r.steps = &StepEngine{State: state, Exec: r.exec, Notify: func() {}}
+ conns.Changed = r.steps.MeteredChanged
+ conns.Readings = r.steps.MeteredChanged
+ conns.Meter.Changed = r.steps.MeteredChanged
+ t.Cleanup(func() { cancel(); r.steps.Wait() })
+ return r
+}
+
+// reading records a subscription's reported windows (used 0 to 1, each
+// resetting at its time).
+func (r *schedRig) reading(id string, used float64, resets time.Time) {
+ r.conns.Observe(id, connect.Limit{Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "five_hour", UsedPercent: used * 100, Minutes: 300, ResetsAt: &resets}}}}, "")
+}
+
+// tensorx adds the person's validated metered connection.
+func (r *schedRig) tensorx(budget wire.Budget) {
+ err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
+ if err := metered.Add(r.ctx, tx, metered.Conn{Connection: "cn_tx", LocalID: piLocal, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: r.t.TempDir(), Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: budget}, time.Now()); err != nil {
+ return err
+ }
+ return metered.Checked(r.ctx, tx, piLocal, true)
+ })
+ if err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+// exec is the step function: admitted through the scheduler (failover
+// included, the refused connection avoided), or held.
+func (r *schedRig) exec(ctx context.Context, row stepRow, progress func(wire.StepReport)) wire.StepReport {
+ rep := wire.StepReport{TaskID: row.TaskID, StepID: row.StepID, Attempt: row.Attempt, Findings: []wire.Finding{}}
+ var avoid []string
+ for {
+ b, hold, admit, err := r.conns.admit(ctx, row, connect.RoleEngineering, "", avoid, nil)
+ if err != nil {
+ rep.State, rep.Reason, rep.Termination = wire.StepFailed, "account_unavailable", true
+ return rep
+ }
+ if hold != nil {
+ return heldReport(rep, hold)
+ }
+ if admit != nil {
+ h := metered.Holder{Step: row.StepID, Attempt: row.Attempt, Role: metered.RoleEngineering}
+ adm, err := r.conns.Meter.Admit(ctx, b.LocalID, h, func(t *sql.Tx) error { return admit(ctx, t) })
+ if err != nil || !adm.Admitted {
+ rep.State, rep.Reason, rep.Termination = wire.StepFailed, "metered_refused", true
+ return rep
+ }
+ _ = r.conns.Meter.Finish(ctx, b.LocalID, h, metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}}, nil)
+ }
+ r.mu.Lock()
+ r.ran[row.StepID+"/"+itoa(row.Attempt)] = b.ID
+ refuse := r.fail[b.ID]
+ delete(r.fail, b.ID)
+ r.mu.Unlock()
+ if !refuse {
+ rep.State, rep.Termination, rep.Account = wire.StepDone, true, b.ID
+ return rep
+ }
+ // Refused on quota, its exit proven: the next attempt, advanced
+ // durably, admitted with the refused connection avoided.
+ r.conns.Limit(b.ID, connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)})
+ if err := r.state.advanceStep(ctx, &row, nil, rep); err != nil {
+ r.t.Error(err)
+ return rep
+ }
+ rep.Attempt = row.Attempt
+ avoid = append(avoid, b.ID)
+ }
+}
+
+func (r *schedRig) dispatch(step string, priority string) {
+ r.t.Helper()
+ d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-" + step, StepID: step, Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: priority}
+ if err := r.state.AcceptDispatch(r.ctx, "f-"+step, d); err != nil {
+ r.t.Fatal(err)
+ }
+ r.steps.Wake()
+}
+
+func (r *schedRig) start() {
+ r.t.Helper()
+ if err := r.steps.Start(r.ctx); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+// reports are the step reports queued for the instance, oldest first.
+func (r *schedRig) reports(step string) []wire.StepReport {
+ r.t.Helper()
+ rows, err := r.state.db.Query("SELECT body FROM outbox WHERE kind=? ORDER BY seq", wire.FrameStep)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ defer rows.Close()
+ var out []wire.StepReport
+ for rows.Next() {
+ var body string
+ rows.Scan(&body)
+ var rep wire.StepReport
+ json.Unmarshal([]byte(body), &rep)
+ if rep.StepID == step {
+ out = append(out, rep)
+ }
+ }
+ return out
+}
+
+// until waits for cond, failing after d.
+func (r *schedRig) until(d time.Duration, what string, cond func() bool) {
+ r.t.Helper()
+ deadline := time.Now().Add(d)
+ for !cond() {
+ if time.Now().After(deadline) {
+ r.t.Fatalf("timed out waiting for %s", what)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+func (r *schedRig) ranOn(step string, attempt int64) string {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.ran[step+"/"+itoa(attempt)]
+}
+
+func (r *schedRig) final(step string) (wire.StepReport, bool) {
+ for _, rep := range r.reports(step) {
+ if wire.StepTerminal(rep.State) {
+ return rep, true
+ }
+ }
+ return wire.StepReport{}, false
+}
+
+// The S3 finish line: a low step holds at 0.61 and starts by itself
+// after the reset, its hold said once with a wake-up strictly in the
+// future; a held step never blocks one that can run.
+func TestScheduleLowHoldsThenStartsAfterReset(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ reset := time.Now().Add(900 * time.Millisecond)
+ r.reading("claude-a", 0.61, reset)
+ r.start()
+ before := time.Now()
+ r.dispatch("low1", wire.PriorityLow)
+ r.until(5*time.Second, "the hold", func() bool { return len(r.reports("low1")) > 0 })
+ held := r.reports("low1")[0]
+ if held.State != wire.StepRunning || held.Hold == nil || held.Hold.Reason != wire.HoldHeadroom || held.Hold.Connection != "claude-a" || held.Hold.Provider != "claude" || held.Hold.StepRevision != 1 {
+ t.Fatalf("held report %+v %+v", held, held.Hold)
+ }
+ if held.Hold.WakeAt == nil || !held.Hold.WakeAt.After(before) || held.Hold.WakeAt.Sub(reset).Abs() > time.Millisecond {
+ t.Fatalf("wake-up %v, reset %v", held.Hold.WakeAt, reset)
+ }
+ if r.ranOn("low1", 1) != "" {
+ t.Fatal("the low step ran at 0.61")
+ }
+ // A normal step runs meanwhile: the held one does not block it.
+ r.dispatch("normal1", wire.PriorityNormal)
+ r.until(5*time.Second, "the normal step", func() bool { _, ok := r.final("normal1"); return ok })
+ // Facts change (a reading that says the same): the step looks again
+ // and is held again, said only once.
+ for range 3 {
+ r.steps.MeteredChanged()
+ time.Sleep(30 * time.Millisecond)
+ }
+ if _, done := r.final("low1"); done {
+ t.Fatal("the low step ran before its reset")
+ }
+ r.until(5*time.Second, "the low step after the reset", func() bool { _, ok := r.final("low1"); return ok })
+ if !time.Now().After(reset) || r.ranOn("low1", 1) != "claude-a" {
+ t.Fatalf("ran on %q at %v (reset %v)", r.ranOn("low1", 1), time.Now(), reset)
+ }
+ holds := 0
+ for _, rep := range r.reports("low1") {
+ if rep.Hold != nil {
+ holds++
+ }
+ }
+ if holds != 1 {
+ t.Fatalf("the hold was said %d times", holds)
+ }
+ var reason string
+ if err := r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id=? AND attempt=1", "low1").Scan(&reason); err != nil || reason != "headroom" {
+ t.Fatalf("admission %q %v", reason, err)
+ }
+}
+
+// Run now: a release for the held step revision is consumed with the
+// admission it causes and becomes a grant (a normal step, so only the
+// release lets it spend on TensorX); a replayed release, and a release
+// for a stale step revision, start nothing.
+func TestScheduleReleaseOnceAndStaleRefused(t *testing.T) {
+ r := newSchedRig(t)
+ r.tensorx(bigBudget)
+ r.start()
+ r.dispatch("s1", wire.PriorityNormal)
+ r.until(5*time.Second, "the hold", func() bool { return len(r.reports("s1")) > 0 })
+ if h := r.reports("s1")[0].Hold; h == nil || h.Reason != wire.HoldNoConnection || h.NeedsPerson != wire.HoldNeedsNoConnection {
+ t.Fatalf("hold %+v", h)
+ }
+ // A stale step revision: acked and ignored; the step stays held.
+ if kept, err := r.state.Release(r.ctx, "fr-stale", wire.ReleaseCommand{ID: "rl_stale", Person: connPerson, TaskID: "tk-s1", StepID: "s1", StepRevision: 2}); err != nil || kept {
+ t.Fatalf("a stale release was kept: %v %v", kept, err)
+ }
+ // Another person's release for it: ignored too.
+ if kept, _ := r.state.Release(r.ctx, "fr-other", wire.ReleaseCommand{ID: "rl_other", Person: "q@example.com", TaskID: "tk-s1", StepID: "s1", StepRevision: 1}); kept {
+ t.Fatal("another person's release was kept")
+ }
+ r.steps.MeteredChanged()
+ time.Sleep(200 * time.Millisecond)
+ if _, done := r.final("s1"); done || r.ranOn("s1", 1) != "" {
+ t.Fatal("a stale release started the step")
+ }
+ if kept, err := r.state.Release(r.ctx, "fr-1", wire.ReleaseCommand{ID: "rl_1", Person: connPerson, TaskID: "tk-s1", StepID: "s1", StepRevision: 1}); err != nil || !kept {
+ t.Fatalf("release %v %v", kept, err)
+ }
+ r.steps.MeteredChanged()
+ r.until(5*time.Second, "the released step", func() bool { _, ok := r.final("s1"); return ok })
+ if r.ranOn("s1", 1) != piLocal {
+ t.Fatalf("ran on %q", r.ranOn("s1", 1))
+ }
+ var state, reason string
+ r.state.db.QueryRow("SELECT state FROM releases WHERE id='rl_1'").Scan(&state)
+ r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id='s1'").Scan(&reason)
+ var grants int
+ r.state.db.QueryRow("SELECT count(*) FROM grants WHERE step_id='s1' AND step_revision=1 AND release_id='rl_1'").Scan(&grants)
+ if state != releaseConsumed || reason != "metered_release" || grants != 1 {
+ t.Fatalf("release %q, admission %q, grants %d", state, reason, grants)
+ }
+ // Replayed: the same frame is seen; the same release under another
+ // frame id finds the grant. Neither starts anything.
+ for _, frame := range []string{"fr-1", "fr-1-again"} {
+ if kept, err := r.state.Release(r.ctx, frame, wire.ReleaseCommand{ID: "rl_1b", Person: connPerson, TaskID: "tk-s1", StepID: "s1", StepRevision: 1}); err != nil || kept {
+ t.Fatalf("a replayed release was kept (%s): %v", frame, err)
+ }
+ }
+ var admissions int
+ r.state.db.QueryRow("SELECT count(*) FROM admissions WHERE step_id='s1'").Scan(&admissions)
+ if admissions != 1 {
+ t.Fatalf("%d admissions", admissions)
+ }
+ // A step revision that holds a grant (its release consumed, the step
+ // still going: a failover attempt held on its budget) keeps no
+ // second release: the grant is the one key.
+ r.dispatch("s2", wire.PriorityNormal)
+ r.until(5*time.Second, "the second hold", func() bool { return len(r.reports("s2")) > 0 })
+ if _, err := r.state.db.Exec("INSERT INTO grants(step_id, step_revision, release_id, at) VALUES('s2', 1, 'rl_s2', '')"); err != nil {
+ t.Fatal(err)
+ }
+ if kept, err := r.state.Release(r.ctx, "fr-s2", wire.ReleaseCommand{ID: "rl_s2b", Person: connPerson, TaskID: "tk-s2", StepID: "s2", StepRevision: 1}); err != nil || kept {
+ t.Fatalf("a second release for a granted revision was kept: %v %v", kept, err)
+ }
+}
+
+// A failover attempt inside a grant is admitted: the released step's
+// first attempt starts on Claude above its normal threshold (a release is
+// urgent for thresholds), Claude refuses on quota, and the next attempt,
+// admitted with Claude avoided, goes to TensorX on the same grant.
+func TestScheduleFailoverInsideAGrant(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ r.tensorx(bigBudget)
+ r.reading("claude-a", 0.9, time.Now().Add(time.Hour))
+ r.fail["claude-a"] = true
+ r.start()
+ r.dispatch("f1", wire.PriorityNormal)
+ r.until(5*time.Second, "the hold", func() bool { return len(r.reports("f1")) > 0 })
+ if _, err := r.state.Release(r.ctx, "fr-f1", wire.ReleaseCommand{ID: "rl_f1", Person: connPerson, TaskID: "tk-f1", StepID: "f1", StepRevision: 1}); err != nil {
+ t.Fatal(err)
+ }
+ r.steps.MeteredChanged()
+ r.until(5*time.Second, "the step", func() bool { _, ok := r.final("f1"); return ok })
+ if r.ranOn("f1", 1) != "claude-a" || r.ranOn("f1", 2) != piLocal {
+ t.Fatalf("attempts on %q then %q", r.ranOn("f1", 1), r.ranOn("f1", 2))
+ }
+ var reason string
+ var revision int64
+ r.state.db.QueryRow("SELECT reason, step_revision FROM admissions WHERE step_id='f1' AND attempt=2").Scan(&reason, &revision)
+ if reason != "metered_release" || revision != 1 {
+ t.Fatalf("the failover attempt: %q revision %d", reason, revision)
+ }
+}
+
+// Without a release or urgent, a normal step never spends: it holds on
+// no_connection while the only connection that could run it is metered,
+// and an urgent priority change (the person's tap) lets it run.
+func TestSchedulePriorityChangeGivesLeave(t *testing.T) {
+ r := newSchedRig(t)
+ r.tensorx(bigBudget)
+ r.start()
+ r.dispatch("p1", wire.PriorityNormal)
+ r.until(5*time.Second, "the hold", func() bool { return len(r.reports("p1")) > 0 })
+ time.Sleep(100 * time.Millisecond)
+ if r.ranOn("p1", 1) != "" {
+ t.Fatal("a normal step spent")
+ }
+ if ok, err := r.state.SetPriority(r.ctx, "fp-1", wire.PriorityCommand{Person: connPerson, TaskID: "tk-p1", Priority: wire.PriorityUrgent, Revision: 2}); err != nil || !ok {
+ t.Fatalf("priority %v %v", ok, err)
+ }
+ // An older revision changes nothing.
+ if ok, _ := r.state.SetPriority(r.ctx, "fp-0", wire.PriorityCommand{Person: connPerson, TaskID: "tk-p1", Priority: wire.PriorityLow, Revision: 1}); ok {
+ t.Fatal("an older priority applied")
+ }
+ r.steps.MeteredChanged()
+ r.until(5*time.Second, "the urgent step", func() bool { _, ok := r.final("p1"); return ok })
+ var reason string
+ r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id='p1'").Scan(&reason)
+ if r.ranOn("p1", 1) != piLocal || reason != "metered_urgent" {
+ t.Fatalf("ran on %q, %q", r.ranOn("p1", 1), reason)
+ }
+}
+
+// The release order: urgent, then the earliest deadline, then normal,
+// then low, then the oldest.
+func TestScheduleReleaseOrder(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ soon, later := time.Now().Add(48*time.Hour), time.Now().Add(96*time.Hour)
+ for _, d := range []wire.DispatchCommand{
+ {StepID: "low", Priority: wire.PriorityLow},
+ {StepID: "normal-old", Priority: wire.PriorityNormal},
+ {StepID: "by-later", Priority: wire.PriorityLow, By: &later},
+ {StepID: "normal-new"},
+ {StepID: "by-soon", Priority: wire.PriorityNormal, By: &soon},
+ {StepID: "urgent", Priority: wire.PriorityUrgent},
+ } {
+ d.Person, d.TaskID, d.Attempt, d.Specialist, d.Findings = connPerson, "tk-"+d.StepID, 1, wire.SpecialistEngineering, []wire.Finding{}
+ if err := r.state.AcceptDispatch(r.ctx, "f-"+d.StepID, d); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(2 * time.Millisecond)
+ }
+ var order []string
+ for range 6 {
+ row, ok, err := r.state.nextStep(r.ctx)
+ if err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ order = append(order, row.StepID)
+ if _, err := r.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, row.StepID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ want := []string{"urgent", "by-soon", "by-later", "normal-old", "normal-new", "low"}
+ for i := range want {
+ if order[i] != want[i] {
+ t.Fatalf("order %v, want %v", order, want)
+ }
+ }
+}
+
+// The admission reads the facts again in its transaction: a reading that
+// moved after Decide read it refuses the admission (Decide runs again).
+func TestScheduleAdmissionRechecksFacts(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ r.reading("claude-a", 0.5, time.Now().Add(time.Hour))
+ row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}}
+ if err := r.state.AcceptDispatch(r.ctx, "f", row.DispatchCommand); err != nil {
+ t.Fatal(err)
+ }
+ d, err := r.conns.decide(r.ctx, row, connect.RoleEngineering, "", nil, nil)
+ if err != nil || !d.d.Run {
+ t.Fatalf("%+v %v", d.d, err)
+ }
+ r.reading("claude-a", 0.85, time.Now().Add(time.Hour))
+ if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return r.conns.admitTx(r.ctx, tx, row, d) }); !errors.Is(err, errFactsMoved) {
+ t.Fatalf("admitted on moved facts: %v", err)
+ }
+ // Decided again: held now.
+ _, hold, _, err := r.conns.admit(r.ctx, row, connect.RoleEngineering, "", nil, nil)
+ if err != nil || hold == nil || hold.Reason != wire.HoldHeadroom {
+ t.Fatalf("hold %+v %v", hold, err)
+ }
+}
+
+// A preference with an end is Automatic once the end passes.
+func TestPreferenceUntilEnds(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ until := time.Now().Add(time.Hour)
+ if err := r.conns.Prefer(r.ctx, "pf1", wire.PreferenceCommand{Person: connPerson, Provider: "codex", Revision: 1, Until: &until}); err != nil {
+ t.Fatal(err)
+ }
+ if p, _ := r.conns.Preference(r.ctx, connPerson); p.Provider != "codex" {
+ t.Fatalf("in force: %+v", p)
+ }
+ r.conns.now = func() time.Time { return until.Add(time.Second) }
+ if p, _ := r.conns.Preference(r.ctx, connPerson); p.Provider != "" {
+ t.Fatalf("after its end: %+v", p)
+ }
+}
+
+// A stale reading is refreshed by the connection's reading probe before
+// the decision (outside it), at most once per fifteen minutes.
+func TestScheduleRefreshesStaleReadings(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ r.reading("claude-a", 0.9, time.Now().Add(time.Hour))
+ probes := 0
+ r.conns.Reading = func(context.Context, runner.AccountBinding) (*connect.Limit, error) {
+ probes++
+ at := time.Now().Add(time.Hour)
+ return &connect.Limit{Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "five_hour", UsedPercent: 10, Minutes: 300, ResetsAt: &at}}}}, nil
+ }
+ row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}}
+ // Fresh: not probed, held at 0.9.
+ if d, _ := r.conns.decide(r.ctx, row, connect.RoleEngineering, "", nil, nil); d.d.Run || probes != 0 {
+ t.Fatalf("fresh reading: %+v, %d probes", d.d, probes)
+ }
+ r.conns.now = func() time.Time { return time.Now().Add(16 * time.Minute) }
+ if d, _ := r.conns.decide(r.ctx, row, connect.RoleEngineering, "", nil, nil); !d.d.Run || probes != 1 {
+ t.Fatalf("stale reading: %+v, %d probes", d.d, probes)
+ }
+ r.conns.now = func() time.Time { return time.Now().Add(20 * time.Minute) }
+ r.conns.decide(r.ctx, row, connect.RoleEngineering, "", nil, nil)
+ if probes != 1 {
+ t.Fatalf("probed %d times within fifteen minutes", probes)
+ }
+}
diff --git a/internal/runner/thin/spend.go b/internal/runner/thin/spend.go
index e13cb828..9aa741e9 100644
--- a/internal/runner/thin/spend.go
+++ b/internal/runner/thin/spend.go
@@ -1,20 +1,10 @@
package thin
-// leaveToSpend is a step's leave to spend metered money (connectors spec
-// §0 decision 5 and §7): an urgent task or a released step. Steps carry
-// neither until slice S3 adds priority and Run now, so it is false in
-// every release build: no step is chosen onto a metered connection. A
-// test build may grant it (spend_testbuild.go), for the Pi cells' tests.
-func leaveToSpend(r stepRow) bool {
- return testLeaveToSpend != nil && testLeaveToSpend(r)
-}
-
-// testLeaveToSpend is nil in every build but a test build.
-var testLeaveToSpend func(stepRow) bool
-
// piTestCA is a test build's certificate authority for a fake provider
// a real Pi talks to ("" in every release build: provider.BuildPiPolicy
-// refuses one there anyway).
+// refuses one there anyway). Leave to spend metered money is no seam: it
+// comes only from the step's own facts, an urgent task or a consumed Run
+// now (schedule.go).
func piTestCA() string {
if testPiCA == nil {
return ""
diff --git a/internal/runner/thin/spend_testbuild.go b/internal/runner/thin/spend_testbuild.go
index 9c678470..039aa5ba 100644
--- a/internal/runner/thin/spend_testbuild.go
+++ b/internal/runner/thin/spend_testbuild.go
@@ -4,12 +4,10 @@ package thin
import "os"
-// A test build grants leave to spend to every step while
-// EQUIPO_TEST_LEAVE_TO_SPEND is 1 (a real Pi Review on a fake TensorX,
-// before S3 gives steps their own leave). A release build never passes
-// -tags testbuild (scripts/no-fake-worker.sh refuses one that has it).
+// A test build reads the fake provider's certificate authority from
+// EQUIPO_TEST_PI_CA (a real Pi against a fake TensorX). A release build
+// never passes -tags testbuild (scripts/no-fake-worker.sh refuses one
+// that has a test build's markers).
func init() {
- testLeaveToSpend = func(stepRow) bool { return os.Getenv("EQUIPO_TEST_LEAVE_TO_SPEND") == "1" }
- // The fake provider's certificate authority (EQUIPO_TEST_PI_CA).
testPiCA = func() string { return os.Getenv("EQUIPO_TEST_PI_CA") }
}
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index e5eaa45a..0eeb44b9 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -55,7 +55,7 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
return nil, err
}
d.SetMaxOpenConns(1)
- if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+connectSchema+effectSchema+fileSchema+relaySchema+metered.Schema+researchSchema); err != nil {
+ if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+connectSchema+effectSchema+fileSchema+relaySchema+metered.Schema+researchSchema+scheduleSchema); err != nil {
d.Close()
return nil, err
}
@@ -91,6 +91,16 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
return nil, err
}
}
+ // Added with the scheduler (connectors spec S3): a step's revision
+ // (the attempt the instance sent; failover keeps it), priority,
+ // deadline and rank in the release order, its hold, and whether its
+ // deadline check fired.
+ for _, col := range []string{"revision INTEGER NOT NULL DEFAULT 0", "priority TEXT NOT NULL DEFAULT ''", "by_at TEXT NOT NULL DEFAULT ''", "rank INTEGER NOT NULL DEFAULT 2", "hold TEXT NOT NULL DEFAULT ''", "deadline_notified INTEGER NOT NULL DEFAULT 0"} {
+ if _, err = d.ExecContext(ctx, "ALTER TABLE steps ADD COLUMN "+col); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ d.Close()
+ return nil, err
+ }
+ }
// Added in slice 4c review: until when a merged task's kept sessions
// stay (Paul: ask about merged work for 14 days).
if _, err = d.ExecContext(ctx, "ALTER TABLE kept_sessions ADD COLUMN expires_at TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") {
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go
index 4c2be287..e79797aa 100644
--- a/internal/runner/thin/step.go
+++ b/internal/runner/thin/step.go
@@ -61,8 +61,11 @@ func (s *State) AcceptDispatch(ctx context.Context, frameID string, d wire.Dispa
}
// A step already cancelled here (the cancel came first) keeps its
// row: the dispatch is never executed.
- _, err = t.Exec("INSERT INTO steps(step_id, attempt, task_id, person, body, state, base_sha, created_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", d.StepID, d.Attempt, d.TaskID, d.Person, string(raw), runRunning, d.BaseSHA, now())
- return err
+ if _, err = t.Exec("INSERT INTO steps(step_id, attempt, task_id, person, body, state, base_sha, created_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", d.StepID, d.Attempt, d.TaskID, d.Person, string(raw), runRunning, d.BaseSHA, now()); err != nil {
+ return err
+ }
+ // Its scheduler facts: revision, priority, deadline, a release.
+ return acceptScheduled(t, d)
})
}
@@ -108,10 +111,14 @@ const stepDeferred = "deferred"
// stamp is a time as a fixed-width, ordered string (unix milliseconds).
func stamp(t time.Time) string { return fmt.Sprintf("%015d", t.UnixMilli()) }
-// nextStep is the oldest running step attempt that is due.
+// nextStep is the running step attempt that is due first in the
+// release order (connectors spec §7): urgent, then the earliest
+// deadline, then normal, then low, then the oldest, then the step id. A
+// held step is not due until its wake-up or a fact change, so it never
+// blocks one that can run.
func (s *State) nextStep(ctx context.Context) (stepRow, bool, error) {
var created string
- row := s.db.QueryRowContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, created_at FROM steps WHERE state=? AND (not_before='' OR not_before<=? OR cancel=1) ORDER BY created_at, step_id LIMIT 1", runRunning, stamp(time.Now()))
+ row := s.db.QueryRowContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, created_at FROM steps WHERE state=? AND (not_before='' OR not_before<=? OR cancel=1) ORDER BY rank, CASE WHEN by_at='' THEN 1 ELSE 0 END, by_at, created_at, step_id LIMIT 1", runRunning, stamp(time.Now()))
r, err := scanStep(func(dest ...any) error { return row.Scan(append(dest, &created)...) })
if errors.Is(err, sql.ErrNoRows) {
return r, false, nil
@@ -142,7 +149,7 @@ func (s *State) deferredSince(ctx context.Context, r stepRow) time.Time {
// nextDue is when the earliest deferred attempt is due again.
func (s *State) nextDue(ctx context.Context) (time.Time, bool) {
var v string
- if s.db.QueryRowContext(ctx, "SELECT MIN(v) FROM (SELECT not_before AS v FROM steps WHERE state=? AND not_before<>'' UNION ALL SELECT not_before FROM asks WHERE state=? AND started=0 AND not_before<>'' AND not_before<?)", runRunning, runRunning, heldUntilChange).Scan(&v) != nil || v == "" {
+ if s.db.QueryRowContext(ctx, "SELECT MIN(v) FROM (SELECT not_before AS v FROM steps WHERE state=? AND not_before<>'' AND not_before<? UNION ALL SELECT not_before FROM asks WHERE state=? AND started=0 AND not_before<>'' AND not_before<?)", runRunning, heldUntilChange, runRunning, heldUntilChange).Scan(&v) != nil || v == "" {
return time.Time{}, false
}
var ms int64
@@ -737,6 +744,19 @@ func (e *StepEngine) runOne(ctx context.Context, r stepRow) {
// Shutting down: the attempt stays held; the next start settles it.
return
}
+ if rep.State == stepDeferred && rep.Hold != nil {
+ // Held by the scheduler: kept with its wake-up, said once per
+ // hold (state running; the instance keeps it queued), and looked
+ // at again then or when a fact changes.
+ changed, err := e.State.holdStep(context.WithoutCancel(ctx), r, rep.Hold)
+ e.log("step hold", err)
+ if changed {
+ held := rep
+ held.State = wire.StepRunning
+ report(held)
+ }
+ return
+ }
if rep.State == stepDeferred {
// Held for later; the queue moves on meanwhile.
e.log("step defer", e.State.deferStep(context.WithoutCancel(ctx), r, mergeCIPoll))
diff --git a/internal/schedule/schedule.go b/internal/schedule/schedule.go
index 4ff4c85d..ac026355 100644
--- a/internal/schedule/schedule.go
+++ b/internal/schedule/schedule.go
@@ -114,7 +114,9 @@ type Step struct {
Avoid []string
// Release is the Run now grant the step carries ("" for none).
Release string
- // Engineer is what Engineering ran on, for Review's family rule.
+ // Engineer is what Engineering ran on, for Review's family rule (a
+ // Research step names the coordinator's connection the same way: it
+ // reads pages on another family first).
Engineer *Engineer
}
@@ -307,12 +309,12 @@ func Decide(in Input) Decision {
return holdFor(in, eff)
}
-// tiers are the candidate sets Review's family rule tries in order:
-// another family; then any connection but Engineering's; then all. Every
-// other role has one tier.
+// tiers are the candidate sets the family rule tries in order: another
+// family; then any connection but Engineering's; then all. A step that
+// names no Engineer has one tier.
func tiers(in Input) [][]Conn {
e := in.Step.Engineer
- if in.Step.Role != RoleReview || e == nil {
+ if e == nil {
return [][]Conn{in.Conns}
}
var other, notEngineer []Conn
diff --git a/scripts/no-fake-worker.sh b/scripts/no-fake-worker.sh
index fc075e17..620e5ca3 100755
--- a/scripts/no-fake-worker.sh
+++ b/scripts/no-fake-worker.sh
@@ -13,7 +13,3 @@ if grep -q 'EQUIPO_TEST_EGRESS_UPSTREAM' "$1"; then
echo "refusing $1: it contains the test build's egress route" >&2
exit 1
fi
-if grep -q 'EQUIPO_TEST_LEAVE_TO_SPEND' "$1"; then
- echo "refusing $1: it contains the test build's leave to spend" >&2
- exit 1
-fi