oficina / equipo Public

S3 security round: ten mechanical findings fixed

Priority revision on dispatches and frames (#1); housekeeping provenance
kept on the step and enforced by Decide (#2); held unlaunched steps
survive restart (#3); a launched attempt is never admitted again (#4);
Research takes the scheduler's fields and holds (#5); Review's failover
held by the guard (#6); start_task writes priority only when it starts
(#9); an overdue task keeps its deadline (#10); frozen protocol 13
schemas (#11); the hold after failover on its own attempt (#12).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev ee35a1a39126fb43b2e0237b3178517aadae63e3 parent 3f38c27
23 files changed, +664 −60
  • .rastrillo/budgets.txt +4 −4
  • docs/superpowers/plans/S3-SCHEDULER-PROGRESS.md +59 −0
  • internal/equipo/chat/research.go +16 −1
  • internal/equipo/chat/schedule.go +38 −8
  • internal/equipo/chat/schedule_store_test.go +26 −0
  • internal/equipo/chat/tasks.go +38 −10
  • internal/equipo/migrations/0073_thin_scheduler.sql +2 −0
  • internal/equipo/migrations/schema.sql +2 −2
  • internal/runner/thin/engineer.go +3 −0
  • internal/runner/thin/judge.go +5 −0
  • internal/runner/thin/pistep.go +3 −0
  • internal/runner/thin/pistep_test.go +38 −0
  • internal/runner/thin/schedule.go +49 −9
  • internal/runner/thin/schedule_test.go +181 −1
  • internal/runner/thin/state.go +1 −1
  • internal/runner/thin/step.go +16 −7
  • internal/schedule/schedule.go +7 −1
  • internal/schedule/schedule_test.go +20 −2
  • internal/thintest/scheduler_contract_test.go +82 −2
  • internal/wire/runners.go +2 −2
  • internal/wire/schedule.go +3 −1
  • internal/wire/schedule_test.go +62 −9
  • internal/wire/tasks.go +7 −0

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index ca818445..db16c43f 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -15,7 +15,7 @@ time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial re
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
size internal/equipo 18647 - The instance web layer: pages, handlers, templates and copy for every screen. Measured 18647 source lines.
-size internal/wire 5032 - The runner and person API protocol: every frame, resource and its downgrade up to protocol 14 (the scheduler), one package so Encode sees every type. Measured 5032 source lines.
+size internal/wire 5041 - The runner and person API protocol: every frame, resource and its downgrade up to protocol 14 (the scheduler), one package so Encode sees every type. Measured 5041 source lines.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -36,7 +36,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 21999 13058 The thin runner: steps, link, coordinator, Mac worker, previews, merges, metered connections, Research and the scheduler. Measured 21999 source and 13058 test lines.
+size internal/runner/thin 22059 13276 The thin runner: steps, link, coordinator, Mac worker, previews, merges, metered connections, Research and the scheduler. Measured 22059 source and 13276 test lines.
time internal/thintest 180s Contract tests for Mac runners, transitions and the thin core share one instance harness; loaded CI needs 180s.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -51,7 +51,7 @@ perf GET /api/v1/notebook skip Thin v1 person API: bearer-only JSON for devices;
perf GET /api/v1/thinking skip Thin v1 person API: bearer-only JSON for devices; the browser reads thinking words on /settings/thinking.
perf GET /api/v1/tasks skip Thin v1 person API: bearer-only JSON for devices; the browser reads tasks through /tasks.
perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads a task through /tasks/{id}.
-size internal/equipo/chat 20342 - The instance store: tasks, steps, cards, merge authority, housekeeping, placement, metered connections, Research and the scheduler. Measured 20342 source lines.
+size internal/equipo/chat 20415 - The instance store: tasks, steps, cards, merge authority, housekeeping, placement, metered connections, Research and the scheduler. Measured 20415 source lines.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -66,5 +66,5 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 9766 End-to-end scenarios through a real runner and instance, plus browser drives. Measured 9766 test lines.
-size internal/thintest - 20055 Thin v1 contract and page tests; one package keeps one instance harness. Measured 20055 test lines.
+size internal/thintest - 20135 Thin v1 contract and page tests; one package keeps one instance harness. Measured 20135 test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
diff --git a/docs/superpowers/plans/S3-SCHEDULER-PROGRESS.md b/docs/superpowers/plans/S3-SCHEDULER-PROGRESS.md
index 09a0015f..65845521 100644
--- a/docs/superpowers/plans/S3-SCHEDULER-PROGRESS.md
+++ b/docs/superpowers/plans/S3-SCHEDULER-PROGRESS.md
@@ -164,6 +164,65 @@ rows 4, 6 and 7. No real key, sign-in or provider: fakes only.
- IM16 held card left open after Run now -> TestContractScheduler
- IM17 page offers Run it now on a spending bar -> TestContractScheduler (spend unknown offers Run now)
+## Security round (Astra, read-only, on e38bc7e5)
+
+Verdict NOT READY, twelve findings: ten mechanical, fixed here, each
+with a test written first and a mutation observed; two design findings
+(#7 and #8) left to the controller unchanged.
+
+1. Cached urgency over a newer dispatch (Critical): the task's priority
+ has its own revision (`chat_tasks.priority_revision`), bumped by every
+ change; dispatches and priority frames carry it, and the runner keeps a
+ frame's value only while no dispatch carries a newer one, then keeps
+ the newer dispatch's as the task's.
+2. Housekeeping only "dispatched as low" (Critical): the attempt
+ housekeeping dispatched is kept on the step
+ (`chat_steps.housekeeping_attempt`), so a later placement is still
+ housekeeping's; the dispatch says `housekeeping`; the runner keeps it
+ per step and Decide treats it as low with no leave to spend whatever
+ its priority, a priority frame or a release; Run now on it is refused
+ and its held card offers Wait only.
+3. Recovery failed held, never-launched steps: a step with a hold and no
+ namespace recorded keeps its hold and wake-up across a restart.
+4. Duplicate admission was an UPSERT: an attempt admitted and launched
+ (its namespace recorded) is refused another admission (`errAdmitted`);
+ one that launched nothing may be admitted again, explicitly.
+5. Research skipped the scheduler's dispatch fields and holds: both
+ Research paths use the shared fields (`schedulerFields`) and hold
+ handling; a held Research step stays queued, is Needs you and takes
+ Run now.
+6. Review's failover launch ignored a guard hold: it is held there, as
+ the first attempt is.
+9. A repeated start_task could set the priority: the fields are written
+ only when the start would go ahead (`startable`).
+10. An overdue task could not change priority: an unchanged deadline is
+ kept; only a newly given one must be ahead.
+11. Frozen protocol 13 schemas: what is sent below 14 (a dispatch, a
+ preference, a step report, record_task's and start_task's
+ arguments) decodes strictly against the protocol 13 key sets.
+12. A hold after failover was written against the original attempt: it
+ is kept against the attempt the step moved to.
+
+Not changed (design, for the controller): #7, no production reading
+probe (see Open); #8, a kept metered session without leave starting
+afresh on a subscription (S2's rule).
+
+Mutations observed:
+
+- #11 each stripping guard below 14 removed (dispatch priority, by, release, housekeeping; record_task priority, by; start_task's arguments; the held report's refusal) -> TestEncodeBelowProtocol14AgainstFrozenSchemas (frozen protocol 13 key sets) or TestEncodeBelowProtocol14DropsScheduler, each caught
+- #2 (Decide) housekeeping given leave by urgent or a release -> TestDecideHousekeeping (housekeeping spent), TestDecideInvariants (b); housekeeping not counted as low -> TestDecideHousekeeping (above low's threshold)
+- #1 the cached priority taking precedence over a newer dispatch -> TestScheduleNewerDispatchBeatsCachedPriority ("urgent"); a newer dispatch's value not kept as the task's -> first MISSED (the stale frame shared the held revision, so it was refused anyway); the case now sends a frame between the two revisions, then caught
+- #2 (runner) the housekeeping flag not read -> TestScheduleHousekeepingNeverSpends (spent on TensorX)
+- #3 recovery failing a held, never-launched step -> TestScheduleHoldSurvivesRestart (state reported, 1 report)
+- #4 a launched attempt admitted again (the UPSERT) -> TestScheduleDuplicateAdmissionRefused
+- #12 the hold persisted against the original attempt -> TestScheduleHoldAfterFailover (the held step ran 2 times)
+- #6 a failover Review held by the guard -> TestPiReviewFailoverHeldByTheGuard (failed metered_held), observed before the fix (written first)
+- #1 (instance) the dispatch without its priority revision -> TestContractScheduler (dispatch); the priority frame carrying the task's revision, not the priority revision -> TestContractScheduler (priority frame Revision 5)
+- #2 (instance) housekeeping provenance not kept on the step -> TestContractSchedulerHousekeeping (retry not housekeeping); the dispatch not saying housekeeping -> same; Run now allowed on housekeeping's attempt -> same (Run now accepted); its held card offering Run it now -> same
+- #5 Research dispatch without the scheduler fields -> TestContractSchedulerResearch (research dispatch); its hold not kept -> same (Hold nil); a held Research step marked running -> same (state running); held Research not Needs you -> same (needs "")
+- #9 a repeated start_task in the same turn setting the priority -> TestContractScheduler (a second start_task set the priority)
+- #10 an unchanged past deadline refused -> TestSchedulerOverdueDeadlineKept
+
## Decisions where the spec was open
- The step revision is the attempt the instance dispatched (runner
diff --git a/internal/equipo/chat/research.go b/internal/equipo/chat/research.go
index ddae3c75..b6545e9d 100644
--- a/internal/equipo/chat/research.go
+++ b/internal/equipo/chat/research.go
@@ -584,6 +584,13 @@ func (t *txn) dispatchResearch(k *taskRecord, s *stepRecord) error {
in.Sources = append(in.Sources, wire.ResearchSource{ID: src.SourceID, URL: src.URL, Origin: src.Origin})
}
cmd := wire.DispatchCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, Specialist: wire.SpecialistResearch, Title: k.Title, Brief: k.Brief, Findings: []wire.Finding{}, RunnerID: s.RunnerID, Research: in}
+ // The scheduler's facts, as for every step.
+ if t.hk != nil {
+ s.HousekeepingAttempt = s.Attempt
+ }
+ if err := t.schedulerFields(*k, *s, &cmd); err != nil {
+ return err
+ }
return t.commandTo(s.RunnerID, s.Person, wire.FrameDispatch, cmd)
}
@@ -614,9 +621,13 @@ func (t *txn) researchReport(l Lease, k *taskRecord, s *stepRecord, v *wire.Step
if v.Family != "" && s.Family != v.Family || v.Account != "" && s.Account != v.Account {
s.Family, s.Account, changed = firstSet(v.Family, s.Family), firstSet(v.Account, s.Account), true
}
+ // The scheduler's hold, as for every step.
+ if acceptHold(s, v) {
+ changed = true
+ }
switch v.State {
case wire.StepRunning:
- if s.State == wire.StepQueued {
+ if s.State == wire.StepQueued && v.Hold == nil {
s.State, changed = wire.StepRunning, true
if s.StartedAt == nil {
s.StartedAt = &now
@@ -660,6 +671,10 @@ func (t *txn) researchReport(l Lease, k *taskRecord, s *stepRecord, v *wire.Step
return err
}
}
+ // Needs you for a held Research step, as for any step.
+ if err := t.heldCard(*k, *s); err != nil {
+ return err
+ }
return t.advance(k)
}
diff --git a/internal/equipo/chat/schedule.go b/internal/equipo/chat/schedule.go
index 178ebbcf..887aede0 100644
--- a/internal/equipo/chat/schedule.go
+++ b/internal/equipo/chat/schedule.go
@@ -83,7 +83,8 @@ func (t *txn) coordinatorSetsPriority(k *taskRecord, r turnRecord, priority stri
return nil
}
k.Priority, k.DueBy, k.PrioritySetBy = priority, by, wire.PrioritySetByCoordinator
- return t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Updates(map[string]any{"priority": k.Priority, "due_by": k.DueBy, "priority_set_by": k.PrioritySetBy}).Error
+ k.PriorityRevision++
+ return t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Updates(map[string]any{"priority": k.Priority, "due_by": k.DueBy, "priority_set_by": k.PrioritySetBy, "priority_revision": k.PriorityRevision}).Error
}
// taskPriority is a task's priority on its read shape; absent while it
@@ -160,13 +161,17 @@ func (s *Store) SetPriority(ctx context.Context, person, id string, in wire.SetP
var by *time.Time
if in.By != nil {
b := in.By.UTC()
- if !b.After(t.now()) || b.Sub(t.now()) > wire.MaxByAhead {
+ unchanged := k.DueBy != nil && k.DueBy.Equal(b)
+ // A deadline newly given must be ahead; the one the task has may
+ // have passed (an overdue task can still change priority).
+ if !unchanged && (!b.After(t.now()) || b.Sub(t.now()) > wire.MaxByAhead) {
return ErrInvalid
}
by = &b
}
k.Priority, k.DueBy, k.PrioritySetBy = in.Priority, by, wire.PrioritySetByPerson
- if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("priority", "due_by", "priority_set_by").Updates(&k).Error; err != nil {
+ k.PriorityRevision++
+ if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("priority", "due_by", "priority_set_by", "priority_revision").Updates(&k).Error; err != nil {
return err
}
if err := t.saveTask(&k); err != nil {
@@ -209,7 +214,7 @@ func (t *txn) sendPriority(k taskRecord) error {
if p == "" {
p = wire.PriorityNormal
}
- if err := t.commandTo(st.RunnerID, st.Person, wire.FramePriority, wire.PriorityCommand{Person: st.Person, TaskID: k.ID, Priority: p, By: k.DueBy, Revision: k.Revision}); err != nil {
+ if err := t.commandTo(st.RunnerID, st.Person, wire.FramePriority, wire.PriorityCommand{Person: st.Person, TaskID: k.ID, Priority: p, By: k.DueBy, Revision: k.PriorityRevision}); err != nil {
return err
}
}
@@ -267,7 +272,9 @@ func (t *txn) release(k taskRecord, person, step string, revision int64) (string
// Not held, or held at another revision now: stale.
return "", ErrConflict
}
- if h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown {
+ if h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown || housekeepingAttempt(st) {
+ // Never past a spending bar, and never for housekeeping's own
+ // attempt, which does not spend.
return "", ErrHoldBar
}
proto, err := t.runnerProtocol(st.Person, st.RunnerID)
@@ -291,6 +298,29 @@ func (t *txn) release(k taskRecord, person, step string, revision int64) (string
return r.ID, t.commandTo(st.RunnerID, st.Person, wire.FrameRelease, wire.ReleaseCommand{ID: r.ID, Person: st.Person, TaskID: k.ID, StepID: st.ID, StepRevision: revision})
}
+// schedulerFields puts the scheduler's facts on a step's dispatch (protocol
+// 14; Encode drops them for an older runner): the task's priority,
+// deadline and priority revision, and a Run now written for this
+// attempt. An attempt housekeeping dispatched counts as low, carries no
+// release and says so, wherever and whenever it is placed (§7,
+// Housekeeping).
+func (t *txn) schedulerFields(k taskRecord, s stepRecord, cmd *wire.DispatchCommand) error {
+ cmd.Priority, cmd.By, cmd.PriorityRevision = k.Priority, k.DueBy, k.PriorityRevision
+ if housekeepingAttempt(s) {
+ cmd.Priority, cmd.Housekeeping = wire.PriorityLow, true
+ return nil
+ }
+ var err error
+ cmd.Release, err = t.openRelease(s)
+ return err
+}
+
+// housekeepingAttempt reports whether the step's current attempt is one
+// housekeeping dispatched.
+func housekeepingAttempt(s stepRecord) bool {
+ return s.HousekeepingAttempt != 0 && s.HousekeepingAttempt == s.Attempt
+}
+
// openRelease is an unconsumed release the instance wrote for the step's
// dispatched attempt (a step placed again carries it).
func (t *txn) openRelease(s stepRecord) (string, error) {
@@ -319,9 +349,9 @@ func (t *txn) heldCard(k taskRecord, s stepRecord) error {
return err
}
options := []string{ChoiceWait, ChoiceRunNow}
- if h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown {
- // Run now cannot pass a spending bar: the hold's own actions are
- // on the task.
+ if h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown || housekeepingAttempt(s) {
+ // Run now cannot pass a spending bar, nor give housekeeping's own
+ // attempt leave: the hold's own actions are on the task.
options = []string{ChoiceWait}
}
opts, _ := json.Marshal(options)
diff --git a/internal/equipo/chat/schedule_store_test.go b/internal/equipo/chat/schedule_store_test.go
index 5f941aad..d6bd505a 100644
--- a/internal/equipo/chat/schedule_store_test.go
+++ b/internal/equipo/chat/schedule_store_test.go
@@ -5,6 +5,7 @@ import (
"errors"
"slices"
"testing"
+ "time"
"amadan.net/oficina/equipo/internal/wire"
)
@@ -52,3 +53,28 @@ func TestSchedulerWritesCheckCreatorAndRoster(t *testing.T) {
t.Fatalf("audits %v", r.audits)
}
}
+
+// Security round #10: an overdue task can still be made urgent or not
+// urgent, keeping its deadline; a deadline newly given must be ahead.
+func TestSchedulerOverdueDeadlineKept(t *testing.T) {
+ r := newMeteredRig(t)
+ now := r.s.now()
+ past := now.Add(-48 * time.Hour)
+ g := r.s.db.G
+ g.Create(&projectRecord{ID: "p_1", Repo: "amadan.net/oficina/sample", State: wire.ProjectActive, CreatedAt: now, UpdatedAt: now})
+ if err := g.Create(&taskRecord{ID: "tk1", ProjectID: "p_1", Title: "T", Stage: wire.StageInProgress, Creator: "owner@example.com", Revision: 3, DueBy: &past, PrioritySetBy: wire.PrioritySetByCoordinator, CreatedAt: now, UpdatedAt: now}).Error; err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ out, err := r.s.SetPriority(ctx, "owner@example.com", "tk1", wire.SetPriority{Priority: wire.PriorityUrgent, By: &past, Revision: 3})
+ if err != nil || out.Priority == nil || out.Priority.Priority != wire.PriorityUrgent || out.Priority.By == nil || !out.Priority.By.Equal(past) {
+ t.Fatalf("an overdue task made urgent: %+v %v", out.Priority, err)
+ }
+ other := past.Add(time.Hour)
+ if _, err := r.s.SetPriority(ctx, "owner@example.com", "tk1", wire.SetPriority{Priority: wire.PriorityNormal, By: &other, Revision: out.Revision}); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("a new deadline in the past: %v", err)
+ }
+ if _, err := r.s.SetPriority(ctx, "owner@example.com", "tk1", wire.SetPriority{Priority: wire.PriorityNormal, By: &past, Revision: out.Revision}); err != nil {
+ t.Fatalf("an overdue task made not urgent: %v", err)
+ }
+}
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 20b15064..2d5c44b1 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -108,6 +108,9 @@ type taskRecord struct {
Priority string
DueBy *time.Time
PrioritySetBy string
+ // PriorityRevision orders the priority and deadline: every change
+ // bumps it, and dispatches and priority frames carry it.
+ PriorityRevision int64
}
func (taskRecord) TableName() string { return "chat_tasks" }
@@ -241,8 +244,11 @@ type stepRecord struct {
ResearchGrant string
ResearchGrantRevision int64
// Hold is why the runner holds the step now (wire.StepHold JSON, ""
- // when it does not): the scheduler's report.
- Hold string
+ // when it does not): the scheduler's report. HousekeepingAttempt is
+ // the attempt housekeeping dispatched (0: none): that attempt counts
+ // as low and never spends, wherever and whenever it is placed.
+ Hold string
+ HousekeepingAttempt int64
}
func (stepRecord) TableName() string { return "chat_steps" }
@@ -478,6 +484,15 @@ func (t *txn) taskView(k taskRecord) (wire.Task, error) {
v.ChecksSandbox = pr.checks.ChecksSandbox
}
v.NeedsYou = pr.needsYou(k)
+ if v.NeedsYou == "" && !wire.FinalStage(k.Stage) && !k.CancelRequested {
+ // Research is never the task's last word, but a held Research step
+ // that needs its person is Needs you all the same (§8).
+ for _, st := range steps {
+ if h := stepHold(st); st.Specialist == wire.SpecialistResearch && h != nil && h.NeedsPerson != "" && !wire.StepTerminal(st.State) {
+ v.NeedsYou = wire.NeedsHeld
+ }
+ }
+ }
v.Priority = taskPriority(k)
if pr.eng != nil {
v.FixRounds = pr.eng.Round
@@ -604,7 +619,7 @@ func (t *txn) writeStep(s *stepRecord) error {
}
s.Revision++
s.UpdatedAt = t.now()
- if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold").Updates(s).Error; err != nil {
+ if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold", "housekeeping_attempt").Updates(s).Error; err != nil {
return err
}
members, err := t.members()
@@ -793,6 +808,16 @@ func catalogHas(h wire.Hello, repo string) bool {
return false
}
+// startable reports whether start_task would start the task now: no
+// step yet, still noted or investigated.
+func (t *txn) startable(k taskRecord) bool {
+ if wire.FinalStage(k.Stage) || k.CancelRequested || k.Stage != wire.StageNoted && k.Stage != wire.StageInvestigated {
+ return false
+ }
+ _, found, err := t.latestStep(k.ID)
+ return err == nil && !found
+}
+
// startTask dispatches the task's Engineering step to the person's own
// runner: the step, the dispatch command and the task event in one
// transaction.
@@ -857,6 +882,11 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
if err := t.hkSpend(s.Person); err != nil {
return err
}
+ if t.hk != nil {
+ // Its provenance is kept on the record: a placement after this
+ // pass still dispatches it as housekeeping's.
+ s.HousekeepingAttempt = s.Attempt
+ }
if s.Specialist == wire.SpecialistResearch {
return t.dispatchResearch(k, s)
}
@@ -895,10 +925,7 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
// runner): the task's priority and deadline, and a Run now written for
// this attempt. Housekeeping's own dispatches count as low and carry
// no release: they never spend (§7, Housekeeping).
- cmd.Priority, cmd.By = k.Priority, k.DueBy
- if t.hk != nil {
- cmd.Priority = wire.PriorityLow
- } else if cmd.Release, err = t.openRelease(*s); err != nil {
+ if err := t.schedulerFields(*k, *s, &cmd); err != nil {
return err
}
if s.Specialist != wire.SpecialistEngineering || s.Republish {
@@ -1823,9 +1850,10 @@ func (t *txn) taskTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error)
return refused("invalid", toolBadPriority), nil
}
if priority != "" || by != nil {
- // Only on a task this turn recorded and nobody set before: the
- // coordinator sets them at creation, never later (§6).
- if k, err := t.loadTask(strings.TrimSpace(in.Task)); err == nil && k.Creator == r.Person {
+ // Only on a task this turn recorded, nobody set before, and not
+ // started yet: the coordinator sets them at creation, never
+ // later (§6). A start that will be refused writes nothing.
+ if k, err := t.loadTask(strings.TrimSpace(in.Task)); err == nil && k.Creator == r.Person && t.startable(k) {
if err := t.coordinatorSetsPriority(&k, r, priority, by); err != nil {
return wire.ToolResult{}, err
}
diff --git a/internal/equipo/migrations/0073_thin_scheduler.sql b/internal/equipo/migrations/0073_thin_scheduler.sql
index 51054e85..7133a6b7 100644
--- a/internal/equipo/migrations/0073_thin_scheduler.sql
+++ b/internal/equipo/migrations/0073_thin_scheduler.sql
@@ -5,3 +5,5 @@ ALTER TABLE chat_steps ADD COLUMN hold text;
CREATE TABLE chat_releases (id text PRIMARY KEY, task_id text, step_id text, step_revision integer, person text, runner_id text, created_at datetime);
CREATE INDEX chat_release_task ON chat_releases(task_id);
CREATE UNIQUE INDEX chat_release_step ON chat_releases(step_id, step_revision);
+ALTER TABLE chat_tasks ADD COLUMN priority_revision integer;
+ALTER TABLE chat_steps ADD COLUMN housekeeping_attempt integer;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 604558ee..de415f0c 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -596,9 +596,9 @@ CREATE TABLE chat_coordinators (person text PRIMARY KEY, state text, turn_id tex
CREATE TABLE chat_notebooks (person text PRIMARY KEY, entries text, revision integer, updated_at datetime);
CREATE INDEX chat_card_task ON chat_cards(task_id);
CREATE TABLE chat_project_attachments (project_id text, kind text, ref text, name text, created_at datetime, PRIMARY KEY (project_id, kind, ref));
-CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, ready_sha text, merge_eligible text, done_at datetime, duplicate_of text, folded_into text, folded_stage text, folded_at datetime, engineering_runner text, merge_hold text, merge_verified numeric, revert_of text, revert_sha text, kind text, direction_asked text, built_as text, explored_from text, priority text, due_by datetime, priority_set_by text);
+CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, ready_sha text, merge_eligible text, done_at datetime, duplicate_of text, folded_into text, folded_stage text, folded_at datetime, engineering_runner text, merge_hold text, merge_verified numeric, revert_of text, revert_sha text, kind text, direction_asked text, built_as text, explored_from text, priority text, due_by datetime, priority_set_by text, priority_revision integer);
CREATE INDEX chat_task_project ON chat_tasks(project_id);
-CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text, change_facts text, decided_by text, merge_source text, merge_parents text, hosted_ci text, sandbox_runner text, unsandboxed_by text, unsandboxed_at datetime, unsandboxed_attempt integer, unsandboxed_runner text, has_preview numeric, preview text, kind text, note text, boundary text, question text, request_turn text, sources_card text, sources_hash text, research_grant text, research_grant_revision integer, hold text);
+CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text, change_facts text, decided_by text, merge_source text, merge_parents text, hosted_ci text, sandbox_runner text, unsandboxed_by text, unsandboxed_at datetime, unsandboxed_attempt integer, unsandboxed_runner text, has_preview numeric, preview text, kind text, note text, boundary text, question text, request_turn text, sources_card text, sources_hash text, research_grant text, research_grant_revision integer, hold text, housekeeping_attempt integer);
CREATE INDEX chat_step_task ON chat_steps(task_id);
CREATE TABLE chat_task_entries (id text PRIMARY KEY, task_id text, idempotency_key text, kind text, author text, text text, repo text, path text, line integer, created_at datetime, headline text, folded_from text);
CREATE INDEX chat_entry_task ON chat_task_entries(task_id);
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go
index d8889b0a..c21da0fd 100644
--- a/internal/runner/thin/engineer.go
+++ b/internal/runner/thin/engineer.go
@@ -117,6 +117,9 @@ type Engineer struct {
ResearchAddresses func()
// rh are the Research step's seams (tests).
rh researchHooks
+ // beforeAdmit, in tests, runs just before a metered attempt's
+ // admission (a race between the decision and the guard).
+ beforeAdmit func(local string)
}
func (e *Engineer) root() string { return filepath.Join(e.O.Runner.StateDir, "steps") }
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go
index 4e224a3d..61869698 100644
--- a/internal/runner/thin/judge.go
+++ b/internal/runner/thin/judge.go
@@ -793,6 +793,11 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste
rep.Switched.To = b.Provider
progress(rep)
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 guard held the failover attempt at its admission: held
+ // there, as the first attempt is.
+ return heldGuard(rep, res)
+ }
e.observe(b.ID, res)
}
if res.family != "" && res.family != b.Family {
diff --git a/internal/runner/thin/pistep.go b/internal/runner/thin/pistep.go
index 6af68bc8..3e90ce06 100644
--- a/internal/runner/thin/pistep.go
+++ b/internal/runner/thin/pistep.go
@@ -69,6 +69,9 @@ func (e *Engineer) runPi(ctx context.Context, r stepRow, tree workspace.TaskTree
// The scheduler's admission commits with the slot's claim.
admit = func(t *sql.Tx) error { return spec.admit(ctx, t) }
}
+ if e.beforeAdmit != nil {
+ e.beforeAdmit(b.LocalID)
+ }
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)
diff --git a/internal/runner/thin/pistep_test.go b/internal/runner/thin/pistep_test.go
index 5b4f886d..6a21d682 100644
--- a/internal/runner/thin/pistep_test.go
+++ b/internal/runner/thin/pistep_test.go
@@ -612,3 +612,41 @@ func TestPiKeptSessionStaysPut(t *testing.T) {
t.Fatalf("after the budget hold the round moved to %s", id)
}
}
+
+// Security round #6: a Review failover attempt whose admission the
+// metered guard refuses (its slot taken between the decision and the
+// admission) is held there, with its hold, as the first attempt is: never
+// a terminal failure.
+func TestPiReviewFailoverHeldByTheGuard(t *testing.T) {
+ r := newPiRig(t, fakePiInstall(t), bigBudget)
+ r.urgent()
+ const second = "tensorx-second000000"
+ home := filepath.Join(t.TempDir(), second)
+ os.MkdirAll(home, 0700)
+ os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(fakepi.TestKey), 0600)
+ err := r.state.tx(r.ctx, func(tx *sql.Tx) error {
+ if err := metered.Add(r.ctx, tx, metered.Conn{Connection: "cn_tx2", LocalID: second, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: home, Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: bigBudget}, time.Now()); err != nil {
+ return err
+ }
+ return metered.Checked(r.ctx, tx, second, true)
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The first attempt runs on one TensorX key, which is refused; the
+ // failover is decided onto the other, whose slot another attempt takes
+ // just before its admission.
+ r.e.beforeAdmit = func(local string) {
+ if local != second {
+ return
+ }
+ r.state.tx(r.ctx, func(tx *sql.Tx) error {
+ _, err := metered.Admit(r.ctx, tx, local, metered.Holder{Step: "other", Attempt: 1, Role: metered.RoleReview}, time.Now())
+ return err
+ })
+ }
+ rep := r.runReview("keyrefused", 1)
+ if rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldBusy || rep.Hold.Connection != second || rep.Attempt != 2 {
+ t.Fatalf("report %+v, hold %+v", rep, rep.Hold)
+ }
+}
diff --git a/internal/runner/thin/schedule.go b/internal/runner/thin/schedule.go
index f8c43848..aa1484fc 100644
--- a/internal/runner/thin/schedule.go
+++ b/internal/runner/thin/schedule.go
@@ -51,6 +51,10 @@ const staleAfter = 15 * time.Minute
// decides again before the step is held briefly.
const admitRetries = 4
+// errAdmitted: the attempt was admitted and launched already; it is
+// never admitted again (a replay starts nothing).
+var errAdmitted = errors.New("the attempt was admitted already")
+
// errFactsMoved: the facts Decide read changed before the admission
// committed; it decides again.
var errFactsMoved = errors.New("the scheduler's facts changed")
@@ -90,6 +94,7 @@ func parseBy(v string) *time.Time {
// stepFacts are the step's own scheduler facts as the runner holds them.
type stepFacts struct {
priority string
+ housekeeping bool
by *time.Time
deadlineNotified bool
revision int64
@@ -108,14 +113,15 @@ type querier interface {
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)
+ var notified, housekeeping int
+ err := q.QueryRowContext(ctx, "SELECT priority, by_at, deadline_notified, revision, housekeeping FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&f.priority, &by, &notified, &f.revision, &housekeeping)
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
+ f.priority, f.by, f.revision, f.housekeeping = r.Priority, r.By, r.Attempt, r.Housekeeping
err = nil
}
+ f.housekeeping = f.housekeeping || housekeeping == 1
if err != nil {
return f, err
}
@@ -316,7 +322,7 @@ func (c *Conns) stepInput(ctx context.Context, q querier, r stepRow, role, kept
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}}
+ 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, Housekeeping: f.housekeeping, 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}
}
@@ -368,7 +374,29 @@ func (c *Conns) admitTx(ctx context.Context, t *sql.Tx, r stepRow, d decision) e
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 {
+ // One execution per admission: an attempt admitted and launched (its
+ // namespace recorded) is never admitted again. The one exception is
+ // explicit: an attempt admitted that launched nothing (a kept
+ // transcript that could not be put in place, a guard that then held
+ // it) may be admitted again.
+ var prior, ns string
+ err = t.QueryRowContext(ctx, "SELECT connection FROM admissions WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&prior)
+ switch {
+ case err == nil:
+ if err := t.QueryRowContext(ctx, "SELECT ns_id FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&ns); err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
+ if ns != "" {
+ return errAdmitted
+ }
+ if _, err := t.ExecContext(ctx, "UPDATE admissions SET connection=?, reason=?, at=? WHERE step_id=? AND attempt=?", d.d.Connection, d.d.Reason, now(), r.StepID, r.Attempt); err != nil {
+ return err
+ }
+ case errors.Is(err, sql.ErrNoRows):
+ if _, err := t.ExecContext(ctx, "INSERT INTO admissions(step_id, attempt, step_revision, connection, reason, at) VALUES(?,?,?,?,?,?)", r.StepID, r.Attempt, d.step.revision, d.d.Connection, d.d.Reason, now()); err != nil {
+ return err
+ }
+ default:
return err
}
_, err = t.ExecContext(ctx, "UPDATE steps SET hold='', not_before='' WHERE step_id=? AND attempt=? AND state=?", r.StepID, r.Attempt, runRunning)
@@ -565,16 +593,28 @@ func (s *State) SetPriority(ctx context.Context, frameID string, cmd wire.Priori
// 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 {
+ // The newest priority wins: a priority frame's value only while no
+ // dispatch carries a newer revision; a newer dispatch's value is kept
+ // as the task's, so an older frame cannot bring it back.
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)
+ var heldRevision int64
+ err := t.QueryRow("SELECT priority, by_at, revision FROM task_priority WHERE task_id=? AND person=?", d.TaskID, d.Person).Scan(&held, &heldBy, &heldRevision)
switch {
- case err == nil:
+ case err == nil && heldRevision > d.PriorityRevision:
priority, by = held, parseBy(heldBy)
- case !errors.Is(err, sql.ErrNoRows):
+ case err != nil && !errors.Is(err, sql.ErrNoRows):
return err
+ case d.PriorityRevision > 0:
+ if _, err := t.Exec("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 WHERE excluded.revision > task_priority.revision", d.TaskID, d.Person, d.Priority, byStamp(d.By), d.PriorityRevision); err != nil {
+ return err
+ }
+ }
+ housekeeping := 0
+ if d.Housekeeping {
+ housekeeping = 1
}
- 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 {
+ if _, err := t.Exec("UPDATE steps SET revision=?, priority=?, by_at=?, rank=?, housekeeping=? WHERE step_id=? AND attempt=? AND revision=0", d.Attempt, priority, byStamp(by), priorityRank(priority, by), housekeeping, d.StepID, d.Attempt); err != nil {
return err
}
if d.Release == "" {
diff --git a/internal/runner/thin/schedule_test.go b/internal/runner/thin/schedule_test.go
index da9e03b5..5fa2fabd 100644
--- a/internal/runner/thin/schedule_test.go
+++ b/internal/runner/thin/schedule_test.go
@@ -33,6 +33,8 @@ type schedRig struct {
ran map[string]string
// fail makes an attempt on a connection refuse on quota once.
fail map[string]bool
+ // execs counts the step function's runs per step.
+ execs map[string]int
}
func newSchedRig(t *testing.T, subs ...string) *schedRig {
@@ -57,7 +59,7 @@ func newSchedRig(t *testing.T, subs ...string) *schedRig {
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 := &schedRig{t: t, ctx: ctx, state: state, conns: conns, ran: map[string]string{}, fail: map[string]bool{}, execs: map[string]int{}}
r.steps = &StepEngine{State: state, Exec: r.exec, Notify: func() {}}
conns.Changed = r.steps.MeteredChanged
conns.Readings = r.steps.MeteredChanged
@@ -89,6 +91,9 @@ func (r *schedRig) tensorx(budget wire.Budget) {
// 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{}}
+ r.mu.Lock()
+ r.execs[row.StepID]++
+ r.mu.Unlock()
var avoid []string
for {
b, hold, admit, err := r.conns.admit(ctx, row, connect.RoleEngineering, "", avoid, nil)
@@ -473,3 +478,178 @@ func TestScheduleRefreshesStaleReadings(t *testing.T) {
t.Fatalf("probed %d times within fifteen minutes", probes)
}
}
+
+// Security round #1: a priority frame's value never outlives a newer
+// dispatch. Urgent while a step ran, then normal and a Retry: the retry's
+// dispatch (a newer priority revision) is what counts.
+func TestScheduleNewerDispatchBeatsCachedPriority(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ if ok, err := r.state.SetPriority(r.ctx, "fp", wire.PriorityCommand{Person: connPerson, TaskID: "tk-x", Priority: wire.PriorityUrgent, Revision: 2}); err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ facts := func(step string, priority string, revision int64) string {
+ t.Helper()
+ d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-x", StepID: step, Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: priority, PriorityRevision: revision}
+ if err := r.state.AcceptDispatch(r.ctx, "f-"+step, d); err != nil {
+ t.Fatal(err)
+ }
+ f, err := readStepFacts(r.ctx, r.state.db, stepRow{DispatchCommand: d})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The attempt ends: one running step per task.
+ if _, err := r.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, step); err != nil {
+ t.Fatal(err)
+ }
+ return f.priority
+ }
+ if p := facts("older", wire.PriorityNormal, 1); p != wire.PriorityUrgent {
+ t.Fatalf("an older dispatch: %q", p)
+ }
+ if p := facts("newer", wire.PriorityNormal, 4); p != wire.PriorityNormal {
+ t.Fatalf("a newer dispatch lost to the cached urgent: %q", p)
+ }
+ // And the newer value is the one held now: a stale frame cannot
+ // bring urgent back.
+ if ok, _ := r.state.SetPriority(r.ctx, "fp2", wire.PriorityCommand{Person: connPerson, TaskID: "tk-x", Priority: wire.PriorityUrgent, Revision: 3}); ok {
+ t.Fatal("a priority frame older than the newest dispatch applied")
+ }
+}
+
+// Security round #2: a housekeeping attempt never spends, whatever a
+// priority frame, an urgent dispatch or a release says.
+func TestScheduleHousekeepingNeverSpends(t *testing.T) {
+ r := newSchedRig(t)
+ r.tensorx(bigBudget)
+ r.start()
+ d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-hk", StepID: "hk", Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: wire.PriorityUrgent, Release: "rl_hk", Housekeeping: true}
+ if err := r.state.AcceptDispatch(r.ctx, "f-hk", d); err != nil {
+ t.Fatal(err)
+ }
+ r.steps.Wake()
+ r.until(5*time.Second, "the hold", func() bool { return len(r.reports("hk")) > 0 })
+ r.state.SetPriority(r.ctx, "fp-hk", wire.PriorityCommand{Person: connPerson, TaskID: "tk-hk", Priority: wire.PriorityUrgent, Revision: 9})
+ r.state.Release(r.ctx, "fr-hk", wire.ReleaseCommand{ID: "rl_hk2", Person: connPerson, TaskID: "tk-hk", StepID: "hk", StepRevision: 1})
+ r.steps.MeteredChanged()
+ time.Sleep(300 * time.Millisecond)
+ if r.ranOn("hk", 1) != "" {
+ t.Fatalf("housekeeping spent on %q", r.ranOn("hk", 1))
+ }
+}
+
+// Security round #3: a held step that never launched keeps its hold
+// across a restart (reopening thin.db before its wake-up), and is not
+// failed runner_restarted.
+func TestScheduleHoldSurvivesRestart(t *testing.T) {
+ dir := t.TempDir()
+ state, err := OpenState(context.Background(), dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-r", StepID: "r1", Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}}
+ if err := state.AcceptDispatch(context.Background(), "f", d); err != nil {
+ t.Fatal(err)
+ }
+ wake := time.Now().Add(time.Hour).UTC().Truncate(time.Millisecond)
+ if _, err := state.holdStep(context.Background(), stepRow{DispatchCommand: d}, &wire.StepHold{Reason: wire.HoldHeadroom, WakeAt: &wake, StepRevision: 1}); err != nil {
+ t.Fatal(err)
+ }
+ state.Close()
+ state, err = OpenState(context.Background(), dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer state.Close()
+ if err := state.RecoverSteps(context.Background(), func(context.Context, string) bool { return true }); err != nil {
+ t.Fatal(err)
+ }
+ var st, hold string
+ state.db.QueryRow("SELECT state, hold FROM steps WHERE step_id='r1'").Scan(&st, &hold)
+ var reports int
+ state.db.QueryRow("SELECT count(*) FROM outbox WHERE kind=?", wire.FrameStep).Scan(&reports)
+ if st != runRunning || hold == "" || reports != 0 {
+ t.Fatalf("after a restart: state %q, hold %q, %d reports", st, hold, reports)
+ }
+ if due, ok := state.nextDue(context.Background()); !ok || !due.Equal(wake) {
+ t.Fatalf("wake-up %v %v, want %v", due, ok, wake)
+ }
+}
+
+// Security round #4: an execution is admitted once. A second admission
+// of a launched attempt is refused; a retry before anything launched is
+// the one explicit exception.
+func TestScheduleDuplicateAdmissionRefused(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ 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)
+ }
+ admit := func() error {
+ 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)
+ }
+ return r.state.tx(r.ctx, func(tx *sql.Tx) error { return r.conns.admitTx(r.ctx, tx, row, d) })
+ }
+ launches := 0
+ r.reading("claude-a", 0.1, time.Now().Add(time.Hour))
+ if err := admit(); err != nil {
+ t.Fatal(err)
+ }
+ // Before anything launched: admitted again (a prelaunch retry).
+ if err := admit(); err != nil {
+ t.Fatalf("a prelaunch retry: %v", err)
+ }
+ launches++
+ if err := r.state.setStepNamespace(r.ctx, row, "ns-1"); err != nil {
+ t.Fatal(err)
+ }
+ if err := admit(); !errors.Is(err, errAdmitted) {
+ t.Fatalf("a launched attempt admitted again: %v", err)
+ } else {
+ // Refused: nothing launches.
+ }
+ if launches != 1 {
+ t.Fatalf("%d launches", launches)
+ }
+}
+
+// Security round #12: a hold after a failover is kept against the
+// attempt the step moved to, and said once.
+func TestScheduleHoldAfterFailover(t *testing.T) {
+ r := newSchedRig(t, "claude-a")
+ r.reading("claude-a", 0.1, time.Now().Add(time.Hour))
+ r.fail["claude-a"] = true
+ r.start()
+ r.dispatch("fo", wire.PriorityNormal)
+
+ r.until(5*time.Second, "the held second attempt", func() bool {
+ for _, rep := range r.reports("fo") {
+ if rep.Hold != nil && rep.Attempt == 2 {
+ return true
+ }
+ }
+ return false
+ })
+ var hold string
+ r.state.db.QueryRow("SELECT hold FROM steps WHERE step_id='fo' AND attempt=2").Scan(&hold)
+ if hold == "" {
+ t.Fatal("the hold after the failover was not kept")
+ }
+ time.Sleep(200 * time.Millisecond)
+ n := 0
+ for _, rep := range r.reports("fo") {
+ if rep.Hold != nil {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Fatalf("the hold was said %d times", n)
+ }
+ // Kept, so the step is not looked at again at once.
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.execs["fo"] != 1 {
+ t.Fatalf("the held step ran %d times", r.execs["fo"])
+ }
+}
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index 0eeb44b9..ae3e98fe 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -95,7 +95,7 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
// (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"} {
+ 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", "housekeeping 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
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go
index e79797aa..a17926da 100644
--- a/internal/runner/thin/step.go
+++ b/internal/runner/thin/step.go
@@ -351,17 +351,23 @@ func unrecordedKey(id string) (string, bool) { return strings.CutPrefix(id, unre
func (s *State) RecoverSteps(ctx context.Context, verify func(context.Context, string) bool) error {
var all []stepRow
ns := map[string]string{}
- rows, err := s.db.QueryContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, ns_id FROM steps WHERE state=?", runRunning)
+ rows, err := s.db.QueryContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, ns_id, hold FROM steps WHERE state=?", runRunning)
if err != nil {
return err
}
for rows.Next() {
- var id string
- r, err := scanStep(func(dest ...any) error { return rows.Scan(append(dest, &id)...) })
+ var id, hold string
+ r, err := scanStep(func(dest ...any) error { return rows.Scan(append(dest, &id, &hold)...) })
if err != nil {
rows.Close()
return err
}
+ if hold != "" && id == "" && !r.Cancel {
+ // Held by the scheduler and never launched since (an admission
+ // clears the hold; a launch records its namespace): nothing of
+ // it ran, so it keeps its hold and its wake-up.
+ continue
+ }
all = append(all, r)
ns[r.key()] = id
}
@@ -748,12 +754,15 @@ func (e *StepEngine) runOne(ctx context.Context, r stepRow) {
// 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)
+ // The step may have moved to a later attempt (a failover) first.
+ held := r
+ held.Attempt = max(rep.Attempt, r.Attempt)
+ changed, err := e.State.holdStep(context.WithoutCancel(ctx), held, rep.Hold)
e.log("step hold", err)
if changed {
- held := rep
- held.State = wire.StepRunning
- report(held)
+ out := rep
+ out.State = wire.StepRunning
+ report(out)
}
return
}
diff --git a/internal/schedule/schedule.go b/internal/schedule/schedule.go
index ac026355..e00c436a 100644
--- a/internal/schedule/schedule.go
+++ b/internal/schedule/schedule.go
@@ -114,6 +114,9 @@ type Step struct {
Avoid []string
// Release is the Run now grant the step carries ("" for none).
Release string
+ // Housekeeping: the attempt was dispatched by housekeeping. It counts
+ // as low and never spends, whatever its task's priority or a release.
+ Housekeeping bool
// 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).
@@ -184,6 +187,9 @@ type Decision struct {
// Effective is a step's effective priority: urgent with a release,
// else its own (normal when unset or unknown).
func Effective(s Step) string {
+ if s.Housekeeping {
+ return Low
+ }
if s.Release != "" {
return Urgent
}
@@ -257,7 +263,7 @@ func spendBar(c Conn) string {
}
// leave is the step's leave to spend metered money (§0 decision 5).
-func leave(s Step) bool { return s.Priority == Urgent || s.Release != "" }
+func leave(s Step) bool { return !s.Housekeeping && (s.Priority == Urgent || s.Release != "") }
// eligible are the bars every candidate passes, Run now included: capable,
// usable, not avoided.
diff --git a/internal/schedule/schedule_test.go b/internal/schedule/schedule_test.go
index ca754045..1089b006 100644
--- a/internal/schedule/schedule_test.go
+++ b/internal/schedule/schedule_test.go
@@ -117,6 +117,22 @@ func TestDecideRules(t *testing.T) {
}
}
+// A housekeeping attempt counts as low and never spends, whatever its
+// task's priority or a release (§7, Housekeeping).
+func TestDecideHousekeeping(t *testing.T) {
+ for _, step := range []Step{{Housekeeping: true, Priority: Urgent}, {Housekeeping: true, Release: "r"}, {Housekeeping: true, Priority: Urgent, Release: "r"}} {
+ if d := Decide(in(step, meter("t", 0, 0))); d.Run {
+ t.Fatalf("housekeeping spent: %+v", d)
+ }
+ if d := Decide(in(step, sub("a", "claude", 0.61))); d.Run || d.Effective != Low {
+ t.Fatalf("housekeeping above low's threshold: %+v", d)
+ }
+ if d := Decide(in(step, sub("a", "claude", 0.59))); !d.Run {
+ t.Fatalf("housekeeping under low's threshold: %+v", d)
+ }
+ }
+}
+
// TestDecideReviewFamily: Review prefers another family, then another
// account, then Engineering's own; a release never overrides the order.
func TestDecideReviewFamily(t *testing.T) {
@@ -270,6 +286,7 @@ func randomInput(r *rand.Rand) Input {
if r.IntN(3) == 0 {
step.Release = "r1"
}
+ step.Housekeeping = r.IntN(6) == 0
if r.IntN(2) == 0 {
step.By = dur()
}
@@ -359,8 +376,9 @@ func TestDecideInvariants(t *testing.T) {
t.Fatalf("#%d: a bar passed: %+v on %#v", n, d, c)
}
if c.Billing == Metered {
- // (b) no metered admission without urgent or a release.
- if i.Step.Priority != Urgent && i.Step.Release == "" {
+ // (b) no metered admission without urgent or a release, and
+ // never for housekeeping.
+ if i.Step.Priority != Urgent && i.Step.Release == "" || i.Step.Housekeeping {
t.Fatalf("#%d: metered without leave: %+v", n, d)
}
// (c) never two attempts on one slot; (d) never at the budget
diff --git a/internal/thintest/scheduler_contract_test.go b/internal/thintest/scheduler_contract_test.go
index 8ea5705d..8d16a399 100644
--- a/internal/thintest/scheduler_contract_test.go
+++ b/internal/thintest/scheduler_contract_test.go
@@ -54,13 +54,27 @@ func TestContractScheduler(t *testing.T) {
if err != nil || k.Priority == nil || k.Priority.Priority != wire.PriorityLow || k.Priority.By == nil || k.Priority.SetBy != wire.PrioritySetByCoordinator {
t.Fatalf("priority %+v %v", k.Priority, err)
}
+ // Security round #9: a task recorded and started with nothing set,
+ // then start_task again in the same turn with fields: refused, and
+ // nothing set.
+ plain := taskID(t, r.call("n1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Plain one", "brief": "b"}))
+ if res := r.call("n2", wire.ToolStartTask, map[string]string{"task": plain, "brief": "go"}); res.IsError {
+ t.Fatalf("start: %+v", res)
+ }
+ r.expect(wire.FrameDispatch)
+ if res := r.call("n3", wire.ToolStartTask, map[string]string{"task": plain, "brief": "again", "priority": "low", "by": by}); !res.IsError {
+ t.Fatalf("a second start: %+v", res)
+ }
+ if k, _ := r.client.Task(ctx, plain); k.Priority != nil {
+ t.Fatalf("a second start_task set the priority: %+v", k.Priority)
+ }
// start_task cannot change what is set.
if res := r.call("p2", wire.ToolStartTask, map[string]string{"task": id, "brief": "go", "priority": "normal"}); res.IsError {
t.Fatalf("start: %+v", res)
}
_, body := r.expect(wire.FrameDispatch)
d := body.(*wire.DispatchCommand)
- if d.Priority != wire.PriorityLow || d.By == nil || !d.By.Equal(*k.Priority.By) || d.Release != "" {
+ if d.Priority != wire.PriorityLow || d.By == nil || !d.By.Equal(*k.Priority.By) || d.Release != "" || d.PriorityRevision != 1 || d.Housekeeping {
t.Fatalf("dispatch %+v", d)
}
if k, _ = r.client.Task(ctx, id); k.Priority.Priority != wire.PriorityLow {
@@ -130,7 +144,7 @@ func TestContractScheduler(t *testing.T) {
}
_, body = r.expect(wire.FramePriority)
shape(t, "frames/priority.json", r.runner.Received[len(r.runner.Received)-1])
- if p := body.(*wire.PriorityCommand); p.TaskID != id || p.Priority != wire.PriorityUrgent || p.Revision != k.Revision || p.Person != Owner {
+ if p := body.(*wire.PriorityCommand); p.TaskID != id || p.Priority != wire.PriorityUrgent || p.Revision != 2 || p.Person != Owner {
t.Fatalf("priority frame %+v", p)
}
@@ -217,3 +231,69 @@ func TestContractSchedulerOlderRunner(t *testing.T) {
t.Fatalf("preference frame %+v", c)
}
}
+
+// Security round #2: housekeeping's retry is dispatched as housekeeping
+// (low, no release, whatever the task's priority) and it stays so on the
+// record, for a placement after the housekeeping pass; Run now on it is
+// refused, and its held card offers Wait only.
+func TestContractSchedulerHousekeeping(t *testing.T) {
+ r := newToolRigAt(t, wire.ProtocolScheduler)
+ id, d := r.started("hk", "Retry me by housekeeping")
+ k := r.task(id)
+ if _, err := r.client.SetPriority(r.ctx, id, wire.SetPriority{Priority: wire.PriorityUrgent, Revision: k.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ r.expect(wire.FramePriority)
+ r.stop("hk1", d, "runner_restarted")
+ again := r.nextDispatch()
+ if again.Attempt != 2 || !again.Housekeeping || again.Priority != wire.PriorityLow || again.Release != "" {
+ t.Fatalf("housekeeping's retry %+v", again)
+ }
+ var attempt int64
+ if err := r.inst.DB.Writer().QueryRow("SELECT housekeeping_attempt FROM chat_steps WHERE id = ?", again.StepID).Scan(&attempt); err != nil || attempt != 2 {
+ t.Fatalf("housekeeping provenance %d %v", attempt, err)
+ }
+ r.hold("hk2", again, wire.StepHold{Reason: wire.HoldNoConnection, NeedsPerson: wire.HoldNeedsNoConnection, StepRevision: 2})
+ if _, err := r.client.RunNow(r.ctx, id, wire.RunNow{Step: again.StepID, StepRevision: 2}); Status(err) != 409 {
+ t.Fatalf("Run now on housekeeping's attempt: %v", err)
+ }
+ snap, _ := r.client.Snapshot(r.ctx)
+ for _, c := range snap.Cards {
+ if c.Kind == wire.CardHeld && c.TaskID == id && c.State == wire.CardOpen && len(c.Options) != 1 {
+ t.Fatalf("housekeeping's held card %+v", c)
+ }
+ }
+}
+
+// Security round #5: Research takes the task's priority and deadline on
+// its dispatch, and its hold is kept (queued, not running) with Needs you
+// and Run now, as for any step.
+func TestContractSchedulerResearch(t *testing.T) {
+ r := newToolRigSaying(t, wire.ProtocolScheduler, personWords)
+ r.researchOn()
+ r.inventoryOn()
+ id := r.shopTask("a")
+ k := r.task(id)
+ if _, err := r.client.SetPriority(r.ctx, id, wire.SetPriority{Priority: wire.PriorityUrgent, Revision: k.Revision}); err != nil {
+ t.Fatal(err)
+ }
+ r.research("a-r", id)
+ r.begin("a-start", id)
+ d := r.nextDispatch()
+ if d.Specialist != wire.SpecialistResearch || d.Priority != wire.PriorityUrgent || d.PriorityRevision == 0 {
+ t.Fatalf("research dispatch %+v", d)
+ }
+ k = r.hold("a-h", d, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-a", Provider: "claude", NeedsPerson: wire.HoldNeedsNoReset, StepRevision: 1})
+ var research wire.Step
+ for _, s := range k.Steps {
+ if s.ID == d.StepID {
+ research = s
+ }
+ }
+ if research.State != wire.StepQueued || research.Hold == nil || k.NeedsYou != wire.NeedsHeld {
+ t.Fatalf("held Research %+v needs %q", research, k.NeedsYou)
+ }
+ if rel, err := r.client.RunNow(r.ctx, id, wire.RunNow{Step: d.StepID, StepRevision: 1}); err != nil || rel.Release == "" {
+ t.Fatalf("Run now on Research: %+v %v", rel, err)
+ }
+}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index 50984525..8aa022a4 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -602,8 +602,8 @@ var schedulerOnly = map[string]bool{FrameRelease: true, FramePriority: true}
func downgradeScheduler(body any) bool {
switch v := body.(type) {
case *DispatchCommand:
- set := v.Priority != "" || v.By != nil || v.Release != ""
- v.Priority, v.By, v.Release = "", nil, ""
+ set := v.Priority != "" || v.By != nil || v.Release != "" || v.PriorityRevision != 0 || v.Housekeeping
+ v.Priority, v.By, v.Release, v.PriorityRevision, v.Housekeeping = "", nil, "", 0, false
return set
case *ToolCall:
// record_task's and start_task's priority and deadline: an older
diff --git a/internal/wire/schedule.go b/internal/wire/schedule.go
index 7fe3eed5..08284922 100644
--- a/internal/wire/schedule.go
+++ b/internal/wire/schedule.go
@@ -117,7 +117,9 @@ type ReleaseCommand struct {
// A revision at or below the one held changes nothing.
const FramePriority = "priority"
-// PriorityCommand is a priority change for the runner.
+// PriorityCommand is a priority change for the runner. Revision is the
+// task's priority revision (DispatchCommand.PriorityRevision orders the
+// same values).
type PriorityCommand struct {
Person string `json:"person"`
TaskID string `json:"task_id"`
diff --git a/internal/wire/schedule_test.go b/internal/wire/schedule_test.go
index 9335a048..1a86f933 100644
--- a/internal/wire/schedule_test.go
+++ b/internal/wire/schedule_test.go
@@ -67,16 +67,69 @@ func TestEncodeBelowProtocol14DropsScheduler(t *testing.T) {
}
}
-// record_task's priority and deadline never reach an older instance
-// (it decodes the arguments strictly); at 14 they go out whole.
-func TestEncodeBelowProtocol14DropsToolPriority(t *testing.T) {
- call, _ := wire.NewFrame("t", wire.FrameToolCall, wire.ToolCall{CallID: "c", TurnID: "t", Attempt: 1, Name: wire.ToolRecordTask, Args: json.RawMessage(`{"brief":"b","by":"2026-11-20","priority":"low","repo":"r","title":"x"}`)})
- if same, err := wire.Encode(call, wire.Protocol14); err != nil || !bytes.Equal(same.Data, call.Data) {
- t.Fatalf("changed at 14: %v", err)
+// Frozen protocol 13 schemas: the JSON keys each body had at protocol
+// 13 (main at 379fe0d, before the scheduler), written out so that a
+// field added later cannot slip into them.
+var (
+ frozen13Dispatch = keySet("person task_id step_id attempt specialist repo branch base_sha title brief findings candidate_sha republish from_attempt avoid_account round feedback rebase from_base needs runner_id revert_sha hosted_checks unsandboxed research research_note")
+ frozen13Step = keySet("task_id step_id attempt state reason base_sha candidate_sha pushed termination summary headline log_tail family account verdict review_label findings checks gate exit_code output askable merge_sha into strategy usage switched termination_kind have phase apple checks_sandbox change merge_source merge_parents hosted has_preview preview research")
+ frozen13Preference = keySet("person provider revision")
+ frozen13Record = keySet("repo title brief separate kind")
+ frozen13Start = keySet("task brief")
+)
+
+func keySet(s string) map[string]bool {
+ out := map[string]bool{}
+ for _, k := range strings.Fields(s) {
+ out[k] = true
+ }
+ return out
+}
+
+// frozen13 strictly reads raw against a frozen schema: every key one it
+// had at protocol 13.
+func frozen13(t *testing.T, what string, raw []byte, schema map[string]bool) {
+ t.Helper()
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &m); err != nil {
+ t.Fatalf("%s: %v", what, err)
+ }
+ for k := range m {
+ if !schema[k] {
+ t.Fatalf("%s carries %q, which a protocol 13 peer refuses: %s", what, k, raw)
+ }
}
- got, err := wire.Encode(call, wire.Protocol13)
- if err != nil || strings.Contains(string(got.Data), "priority") || strings.Contains(string(got.Data), `\"by\"`) || !strings.Contains(string(got.Data), "brief") {
- t.Fatalf("at 13: %v %s", err, got.Data)
+}
+
+// What is still sent below 14 decodes strictly against the frozen
+// protocol 13 schemas: a dispatch, a preference, a step report, and
+// record_task's and start_task's arguments.
+func TestEncodeBelowProtocol14AgainstFrozenSchemas(t *testing.T) {
+ by := time.Date(2026, 11, 20, 17, 0, 0, 0, time.UTC)
+ dispatch, _ := wire.NewFrame("d", wire.FrameDispatch, wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: wire.PriorityUrgent, By: &by, Release: "rl", PriorityRevision: 3, Housekeeping: true})
+ pref, _ := wire.NewFrame("p", wire.FramePreference, wire.PreferenceCommand{Person: "p", Provider: "codex", Revision: 2})
+ step, _ := wire.NewFrame("s", wire.FrameStep, wire.StepReport{TaskID: "tk", StepID: "s", Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}})
+ record, _ := wire.NewFrame("r", wire.FrameToolCall, wire.ToolCall{CallID: "c", TurnID: "t", Attempt: 1, Name: wire.ToolRecordTask, Args: json.RawMessage(`{"brief":"b","by":"2026-11-20","kind":"change","priority":"low","repo":"r","separate":false,"title":"x"}`)})
+ start, _ := wire.NewFrame("t", wire.FrameToolCall, wire.ToolCall{CallID: "c2", TurnID: "t", Attempt: 1, Name: wire.ToolStartTask, Args: json.RawMessage(`{"brief":"go","by":"2026-11-20","priority":"normal","task":"tk"}`)})
+ for _, c := range []struct {
+ what string
+ f wire.Frame
+ schema map[string]bool
+ args bool
+ }{{"dispatch", dispatch, frozen13Dispatch, false}, {"preference", pref, frozen13Preference, false}, {"step", step, frozen13Step, false}, {"record_task", record, frozen13Record, true}, {"start_task", start, frozen13Start, true}} {
+ old, err := wire.Encode(c.f, wire.Protocol13)
+ if err != nil {
+ t.Fatalf("%s: %v", c.what, err)
+ }
+ raw := []byte(old.Data)
+ if c.args {
+ var call wire.ToolCall
+ if err := wire.Strict(old.Data, &call); err != nil {
+ t.Fatal(err)
+ }
+ raw = call.Args
+ }
+ frozen13(t, c.what, raw, c.schema)
}
}
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go
index dd63ac83..7c96ea7c 100644
--- a/internal/wire/tasks.go
+++ b/internal/wire/tasks.go
@@ -688,6 +688,13 @@ type DispatchCommand struct {
Priority string `json:"priority,omitempty"`
By *time.Time `json:"by,omitempty"`
Release string `json:"release,omitempty"`
+ // PriorityRevision orders the task's priority and deadline: the
+ // runner keeps a priority frame's value only while no dispatch carries
+ // a newer one. Housekeeping marks an attempt housekeeping dispatched:
+ // it counts as low and never spends, whatever its task's priority or
+ // a release (§7, Housekeeping).
+ PriorityRevision int64 `json:"priority_revision,omitempty"`
+ Housekeeping bool `json:"housekeeping,omitempty"`
}
// WatchMergeCommand watches a task's branch for its candidate landing on