Astra round 1: attempt ownership, withdrawal order, worker identity
A revoked primary's attempts stay its own (only conversation commands move). Withdrawal comes first in reports and sync; only a termination proof counts and it places the next attempt; Retry clears it. Waiting steps end locally on Cancel and nothing goes to an empty runner. The Engineering pin rides the task value. A worker keeps its role in state: no protocol 1 fallback, no primary welcome. Worker reports keep the primary's publication. Oversize is a chunk count past MaxTransferChunks at both ends. An ask of an offline runner is 409 runner_offline. Each with a test that failed first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+547
−53
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/RUNNERS-PROGRESS.md+32 −2internal/equipo/chat/housekeeping_store_test.go+9 −3internal/equipo/chat/questions.go+7 −0internal/equipo/chat/review.go+1 −1internal/equipo/chat/runners.go+45 −12internal/equipo/chat/tasks.go+48 −18internal/equipo/chat/transfers.go+20 −12internal/runner/thin/link.go+32 −3internal/runner/thin/protocol_test.go+58 −0internal/runner/thin/relay.go+5 −1internal/runner/thin/relay_test.go+29 −0internal/thintest/review1_contract_test.go+256 −0internal/wire/runners.go+4 −0
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 4facd89b..3992b3da 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -36,7 +36,7 @@ perf GET /releases/* skip Verified runner release file downloads, not browser GE |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; niced serial reruns measured 5.773s and 5.750s. The added coordinator mount check has no repeated launches to remove; 15s leaves 38 percent headroom for namespace, process-exit and recovery assertions. |
| time internal/tryequipo 30s Release starter-set controller K3 records CI runs of 10.8s and 13.1s; 30s retains the guide integration checks with headroom on the shared runner. |
| size internal/runner/thin 14900 - Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| -time internal/thintest 110s Mac runners slices A and B add role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 8s). Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s. |
| +time internal/thintest 180s Mac runners slices A and B add role, scoping, migration, placement, withdrawal, transfer and publication contracts, and Astra round 1 eight transition contracts (about 15s; the package measured 126s locally under load). Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s. |
| 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). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom. |
| time internal/headless 720s Mac runners add TestMacWorker (M1, M2, M4, M5 with the fake worker; about 25s) and TestMixedVersions (M8: builds the staging line's headless test binary from git history, about 60 to 150s cold, then both pairs, about 20s). Connections slice 1 after Astra round 1 adds attempts that wait for a connection, Review on a refused credential, Codex Engineering and Review and the preference (about 90s more; loaded CI measured 6m42s). It first adds TestHeadlessConnections (usage rows, failover, Codex coordinator, device code, Claude sign-in, failure kinds, cancel and sign-out, writes replayed, Engineering and Review moving connection, the waiting turn): eleven scenarios, about 55 to 100s locally. Thin v1 headless suite: real instance, runner and bubblewrap per scenario (spec 7, under two minutes). Slice 4 adds the review and checks scenarios (4_review with its fix rounds, branch move and merge; 4_checks_honest); loaded CI measured 170s on 2026-11-07. Slice 4b adds 4b_ask (about 12s); loaded CI measured 182.9s. 240s keeps 30 percent headroom. |
| perf GET /api/v1/turns/{id} skip Thin v1 person API: bearer-only JSON for devices, not a browser screen. |
diff --git a/docs/superpowers/plans/RUNNERS-PROGRESS.md b/docs/superpowers/plans/RUNNERS-PROGRESS.md| index 6c5a5fd8..434308c3 100644 |
| --- a/docs/superpowers/plans/RUNNERS-PROGRESS.md |
| +++ b/docs/superpowers/plans/RUNNERS-PROGRESS.md |
| @@ -115,6 +115,35 @@ scripts as in `SLICE1-PROGRESS.md` to `SLICE4C-PROGRESS.md`. |
| Mutations: about 25, each observed failing a test (listed in the |
| commits); defence in depth noted where one survived first. |
| +11. Astra round 1 (REQUEST CHANGES at 1b89bd1, 7 Important, 1 Minor), |
| + each fix with a test that failed first: |
| + 1. A revoked primary keeps its attempts: only conversation commands |
| + move to the replacement; dispatches, cancels, asks, transfers and |
| + publications stay with the runner that may still run them, and the |
| + replacement's empty sync settles none of its steps |
| + (`TestContractRevokedPrimaryKeepsItsAttempts`). |
| + 2. Withdrawal comes first in a step report and in sync: a withdrawn |
| + attempt's results never count; only its termination proof does, |
| + whenever it arrives, and places the next attempt; Retry clears the |
| + withdrawal (`TestContractWithdrawnAttemptReports`, |
| + `TestContractWithdrawnProofAfterFailure`). |
| + 3. A waiting, never-dispatched step ends locally on Cancel, and |
| + nothing is ever sent to an empty runner id |
| + (`TestContractCancelWaitingSteps`). |
| + 4. The Engineering pin is set on the task value the transaction |
| + saves (`TestContractEngineeringPinKept`). |
| + 5. A worker's role is kept in its state: it never falls back to |
| + protocol 1 and never serves under a primary welcome, whatever its |
| + OS (`TestWorkerIdentityPersists`, `TestWorkerRefusesAPrimaryWelcome`). |
| + 6. A worker's report never clears the primary's `Pushed` or |
| + publication (`TestContractPublishedBeforeWorkerDone`). |
| + 7. Oversize is declared by a chunk count past `wire.MaxTransferChunks`, |
| + refused at once by the instance (checks `checks_unavailable`) and |
| + by a receiver (`TestContractTransferDeclaredTooLarge`, |
| + `TestRelayDeclaresOversize`). |
| + 8. Asking a step whose runner is offline answers 409 `runner_offline` |
| + at once (`TestContractAskOfflineRunner`). |
| + |
| ## Decisions |
| - New wire fields are `omitempty` rather than always present: the slice |
| @@ -141,8 +170,9 @@ commits); defence in depth noted where one survived first. |
| ## Open issues |
| -- Revoking a worker with a started step leaves it unproven (Cancel |
| - stays); a revoked primary's steps are rebound to the new primary. |
| +- Revoking a runner with a started step or an unacked dispatch leaves |
| + that attempt unproven: nothing else may supply its proof, so the task |
| + waits (Cancel is accepted, the step stays with the revoked runner). |
| - `have`/thin packs are on the wire but packs are whole one-commit packs. |
| - Copy for the runner lines (waiting, offline, Runners) is not written; |
| slice D/E, with Luna's pass. |
diff --git a/internal/equipo/chat/housekeeping_store_test.go b/internal/equipo/chat/housekeeping_store_test.go| index 0314de47..ae07d265 100644 |
| --- a/internal/equipo/chat/housekeeping_store_test.go |
| +++ b/internal/equipo/chat/housekeeping_store_test.go |
| @@ -315,8 +315,13 @@ func TestHousekeepingNever(t *testing.T) { |
| c.State = wire.CardResolved |
| return t.saveCard(&c) |
| }, |
| - "dispatch, no reserve": func(t *txn) error { var s stepRecord; t.db.First(&s); return t.dispatchStep(r.load(k.ID), &s) }, |
| - "a turn, no reserve": func(t *txn) error { return t.dispatch(&turnRecord{ID: "t1", Person: hkOwner}) }, |
| + "dispatch, no reserve": func(t *txn) error { |
| + var s stepRecord |
| + t.db.First(&s) |
| + kk := r.load(k.ID) |
| + return t.dispatchStep(&kk, &s) |
| + }, |
| + "a turn, no reserve": func(t *txn) error { return t.dispatch(&turnRecord{ID: "t1", Person: hkOwner}) }, |
| } |
| for name, fn := range never { |
| err := r.tx(func(t *txn) error { |
| @@ -346,7 +351,8 @@ func TestHousekeepingNever(t *testing.T) { |
| t.hk = reserved |
| var s stepRecord |
| t.db.First(&s) |
| - return t.dispatchStep(r.load(k.ID), &s) |
| + kk := r.load(k.ID) |
| + return t.dispatchStep(&kk, &s) |
| }) |
| } |
| if err := dispatch(); !errors.Is(err, ErrHousekeepingForbidden) { |
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go| index a50d57fd..5e5469fa 100644 |
| --- a/internal/equipo/chat/questions.go |
| +++ b/internal/equipo/chat/questions.go |
| @@ -168,6 +168,13 @@ func (s *Store) Ask(ctx context.Context, person, taskID string, in wire.AskQuest |
| if !ok || target.Person != person { |
| return ErrNotAskable |
| } |
| + // The session lives on the runner that ran the step: offline, the |
| + // person is told so now (ask again when it is back). |
| + if online, err := t.runnerOnline(person, target.RunnerID); err != nil { |
| + return err |
| + } else if !online { |
| + return ErrRunnerOffline |
| + } |
| var n int64 |
| if err := t.db.Model(&questionRecord{}).Where("task_id = ?", k.ID).Count(&n).Error; err != nil { |
| return err |
diff --git a/internal/equipo/chat/review.go b/internal/equipo/chat/review.go| index ef08ca05..fdb3136f 100644 |
| --- a/internal/equipo/chat/review.go |
| +++ b/internal/equipo/chat/review.go |
| @@ -226,7 +226,7 @@ func (t *txn) nextStep(k *taskRecord, steps []stepRecord, s stepRecord) error { |
| if err := t.db.Create(&s).Error; err != nil { |
| return err |
| } |
| - if err := t.dispatchStep(*k, &s); err != nil { |
| + if err := t.dispatchStep(k, &s); err != nil { |
| return err |
| } |
| return t.saveStep(&s, k) |
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go| index a1694fae..d8060423 100644 |
| --- a/internal/equipo/chat/runners.go |
| +++ b/internal/equipo/chat/runners.go |
| @@ -33,19 +33,35 @@ func UnboundSteps(tx *gorm.DB) (int64, error) { |
| // current primary's. |
| const orphanedBy = `SELECT id FROM runners WHERE person = ? AND revoked_at IS NOT NULL AND coalesce(role, '') IN ('primary', '')` |
| -// rebind gives the person's primary what no runner holds: commands |
| -// written while the person had no primary, and the unacked commands and |
| -// unfinished steps of a revoked primary. A worker's are re-placed instead. |
| +// attemptKinds are commands that belong to one attempt on one runner: a |
| +// dispatch whose ack was lost may already run there, so they never move. |
| +var attemptKinds = []string{wire.FrameDispatch, wire.FrameCancelStep, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameBlob, wire.FrameSendPack, wire.FramePublish} |
| + |
| +// rebind gives the person's primary the conversation's commands no runner |
| +// holds: those written while the person had no primary, and a revoked |
| +// primary's unacked ones. A revoked runner's attempts stay its own (steps, |
| +// dispatches, questions, transfers, publications) until their termination |
| +// is proven; the replacement's sync never settles them. |
| func (t *txn) rebind(p RunnerPrincipal) error { |
| if primary, err := t.s.authority.PrimaryRunner(t.db, p.Person); err != nil || primary != p.RunnerID { |
| return err |
| } |
| - if err := t.db.Exec(`UPDATE runner_commands SET runner_id = ? WHERE person = ? AND acked_at IS NULL |
| - AND (coalesce(runner_id, '') = '' OR runner_id IN (`+orphanedBy+`))`, p.RunnerID, p.Person, p.Person).Error; err != nil { |
| + return t.db.Exec(`UPDATE runner_commands SET runner_id = ? WHERE person = ? AND acked_at IS NULL AND kind NOT IN ? |
| + AND (coalesce(runner_id, '') = '' OR runner_id IN (`+orphanedBy+`))`, p.RunnerID, p.Person, attemptKinds, p.Person).Error |
| +} |
| + |
| +// withdrawnEnded applies the termination proof of a withdrawn attempt: |
| +// it ends as not run when it was withdrawn for that (a pack too large to |
| +// relay), else the next attempt is placed. |
| +func (t *txn) withdrawnEnded(k *taskRecord, s *stepRecord) error { |
| + if s.Reason != "" { |
| + s.Terminated = true |
| + return t.resolveNotRun(k, s, s.Reason) |
| + } |
| + if err := t.replace(k, s); err != nil { |
| return err |
| } |
| - return t.db.Exec(`UPDATE chat_steps SET runner_id = ? WHERE person = ? AND state IN (?, ?) |
| - AND runner_id IN (`+orphanedBy+`)`, p.RunnerID, p.Person, wire.StepQueued, wire.StepRunning, p.Person).Error |
| + return t.saveStep(s, k) |
| } |
| // MaxRunnerLabel bounds the machine label a runner reports. |
| @@ -131,6 +147,20 @@ func (t *txn) runners(person string) ([]runnerInfo, error) { |
| return out, nil |
| } |
| +// runnerOnline reports whether one of the person's runners is online now. |
| +func (t *txn) runnerOnline(person, id string) (bool, error) { |
| + rs, err := t.runners(person) |
| + if err != nil { |
| + return false, err |
| + } |
| + for _, r := range rs { |
| + if r.ID == id { |
| + return r.Online, nil |
| + } |
| + } |
| + return false, nil |
| +} |
| + |
| // runnerView is the Runner resource. |
| func runnerView(r runnerInfo) wire.Runner { |
| v := wire.Runner{ID: r.ID, Revision: r.Revision, Online: r.Online, Label: r.Label, Role: r.Role, Platform: r.Hello.Platform, Capabilities: r.Hello.Capabilities} |
| @@ -233,7 +263,7 @@ func encodeList(v []string) string { |
| // leaves the step waiting (placed false). When no runner has ever had the |
| // tags, or the primary cannot relay a pack (protocol 1), the step goes to |
| // the primary without needs and ends honestly there (needs_macos). |
| -func (t *txn) place(k taskRecord, s *stepRecord) (placed bool, err error) { |
| +func (t *txn) place(k *taskRecord, s *stepRecord) (placed bool, err error) { |
| primary, err := t.s.authority.PrimaryRunner(t.db, s.Person) |
| if err != nil { |
| return false, err |
| @@ -257,6 +287,9 @@ func (t *txn) place(k taskRecord, s *stepRecord) (placed bool, err error) { |
| } |
| } |
| if k.EngineeringRunner == "" && s.RunnerID != "" { |
| + // On the task value the transaction carries, so its next save |
| + // keeps the pin. |
| + k.EngineeringRunner = s.RunnerID |
| if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("engineering_runner", s.RunnerID).Error; err != nil { |
| return false, err |
| } |
| @@ -267,7 +300,7 @@ func (t *txn) place(k taskRecord, s *stepRecord) (placed bool, err error) { |
| s.Needs, s.RunnerID = "", primary |
| return true, nil |
| } |
| - needs, err := t.checksNeeds(k, *s) |
| + needs, err := t.checksNeeds(*k, *s) |
| if err != nil { |
| return false, err |
| } |
| @@ -321,7 +354,7 @@ func (t *txn) place(k taskRecord, s *stepRecord) (placed bool, err error) { |
| // replace ends the current attempt's placement and places the next one: |
| // after a refusal, a withdrawal before it started, or a withdrawn |
| // attempt's termination. The caller saves s. |
| -func (t *txn) replace(k taskRecord, s *stepRecord) error { |
| +func (t *txn) replace(k *taskRecord, s *stepRecord) error { |
| if err := t.voidAttempt(*s); err != nil { |
| return err |
| } |
| @@ -350,7 +383,7 @@ func (t *txn) withdraw(k *taskRecord, s *stepRecord) error { |
| return nil |
| } |
| if s.StartedAt == nil { |
| - if err := t.replace(*k, s); err != nil { |
| + if err := t.replace(k, s); err != nil { |
| return err |
| } |
| return t.saveStep(s, k) |
| @@ -408,7 +441,7 @@ func (t *txn) placeWaiting(person string) error { |
| continue |
| } |
| since := s.WaitingSince |
| - if err := t.dispatchStep(k, &s); err != nil { |
| + if err := t.dispatchStep(&k, &s); err != nil { |
| return err |
| } |
| if s.Placement == wire.PlacementWaiting { |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index cf37f3a4..298832ec 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -684,7 +684,7 @@ func (t *txn) startTask(r turnRecord, id, brief string) (wire.ToolResult, error) |
| if err := t.db.Create(&s).Error; err != nil { |
| return wire.ToolResult{}, err |
| } |
| - if err := t.dispatchStep(k, &s); err != nil { |
| + if err := t.dispatchStep(&k, &s); err != nil { |
| return wire.ToolResult{}, err |
| } |
| k.Stage = wire.StageInProgress |
| @@ -697,7 +697,7 @@ func (t *txn) startTask(r turnRecord, id, brief string) (wire.ToolResult, error) |
| // dispatchStep queues the dispatch command for the step's attempt on the |
| // runner it is placed on, with the task's findings. The caller saves s. |
| -func (t *txn) dispatchStep(k taskRecord, s *stepRecord) error { |
| +func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error { |
| // Housekeeping dispatches only within its reservation, on a connection |
| // that is not standing down. |
| if err := t.hkSpend(s.Person); err != nil { |
| @@ -707,11 +707,21 @@ func (t *txn) dispatchStep(k taskRecord, s *stepRecord) error { |
| if err != nil || !placed { |
| return err |
| } |
| + if s.RunnerID == "" { |
| + // No runner at all (no primary yet): it waits, and is placed when |
| + // one connects. Nothing is ever sent to nobody. |
| + now := t.now() |
| + s.Placement = wire.PlacementWaiting |
| + if s.WaitingSince == nil { |
| + s.WaitingSince = &now |
| + } |
| + return nil |
| + } |
| var p projectRecord |
| if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil { |
| return err |
| } |
| - v, err := t.taskView(k) |
| + v, err := t.taskView(*k) |
| if err != nil { |
| return err |
| } |
| @@ -719,7 +729,7 @@ func (t *txn) dispatchStep(k taskRecord, s *stepRecord) error { |
| if base == "" && !s.Rebase { |
| base = k.BaseSHA |
| } |
| - brief, err := t.stepBrief(k, *s) |
| + brief, err := t.stepBrief(*k, *s) |
| if err != nil { |
| return err |
| } |
| @@ -745,7 +755,7 @@ func (t *txn) dispatchStep(k taskRecord, s *stepRecord) error { |
| // from the primary as a pack in an inbound transfer. |
| cmd.Needs = decodeList(s.Needs) |
| if s.Specialist == wire.SpecialistChecks { |
| - if _, err := t.openTransfer(k, *s, primary, s.RunnerID, wire.TransferInbound, cmd.BaseSHA, s.CandidateSHA); err != nil { |
| + if _, err := t.openTransfer(*k, *s, primary, s.RunnerID, wire.TransferInbound, cmd.BaseSHA, s.CandidateSHA); err != nil { |
| return err |
| } |
| } |
| @@ -819,6 +829,14 @@ func (t *txn) cancelTask(person, id string) (int64, error) { |
| k.Stage = wire.StageCancelled |
| return s.Attempt, t.saveTask(&k) |
| } |
| + if s.RunnerID == "" { |
| + // Waiting for a runner and never dispatched: nothing runs, so it |
| + // ends here. |
| + now := t.now() |
| + s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince = wire.StepCancelled, "cancelled", true, &now, "", nil |
| + k.Stage = wire.StageCancelled |
| + return s.Attempt, t.saveStep(&s, &k) |
| + } |
| k.CancelRequested = true |
| if err := t.saveTask(&k); err != nil { |
| return 0, err |
| @@ -882,22 +900,20 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| if v.TerminationKind != "" && s.TerminationKind == "" && (v.TerminationKind == wire.TerminationNamespace || v.TerminationKind == wire.TerminationProcessGroup) { |
| s.TerminationKind = v.TerminationKind |
| } |
| + if s.Withdrawn { |
| + // A withdrawn attempt's results never count, whatever arrives first; |
| + // only its termination proof does, and it places the next attempt. |
| + if advanced || !wire.StepTerminal(v.State) || !v.Termination { |
| + return nil |
| + } |
| + return t.withdrawnEnded(&k, &s) |
| + } |
| if !wire.StepTerminal(s.State) && wire.StepTerminal(v.State) && v.State != wire.StepDone && v.Termination { |
| switch { |
| - case s.Withdrawn && s.Reason != "": |
| - // Withdrawn to end as not run (a pack too large to relay). |
| - s.Terminated, s.TerminationKind = true, firstSet(v.TerminationKind, s.TerminationKind) |
| - return t.resolveNotRun(&k, &s, s.Reason) |
| - case s.Withdrawn: |
| - // Its termination is proven: the next attempt goes elsewhere. |
| - if err := t.replace(k, &s); err != nil { |
| - return err |
| - } |
| - return t.saveStep(&s, &k) |
| case v.State == wire.StepFailed && v.Reason == "placement_refused": |
| // It lacks a need: place it again without that runner. |
| s.RefusedBy = encodeList(append(decodeList(s.RefusedBy), l.Runner.RunnerID)) |
| - if err := t.replace(k, &s); err != nil { |
| + if err := t.replace(&k, &s); err != nil { |
| return err |
| } |
| return t.saveStep(&s, &k) |
| @@ -955,7 +971,12 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| if s.CandidateSHA == "" || v.CandidateSHA != s.CandidateSHA || !v.Pushed && role == wire.RolePrimary { |
| return nil |
| } |
| - s.Pushed, s.Apple = v.Pushed, v.Apple |
| + // Pushed is the primary's word: for a worker's commit only the |
| + // primary's published report sets it, and this report keeps it. |
| + if role == wire.RolePrimary { |
| + s.Pushed = true |
| + } |
| + s.Apple = v.Apple |
| s.Askable = v.Askable |
| if s.Rebase && s.BaseSHA != "" { |
| // The change sits on the new tip now: review reads it from |
| @@ -1111,6 +1132,14 @@ func (t *txn) syncSteps(l Lease, held []wire.StepRun) error { |
| if err != nil { |
| return err |
| } |
| + if s.Withdrawn { |
| + // Its runner holds nothing of it and verified none survives: |
| + // the withdrawn attempt is over, and the next one is placed. |
| + if err := t.withdrawnEnded(&k, &s); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| now := t.now() |
| s.State, s.Reason, s.Terminated, s.FinishedAt = wire.StepFailed, "interrupted", true, &now |
| if k.CancelRequested { |
| @@ -1280,7 +1309,8 @@ func (s *Store) RetryTask(ctx context.Context, person, id string) (attempt int64 |
| if st.Specialist == wire.SpecialistMerge { |
| st.MergeSHA, st.MergeInto, st.MergeStrategy = "", "", "" |
| } |
| - if err := t.dispatchStep(k, &st); err != nil { |
| + st.Withdrawn, st.RefusedBy = false, "" |
| + if err := t.dispatchStep(&k, &st); err != nil { |
| return err |
| } |
| k.Stage = wire.StageInProgress |
diff --git a/internal/equipo/chat/transfers.go b/internal/equipo/chat/transfers.go| index af391996..2c8579a0 100644 |
| --- a/internal/equipo/chat/transfers.go |
| +++ b/internal/equipo/chat/transfers.go |
| @@ -112,6 +112,10 @@ func (t *txn) blob(l Lease, v *wire.Blob) error { |
| if s.Attempt != tr.Attempt || s.Withdrawn || wire.FinalStage(k.Stage) || k.CancelRequested || tr.Direction == wire.TransferInbound && wire.StepTerminal(s.State) { |
| return errTransferRefused("attempt not current") |
| } |
| + if v.Total > wire.MaxTransferChunks { |
| + // Declared too large to relay: the checks cannot run on that runner. |
| + return t.tooLarge(&k, &s, tr) |
| + } |
| data, err := base64.StdEncoding.DecodeString(v.Data) |
| if err != nil || len(v.Data) > wire.MaxBlobData || !hexDigest.MatchString(v.SHA256) || v.Total < 1 || v.Index < 0 || v.Index >= v.Total { |
| return errTransferRefused("bad chunk") |
| @@ -120,18 +124,7 @@ func (t *txn) blob(l Lease, v *wire.Blob) error { |
| return errTransferRefused("chunk out of order") |
| } |
| if tr.Bytes+int64(len(data)) > wire.MaxTransferBytes { |
| - tr.State = transferClosed |
| - if err := t.dropChunks(tr); err != nil { |
| - return err |
| - } |
| - if err := t.db.Model(&transferRecord{}).Where("id = ?", tr.ID).Update("state", transferClosed).Error; err != nil { |
| - return err |
| - } |
| - // Too large to relay: the checks cannot run on that runner. |
| - if tr.Direction == wire.TransferInbound && !wire.StepTerminal(s.State) { |
| - return t.withdrawResolving(&k, &s, "checks_unavailable") |
| - } |
| - return nil |
| + return t.tooLarge(&k, &s, tr) |
| } |
| tr.Total, tr.SHA256, tr.Received, tr.Bytes = v.Total, v.SHA256, tr.Received+1, tr.Bytes+int64(len(data)) |
| if tr.Received == tr.Total { |
| @@ -149,6 +142,21 @@ func (t *txn) blob(l Lease, v *wire.Blob) error { |
| return nil |
| } |
| +// tooLarge closes a transfer past the bound; inbound, its checks end as |
| +// not run (checks_unavailable). |
| +func (t *txn) tooLarge(k *taskRecord, s *stepRecord, tr transferRecord) error { |
| + if err := t.dropChunks(tr); err != nil { |
| + return err |
| + } |
| + if err := t.db.Model(&transferRecord{}).Where("id = ?", tr.ID).Update("state", transferClosed).Error; err != nil { |
| + return err |
| + } |
| + if tr.Direction == wire.TransferInbound && !wire.StepTerminal(s.State) { |
| + return t.withdrawResolving(k, s, "checks_unavailable") |
| + } |
| + return nil |
| +} |
| + |
| // blobAcked closes a transfer once its receiver acked the last chunk. |
| func (t *txn) blobAcked(body string) error { |
| var v wire.Blob |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index 5d265f33..272200f4 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -27,6 +27,24 @@ var ErrRevoked = errors.New("runner credential refused") |
| // instance) and tries again later. |
| var ErrInstanceTooOld = errors.New("the instance speaks only protocol 1, which has no workers: update the instance first") |
| +// ErrRoleMismatch means the instance welcomed a worker as something else: |
| +// a runner the instance once made a worker stays one (only a new |
| +// enrolment makes a primary), so it does not serve. |
| +var ErrRoleMismatch = errors.New("this runner is a worker and the instance welcomed it as a primary") |
| + |
| +// metaRole keeps the role the instance gave this runner, in its state. |
| +const metaRole = "role" |
| + |
| +// workerOnly: this runner can only be a worker, by its platform or |
| +// because the instance made it one. |
| +func (l *Link) workerOnly(ctx context.Context) bool { |
| + if l.WorkerOnly { |
| + return true |
| + } |
| + role, err := l.State.meta(ctx, metaRole) |
| + return err != nil || role == wire.RoleWorker |
| +} |
| + |
| // olderRetry is how long a worker waits before asking an older instance |
| // again. |
| var olderRetry = time.Minute |
| @@ -309,7 +327,7 @@ func (l *Link) Run(ctx context.Context) error { |
| } |
| return err |
| } |
| - if errors.Is(err, ErrInstanceTooOld) { |
| + if errors.Is(err, ErrInstanceTooOld) || errors.Is(err, ErrRoleMismatch) { |
| retry = olderRetry |
| if l.Logger != nil { |
| l.Logger.Error("runner refused: this runner is a worker and the instance is an older release", "origin", l.Origin, "err", err) |
| @@ -375,7 +393,7 @@ func (l *Link) session(ctx context.Context) (time.Duration, error) { |
| if offer < wire.Protocol2 || websocket.CloseStatus(err) != websocket.StatusPolicyViolation { |
| return 0, err |
| } |
| - if l.WorkerOnly { |
| + if l.workerOnly(ctx) { |
| return 0, ErrInstanceTooOld |
| } |
| if l.Logger != nil { |
| @@ -427,10 +445,21 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire |
| if welcome.Protocol == 0 { |
| spoken, role = wire.Protocol1, wire.RolePrimary |
| } |
| - if spoken < wire.Protocol2 && l.WorkerOnly { |
| + worker := l.workerOnly(ctx) |
| + if spoken < wire.Protocol2 && worker { |
| c.CloseNow() |
| return nil, nil, ErrInstanceTooOld |
| } |
| + if worker && role != wire.RoleWorker { |
| + c.CloseNow() |
| + return nil, nil, ErrRoleMismatch |
| + } |
| + if role == wire.RoleWorker { |
| + if err := l.State.setMeta(ctx, metaRole, wire.RoleWorker); err != nil { |
| + c.CloseNow() |
| + return nil, nil, err |
| + } |
| + } |
| l.mu.Lock() |
| l.proto, l.role = min(spoken, offer), role |
| l.mu.Unlock() |
diff --git a/internal/runner/thin/protocol_test.go b/internal/runner/thin/protocol_test.go| index 306811ca..5c51c557 100644 |
| --- a/internal/runner/thin/protocol_test.go |
| +++ b/internal/runner/thin/protocol_test.go |
| @@ -130,3 +130,61 @@ func TestLinkSpeaksProtocol2(t *testing.T) { |
| t.Fatalf("spoken %d %q", p, role) |
| } |
| } |
| + |
| +// A runner the instance made a worker stays one, whatever its OS: the |
| +// role is kept in its state; refused by an older instance it does not fall |
| +// back to protocol 1, and it never accepts a primary's welcome. |
| +func TestWorkerIdentityPersists(t *testing.T) { |
| + defer func(d time.Duration) { olderRetry = d }(olderRetry) |
| + olderRetry = time.Hour |
| + inst := newFakeInstance(t) |
| + logs := &syncBuffer{} |
| + link, state, _, _ := startLink(t, inst.url, &stubCoordinator{}) |
| + link.Logger = slog.New(slog.NewTextHandler(logs, nil)) |
| + c := <-inst.conns |
| + read(t, c, wire.FrameHello) |
| + write(t, c, wiretest.Fixture("frames/welcome-worker.json")) |
| + read(t, c, wire.FrameSync) |
| + if role, _ := state.meta(context.Background(), "role"); role != wire.RoleWorker { |
| + t.Fatalf("role not kept: %q", role) |
| + } |
| + write(t, c, wiretest.Fixture("frames/drain.json")) |
| + older := <-inst.conns |
| + if refused, _ := olderInstance(t, older); !refused { |
| + t.Fatal("the worker's hello was not protocol 2") |
| + } |
| + select { |
| + case again := <-inst.conns: |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + _, raw, _ := again.Read(ctx) |
| + t.Fatalf("a worker fell back to protocol 1: %s", raw) |
| + case <-time.After(1500 * time.Millisecond): |
| + } |
| +} |
| + |
| +func TestWorkerRefusesAPrimaryWelcome(t *testing.T) { |
| + defer func(d time.Duration) { olderRetry = d }(olderRetry) |
| + olderRetry = time.Hour |
| + inst := newFakeInstance(t) |
| + _, _, _, _ = startLink(t, inst.url, &stubCoordinator{}, func(s *State) { |
| + if err := s.setMeta(context.Background(), "role", wire.RoleWorker); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + c := <-inst.conns |
| + read(t, c, wire.FrameHello) |
| + raw, _ := json.Marshal(wire.Frame{ID: "w-p", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":2,"role":"primary"}`)}) |
| + write(t, c, raw) |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + for { |
| + _, msg, err := c.Read(ctx) |
| + if err != nil { |
| + return |
| + } |
| + if f, _, _ := wire.ParseFrame(msg); f.Type == wire.FrameSync { |
| + t.Fatalf("a worker served as primary: %s", msg) |
| + } |
| + } |
| +} |
diff --git a/internal/runner/thin/relay.go b/internal/runner/thin/relay.go| index 8024d1ec..b3aa726c 100644 |
| --- a/internal/runner/thin/relay.go |
| +++ b/internal/runner/thin/relay.go |
| @@ -120,6 +120,10 @@ func (s *State) pack(ctx context.Context, want wire.TransferHeader) ([]byte, err |
| if total == -1 { |
| total, digest = tot, sum |
| } |
| + if tot > wire.MaxTransferChunks { |
| + // Declared too large to relay. |
| + return nil, errPackRefused |
| + } |
| if idx != n || tot != total || sum != digest || int64(buf.Len()+len(data)) > wire.MaxTransferBytes { |
| return nil, errPackRefused |
| } |
| @@ -175,7 +179,7 @@ func (s *State) queueUpload(ctx context.Context, h wire.TransferHeader, pack []b |
| if int64(len(pack)) > wire.MaxTransferBytes { |
| // Too large to relay: one chunk says so (the instance refuses a |
| // total past the bound and the checks end as not run). |
| - total = int(wire.MaxTransferBytes/wire.MaxBlobChunk) + 2 |
| + total = wire.MaxTransferChunks + 1 |
| pack = pack[:wire.MaxBlobChunk] |
| } |
| return s.tx(ctx, func(t *sql.Tx) error { |
diff --git a/internal/runner/thin/relay_test.go b/internal/runner/thin/relay_test.go| index 996591f1..c4ec0c03 100644 |
| --- a/internal/runner/thin/relay_test.go |
| +++ b/internal/runner/thin/relay_test.go |
| @@ -238,3 +238,32 @@ func TestRelayRefusesAWrongCommit(t *testing.T) { |
| t.Fatalf("wrong commit %+v", reps) |
| } |
| } |
| + |
| +// A pack too large to relay is declared by a chunk count past the shared |
| +// bound, which the instance refuses at once; the worker refuses it too. |
| +func TestRelayDeclaresOversize(t *testing.T) { |
| + r := newRelayRig(t) |
| + h := r.header() |
| + if err := r.e.O.State.AcceptUpload(context.Background(), "up-1", wire.SendPackCommand{Transfer: h, Have: []string{}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + big := make([]byte, wire.MaxTransferBytes+10) |
| + if err := r.e.O.State.queueUpload(context.Background(), h, big); err != nil { |
| + t.Fatal(err) |
| + } |
| + frames, _, _ := r.e.O.State.Unacked(context.Background(), 0) |
| + if len(frames) != 1 { |
| + t.Fatalf("%d chunks for an oversized pack", len(frames)) |
| + } |
| + var b wire.Blob |
| + json.Unmarshal(frames[0].Data, &b) |
| + if b.Total <= wire.MaxTransferChunks { |
| + t.Fatalf("declared total %d is within the bound %d", b.Total, wire.MaxTransferChunks) |
| + } |
| + if err := r.e.O.State.AcceptChunk(context.Background(), "in-1", b); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := r.e.O.State.pack(context.Background(), h); !errors.Is(err, errPackRefused) { |
| + t.Fatalf("the receiver took a declared oversize: %v", err) |
| + } |
| +} |
diff --git a/internal/thintest/review1_contract_test.go b/internal/thintest/review1_contract_test.go| new file mode 100644 |
| index 00000000..a1823a5e |
| --- /dev/null |
| +++ b/internal/thintest/review1_contract_test.go |
| @@ -0,0 +1,256 @@ |
| +package thintest |
| + |
| +import ( |
| + "context" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// revoke revokes a runner as the owner. |
| +func (r *runnersRig) revoke(id string) { |
| + r.t.Helper() |
| + var revision int64 |
| + if err := r.inst.DB.Writer().QueryRow("SELECT revision FROM runners WHERE id = ?", id).Scan(&revision); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + if err := r.inst.Store.RevokeRunner(r.ctx, equipo.Actor{Address: Owner}, id, revision); err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +// A revoked primary keeps its attempts until their termination is |
| +// proven: its unacked dispatch is not sent to the replacement (a lost ack |
| +// may mean it runs), its running step stays its own, the replacement's |
| +// empty sync ends neither, and Retry stays refused. |
| +func TestContractRevokedPrimaryKeepsItsAttempts(t *testing.T) { |
| + r := newRunnersRig(t) |
| + ctx := r.ctx |
| + old := r.runner.Welcome.RunnerID |
| + running := taskID(t, r.call("v1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Running when revoked", "brief": "b"})) |
| + r.call("v2", wire.ToolStartTask, map[string]string{"task": running, "brief": "go"}) |
| + _, body := r.expect(wire.FrameDispatch) |
| + d := body.(*wire.DispatchCommand) |
| + r.step("v-run", wire.StepReport{TaskID: running, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40), Findings: []wire.Finding{}}) |
| + unacked := taskID(t, r.call("v3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Dispatched, never acked", "brief": "b"})) |
| + r.call("v4", wire.ToolStartTask, map[string]string{"task": unacked, "brief": "go"}) |
| + r.runner.Close() |
| + r.revoke(old) |
| + |
| + token := r.inst.EnrolRunner(t).Token |
| + p, err := DialRunnerHello(ctx, r.inst.URL, token, primaryHello(0)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer p.Close() |
| + if p.Welcome.Role != wire.RolePrimary { |
| + t.Fatalf("replacement welcome %+v", p.Welcome) |
| + } |
| + np := &peer{t: t, r: r.toolRig, fr: p} |
| + np.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}) |
| + np.send(wire.FrameStep, wire.StepReport{TaskID: running, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}}) |
| + for _, id := range []string{running, unacked} { |
| + k, err := r.client.Task(ctx, id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if s := k.Steps[0]; wire.StepTerminal(s.State) || s.Terminated || s.RunnerID != old { |
| + t.Fatalf("the replacement took the revoked primary's attempt %s: %+v", id, s) |
| + } |
| + if _, err := r.client.RetryTask(ctx, id); Status(err) != 409 { |
| + t.Fatalf("retry of an unproven attempt: %v", err) |
| + } |
| + } |
| + np.none(wire.FrameDispatch, 100*time.Millisecond) |
| +} |
| + |
| +// Never-dispatched waiting checks end on Cancel, locally: nothing is |
| +// sent to an empty runner id, and the task is cancelled at once. |
| +func TestContractCancelWaitingSteps(t *testing.T) { |
| + r := newRunnersRig(t) |
| + w, _ := r.newWorker("Tito Studio") |
| + w.fr.Close() |
| + time.Sleep(100 * time.Millisecond) |
| + task, _ := r.candidate("iOS waiting", true) |
| + if s := r.checksStep(task); s.Placement != wire.PlacementWaiting { |
| + t.Fatalf("not waiting %+v", s) |
| + } |
| + if _, err := r.client.CancelTask(r.ctx, task); err != nil { |
| + t.Fatal(err) |
| + } |
| + k, _ := r.client.Task(r.ctx, task) |
| + s := r.checksStep(task) |
| + if k.Stage != wire.StageCancelled || s.State != wire.StepCancelled || !s.Terminated { |
| + t.Fatalf("cancel of a waiting step: task %s step %+v", k.Stage, s) |
| + } |
| + var n int |
| + if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE coalesce(runner_id, '') = '' AND kind IN (?, ?)", wire.FrameCancelStep, wire.FrameDispatch).Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("%d commands to nobody: %v", n, err) |
| + } |
| +} |
| + |
| +// Engineering's pin survives the step's own save: a new task records the |
| +// runner its Engineering ran on. |
| +func TestContractEngineeringPinKept(t *testing.T) { |
| + r := newRunnersRig(t) |
| + task, _ := r.candidate("Pinned", false) |
| + k, err := r.client.Task(r.ctx, task) |
| + if err != nil || k.EngineeringRunner != r.runner.Welcome.RunnerID { |
| + t.Fatalf("pin %q, want %q: %v", k.EngineeringRunner, r.runner.Welcome.RunnerID, err) |
| + } |
| +} |
| + |
| +// startedOnWorker places checks on the only worker, starts the attempt, |
| +// takes the worker away for the offline limit (a fake clock), and has the |
| +// sweep withdraw the started attempt; the worker comes back to its cancel. |
| +func (r *runnersRig) startedOnWorker(title string) (task, step string, w *peer, sha string) { |
| + r.t.Helper() |
| + w, token := r.newWorker("Tito Studio") |
| + task, sha = r.candidate(title, true) |
| + _, body := w.expect(wire.FrameDispatch) |
| + d := body.(*wire.DispatchCommand) |
| + if !w.lease(d.StepID, 1) { |
| + r.t.Fatal("start refused") |
| + } |
| + gen := w.fr.Welcome.Generation |
| + w.fr.Close() |
| + later := time.Now().UTC().Add(chat.OfflineLimit + time.Minute) |
| + r.inst.Store.Chat().SetClock(func() time.Time { return later }) |
| + if err := r.inst.Store.Chat().Place(r.ctx); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + r.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() }) |
| + w = r.dialWorker(token, "Tito Studio", gen) |
| + _, body = w.expect(wire.FrameCancelStep) |
| + if c := body.(*wire.CancelStepCommand); c.StepID != d.StepID || c.Attempt != 1 { |
| + r.t.Fatalf("cancel %+v", c) |
| + } |
| + return task, d.StepID, w, sha |
| +} |
| + |
| +// Withdrawal comes first (M6): a withdrawn attempt's delayed success does |
| +// not count; a failure without proof waits for the proof, and the proof |
| +// then places the next attempt; Retry works on that next attempt. |
| +func TestContractWithdrawnAttemptReports(t *testing.T) { |
| + r := newRunnersRig(t) |
| + task, step, w, sha := r.startedOnWorker("Withdrawn, then passed") |
| + w.send(wire.FrameStep, passed(task, step, 1, sha)) |
| + s := r.checksStep(task) |
| + if s.Checks == wire.ChecksPassed || s.Attempt != 2 { |
| + t.Fatalf("a withdrawn attempt's delayed success counted: %+v", s) |
| + } |
| + _, body := w.expect(wire.FrameDispatch) |
| + if d := body.(*wire.DispatchCommand); d.StepID != step || d.Attempt != 2 { |
| + t.Fatalf("next attempt %+v", d) |
| + } |
| + // Attempt 2 fails normally (with its proof): Retry gives attempt 3, |
| + // which may start. |
| + if !w.lease(step, 2) { |
| + t.Fatal("attempt 2 refused") |
| + } |
| + w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: step, Attempt: 2, State: wire.StepFailed, Reason: "provider_failed", Termination: true, Findings: []wire.Finding{}}) |
| + if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 3 { |
| + t.Fatalf("retry after withdrawal %+v %v", acc, err) |
| + } |
| + w.expect(wire.FrameDispatch) |
| + if !w.lease(step, 3) { |
| + t.Fatal("attempt 3 refused after Retry") |
| + } |
| +} |
| + |
| +func TestContractWithdrawnProofAfterFailure(t *testing.T) { |
| + r := newRunnersRig(t) |
| + task, step, w, _ := r.startedOnWorker("Withdrawn, failed, proven") |
| + w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: step, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", Findings: []wire.Finding{}}) |
| + if s := r.checksStep(task); s.Attempt != 1 || s.Terminated { |
| + t.Fatalf("before the proof %+v", s) |
| + } |
| + w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: step, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) |
| + _, body := w.expect(wire.FrameDispatch) |
| + if d := body.(*wire.DispatchCommand); d.StepID != step || d.Attempt != 2 { |
| + t.Fatalf("the proof did not place the next attempt: %+v", d) |
| + } |
| +} |
| + |
| +// The primary may publish before the worker's final report: that report |
| +// keeps the primary's publication, and checks follow. |
| +func TestContractPublishedBeforeWorkerDone(t *testing.T) { |
| + r := newRunnersRig(t) |
| + w, _ := r.newWorker("Mac A") |
| + task := taskID(t, r.call("c-early", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Published early", "brief": "b"})) |
| + r.pinWorker(task, w) |
| + r.call("s-early", wire.ToolStartTask, map[string]string{"task": task, "brief": "go"}) |
| + _, body := w.expect(wire.FrameDispatch) |
| + d := body.(*wire.DispatchCommand) |
| + if !w.lease(d.StepID, d.Attempt) { |
| + t.Fatal("start refused") |
| + } |
| + sha := strings.Repeat("c", 40) |
| + w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40), Findings: []wire.Finding{}}) |
| + w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, CandidateSHA: sha, Phase: "committed", Findings: []wire.Finding{}}) |
| + _, body = w.expect(wire.FrameSendPack) |
| + h := body.(*wire.SendPackCommand).Transfer |
| + w.send(wire.FrameBlob, chunk(h, []byte("PACK commit"))) |
| + _, body = r.primary.expect(wire.FramePublish) |
| + pub := body.(*wire.PublishCommand) |
| + r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: 1, CandidateSHA: sha, Pushed: true}) |
| + w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: sha, Termination: true, Findings: []wire.Finding{}}) |
| + k, _ := r.client.Task(r.ctx, task) |
| + if !k.Steps[0].Pushed || k.Steps[0].Publication != wire.PublicationPublished || k.CandidateSHA != sha { |
| + t.Fatalf("the worker's report cleared the publication: %+v", k.Steps[0]) |
| + } |
| + _, body = r.expect(wire.FrameDispatch) |
| + if c := body.(*wire.DispatchCommand); c.Specialist != wire.SpecialistChecks || c.CandidateSHA != sha { |
| + t.Fatalf("checks %+v", c) |
| + } |
| +} |
| + |
| +// A pack too large to relay is declared by its chunk count, and both ends |
| +// read it the same way: the checks end as not run (checks_unavailable). |
| +func TestContractTransferDeclaredTooLarge(t *testing.T) { |
| + r := newRunnersRig(t) |
| + w, _ := r.newWorker("Mac A") |
| + task, _ := r.candidate("iOS huge", true) |
| + _, body := r.primary.expect(wire.FrameSendPack) |
| + h := body.(*wire.SendPackCommand).Transfer |
| + w.expect(wire.FrameDispatch) |
| + c := chunk(h, []byte("PACK")) |
| + c.Total = wire.MaxTransferChunks + 1 |
| + r.primary.send(wire.FrameBlob, c) |
| + s := r.checksStep(task) |
| + if s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != "checks_unavailable" { |
| + t.Fatalf("declared oversize %+v", s) |
| + } |
| + if n := r.relayed(w); n != 0 { |
| + t.Fatal("an oversized chunk was relayed") |
| + } |
| +} |
| + |
| +// Asking a specialist whose runner is offline is answered at once: the |
| +// runner is offline (runner_offline), nothing queues. |
| +func TestContractAskOfflineRunner(t *testing.T) { |
| + r := newToolRig(t) |
| + id, _, _ := r.askableTask("o", strings.Repeat("1", 40), strings.Repeat("2", 40)) |
| + r.runner.Close() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for { |
| + runners, err := r.client.Runners(context.Background()) |
| + if err == nil && len(runners.Items) == 1 && !runners.Items[0].Online { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("runner still online: %+v %v", runners, err) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + if _, err := r.client.Ask(r.ctx, id, "What did you change?", "", "off-1"); Status(err) != 409 || !strings.Contains(err.Error(), "runner_offline") { |
| + t.Fatalf("ask of an offline runner: %v", err) |
| + } |
| + if k, _ := r.client.Task(r.ctx, id); len(k.Questions) != 0 { |
| + t.Fatalf("a question queued for an offline runner: %+v", k.Questions) |
| + } |
| +} |
diff --git a/internal/wire/runners.go b/internal/wire/runners.go| index cfc4ede3..3c64c543 100644 |
| --- a/internal/wire/runners.go |
| +++ b/internal/wire/runners.go |
| @@ -198,6 +198,10 @@ const ( |
| MaxBlobChunk = MaxBlobData / 4 * 3 |
| MaxTransferBytes = 64 << 20 |
| TransferTTL = 24 * time.Hour |
| + // MaxTransferChunks is the most chunks a transfer within the bound |
| + // has. A sender declares a pack too large to relay by a total past it, |
| + // and the receiver refuses such a transfer at its first chunk. |
| + MaxTransferChunks = (MaxTransferBytes + MaxBlobChunk - 1) / MaxBlobChunk |
| ) |
| // Protocol 2 frames. |