moves: offline run's dispatch gate and one status classifier
Astra branch review round 2, R2-1/R2-2 and R2-3, under stopping rule 2: Paul chose to state each invariant, enforce it in one place and hold it with guard tests. A. "A pending pre-open interrupt prevents forward mutation, and the first pre-open interrupt on a bound move follows abort through completion." offlinerun.Runner.dispatch is the one way an action reaches the doors: it takes pending Ctrl-Cs, decides, lets the watcher write everything said before the request, then checks once more right before dispatch; one pending there withdraws the action and the view is decided again, so before open it becomes the abort. Only dispatch calls Doors.Post/Nudge (TestGateIsTheOnlyWayToPost), and in the CLI only runDoors.send makes a POST, reached only from runDoors.Post/Nudge (TestRunDoorsPostOnlyThroughTheGate). The step line's "sent" now comes with the answer, so a withdrawn POST is never said to be sent. A Ctrl-C that cuts short a status read is ErrInterrupted: Run reads again rather than ending, so a --resume run follows the abort it promised (R2-2); OR28 waits for a view that names the region. Guard tests at the four boundaries (before output, after output from the writer, during a back-off, a resumed run's first read) in gate_test.go and TestMoveOfflineRunGateBoundaries; the simulation now presses Ctrl-C at random points and asserts nothing is dispatched past a pending one, no forward POST follows a pre-open one, and how each run ends. B. "A status failure that won't pass stops run." classifyStatus is the only classifier, by status alone: no response, 5xx, 429 and a 200 cut short pass; every redirect, every other 4xx (unreadable body or not) and any reply that is not a status view are refused for good: exit 1, the console's sentence or the mover's own, then OR29 and the status command. TestRunStatusClasses is the table (302 to /login, 401 cut short with io.ErrUnexpectedEOF included); TestMoveOfflineRunStatusRefusedMidRun runs both end to end. No new copy. Census envelopes re-pinned with the unchanged claim.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+872
−92
internal/host/movesoffline_e2e_test.go+160 −9internal/moves/offlinerun/gate_test.go+240 −0internal/moves/offlinerun/run.go+91 −53internal/moves/offlinerun/run_test.go+1 −0internal/provision/testdata/plan14-root-reads-omr-run.tsv+2 −2move_offline_run.go+99 −28move_offline_run_test.go+276 −0move_test.go+3 −0
Intent
diff --git a/internal/host/movesoffline_e2e_test.go b/internal/host/movesoffline_e2e_test.go| index 9c606148b..8fb780c63 100644 |
| --- a/internal/host/movesoffline_e2e_test.go |
| +++ b/internal/host/movesoffline_e2e_test.go |
| @@ -1960,6 +1960,8 @@ func offlineArmedReleaser(t *testing.T) { |
| // of it. |
| type e2eRunPost struct { |
| hand bool |
| + pending bool // a Ctrl-C was pending as the run dispatched it |
| + afterAbort bool // the run had taken a pre-open Ctrl-C (InterruptAbort) before it |
| verb, id string |
| code int |
| lost bool // the reply was lost after the door answered |
| @@ -2002,6 +2004,12 @@ type e2eRunDoors struct { |
| // after its status read, before its POST (a second operator's hand in |
| // between, Astra branch round 1, finding 1). |
| beforeRunPost func(verb string) |
| + // ints is the run's Ctrl-Cs, aborted that it has taken a pre-open |
| + // one: each run POST is kept with both as it was dispatched. |
| + ints *offlinerun.Interrupts |
| + aborted bool |
| + // onStatus, when set, runs inside each status read. |
| + onStatus func() |
| } |
| // e2eToken is a CLI login's token and the requests it has made. The |
| @@ -2030,6 +2038,9 @@ func (d *e2eRunDoors) do(hand bool, method, u, body string) (int, string) { |
| func (d *e2eRunDoors) Status(context.Context) (offlinerun.View, error) { |
| code, out := d.do(false, http.MethodGet, d.w.base, "") |
| + if d.onStatus != nil { |
| + d.onStatus() |
| + } |
| if code != http.StatusOK { |
| return offlinerun.View{}, fmt.Errorf("status = %d %s", code, out) |
| } |
| @@ -2094,14 +2105,44 @@ func (d *e2eRunDoors) answer(code int, out string) offlinerun.Answer { |
| } |
| func (d *e2eRunDoors) Post(_ context.Context, verb, id string) offlinerun.Answer { |
| + pending, aborted := d.ints.Pending(), d.aborted |
| if d.beforeRunPost != nil { |
| d.beforeRunPost(verb) |
| } |
| - return d.answer(d.post(false, verb, id)) |
| + code, out := d.post(false, verb, id) |
| + last := &d.posts[len(d.posts)-1] |
| + last.pending, last.afterAbort = pending, aborted |
| + return d.answer(code, out) |
| } |
| func (d *e2eRunDoors) Nudge(_ context.Context, id string) offlinerun.Answer { |
| - return d.answer(d.post(false, "nudge", id)) |
| + pending, aborted := d.ints.Pending(), d.aborted |
| + code, out := d.post(false, "nudge", id) |
| + last := &d.posts[len(d.posts)-1] |
| + last.pending, last.afterAbort = pending, aborted |
| + return d.answer(code, out) |
| +} |
| + |
| +// e2ePressWatch is the simulation's Watcher: it may press Ctrl-C while it |
| +// "writes" (Saw, Acting), and keeps every Ctrl-C the run took. |
| +type e2ePressWatch struct { |
| + press func() |
| + doors *e2eRunDoors |
| + kinds []offlinerun.Interrupt |
| + takes int |
| + pressN *int |
| +} |
| + |
| +func (w *e2ePressWatch) Saw(offlinerun.View) { w.press() } |
| +func (w *e2ePressWatch) Acting(offlinerun.Action, offlinerun.Memory) { w.press() } |
| +func (w *e2ePressWatch) Withdrawn(offlinerun.Action) {} |
| +func (w *e2ePressWatch) Acted(offlinerun.Action, offlinerun.Result, offlinerun.Memory) { |
| +} |
| +func (w *e2ePressWatch) Interrupted(i offlinerun.Interrupt, _ offlinerun.Memory) { |
| + w.kinds = append(w.kinds, i) |
| + if i == offlinerun.InterruptAbort { |
| + w.doors.aborted = true |
| + } |
| } |
| // runVerbs lists the run's POSTs as "<verb>" in order. |
| @@ -2120,6 +2161,7 @@ type e2eQuiet struct{} |
| func (e2eQuiet) Saw(offlinerun.View) {} |
| func (e2eQuiet) Acting(offlinerun.Action, offlinerun.Memory) {} |
| +func (e2eQuiet) Withdrawn(offlinerun.Action) {} |
| func (e2eQuiet) Acted(offlinerun.Action, offlinerun.Result, offlinerun.Memory) {} |
| func (e2eQuiet) Interrupted(offlinerun.Interrupt, offlinerun.Memory) {} |
| @@ -2199,6 +2241,10 @@ type e2eRun struct { |
| now time.Duration |
| between func() |
| ticks int |
| + // ints and watch, when set, are the run's Ctrl-Cs and its Watcher |
| + // (e2eQuiet when nil). |
| + ints *offlinerun.Interrupts |
| + watch offlinerun.Watcher |
| } |
| func (r *e2eRun) probe(context.Context) int { |
| @@ -2212,8 +2258,12 @@ func (r *e2eRun) probe(context.Context) int { |
| func (r *e2eRun) run(maxTicks int) offlinerun.Done { |
| t := r.w.t |
| t.Helper() |
| + var watch offlinerun.Watcher = e2eQuiet{} |
| + if r.watch != nil { |
| + watch = r.watch |
| + } |
| runner := &offlinerun.Runner{Doors: r.doors, Probe: r.probe, Policy: r.policy, |
| - Clock: func() time.Duration { return r.now }, Poll: offlinerun.DefaultPoll, Watch: e2eQuiet{}} |
| + Clock: func() time.Duration { return r.now }, Poll: offlinerun.DefaultPoll, Watch: watch, Interrupts: r.ints} |
| m := offlinerun.NewMemory("") |
| for ; r.ticks < maxTicks; r.ticks++ { |
| next, done, err := runner.Step(context.Background(), m) |
| @@ -2530,7 +2580,8 @@ func TestOfflineMoveRunSimulation(t *testing.T) { |
| t.Logf("%d seeds: %+v", seeds, all) |
| // The faults happened: a simulation that injected none proves nothing. |
| if !t.Failed() && seeds >= offlineRunSimSeeds && |
| - (all.done == 0 || all.aborted == 0 || all.stopped == 0 || all.refused == 0 || all.runAborts == 0 || all.lost == 0 || all.missed == 0 || all.handWrites == 0) { |
| + (all.done == 0 || all.aborted == 0 || all.stopped == 0 || all.refused == 0 || all.runAborts == 0 || all.lost == 0 || all.missed == 0 || all.handWrites == 0 || |
| + all.pressAbort == 0 || all.pressOpen == 0 || all.pressStop == 0) { |
| t.Fatalf("the seeds did not exercise every fault and ending: %+v", all) |
| } |
| } |
| @@ -2550,14 +2601,22 @@ const ( |
| simHandBeforePost = 0.04 |
| simHandStagesFirst = 0.06 |
| simLoseFirstStage = 0.03 |
| + // simPress is a Ctrl-C at each point one can land on, on the seeds |
| + // that press. |
| + simPress = 0.015 |
| ) |
| type offlineRunSimTally struct { |
| - done, aborted, stopped int |
| - refused int |
| - lost, missed, handPosts int |
| - handWrites, nudges, ticks int |
| - runAborts int |
| + done, aborted, stopped int |
| + refused int |
| + // Ctrl-Cs: pressed, taken by the run, and of those the first before |
| + // open (abort), after open (or an open with no answer), and the rest |
| + // (a second one, or before anything was sent). |
| + pressed, taken int |
| + pressAbort, pressOpen, pressStop int |
| + lost, missed, handPosts int |
| + handWrites, nudges, ticks int |
| + runAborts int |
| } |
| func (a *offlineRunSimTally) add(b offlineRunSimTally) { |
| @@ -2565,6 +2624,11 @@ func (a *offlineRunSimTally) add(b offlineRunSimTally) { |
| a.aborted += b.aborted |
| a.stopped += b.stopped |
| a.refused += b.refused |
| + a.pressed += b.pressed |
| + a.taken += b.taken |
| + a.pressAbort += b.pressAbort |
| + a.pressOpen += b.pressOpen |
| + a.pressStop += b.pressStop |
| a.lost += b.lost |
| a.missed += b.missed |
| a.handPosts += b.handPosts |
| @@ -2615,6 +2679,33 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| r.doors.post(true, hands[rng.IntN(len(hands))], "") |
| } |
| } |
| + // Ctrl-C at random points, on half the seeds (the other half keep the |
| + // run's own endings common): while a status read is on the wire, while |
| + // the run writes a view or an action's line (before the gate's last |
| + // check), inside a POST already dispatched, and between ticks. |
| + pressing := rng.IntN(2) == 0 |
| + pressed := 0 |
| + press := func() { |
| + if pressing && rng.Float64() < simPress { |
| + pressed++ |
| + r.ints.Add() |
| + } |
| + } |
| + r.ints = offlinerun.NewInterrupts() |
| + r.doors.ints = r.ints |
| + watch := &e2ePressWatch{press: press, doors: r.doors} |
| + r.watch = watch |
| + r.doors.onStatus = press |
| + hand := r.between |
| + r.between = func() { |
| + hand() |
| + press() |
| + } |
| + handBefore := r.doors.beforeRunPost |
| + r.doors.beforeRunPost = func(verb string) { |
| + handBefore(verb) |
| + press() |
| + } |
| // Half the seeds run on budgets short enough for the run's own aborts |
| // (a step or the time offline over its limit) to land at random points. |
| if rng.IntN(2) == 0 { |
| @@ -2626,6 +2717,18 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| var tally offlineRunSimTally |
| tally.missed, tally.ticks = r.boxes.missed, r.ticks |
| + tally.pressed = pressed |
| + for _, k := range watch.kinds { |
| + tally.taken++ |
| + switch k { |
| + case offlinerun.InterruptAbort: |
| + tally.pressAbort++ |
| + case offlinerun.InterruptAfterOpen, offlinerun.InterruptOpenUncertain: |
| + tally.pressOpen++ |
| + default: |
| + tally.pressStop++ |
| + } |
| + } |
| var trail []string |
| for _, p := range r.doors.posts { |
| who := "run" |
| @@ -2678,6 +2781,18 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| case p.id != mine: |
| fail("the run posted %s naming %q; its move is %s", p.verb, p.id, mine) |
| } |
| + // The dispatch gate (Astra round 2, R2-1/R2-2): nothing leaves |
| + // while a Ctrl-C is pending, and after a pre-open one no forward |
| + // POST leaves at all. |
| + if !p.hand && p.pending { |
| + fail("the run dispatched %s with a Ctrl-C pending", p.verb) |
| + } |
| + if !p.hand && p.afterAbort { |
| + switch p.verb { |
| + case offlinerun.VerbStage, offlinerun.VerbStart, offlinerun.VerbSeal, offlinerun.VerbFlip, offlinerun.VerbOpen: |
| + fail("the run posted %s after a Ctrl-C before open", p.verb) |
| + } |
| + } |
| if !p.hand && p.verb == offlinerun.VerbAbort { |
| tally.runAborts++ |
| if opened[p.before.id] || p.before.opened { |
| @@ -2705,6 +2820,38 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| } |
| end := w.snap() |
| + // A run that took a Ctrl-C ends aborted, or stopped (exit 4); done |
| + // only when every Ctrl-C it took came after open; exit 5 only when its |
| + // first stage was refused and nothing of its own exists. |
| + if len(watch.kinds) > 0 { |
| + afterOpenOnly := true |
| + for _, k := range watch.kinds { |
| + if k != offlinerun.InterruptAfterOpen { |
| + afterOpenOnly = false |
| + } |
| + } |
| + switch done.Exit { |
| + case offlinerun.ExitAborted, offlinerun.ExitStopped: |
| + case offlinerun.ExitDone: |
| + if !afterOpenOnly { |
| + fail("done after Ctrl-Cs %v", watch.kinds) |
| + } |
| + case offlinerun.ExitRefused: |
| + if mine != "" { |
| + fail("exit 5 after Ctrl-Cs %v with a move of its own", watch.kinds) |
| + } |
| + default: |
| + fail("exit %d after Ctrl-Cs %v", done.Exit, watch.kinds) |
| + } |
| + // The first pre-open Ctrl-C on a bound move is followed through: |
| + // once it was taken, the run ends aborted unless a second Ctrl-C, |
| + // an open or another operator ended it otherwise. |
| + if watch.kinds[0] == offlinerun.InterruptAbort && len(watch.kinds) == 1 && done.Exit == offlinerun.ExitStopped && |
| + done.Reason != offlinerun.ReasonOtherMove && done.Reason != offlinerun.ReasonProbeFailed && done.Reason != offlinerun.ReasonMoveGone && |
| + done.Reason != offlinerun.ReasonUnexpectedState { |
| + fail("the run took a Ctrl-C before open and stopped (%s) instead of following the abort", done.Reason) |
| + } |
| + } |
| switch done.Exit { |
| case offlinerun.ExitDone: |
| tally.done++ |
| @@ -2744,6 +2891,10 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| // adopting the move it then read, and sent nothing more. |
| case done.Reason == offlinerun.ReasonStageUncertain && runs == 1 && end.id != "": |
| case done.Reason == offlinerun.ReasonStageNotWritten && runs == 1 && mine == "": |
| + // Stopped by Ctrl-C: before anything was sent, or a second one, |
| + // one after open, or one after an open with no answer. |
| + case done.Reason == offlinerun.ReasonNothingSent && runs == 0: |
| + case done.Reason == offlinerun.ReasonStoppedWatching && len(watch.kinds) > 0: |
| default: |
| fail("exit 4 (%s) with the record %s", done.Reason, end) |
| } |
diff --git a/internal/moves/offlinerun/gate_test.go b/internal/moves/offlinerun/gate_test.go| new file mode 100644 |
| index 000000000..36b1936b2 |
| --- /dev/null |
| +++ b/internal/moves/offlinerun/gate_test.go |
| @@ -0,0 +1,240 @@ |
| +package offlinerun |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "reflect" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The dispatch gate (Astra branch review round 2, R2-1 and R2-2; Paul chose |
| +// to enforce the invariant in one place). Invariant: a pending pre-open |
| +// interrupt prevents forward mutation, and the first pre-open interrupt on |
| +// a bound move follows abort through completion. These are its guard tests, |
| +// one per boundary a Ctrl-C can land on, and the structural check that |
| +// nothing else in the package posts. |
| + |
| +// pressWatch is a Watcher that presses Ctrl-C from inside the output: on |
| +// the nth Acting (1-based), or on the nth Saw, as the terminal blocking |
| +// mid-write would let one land. |
| +type pressWatch struct { |
| + nopWatch |
| + ints *Interrupts |
| + onActing, onSaw int |
| + actings, saws int |
| + withdrawn []string |
| +} |
| + |
| +func (w *pressWatch) Saw(View) { |
| + w.saws++ |
| + if w.saws == w.onSaw { |
| + w.ints.Add() |
| + } |
| +} |
| + |
| +func (w *pressWatch) Acting(a Action, _ Memory) { |
| + w.actings++ |
| + if w.actings == w.onActing { |
| + w.ints.Add() |
| + } |
| +} |
| + |
| +func (w *pressWatch) Withdrawn(a Action) { |
| + if p, ok := a.(Post); ok { |
| + w.withdrawn = append(w.withdrawn, p.Verb) |
| + } else { |
| + w.withdrawn = append(w.withdrawn, fmt.Sprintf("%T", a)) |
| + } |
| +} |
| + |
| +// gateRun is a Runner on fake time over d, with Ctrl-Cs and a pressWatch. |
| +func gateRun(d Doors) (*Runner, *pressWatch) { |
| + r, _ := testRunner(d, func() int { return 200 }) |
| + r.Interrupts = NewInterrupts() |
| + w := &pressWatch{ints: r.Interrupts} |
| + r.Watch = w |
| + return r, w |
| +} |
| + |
| +// landedToAbort: landed with next open, then the abort's views. |
| +func landedToAbort() []View { |
| + return []View{ |
| + withNext(tv(StateLanded), VerbOpen), |
| + withNext(tv(StateReverting), VerbFinish), |
| + none(&Outcome{ID: tID, Outcome: OutcomeAborted}), |
| + } |
| +} |
| + |
| +// TestGateBeforeOutput: a Ctrl-C that lands while the view is said (Saw's |
| +// output, before the action's own) is taken before anything is decided: |
| +// abort, never open, and it follows through to finish. |
| +func TestGateBeforeOutput(t *testing.T) { |
| + d := &fakeDoors{views: landedToAbort()} |
| + r, w := gateRun(d) |
| + w.onSaw = 1 |
| + done, _, err := r.Run(context.Background(), offline(StateLanded, 0)) |
| + if err != nil || done.Exit != ExitAborted { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if got := strings.Join(d.log, ","); got != "status,abort "+tID+",status,finish "+tID+",status" { |
| + t.Fatalf("calls %s", got) |
| + } |
| +} |
| + |
| +// TestGateAfterOutput: a Ctrl-C that lands while the open's own line is |
| +// written (Acting), after every earlier check: the gate's last check, just |
| +// before dispatch, withdraws the open and the abort goes out instead. |
| +func TestGateAfterOutput(t *testing.T) { |
| + d := &fakeDoors{views: landedToAbort()} |
| + r, w := gateRun(d) |
| + w.onActing = 1 |
| + done, _, err := r.Run(context.Background(), offline(StateLanded, 0)) |
| + if err != nil || done.Exit != ExitAborted { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if got := strings.Join(d.log, ","); got != "status,abort "+tID+",status,finish "+tID+",status" { |
| + t.Fatalf("calls %s", got) |
| + } |
| + if !reflect.DeepEqual(w.withdrawn, []string{VerbOpen}) { |
| + t.Fatalf("withdrawn %v, want the open", w.withdrawn) |
| + } |
| + // Every forward verb is withdrawn the same way. |
| + for _, c := range []struct { |
| + state, verb string |
| + }{{StateStopping, VerbSeal}, {StateSealed, VerbFlip}, {StateLanded, VerbOpen}} { |
| + d := &fakeDoors{views: []View{withNext(tv(c.state), c.verb), withNext(tv(StateReverting), VerbFinish), none(&Outcome{ID: tID, Outcome: OutcomeAborted})}} |
| + r, w := gateRun(d) |
| + w.onActing = 1 |
| + done, _, _ := r.Run(context.Background(), offline(c.state, 0)) |
| + if done.Exit != ExitAborted || strings.Contains(strings.Join(d.log, ","), c.verb+" ") { |
| + t.Fatalf("%s: done %#v, calls %q", c.verb, done, d.log) |
| + } |
| + } |
| + // A stage the run would send on its own bound move, too. |
| + d = &fakeDoors{views: []View{staging(5, true, 2*mib), withNext(tv(StateReverting), VerbFinish), none(&Outcome{ID: tID, Outcome: OutcomeAborted})}} |
| + r, w = gateRun(d) |
| + w.onActing = 1 |
| + if done, _, _ := r.Run(context.Background(), bound(StateStaging, 0)); done.Exit != ExitAborted || d.log[1] != "abort "+tID { |
| + t.Fatalf("stage: done %#v, calls %q", done, d.log) |
| + } |
| +} |
| + |
| +// TestGateDuringBackoff: a Ctrl-C during a POST's rate-limit back-off (the |
| +// Doors give the POST up: NotSent) is taken before anything else is |
| +// posted: abort, never the open again. |
| +func TestGateDuringBackoff(t *testing.T) { |
| + d := &fakeDoors{views: landedToAbort()} |
| + r, _ := gateRun(d) |
| + first := true |
| + d.answer = func(verb string) Answer { |
| + if verb == VerbOpen && first { |
| + first = false |
| + r.Interrupts.Add() |
| + return Answer{NotSent: true} |
| + } |
| + return Answer{Accepted: true} |
| + } |
| + d.views = []View{withNext(tv(StateLanded), VerbOpen), withNext(tv(StateLanded), VerbOpen), withNext(tv(StateReverting), VerbFinish), none(&Outcome{ID: tID, Outcome: OutcomeAborted})} |
| + done, _, err := r.Run(context.Background(), offline(StateLanded, 0)) |
| + if err != nil || done.Exit != ExitAborted { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if got := strings.Join(d.log, ","); got != "status,open "+tID+",status,abort "+tID+",status,finish "+tID+",status" { |
| + t.Fatalf("calls %s", got) |
| + } |
| +} |
| + |
| +// TestGateResumedFirstRead (R2-2): a Ctrl-C that cancels the first read of |
| +// a --resume run aborts the bound move: the read is tried again, not |
| +// given up, and the abort follows through to finish. |
| +func TestGateResumedFirstRead(t *testing.T) { |
| + d := &fakeDoors{views: []View{{}, withNext(tv(StateLanded), VerbOpen), withNext(tv(StateReverting), VerbFinish), none(&Outcome{ID: tID, Outcome: OutcomeAborted})}} |
| + r, w := gateRun(d) |
| + interrupted := &interruptedDoors{fakeDoors: d, ints: r.Interrupts} |
| + r.Doors = interrupted |
| + done, _, err := r.Run(context.Background(), NewMemory(tID)) |
| + if err != nil || done.Exit != ExitAborted { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if got := strings.Join(d.log, ","); got != "status,status,abort "+tID+",status,finish "+tID+",status" { |
| + t.Fatalf("calls %s", got) |
| + } |
| + if !reflect.DeepEqual(w.interrupts, []Interrupt{InterruptAbort}) { |
| + t.Fatalf("interrupts %v", w.interrupts) |
| + } |
| + // A first read that fails for any other reason still ends the run. |
| + d = &fakeDoors{views: []View{none(nil)}, errs: map[int]bool{0: true}} |
| + r, _ = gateRun(d) |
| + if _, _, err := r.Run(context.Background(), NewMemory(tID)); err == nil || errors.Is(err, ErrInterrupted) { |
| + t.Fatalf("err %v", err) |
| + } |
| +} |
| + |
| +// interruptedDoors: the first status read is cancelled by a Ctrl-C, as the |
| +// CLI's read on a context Interrupts.Bind ended. |
| +type interruptedDoors struct { |
| + *fakeDoors |
| + ints *Interrupts |
| + done bool |
| +} |
| + |
| +func (d *interruptedDoors) Status(ctx context.Context) (View, error) { |
| + v, err := d.fakeDoors.Status(ctx) |
| + if !d.done { |
| + d.done = true |
| + d.ints.Add() |
| + return View{}, fmt.Errorf("status: %w", ErrInterrupted) |
| + } |
| + return v, err |
| +} |
| + |
| +// TestGateIsTheOnlyWayToPost: in this package only dispatch calls the |
| +// Doors' Post and Nudge, so every POST passes the gate's last check. A new |
| +// call anywhere else fails here. |
| +func TestGateIsTheOnlyWayToPost(t *testing.T) { |
| + entries, err := os.ReadDir(".") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + found := 0 |
| + for _, e := range entries { |
| + name := e.Name() |
| + if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { |
| + continue |
| + } |
| + f, err := parser.ParseFile(token.NewFileSet(), name, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, decl := range f.Decls { |
| + fn, ok := decl.(*ast.FuncDecl) |
| + if !ok || fn.Body == nil { |
| + continue |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + sel, ok := call.Fun.(*ast.SelectorExpr) |
| + if !ok || (sel.Sel.Name != "Post" && sel.Sel.Name != "Nudge") { |
| + return true |
| + } |
| + if fn.Name.Name != "dispatch" || fn.Recv == nil { |
| + t.Errorf("%s: %s calls .%s outside the dispatch gate", name, fn.Name.Name, sel.Sel.Name) |
| + } |
| + found++ |
| + return true |
| + }) |
| + } |
| + } |
| + if found != 2 { |
| + t.Fatalf("found %d calls of Post or Nudge, want the gate's two", found) |
| + } |
| +} |
diff --git a/internal/moves/offlinerun/run.go b/internal/moves/offlinerun/run.go| index c33de1891..6d26bed4b 100644 |
| --- a/internal/moves/offlinerun/run.go |
| +++ b/internal/moves/offlinerun/run.go |
| @@ -24,6 +24,10 @@ const ReasonStoppedWatching = "stopped-watching" |
| // and ReasonStatusRefused, since nothing can be decided without a view. |
| var ErrStatusRefused = errors.New("the console refused the status read") |
| +// ErrInterrupted is a status read a Ctrl-C ended (the Doors read on a |
| +// context from Interrupts.Bind). Doors wrap it; Run reads again. |
| +var ErrInterrupted = errors.New("a Ctrl-C ended the status read") |
| + |
| // ReasonStatusRefused ends a run on ErrStatusRefused (exit 1). |
| const ReasonStatusRefused = "status-refused" |
| @@ -159,6 +163,10 @@ func (i *Interrupts) Wake() <-chan struct{} { |
| return i.wake |
| } |
| +// Pending says a Ctrl-C has not been taken yet (for a witness that checks |
| +// nothing is dispatched past one). |
| +func (i *Interrupts) Pending() bool { return i.pending() } |
| + |
| // pending says a Ctrl-C has not been taken yet. |
| func (i *Interrupts) pending() bool { |
| if i == nil { |
| @@ -184,10 +192,14 @@ func (i *Interrupts) take() bool { |
| } |
| // Watcher sees the run: each view read, each action before it is performed |
| -// and its result after, and each Ctrl-C. |
| +// (or withdrawn) and its result after, and each Ctrl-C. |
| type Watcher interface { |
| Saw(v View) |
| + // Acting says an action before the gate dispatches it; Withdrawn that |
| + // the gate did not (a Ctrl-C was pending), so whatever Acting began is |
| + // ended without it; Acted what a dispatched action got. |
| Acting(a Action, m Memory) |
| + Withdrawn(a Action) |
| Acted(a Action, r Result, m Memory) |
| Interrupted(i Interrupt, m Memory) |
| } |
| @@ -212,12 +224,10 @@ type Runner struct { |
| stops int |
| } |
| -// Step reads status once, decides, and performs at most one action. done |
| -// is set when the run ends; err when the status could not be read (nothing |
| -// was decided or sent). A Ctrl-C that arrived by the end of the read is |
| -// taken before anything is decided from it, and one that arrives before a |
| -// POST goes out is taken and the view decided again (finding 2 of the |
| -// branch review): a pending first Ctrl-C becomes an abort, never an open. |
| +// Step reads status once, decides, and performs at most one action through |
| +// the dispatch gate. done is set when the run ends; err when the status |
| +// could not be read (nothing was decided or sent). A Ctrl-C that arrived by |
| +// the end of the read is taken before anything is said or decided. |
| func (r *Runner) Step(ctx context.Context, m Memory) (Memory, *Done, error) { |
| v, err := r.Doors.Status(ctx) |
| var read *View |
| @@ -232,67 +242,95 @@ func (r *Runner) Step(ctx context.Context, m Memory) (Memory, *Done, error) { |
| return m, nil, err |
| } |
| r.Watch.Saw(v) |
| - var a Action |
| + m, stop = r.dispatch(ctx, v, m) |
| + return m, stop, nil |
| +} |
| + |
| +// dispatch is the dispatch gate: the one way an action decided from view v |
| +// reaches the doors (TestGateIsTheOnlyWayToPost holds that nothing else in |
| +// this package calls Doors.Post or Doors.Nudge). |
| +// |
| +// Invariant (Astra branch review round 2, R2-1 and R2-2): a pending |
| +// pre-open interrupt prevents forward mutation, and the first pre-open |
| +// interrupt on a bound move follows abort through completion. |
| +// |
| +// The gate holds it in one place. It takes every pending Ctrl-C, then |
| +// decides; it says what the action will do (Watch.Acting: every piece of |
| +// output before the request), and only then, with nothing more to write, |
| +// checks for a Ctrl-C once more immediately before dispatch. One pending |
| +// there withdraws the action (Watch.Withdrawn) and the gate goes round |
| +// again: the Ctrl-C is taken (before open the first sets the sticky abort, |
| +// so the same view now decides abort; a second stops watching), and the |
| +// view is decided anew. So no forward POST leaves after a Ctrl-C was |
| +// pending, and an abort once decided is posted until the move reverts. |
| +func (r *Runner) dispatch(ctx context.Context, v View, m Memory) (Memory, *Done) { |
| for { |
| - var next Memory |
| - a, next = Decide(v, r.Policy, m, r.Clock()) |
| - if _, post := a.(Post); post && r.Interrupts.pending() { |
| - if m, stop = r.takeInterrupts(m, read); stop != nil { |
| - return m, stop, nil |
| - } |
| - continue |
| - } |
| - m = next |
| - break |
| - } |
| - switch a := a.(type) { |
| - case Done: |
| - return m, &a, nil |
| - case Post: |
| - r.Watch.Acting(a, m) |
| - ans := r.Doors.Post(ctx, a.Verb, m.Bound()) |
| - if ans.NotSent { |
| - m = m.notSent(a.Verb) |
| + var stop *Done |
| + if m, stop = r.takeInterrupts(m, &v); stop != nil { |
| + return m, stop |
| } |
| - if !ans.Accepted && ans.Refused { |
| - m = m.Refused(ans.Sentence) |
| + a, next := Decide(v, r.Policy, m, r.Clock()) |
| + switch a := a.(type) { |
| + case Done: |
| + return next, &a |
| + case Wait: |
| + return next, nil |
| } |
| - if a.Verb == VerbStage && ans.Accepted { |
| - // Bound to the move this stage created, as its reply names |
| - // it, never to whatever the next view shows: someone may have |
| - // staged their own before that read. |
| - m = m.bindTo(ans.ID) |
| + r.Watch.Acting(a, next) |
| + if r.Interrupts.pending() { |
| + r.Watch.Withdrawn(a) |
| + continue |
| } |
| - if a.Verb == VerbOpen && ans.Accepted { |
| - r.openAccepted = true |
| - } else if a.Verb == VerbOpen && !ans.Refused && !ans.NotSent { |
| - r.openUncertain = true |
| + m = next |
| + switch a := a.(type) { |
| + case Post: |
| + ans := r.Doors.Post(ctx, a.Verb, m.Bound()) |
| + if ans.NotSent { |
| + m = m.notSent(a.Verb) |
| + } |
| + if !ans.Accepted && ans.Refused { |
| + m = m.Refused(ans.Sentence) |
| + } |
| + if a.Verb == VerbStage && ans.Accepted { |
| + // Bound to the move this stage created, as its reply |
| + // names it, never to whatever the next view shows: |
| + // someone may have staged their own before that read. |
| + m = m.bindTo(ans.ID) |
| + } |
| + if a.Verb == VerbOpen && ans.Accepted { |
| + r.openAccepted = true |
| + } else if a.Verb == VerbOpen && !ans.Refused && !ans.NotSent { |
| + r.openUncertain = true |
| + } |
| + r.Watch.Acted(a, Result{Answer: ans}, m) |
| + case Nudge: |
| + ans := r.Doors.Nudge(ctx, m.Bound()) |
| + r.Watch.Acted(a, Result{Answer: ans}, m) |
| + case Probe: |
| + code := r.Probe(ctx) |
| + m = m.Probed(code >= 200 && code <= 299) |
| + r.Watch.Acted(a, Result{Status: code}, m) |
| } |
| - r.Watch.Acted(a, Result{Answer: ans}, m) |
| - case Nudge: |
| - r.Watch.Acting(a, m) |
| - ans := r.Doors.Nudge(ctx, m.Bound()) |
| - r.Watch.Acted(a, Result{Answer: ans}, m) |
| - case Probe: |
| - r.Watch.Acting(a, m) |
| - code := r.Probe(ctx) |
| - m = m.Probed(code >= 200 && code <= 299) |
| - r.Watch.Acted(a, Result{Status: code}, m) |
| + return m, nil |
| } |
| - return m, nil, nil |
| } |
| // Run steps until the run ends, sleeping Poll between ticks. A status read |
| -// that fails before any view was read ends it with that error; later ones |
| -// are ridden out (the move is under way, and only a view decides). A |
| -// Ctrl-C (Interrupts) is taken as soon as it arrives between ticks, and |
| -// otherwise by Step. |
| +// that fails before any view was read ends it with that error, unless a |
| +// Ctrl-C ended it (ErrInterrupted): Step has taken that Ctrl-C, and the |
| +// read is tried again, so a --resume run whose first read was cut short |
| +// still follows the abort it promised (R2-2). Later failures are ridden |
| +// out (the move is under way, and only a view decides). A Ctrl-C |
| +// (Interrupts) is taken as soon as it arrives between ticks, and otherwise |
| +// by Step. |
| func (r *Runner) Run(ctx context.Context, m Memory) (Done, Memory, error) { |
| read := false |
| for { |
| next, done, err := r.Step(ctx, m) |
| m = next |
| switch { |
| + case errors.Is(err, ErrInterrupted): |
| + // Read again on a fresh context; the Ctrl-C was taken. |
| case err != nil && !read: |
| return Done{}, m, err |
| case errors.Is(err, ErrStatusRefused): |
diff --git a/internal/moves/offlinerun/run_test.go b/internal/moves/offlinerun/run_test.go| index 2f5489d46..7e333590a 100644 |
| --- a/internal/moves/offlinerun/run_test.go |
| +++ b/internal/moves/offlinerun/run_test.go |
| @@ -58,6 +58,7 @@ type nopWatch struct{ interrupts []Interrupt } |
| func (*nopWatch) Saw(View) {} |
| func (*nopWatch) Acting(Action, Memory) {} |
| +func (*nopWatch) Withdrawn(Action) {} |
| func (*nopWatch) Acted(Action, Result, Memory) {} |
| func (w *nopWatch) Interrupted(i Interrupt, _ Memory) { |
| w.interrupts = append(w.interrupts, i) |
diff --git a/internal/provision/testdata/plan14-root-reads-omr-run.tsv b/internal/provision/testdata/plan14-root-reads-omr-run.tsv| index c741c8e0b..6618a6215 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-omr-run.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-omr-run.tsv |
| @@ -3,5 +3,5 @@ |
| # 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| @legacy 2f0662b82bce7e8e135cbe76c5026e922a7c1b821ce3178dccdb3959500360fb move_offline_run.go mover.offlineRun legacy accepted-legacy accepted-legacy;rev3=census-ruling-omr-run;basis=new: carlos move offline run (offline move run plan, Task 5). Opens the operator's own --log path to append the run's output (os.OpenFile, O_APPEND|O_CREATE|O_WRONLY, 0600); reads nothing from it. The verb refuses root (moveMain, L25) before it gets here, so this is never a root read. file:OpenFile@224 ebbf022f056d3956dffa51fcbf17ca16cbebc8fa934904eacdf87368eda3f61e |
| move_offline_run.go mover.offlineRun legacy accepted-legacy accepted-legacy;rev3=census-ruling-omr-run;basis=new: carlos move offline run (offline move run plan, Task 5). Opens the operator's own --log path to append the run's output (os.OpenFile, O_APPEND|O_CREATE|O_WRONLY, 0600); reads nothing from it. The verb refuses root (moveMain, L25) before it gets here, so this is never a root read. file:OpenFile@224 ebbf022f056d3956dffa51fcbf17ca16cbebc8fa934904eacdf87368eda3f61e |
| -@coverage . 5bb989f3cae7cfe23cdbbf4e0c55c0d3d3d9e9c17457c18446aed3971bc975d9 |
| -@coverage internal/moves/offlinerun dfbc21aa5c17a4e99e7f6a1e9b28b17e06cab8e14575ab7e85df55e59a8f6341 |
| +@coverage . 55bd6e93cf051d972dc29a8d227a8e59b798d9b120145358861ca64dc1f10a95 |
| +@coverage internal/moves/offlinerun a9756b6f6d9a48ab0c2be2774c528fa2663d82a9ee85b2a4f830de2a71d7d245 |
diff --git a/move_offline_run.go b/move_offline_run.go| index c0d0088e0..90fd76ad2 100644 |
| --- a/move_offline_run.go |
| +++ b/move_offline_run.go |
| @@ -257,15 +257,47 @@ type runDoors struct { |
| // so (once an outage). |
| const runStatusNotice = 2 * time.Minute |
| -// refusedForGood says a later status read's reply will not change by |
| -// asking again: the console's token or member check says no (401, 403), |
| -// it does not know the host (404) or any other 4xx but the rate limit's, |
| -// or it has moved. Anything else (no answer, a 5xx, a 429) may pass. |
| -func refusedForGood(r moveReply) bool { |
| - if r.moved != "" { |
| - return true |
| +// runStatusClass is what a status read's reply means for run. |
| +type runStatusClass int |
| + |
| +const ( |
| + statusAnswered runStatusClass = iota // a 200 whose body read |
| + statusPasses // asking again may answer |
| + statusRefused // asking again will not |
| +) |
| + |
| +// classifyStatus is the one classifier of a status read's reply, for the |
| +// first read and every later one. Invariant (Astra branch review round 2, |
| +// R2-3): a status failure that won't pass stops run. What may pass: no |
| +// response at all (a network error, or the context ended), a 5xx, the |
| +// rate limit's 429, and a 200 whose body was cut short in transit. |
| +// Everything else is refused for good, by its status alone: every redirect |
| +// (a console that moved, a proxy sending to /login), every other 4xx |
| +// whether or not its body read, and any other 2xx or a 200 that is not |
| +// JSON. TestRunStatusClasses holds the table. |
| +func classifyStatus(r moveReply) runStatusClass { |
| + switch { |
| + case r.status == 0: |
| + return statusPasses |
| + case r.status == http.StatusTooManyRequests, r.status >= 500 && r.status <= 599: |
| + return statusPasses |
| + case r.status == http.StatusOK && !r.failed: |
| + return statusAnswered |
| + case r.status == http.StatusOK && !r.unread: |
| + return statusPasses |
| + } |
| + return statusRefused |
| +} |
| + |
| +// sayStatusRefused says a status read classifyStatus refused, in the |
| +// mover's own sentences (sayReply): the console's sentence when it gave |
| +// one; else for a reply judged by its status, that status, whether or not |
| +// a body came with it. |
| +func sayStatusRefused(m *mover, r moveReply) { |
| + if r.status/100 != 2 { |
| + r.failed, r.unread = false, false |
| } |
| - return !r.failed && r.status >= 400 && r.status <= 499 && r.status != http.StatusTooManyRequests |
| + m.sayReply(r) |
| } |
| // outage notes a later status read that may pass, and says the notice once |
| @@ -319,18 +351,24 @@ func (d *runDoors) firstRead(ctx context.Context) (r moveReply, code int, interr |
| if interrupted { |
| return moveReply{}, -1, true |
| } |
| - ok := !r.failed && r.moved == "" |
| - switch { |
| - case ok && r.status == http.StatusOK: |
| + switch classifyStatus(r) { |
| + case statusAnswered: |
| return r, -1, false |
| - case r.moved != "" || r.stopped: |
| + case statusRefused: |
| + // A 4xx is the console refusing this run before it wrote |
| + // anything (exit 5); any other refusal is an error (exit 1). |
| + sayStatusRefused(m, r) |
| + if r.status >= 400 && r.status <= 499 { |
| + return moveReply{}, moveExitRefused, false |
| + } |
| + return moveReply{}, moveExitError, false |
| + } |
| + switch { |
| + case r.stopped: |
| m.sayReply(r) |
| return moveReply{}, moveExitError, false |
| - case ok && r.status == http.StatusTooManyRequests: |
| + case r.status == http.StatusTooManyRequests: |
| m.limit() |
| - case ok && r.status >= 400 && r.status < 500: |
| - m.sayReply(r) |
| - return moveReply{}, moveExitRefused, false |
| default: |
| failures++ |
| if failures >= moveTransient { |
| @@ -356,7 +394,7 @@ func (d *runDoors) Status(ctx context.Context) (offlinerun.View, error) { |
| var code int |
| var interrupted bool |
| if r, code, interrupted = d.firstRead(ctx); interrupted { |
| - return offlinerun.View{}, errRunStatus |
| + return offlinerun.View{}, fmt.Errorf("%w", offlinerun.ErrInterrupted) |
| } else if code >= 0 { |
| d.code = code |
| return offlinerun.View{}, errRunStatus |
| @@ -368,13 +406,14 @@ func (d *runDoors) Status(ctx context.Context) (offlinerun.View, error) { |
| // long enough to say so once. |
| var interrupted bool |
| r, interrupted = d.get(ctx) |
| - switch { |
| - case interrupted: |
| - return offlinerun.View{}, errRunStatus |
| - case refusedForGood(r): |
| + if interrupted { |
| + return offlinerun.View{}, fmt.Errorf("%w", offlinerun.ErrInterrupted) |
| + } |
| + switch classifyStatus(r) { |
| + case statusRefused: |
| d.gone = r |
| return offlinerun.View{}, fmt.Errorf("%w: %d", offlinerun.ErrStatusRefused, r.status) |
| - case r.failed || r.status != http.StatusOK: |
| + case statusPasses: |
| d.outage() |
| return offlinerun.View{}, errRunStatus |
| } |
| @@ -383,11 +422,15 @@ func (d *runDoors) Status(ctx context.Context) (offlinerun.View, error) { |
| var full offlineView |
| var v offlinerun.View |
| if json.Unmarshal(r.body, &full) != nil || json.Unmarshal(r.body, &v) != nil { |
| + // A 200 that is not a status view is refused for good too. |
| + r.failed, r.unread = true, true |
| if !d.seen { |
| - moveSay(d.w.m.out, moveUnreadable) |
| + sayStatusRefused(d.w.m, r) |
| d.code = moveExitError |
| + return offlinerun.View{}, errRunStatus |
| } |
| - return offlinerun.View{}, errRunStatus |
| + d.gone = r |
| + return offlinerun.View{}, fmt.Errorf("%w: not a status view", offlinerun.ErrStatusRefused) |
| } |
| d.seen = true |
| d.w.learn(full) |
| @@ -501,6 +544,7 @@ type runWatcher struct { |
| id string // the move this run carries, once the header named it |
| stageSaid int64 // the staged_at whose round was said |
| abortSaid bool // why the run aborts was said |
| + abortOwed bool // OR28 waits for a view that names the region |
| } |
| func (rw *runWatcher) out() io.Writer { return rw.w.m.out } |
| @@ -526,6 +570,10 @@ func (rw *runWatcher) Saw(offlinerun.View) { |
| r := rw.doors.last |
| v := r.v |
| rw.sayHeader(v) |
| + if rw.abortOwed && rw.from(v) != "" { |
| + rw.abortOwed = false |
| + rw.sayMovingBack(v) |
| + } |
| if v.ID == "" || v.ID != rw.id { |
| return // another move's view, or none: Decide says what it means |
| } |
| @@ -610,6 +658,11 @@ func (rw *runWatcher) sayWhy(reason string) { |
| } |
| } |
| +// Acting is everything said before the gate dispatches a POST: why an |
| +// abort was decided, and the step line's time and step, which the log |
| +// keeps even if the process dies with the request in flight. "sent" comes |
| +// with the answer (Acted), so a POST the gate withdraws (a Ctrl-C was |
| +// pending) was never said to be sent. |
| func (rw *runWatcher) Acting(a offlinerun.Action, _ offlinerun.Memory) { |
| p, ok := a.(offlinerun.Post) |
| if !ok { |
| @@ -618,9 +671,14 @@ func (rw *runWatcher) Acting(a offlinerun.Action, _ offlinerun.Memory) { |
| if p.Verb == offlinerun.VerbAbort && p.Reason != "" { |
| rw.sayWhy(p.Reason) |
| } |
| - rw.posted = true |
| rw.column(p.Verb) |
| - runPiece(rw.out(), "sent") |
| +} |
| + |
| +// Withdrawn ends the step line of a POST the gate did not send. |
| +func (rw *runWatcher) Withdrawn(a offlinerun.Action) { |
| + if _, ok := a.(offlinerun.Post); ok { |
| + runSep(rw.out(), "\n") |
| + } |
| } |
| // sayAnswer completes a step line with how the door answered. |
| @@ -653,6 +711,8 @@ func (rw *runWatcher) Acted(a offlinerun.Action, res offlinerun.Result, m offlin |
| rw.bound = m.Bound() |
| switch a := a.(type) { |
| case offlinerun.Post: |
| + rw.posted = true |
| + runPiece(rw.out(), "sent") |
| rw.sayAnswer(a.Verb, res.Answer) |
| rw.sayHeader(rw.lastPostView()) |
| case offlinerun.Nudge: |
| @@ -680,11 +740,22 @@ func (rw *runWatcher) lastPostView() offlineView { |
| return v |
| } |
| +// sayMovingBack is OR28. |
| +func (rw *runWatcher) sayMovingBack(v offlineView) { |
| + moveSay(rw.out(), fmt.Sprintf("Moving %s back to %s. Press Ctrl-C again to stop watching.", rw.w.m.host, rw.from(v))) |
| +} |
| + |
| func (rw *runWatcher) Interrupted(i offlinerun.Interrupt, _ offlinerun.Memory) { |
| host, v := rw.w.m.host, rw.doors.last.v |
| switch i { |
| case offlinerun.InterruptAbort: |
| - moveSay(rw.out(), fmt.Sprintf("Moving %s back to %s. Press Ctrl-C again to stop watching.", host, rw.from(v))) |
| + if rw.from(v) == "" { |
| + // No view has named the region yet (a resumed run's first |
| + // read was cut short): said once one does (Saw). |
| + rw.abortOwed = true |
| + return |
| + } |
| + rw.sayMovingBack(v) |
| case offlinerun.InterruptStop: |
| moveSay(rw.out(), "Stopped watching. The move is still running. To see where it is, run:") |
| sayRunCommand(rw.out(), "status", host) |
| @@ -756,7 +827,7 @@ func (rw *runWatcher) end(d offlinerun.Done) int { |
| // said at the Ctrl-C |
| case offlinerun.ReasonStatusRefused: |
| // The console's own sentence for it, then where to look. |
| - rw.w.m.sayReply(rw.doors.gone) |
| + sayStatusRefused(rw.w.m, rw.doors.gone) |
| moveSay(rw.out(), "Stopped watching. The move is still running. To see where it is, run:") |
| sayRunCommand(rw.out(), "status", host) |
| } |
diff --git a/move_offline_run_test.go b/move_offline_run_test.go| index 3b40bc02b..ab7bc8a39 100644 |
| --- a/move_offline_run_test.go |
| +++ b/move_offline_run_test.go |
| @@ -4,6 +4,9 @@ import ( |
| "bytes" |
| "context" |
| "errors" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| @@ -55,6 +58,8 @@ type offlineSim struct { |
| // getFault, when set, may answer a status read itself (ok true) with |
| // a code and a body, before the boxes tick. |
| getFault func(s *offlineSim) (code int, body frame, ok bool) |
| + // getRaw, when set, may answer a status read itself, any way at all. |
| + getRaw func(s *offlineSim, w http.ResponseWriter) bool |
| } |
| const simEpoch = int64(1794724320) // 2026-11-15T06:32:00Z |
| @@ -1103,3 +1108,274 @@ func TestMoveOfflineRunStagingCaps(t *testing.T) { |
| t.Fatalf("said OR23 for refused restages:\n%s", out) |
| } |
| } |
| + |
| +// TestRunStatusClasses is the one status classifier's table (Astra branch |
| +// review round 2, R2-3; invariant: a status failure that won't pass stops |
| +// run). Every reply comes off a real HTTP exchange through roundTrip, as |
| +// run reads one. Network errors, 5xx and 429 pass; everything else, every |
| +// redirect and every other 4xx (a body that does not read included), is |
| +// refused for good. |
| +func TestRunStatusClasses(t *testing.T) { |
| + view := `{"host":"` + oHost + `","state":"offline-sealing","id":"` + tMoveID + `"}` |
| + for _, c := range []struct { |
| + name string |
| + serve func(w http.ResponseWriter) |
| + want runStatusClass |
| + failed bool // roundTrip marks the reply failed (its body did not read, or is not JSON) |
| + wantFirst string |
| + }{ |
| + {"200 view", func(w http.ResponseWriter) { w.WriteHeader(200); io.WriteString(w, view) }, statusAnswered, false, ""}, |
| + {"no response", nil, statusPasses, false, ""}, |
| + {"500", func(w http.ResponseWriter) { w.WriteHeader(500) }, statusPasses, false, ""}, |
| + {"502 with a sentence", func(w http.ResponseWriter) { |
| + w.WriteHeader(502) |
| + io.WriteString(w, `{"error":"could not read the instance"}`) |
| + }, statusPasses, false, ""}, |
| + {"503", func(w http.ResponseWriter) { w.WriteHeader(503) }, statusPasses, false, ""}, |
| + {"429", func(w http.ResponseWriter) { w.WriteHeader(429); io.WriteString(w, `{"error":"slow down"}`) }, statusPasses, false, ""}, |
| + {"200 cut short", func(w http.ResponseWriter) { |
| + w.Header().Set("Content-Length", "500") |
| + w.WriteHeader(200) |
| + io.WriteString(w, view[:20]) |
| + }, statusPasses, true, ""}, |
| + {"200 not a view", func(w http.ResponseWriter) { w.WriteHeader(200); io.WriteString(w, "<html>") }, statusRefused, true, "The console's answer could not be read."}, |
| + {"204", func(w http.ResponseWriter) { w.WriteHeader(204) }, statusRefused, true, "The console's answer could not be read."}, |
| + {"301 the console moved", func(w http.ResponseWriter) { |
| + w.Header().Set("Location", "https://console.example.net/api/cli/x") |
| + w.WriteHeader(301) |
| + }, statusRefused, false, ""}, |
| + {"302 to /login", func(w http.ResponseWriter) { w.Header().Set("Location", "/login"); w.WriteHeader(302) }, statusRefused, false, "The console answered 302 and gave no reason."}, |
| + {"307", func(w http.ResponseWriter) { w.Header().Set("Location", "/elsewhere"); w.WriteHeader(307) }, statusRefused, false, "The console answered 307 and gave no reason."}, |
| + {"400", func(w http.ResponseWriter) { w.WriteHeader(400); io.WriteString(w, `{"error":"bad request"}`) }, statusRefused, false, "bad request"}, |
| + {"401", func(w http.ResponseWriter) { w.WriteHeader(401); io.WriteString(w, `{"error":"sign in again"}`) }, statusRefused, false, "sign in again"}, |
| + {"401 cut short", func(w http.ResponseWriter) { |
| + w.Header().Set("Content-Length", "500") |
| + w.WriteHeader(401) |
| + io.WriteString(w, `{"error":"sign`) |
| + }, statusRefused, true, "The console answered 401 and gave no reason."}, |
| + {"403", func(w http.ResponseWriter) { w.WriteHeader(403) }, statusRefused, false, "The console answered 403 and gave no reason."}, |
| + {"404", func(w http.ResponseWriter) { w.WriteHeader(404) }, statusRefused, false, "Not found. Check --account and --app, and that you are a member of the instance's account."}, |
| + {"409", func(w http.ResponseWriter) { w.WriteHeader(409); io.WriteString(w, `{"error":"no"}`) }, statusRefused, false, "no"}, |
| + {"410", func(w http.ResponseWriter) { w.WriteHeader(410) }, statusRefused, false, "The console answered 410 and gave no reason."}, |
| + {"418", func(w http.ResponseWriter) { w.WriteHeader(418) }, statusRefused, false, "The console answered 418 and gave no reason."}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if c.serve == nil { |
| + hj, _ := w.(http.Hijacker) |
| + conn, _, _ := hj.Hijack() |
| + conn.Close() |
| + return |
| + } |
| + c.serve(w) |
| + })) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + m := &mover{sess: &apiSession{c: newConsoleClient(ts.URL, "t")}, out: &out, host: oHost, path: "/api/cli/x"} |
| + r := m.roundTrip(context.Background(), http.MethodGet, m.path, nil) |
| + if got := classifyStatus(r); got != c.want { |
| + t.Fatalf("class %d, want %d (reply %+v)", got, c.want, r) |
| + } |
| + if c.failed != (r.failed && r.status != 0) { |
| + t.Fatalf("reply failed %v (status %d), the case wants %v", r.failed, r.status, c.failed) |
| + } |
| + if c.want != statusRefused { |
| + return |
| + } |
| + sayStatusRefused(m, r) |
| + first, _, _ := strings.Cut(out.String(), "\n") |
| + if c.wantFirst != "" && first != c.wantFirst { |
| + t.Fatalf("said %q, want %q", first, c.wantFirst) |
| + } |
| + if first == "" || strings.Contains(out.String(), moveUnreachable) { |
| + t.Fatalf("said %q", out.String()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestMoveOfflineRunStatusRefusedMidRun: the classes that used to poll for |
| +// ever (R2-3), mid-run: a 302 to /login and a 401 whose body is cut short |
| +// end the run with exit 1, OR29 and the status command, nothing posted. |
| +func TestMoveOfflineRunStatusRefusedMidRun(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + serve func(w http.ResponseWriter) |
| + say string |
| + }{ |
| + {"302 to /login", func(w http.ResponseWriter) { w.Header().Set("Location", "/login"); w.WriteHeader(302) }, "The console answered 302 and gave no reason."}, |
| + {"401 cut short", func(w http.ResponseWriter) { |
| + w.Header().Set("Content-Length", "500") |
| + w.WriteHeader(401) |
| + io.WriteString(w, `{"error":"sign`) |
| + }, "The console answered 401 and gave no reason."}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + sim := &offlineSim{holdIn: "offline-sealing"} |
| + sim.getRaw = func(s *offlineSim, w http.ResponseWriter) bool { |
| + if s.state != "offline-sealing" { |
| + return false |
| + } |
| + c.serve(w) |
| + return true |
| + } |
| + f := &fakeOfflineConsole{sim: sim} |
| + code, out := runOfflineRun(t, f, runSeams{}, "--to", "uk") |
| + if code != 1 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(f.postsSent()); got != "stage,start,seal" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + if !strings.HasSuffix(out, c.say+"\n"+ |
| + "Stopped watching. The move is still running. To see where it is, run:\n"+ |
| + " carlos move offline status --host acme.shop.example.com\n") { |
| + t.Fatalf("output:\n%s", out) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// pressingTerm is a terminal that presses Ctrl-C while a write holding |
| +// `at` is under way (once): the operator's key landing as run writes. |
| +type pressingTerm struct { |
| + bytes.Buffer |
| + at string |
| + press *func() |
| + done bool |
| +} |
| + |
| +func (p *pressingTerm) Write(b []byte) (int, error) { |
| + if !p.done && strings.Contains(string(b), p.at) { |
| + p.done = true |
| + (*p.press)() |
| + } |
| + return p.Buffer.Write(b) |
| +} |
| + |
| +// The dispatch gate's boundaries as the CLI meets them (Astra branch |
| +// review round 2, R2-1/R2-2; the gate is offlinerun.Runner.dispatch). |
| +// Invariant: a pending pre-open interrupt prevents forward mutation, and |
| +// the first pre-open interrupt on a bound move follows abort through |
| +// completion. |
| +func TestMoveOfflineRunGateBoundaries(t *testing.T) { |
| + t.Run("before output: during the stage round's line", func(t *testing.T) { |
| + var press func() |
| + term := &pressingTerm{at: "1204 of 1204 objects", press: &press} |
| + c := &fakeOfflineConsole{sim: &offlineSim{}} |
| + code, _ := runOfflineRun(t, c, runSeams{press: &press, term: term}, "--to", "uk") |
| + out := term.String() |
| + if code != 3 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "stage,abort,finish" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + }) |
| + t.Run("after output: during open's own step line", func(t *testing.T) { |
| + var press func() |
| + term := &pressingTerm{at: " open ", press: &press} |
| + c := &fakeOfflineConsole{sim: &offlineSim{}} |
| + code, _ := runOfflineRun(t, c, runSeams{press: &press, term: term}, "--to", "uk") |
| + out := term.String() |
| + if code != 3 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "stage,start,seal,flip,abort,finish" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + // The withdrawn open was never said to be sent. |
| + if strings.Contains(out, "open sent") { |
| + t.Fatalf("said open was sent:\n%s", out) |
| + } |
| + wantLines(t, out, "Moving acme.shop.example.com back to ie. Press Ctrl-C again to stop watching.", orBack) |
| + }) |
| + t.Run("first read of a resumed run", func(t *testing.T) { |
| + var press func() |
| + sim := &offlineSim{} |
| + sim.enter("offline-landed") |
| + sim.onGet = func(s *offlineSim) { |
| + s.onGet = nil |
| + press() // the read is on the wire: it is cut short |
| + } |
| + c := &fakeOfflineConsole{sim: sim} |
| + code, out := runOfflineRun(t, c, runSeams{press: &press}, "--resume", tMoveID) |
| + if code != 3 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "abort,finish" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + wantLines(t, out, "Moving acme.shop.example.com back to ie. Press Ctrl-C again to stop watching.", orBack) |
| + }) |
| +} |
| + |
| +// TestRunDoorsPostOnlyThroughTheGate: the CLI's doors make their POSTs in |
| +// one function (runDoors.send), which only runDoors.Post and Nudge call, |
| +// and nothing in the package calls those: the only caller is the |
| +// offlinerun.Runner's dispatch gate, through the Doors interface |
| +// (TestGateIsTheOnlyWayToPost holds that side). |
| +func TestRunDoorsPostOnlyThroughTheGate(t *testing.T) { |
| + fset := token.NewFileSet() |
| + pkgs, err := parser.ParseDir(fset, ".", func(fi os.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") }, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + recv := func(fn *ast.FuncDecl) string { |
| + if fn.Recv == nil || len(fn.Recv.List) == 0 { |
| + return "" |
| + } |
| + if st, ok := fn.Recv.List[0].Type.(*ast.StarExpr); ok { |
| + if id, ok := st.X.(*ast.Ident); ok { |
| + return id.Name |
| + } |
| + } |
| + return "" |
| + } |
| + sends := 0 |
| + for _, pkg := range pkgs { |
| + for name, f := range pkg.Files { |
| + for _, decl := range f.Decls { |
| + fn, ok := decl.(*ast.FuncDecl) |
| + if !ok || fn.Body == nil { |
| + continue |
| + } |
| + where := recv(fn) + "." + fn.Name.Name |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.SelectorExpr: |
| + if id, ok := n.X.(*ast.Ident); ok && id.Name == "http" && n.Sel.Name == "MethodPost" && name == "move_offline_run.go" && where != "runDoors.send" { |
| + t.Errorf("%s: %s sends a POST outside runDoors.send", name, where) |
| + } |
| + case *ast.CallExpr: |
| + sel, ok := n.Fun.(*ast.SelectorExpr) |
| + if !ok { |
| + return true |
| + } |
| + switch sel.Sel.Name { |
| + case "send": |
| + if recv(fn) == "runDoors" { |
| + sends++ |
| + if where != "runDoors.Post" && where != "runDoors.Nudge" { |
| + t.Errorf("%s: %s calls runDoors.send", name, where) |
| + } |
| + } |
| + case "Post", "Nudge": |
| + if name == "move_offline_run.go" { |
| + t.Errorf("%s: %s calls .%s: only the gate may", name, where, sel.Sel.Name) |
| + } |
| + } |
| + case *ast.Ident: |
| + if n.Name == "runDoors" && name != "move_offline_run.go" { |
| + t.Errorf("%s reaches runDoors", name) |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + } |
| + if sends != 2 { |
| + t.Fatalf("runDoors.send is called %d times, want twice (Post, Nudge)", sends) |
| + } |
| +} |
diff --git a/move_test.go b/move_test.go| index 29a8f96f0..c4e2a69fc 100644 |
| --- a/move_test.go |
| +++ b/move_test.go |
| @@ -1154,6 +1154,9 @@ func (c *fakeOfflineConsole) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| write(http.StatusTooManyRequests, frame{"error": "too many requests"}) |
| return |
| } |
| + if c.sim.getRaw != nil && c.sim.getRaw(c.sim, w) { |
| + return |
| + } |
| if c.sim.getFault != nil { |
| if code, body, ok := c.sim.getFault(c.sim); ok { |
| write(code, body) |