carlos / platform Public

moves: offlinerun.Decide for carlos move offline run (Task 2)

Decide is the pure core of the offline-move glue (plan
2026-11-15-offline-move-run.md section 3): one status view, the
policy, the process's own memory and a monotonic clock in; one
action (Wait, Post, Nudge, Probe, Done) and the updated memory out.
No I/O. The view mirrors the console's offline status JSON; budgets
are the plan's drafts in one place for Task 0 to tune.

Tests cover each row of the section 3 table plus: a ready step beats
a deadline, an id mismatch writes nothing (exit 4), abort is sticky,
nothing aborts after open (a failed probe stops with exit 4 and no
finish), nudge after 30 s of no change then every 60 s, --no-finish,
and the state and outcome names pinned to provision's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1b428362f45cb33cf7aa9fdc40caf159ba72e312 parent e090f19
2 files changed, +858 −0
  • internal/moves/offlinerun/decide.go +479 −0
  • internal/moves/offlinerun/decide_test.go +379 −0

Intent

Human

<task-notification> <task-id>a432f562216f27ead</task-id> <tool-use-id>toolu_01GUymL2BDmF4ArmeAwX1cFz</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/96a09f74-e398-48ed-a97f-140bd1f7e255/tasks/a432f562216f27ead.output</output-file> <status>completed</status> <summary>Agent "Fable runs Task 0 dev rehearsal" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Task 0 stopped at the first door: no move ran on dev, so most acceptance items are not measured. Results are posted as amadan discussion **#1077** on branch `offline-move-run`, with the full operator log in its notes. **What happened (2026-11-15, UTC)** - **Lock:** #421 showed dev free and there was no `control/offline-moves/active.json`. I held the dev lock from 06:21 to 06:27 and released it on #421. - **Instance:** created `moverehearsal-t0.dev.carlosframework.com` (app `moverehearsal`, account `bab`) at 06:21:07. It first answered 200 through DNS at 06:23:06, on sophie, nested. - **Pre-checks:** runbook 2.1–2.5 and 3.1–3.4 all passed, and dennis held nothing for the host. - **Refusal:** `stage --to uk` at 06:24:27 exited 5 in 0.15 s with "ie has high availability turned on. offline moves into or out of it are not available yet". - **State after:** the record's move stayed null, no lock was written, and the instance kept serving. **Why** The dev console runs with `CONSOLE_HA_REGIONS=ie`. `offlineBeginChecks` (`internal/console/apiinstancemove_offline.go:589`, `haTransferRegion` in `internal/console/seedmove.go`) answers 409 when the source or target is an HA region. Dev has only ie and uk, so no offline move can run on dev today. I did not work around it. **Acceptance items** - **Step times:** not measured. - **`next` / `waiting`:** only state `none` was seen; the view is `{"host","state":"none"}` with neither key. The CLI has no `--json`, so I read `GET .../move/offline` with the CLI's own dev token. - **Repeated seal 409:** not reached. - **Edge answers between stop and open:** not reached. Before any move, the host answered 200 through sophie and dennis; leo fails the TLS handshake for it. - **#339 and #413:** both are on dev. 94a6471e and d6c6f3f2 first appear in v0.35.3; dev boxes run v0.35.5 and the console v0.36.0. **Cleanup** - `instances delete` ran at 06:25:34 and the route was gone from sophie by 06:25:50. - I ran none of §10: `cleanup.sh` needs a lifted move tombstone, which a never-moved instance does not have. - Left for a person, all on the source side: - `/data/.instances/&lt;host&gt;/` on sophie (db, env, local Litestream dir) - `/opt/carlos/live/&lt;host&gt;` - `/data/programs/&lt;host&gt;.json` - 18 objects (8 KB) under `instances/&lt;host&gt;/` in `carlos-dev-ie-640012953448` - the host's cert object - Nothing is on dennis or in the uk bucket. - Scratch and the local log are removed. **Deviations from the runbook** - `--resolve` probes need the sandbox off; through its proxy curl ignores `--resolve`. - Dev differs from §13: sophie has no guard policy, leo serves pools `cohort1` and `hapair`, and two IE HA group members publish edges files. - The Appendix A scripts I used (ssm, block, target, facts, sizes, schema, rows, `stage.sh`) ran correctly. `move.sh`, `sealcount.sh` and `cleanup.sh` were not exercised. **What this changes for the plan** 1. Tasks 0 and 9 need somewhere to run. This is Paul's call: - take ie out of dev's `CONSOLE_HA_REGIONS` for a window (this touches region HA, so 8a3d302 too); - add a non-HA region pair to dev; or - rehearse elsewhere. I did not check whether the flagship's ie or uk is an HA region; that decides whether `run` is usable there. 2. `Decide` needs a row for a refused first stage: 409, exit 5, nothing bound, nothing to abort; stop with the console's sentence. 3. The budgets and the repeated-door 409 assumed in Tasks 2–5 stay unverified.</result> <usage><subagent_tokens>127901</subagent_tokens><tool_uses>37</tool_uses><duration_ms>535095</duration_ms></usage> </task-notification>

diff --git a/internal/moves/offlinerun/decide.go b/internal/moves/offlinerun/decide.go
new file mode 100644
index 000000000..94a03a180
--- /dev/null
+++ b/internal/moves/offlinerun/decide.go
@@ -0,0 +1,479 @@
+// Package offlinerun is the glue behind `carlos move offline run`: one
+// offline move driven from the operator's terminal through the existing
+// doors (plan docs/superpowers/plans/2026-11-15-offline-move-run.md §3).
+//
+// Decide is pure. It reads one status view, the policy, the process's own
+// memory and a monotonic clock, and answers the one thing to do next with
+// the memory updated. It does no I/O; the caller performs the action,
+// reads status again and calls Decide again (every 2 s in slice 1).
+package offlinerun
+
+import "time"
+
+// State names as the console's offline status view spells them. Twins of
+// provision.Offline*, pinned by TestDecideNamesMatchProvision.
+const (
+ StateNone = "none"
+ StateStaging = "offline-staging"
+ StateStopping = "offline-stopping"
+ StateSealing = "offline-sealing"
+ StateSealed = "offline-sealed"
+ StateLanding = "offline-landing"
+ StateLanded = "offline-landed"
+ StateOpen = "offline-open"
+ StateFinishing = "offline-finishing"
+ StateReverting = "offline-reverting"
+)
+
+// Door verbs, as the status view's next names them (and abort and stage,
+// which next never names).
+const (
+ VerbStage = "stage"
+ VerbStart = "start"
+ VerbSeal = "seal"
+ VerbFlip = "flip"
+ VerbOpen = "open"
+ VerbFinish = "finish"
+ VerbAbort = "abort"
+)
+
+// Outcomes of an ended offline move (last.outcome). Twins of
+// provision.OfflineOutcome*.
+const (
+ OutcomeDone = "done"
+ OutcomeAborted = "aborted"
+)
+
+// PhaseFailed is a stager report's phase when its round could not finish.
+const PhaseFailed = "failed"
+
+// Exit codes Done carries, the CLI's own (move.go moveExit*).
+const (
+ ExitDone = 0 // the move finished, or stopped at open by --no-finish
+ ExitAborted = 3 // the move was aborted and finished back where it was
+ ExitStopped = 4 // stopped; a human decides what comes next
+)
+
+// Reasons are short codes for the log line and for tests. They are not
+// operator copy; the CLI says each in approved words.
+const (
+ ReasonDone = "done"
+ ReasonAborted = "aborted"
+ ReasonOpenNoFinish = "open-no-finish"
+ ReasonOtherMove = "other-move"
+ ReasonHostHasMove = "host-has-move"
+ ReasonStageNotWritten = "stage-not-written"
+ ReasonMoveGone = "move-gone"
+ ReasonUnexpectedState = "unexpected-state"
+ ReasonProbeFailed = "probe-failed"
+ ReasonFailed = "failed"
+ ReasonStageRounds = "stage-rounds"
+ ReasonBudgetStop = "budget-stop"
+ ReasonBudgetSeal = "budget-seal"
+ ReasonBudgetLanding = "budget-landing"
+ ReasonBudgetOpenCheck = "budget-open-check"
+ ReasonBudgetOffline = "budget-offline"
+ ReasonInterrupted = "interrupted"
+)
+
+// View is the part of the console's offline status answer (GET
+// /api/instances/<host>/move/offline, console offlineView) that Decide
+// reads. Field names and tags are the console's; unknown fields are
+// ignored, so it decodes the full answer.
+type View struct {
+ State string `json:"state"`
+ ID string `json:"id,omitempty"`
+ Next string `json:"next,omitempty"`
+ Waiting string `json:"waiting,omitempty"`
+ Failed bool `json:"failed,omitempty"`
+ StagedAt int64 `json:"staged_at,omitempty"` // Unix nanoseconds
+ RequestedAt int64 `json:"requested_at,omitempty"`
+ UpdatedAt int64 `json:"updated_at,omitempty"`
+ // Stage is the newest stager report, nil before any.
+ Stage *StageView `json:"stage,omitempty"`
+ // Last is the outcome of the move that ended, when State is none.
+ Last *Outcome `json:"last,omitempty"`
+}
+
+// StageView is the stager's latest round (console offlineStageView).
+type StageView struct {
+ Phase string `json:"phase"`
+ At int64 `json:"at"`
+ RoundBytes int64 `json:"round_bytes"`
+ // Request is the staged_at the round answered (Unix nanoseconds).
+ Request int64 `json:"request,omitempty"`
+}
+
+// Outcome is how a move ended (provision.MoveOutcome).
+type Outcome struct {
+ ID string `json:"id"`
+ Outcome string `json:"outcome"`
+}
+
+// Policy is the run's budgets and switches. Every duration is measured on
+// the terminal's monotonic clock from when this process first saw the
+// state (or, for Offline, the first offline state).
+type Policy struct {
+ Stop time.Duration // stopping: the sources stop and fence
+ Seal time.Duration // sealing: the sealer copies the delta
+ Landing time.Duration // landing: the target lands
+ OpenCheck time.Duration // landed: until the open door's check passes
+ Offline time.Duration // stopping to landed in all (--max-offline)
+ // Probe is how long after open the probe may go without a 2xx before
+ // the run stops (exit 4, no finish). Never an abort.
+ Probe time.Duration
+ // StageRoundBytes: a round that copied more than this is big, and
+ // another round runs before start.
+ StageRoundBytes int64
+ // MaxStageRounds caps the stage POSTs this process makes. Past it a
+ // round that is still big aborts (staging never went offline).
+ MaxStageRounds int
+ // SmallRoundFresh: start only within this long of watching a small
+ // round finish; later, stage again.
+ SmallRoundFresh time.Duration
+ // NudgeAfter is the first nudge after a wait with no change; NudgeEvery
+ // the gap between later ones.
+ NudgeAfter time.Duration
+ NudgeEvery time.Duration
+ // NoFinish stops at open once the probe answers 2xx (exit 0).
+ NoFinish bool
+}
+
+// Draft budgets (plan §3). Task 0's rehearsal on dev sets the real ones.
+const (
+ DefaultStop = 3 * time.Minute
+ DefaultSeal = 10 * time.Minute
+ DefaultLanding = 5 * time.Minute
+ DefaultOpenCheck = 2 * time.Minute
+ DefaultOffline = 15 * time.Minute
+ DefaultProbe = 2 * time.Minute
+ DefaultStageRoundBytes = 1 << 20
+ DefaultMaxStageRounds = 5
+ DefaultSmallRoundFresh = 60 * time.Second
+ DefaultNudgeAfter = 30 * time.Second
+ DefaultNudgeEvery = 60 * time.Second
+)
+
+// DefaultPolicy is the draft budgets, finishing after open.
+func DefaultPolicy() Policy {
+ return Policy{
+ Stop: DefaultStop, Seal: DefaultSeal, Landing: DefaultLanding,
+ OpenCheck: DefaultOpenCheck, Offline: DefaultOffline, Probe: DefaultProbe,
+ StageRoundBytes: DefaultStageRoundBytes, MaxStageRounds: DefaultMaxStageRounds,
+ SmallRoundFresh: DefaultSmallRoundFresh,
+ NudgeAfter: DefaultNudgeAfter, NudgeEvery: DefaultNudgeEvery,
+ }
+}
+
+// Action is the one thing to do next: Wait, Post, Nudge, Probe or Done.
+type Action interface{ isAction() }
+
+// Wait reads status again after the poll interval.
+type Wait struct{}
+
+// Post posts a door. Reason says why an abort was decided ("" otherwise).
+type Post struct {
+ Verb string
+ Reason string
+}
+
+// Nudge posts the nudge door: the serial is bumped, the record unchanged.
+type Nudge struct{}
+
+// Probe requests https://<host><probe-path> once; the caller records the
+// answer with Memory.Probed.
+type Probe struct{}
+
+// Done ends the run with Exit (ExitDone, ExitAborted or ExitStopped).
+type Done struct {
+ Exit int
+ Reason string
+}
+
+func (Wait) isAction() {}
+func (Post) isAction() {}
+func (Nudge) isAction() {}
+func (Probe) isAction() {}
+func (Done) isAction() {}
+
+// Memory is what this process remembers between ticks. It is local to the
+// terminal and never written anywhere; a resumed run starts afresh from
+// NewMemory(id). Decide takes it by value and returns it updated.
+type Memory struct {
+ id string // the bound move id; "" until bound
+ stagePosts int // stage POSTs this process decided
+
+ seen bool // a view has been read
+ state string // the state last read
+ stateSince time.Duration // when state was first read
+ fp fingerprint // the decision-relevant view last read
+ lastChange time.Duration // when fp last changed
+ nudged bool // a nudge was sent since the last change
+ lastNudge time.Duration
+
+ offlineSeen bool // a state from stopping to landed was read
+ offlineSince time.Duration // when the first was
+
+ watched int64 // a staged_at this process read unanswered
+ finishedReq int64 // the watched staged_at, once read answered
+ finishedAt time.Duration // when it was first read answered
+
+ aborting bool // abort was decided; sticky until reverting or open
+ abortReason string // why
+
+ opened bool // open (or finishing) was read
+ probeOK bool // the probe answered 2xx
+}
+
+// NewMemory is a fresh run's memory. resume is --resume's move id, bound
+// from the start; "" for a run that stages its own move.
+func NewMemory(resume string) Memory { return Memory{id: resume} }
+
+// Bound is the move id the run is bound to, "" before it is.
+func (m Memory) Bound() string { return m.id }
+
+// Probed records a probe's answer; ok is a 2xx.
+func (m Memory) Probed(ok bool) Memory {
+ if ok {
+ m.probeOK = true
+ }
+ return m
+}
+
+// Abort asks for an abort (the first Ctrl-C). Before open it is sticky:
+// Decide posts abort until the view is reverting or open. After open it is
+// ignored; nothing aborts an opened move.
+func (m Memory) Abort(reason string) Memory {
+ if !m.opened && !m.aborting {
+ m.aborting, m.abortReason = true, reason
+ }
+ return m
+}
+
+// fingerprint is the view's decision-relevant fields: a change to any of
+// them restarts the nudge clock.
+type fingerprint struct {
+ state, id, next, waiting string
+ failed bool
+ stagedAt, updatedAt int64
+ stage StageView
+ hasStage bool
+}
+
+func fingerprintOf(v View) fingerprint {
+ f := fingerprint{state: v.State, id: v.ID, next: v.Next, waiting: v.Waiting,
+ failed: v.Failed, stagedAt: v.StagedAt, updatedAt: v.UpdatedAt}
+ if v.Stage != nil {
+ f.stage, f.hasStage = *v.Stage, true
+ }
+ return f
+}
+
+// preOpen says a state is one abort may still be posted from.
+func preOpen(state string) bool {
+ switch state {
+ case StateStaging, StateStopping, StateSealing, StateSealed, StateLanding, StateLanded:
+ return true
+ }
+ return false
+}
+
+// offlineState says the instance is offline in state (stopping to landed).
+func offlineState(state string) bool { return preOpen(state) && state != StateStaging }
+
+// readyVerb is the verb a pre-open state moves on with once next names it.
+// Staging's start has its own rule (a fresh small round), so it is not here.
+func readyVerb(state string) string {
+ switch state {
+ case StateStopping:
+ return VerbSeal
+ case StateSealed:
+ return VerbFlip
+ case StateLanded:
+ return VerbOpen
+ }
+ return ""
+}
+
+// answered says the stager's report answers the record's latest request.
+func answered(v View) bool { return v.Stage != nil && v.StagedAt != 0 && v.Stage.Request == v.StagedAt }
+
+// observe folds view v, read at now, into the memory: the state clocks, the
+// nudge clock and the stage round this process watched.
+func (m Memory) observe(v View, now time.Duration) Memory {
+ if !m.seen || v.State != m.state {
+ m.state, m.stateSince = v.State, now
+ }
+ if fp := fingerprintOf(v); !m.seen || fp != m.fp {
+ m.fp, m.lastChange, m.nudged = fp, now, false
+ }
+ m.seen = true
+ if offlineState(v.State) && !m.offlineSeen {
+ m.offlineSeen, m.offlineSince = true, now
+ }
+ if v.State == StateStaging && v.StagedAt != 0 {
+ if !answered(v) {
+ m.watched = v.StagedAt
+ } else if v.StagedAt == m.watched && m.finishedReq != v.StagedAt {
+ m.finishedReq, m.finishedAt = v.StagedAt, now
+ }
+ }
+ return m
+}
+
+// Decide answers the one action to take for view v, read at monotonic time
+// now, and the memory with v folded in. The rules are plan §3's table and
+// the rules under it:
+// - a run never writes to a move it is not bound to;
+// - a ready step beats a deadline (next naming the verb posts it);
+// - abort is sticky until the view is reverting or open;
+// - after open nothing aborts; a probe with no 2xx stops with exit 4;
+// - a wait with no change for NudgeAfter nudges, then every NudgeEvery.
+func Decide(v View, p Policy, m Memory, now time.Duration) (Action, Memory) {
+ m = m.observe(v, now)
+
+ if v.State == StateNone {
+ switch {
+ case m.id == "" && m.stagePosts > 0:
+ // The view after our stage POST is authoritative: nothing was
+ // written (refused, or lost before the console committed it).
+ return Done{Exit: ExitStopped, Reason: ReasonStageNotWritten}, m
+ case m.id == "":
+ m.stagePosts++
+ return Post{Verb: VerbStage}, m
+ case v.Last != nil && v.Last.ID == m.id:
+ switch v.Last.Outcome {
+ case OutcomeDone:
+ return Done{Exit: ExitDone, Reason: ReasonDone}, m
+ case OutcomeAborted:
+ return Done{Exit: ExitAborted, Reason: ReasonAborted}, m
+ }
+ return Done{Exit: ExitStopped, Reason: ReasonUnexpectedState}, m
+ default:
+ return Done{Exit: ExitStopped, Reason: ReasonMoveGone}, m
+ }
+ }
+
+ if v.ID == "" {
+ return Done{Exit: ExitStopped, Reason: ReasonUnexpectedState}, m
+ }
+ if m.id == "" {
+ if m.stagePosts == 0 {
+ // A move this run did not stage: never adopted without --resume.
+ return Done{Exit: ExitStopped, Reason: ReasonHostHasMove}, m
+ }
+ m.id = v.ID
+ }
+ if v.ID != m.id {
+ return Done{Exit: ExitStopped, Reason: ReasonOtherMove}, m
+ }
+
+ switch v.State {
+ case StateOpen, StateFinishing:
+ m.opened = true
+ m.aborting = false
+ return m.afterOpen(v, p, now)
+ case StateReverting:
+ if v.Next == VerbFinish {
+ return Post{Verb: VerbFinish}, m
+ }
+ return m.wait(p, now)
+ }
+ if !preOpen(v.State) || m.opened {
+ return Done{Exit: ExitStopped, Reason: ReasonUnexpectedState}, m
+ }
+ return m.beforeOpen(v, p, now)
+}
+
+// beforeOpen decides in staging to landed, where abort is the way back.
+func (m Memory) beforeOpen(v View, p Policy, now time.Duration) (Action, Memory) {
+ if !m.aborting {
+ if v.Failed || (v.State == StateStaging && answered(v) && v.Stage.Phase == PhaseFailed) {
+ m = m.Abort(ReasonFailed)
+ }
+ }
+ if m.aborting {
+ return Post{Verb: VerbAbort, Reason: m.abortReason}, m
+ }
+ if verb := readyVerb(v.State); verb != "" && v.Next == verb {
+ return Post{Verb: verb}, m
+ }
+ if v.State == StateStaging {
+ return m.staging(v, p, now)
+ }
+ if why := m.overBudget(p, now); why != "" {
+ m = m.Abort(why)
+ return Post{Verb: VerbAbort, Reason: why}, m
+ }
+ return m.wait(p, now)
+}
+
+// staging decides between another round, start and waiting. Staging has no
+// time budget (the instance serves throughout); the round cap bounds it.
+func (m Memory) staging(v View, p Policy, now time.Duration) (Action, Memory) {
+ if !answered(v) {
+ return m.wait(p, now)
+ }
+ small := v.Stage.RoundBytes <= p.StageRoundBytes
+ fresh := m.finishedReq == v.StagedAt && now-m.finishedAt < p.SmallRoundFresh
+ if small && fresh {
+ if v.Next == VerbStart {
+ return Post{Verb: VerbStart}, m
+ }
+ return m.wait(p, now)
+ }
+ // A big round, a small one this process did not watch finish (a
+ // resume), or one watched too long ago: run another round.
+ if m.stagePosts >= p.MaxStageRounds {
+ m = m.Abort(ReasonStageRounds)
+ return Post{Verb: VerbAbort, Reason: ReasonStageRounds}, m
+ }
+ m.stagePosts++
+ return Post{Verb: VerbStage}, m
+}
+
+// overBudget names the budget an offline state has run past, "" for none.
+func (m Memory) overBudget(p Policy, now time.Duration) string {
+ in := now - m.stateSince
+ switch {
+ case m.state == StateStopping && in >= p.Stop:
+ return ReasonBudgetStop
+ case m.state == StateSealing && in >= p.Seal:
+ return ReasonBudgetSeal
+ case m.state == StateLanding && in >= p.Landing:
+ return ReasonBudgetLanding
+ case m.state == StateLanded && in >= p.OpenCheck:
+ return ReasonBudgetOpenCheck
+ case m.offlineSeen && now-m.offlineSince >= p.Offline:
+ return ReasonBudgetOffline
+ }
+ return ""
+}
+
+// afterOpen decides in open and finishing: probe, then finish. Never abort.
+func (m Memory) afterOpen(v View, p Policy, now time.Duration) (Action, Memory) {
+ if v.State == StateOpen && !m.probeOK {
+ if now-m.stateSince >= p.Probe {
+ return Done{Exit: ExitStopped, Reason: ReasonProbeFailed}, m
+ }
+ return Probe{}, m
+ }
+ if v.State == StateOpen && p.NoFinish {
+ return Done{Exit: ExitDone, Reason: ReasonOpenNoFinish}, m
+ }
+ if v.Next == VerbFinish {
+ return Post{Verb: VerbFinish}, m
+ }
+ return m.wait(p, now)
+}
+
+// wait is Wait, or Nudge once a wait has seen no change for NudgeAfter and
+// every NudgeEvery after.
+func (m Memory) wait(p Policy, now time.Duration) (Action, Memory) {
+ quiet := now - m.lastChange
+ if (!m.nudged && quiet >= p.NudgeAfter) || (m.nudged && now-m.lastNudge >= p.NudgeEvery) {
+ m.nudged, m.lastNudge = true, now
+ return Nudge{}, m
+ }
+ return Wait{}, m
+}
diff --git a/internal/moves/offlinerun/decide_test.go b/internal/moves/offlinerun/decide_test.go
new file mode 100644
index 000000000..0d84bc06b
--- /dev/null
+++ b/internal/moves/offlinerun/decide_test.go
@@ -0,0 +1,379 @@
+package offlinerun
+
+import (
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+const (
+ tID = "mv-1"
+ tOther = "mv-2"
+ mib = int64(1 << 20)
+)
+
+func at(s float64) time.Duration { return time.Duration(s * float64(time.Second)) }
+
+// tv is a view of our move in state.
+func tv(state string) View { return View{State: state, ID: tID} }
+
+func withNext(v View, next string) View { v.Next = next; return v }
+
+// staging is a staging view whose latest request is req; answered says the
+// stager's report answers it, with round bytes.
+func staging(req int64, answered bool, round int64) View {
+ v := tv(StateStaging)
+ v.StagedAt = req
+ if answered {
+ v.Stage = &StageView{Phase: "staged", Request: req, RoundBytes: round}
+ } else if req > 1 {
+ v.Stage = &StageView{Phase: "staged", Request: req - 1, RoundBytes: round}
+ }
+ return v
+}
+
+func none(last *Outcome) View { return View{State: StateNone, Last: last} }
+
+// bound is the memory of a process that staged this move and has seen
+// state since since.
+func bound(state string, since time.Duration) Memory {
+ return Memory{id: tID, stagePosts: 1, seen: true, state: state, stateSince: since, lastChange: since}
+}
+
+// offline is bound with the offline clock started at since.
+func offline(state string, since time.Duration) Memory {
+ m := bound(state, since)
+ m.offlineSeen, m.offlineSince = true, since
+ return m
+}
+
+// TestDecideTable is one row per line of the plan's section 3 table, each a
+// single decision from a stated memory.
+func TestDecideTable(t *testing.T) {
+ p := DefaultPolicy()
+ smallWatched := bound(StateStaging, 0)
+ smallWatched.watched, smallWatched.finishedReq, smallWatched.finishedAt = 5, 5, at(10)
+ cases := []struct {
+ name string
+ m Memory
+ v View
+ now time.Duration
+ want Action
+ }{
+ {"no move, nothing bound: stage", NewMemory(""), none(nil), 0, Post{Verb: VerbStage}},
+ {"no move, nothing bound, an old move's outcome: stage", NewMemory(""), none(&Outcome{ID: tOther, Outcome: OutcomeDone}), 0, Post{Verb: VerbStage}},
+ {"id differs from the bound id: stop, write nothing", bound(StateStaging, 0), View{State: StateStaging, ID: tOther}, at(1), Done{Exit: ExitStopped, Reason: ReasonOtherMove}},
+ {"staging, round not answered: wait", bound(StateStaging, 0), staging(5, false, 0), at(1), Wait{}},
+ {"staging, no stager report yet: wait", bound(StateStaging, 0), staging(1, false, 0), at(1), Wait{}},
+ {"staging, answered, over 1 MiB, under 5 rounds: stage", bound(StateStaging, 0), staging(5, true, mib+1), at(1), Post{Verb: VerbStage}},
+ {"staging, answered, over 1 MiB, 5 rounds spent: abort", func() Memory { m := bound(StateStaging, 0); m.stagePosts = 5; return m }(), staging(5, true, mib+1), at(1), Post{Verb: VerbAbort, Reason: ReasonStageRounds}},
+ {"staging, small round watched under 60 s ago, next start: start", smallWatched, withNext(staging(5, true, mib), VerbStart), at(69), Post{Verb: VerbStart}},
+ {"staging, small round watched, next not yet start: wait", smallWatched, staging(5, true, mib), at(20), Wait{}},
+ {"staging, small round watched 60 s ago: stage again", smallWatched, withNext(staging(5, true, 10), VerbStart), at(70), Post{Verb: VerbStage}},
+ {"staging, small round not watched (a resume): stage first", NewMemory(tID), withNext(staging(5, true, 10), VerbStart), 0, Post{Verb: VerbStage}},
+ {"stopping with next seal: seal", offline(StateStopping, 0), withNext(tv(StateStopping), VerbSeal), at(1), Post{Verb: VerbSeal}},
+ {"sealed with next flip: flip", offline(StateSealed, 0), withNext(tv(StateSealed), VerbFlip), at(1), Post{Verb: VerbFlip}},
+ {"landed with next open: open", offline(StateLanded, 0), withNext(tv(StateLanded), VerbOpen), at(1), Post{Verb: VerbOpen}},
+ {"stopping, next empty: wait", offline(StateStopping, 0), tv(StateStopping), at(1), Wait{}},
+ {"sealing: wait", offline(StateSealing, 0), tv(StateSealing), at(1), Wait{}},
+ {"landing: wait", offline(StateLanding, 0), tv(StateLanding), at(1), Wait{}},
+ {"sealing, failed: abort", offline(StateSealing, 0), func() View { v := tv(StateSealing); v.Failed = true; return v }(), at(1), Post{Verb: VerbAbort, Reason: ReasonFailed}},
+ {"landing, failed: abort", offline(StateLanding, 0), func() View { v := tv(StateLanding); v.Failed = true; return v }(), at(1), Post{Verb: VerbAbort, Reason: ReasonFailed}},
+ {"staging, the round failed: abort", bound(StateStaging, 0), func() View { v := staging(5, true, 0); v.Stage.Phase = PhaseFailed; return v }(), at(1), Post{Verb: VerbAbort, Reason: ReasonFailed}},
+ {"stopping over 3 min, no ready step: abort", offline(StateStopping, 0), tv(StateStopping), p.Stop, Post{Verb: VerbAbort, Reason: ReasonBudgetStop}},
+ {"sealing over 10 min: abort", func() Memory { m := offline(StateSealing, at(100)); m.offlineSince = at(100); return m }(), tv(StateSealing), at(100) + p.Seal, Post{Verb: VerbAbort, Reason: ReasonBudgetSeal}},
+ {"landing over 5 min: abort", offline(StateLanding, 0), tv(StateLanding), p.Landing, Post{Verb: VerbAbort, Reason: ReasonBudgetLanding}},
+ {"landed over the open check, no next: abort", offline(StateLanded, 0), tv(StateLanded), p.OpenCheck, Post{Verb: VerbAbort, Reason: ReasonBudgetOpenCheck}},
+ {"sealed over the offline total, no next: abort", func() Memory { m := offline(StateSealed, at(800)); m.offlineSince = 0; return m }(), tv(StateSealed), p.Offline, Post{Verb: VerbAbort, Reason: ReasonBudgetOffline}},
+ {"sealing under every budget: wait", func() Memory { m := offline(StateSealing, at(800)); m.offlineSince = 0; return m }(), tv(StateSealing), p.Offline - time.Second, Wait{}},
+ {"open, not probed: probe", offline(StateOpen, 0), withNext(tv(StateOpen), VerbFinish), at(1), Probe{}},
+ {"open, probe answered 2xx, next finish: finish", func() Memory { m := offline(StateOpen, 0); m.probeOK = true; return m }(), withNext(tv(StateOpen), VerbFinish), at(1), Post{Verb: VerbFinish}},
+ {"open, probe answered 2xx, next empty: wait", func() Memory { m := offline(StateOpen, 0); m.probeOK = true; return m }(), tv(StateOpen), at(1), Wait{}},
+ {"finishing with next finish: finish", bound(StateFinishing, 0), withNext(tv(StateFinishing), VerbFinish), at(1), Post{Verb: VerbFinish}},
+ {"finishing, next empty: wait", bound(StateFinishing, 0), tv(StateFinishing), at(1), Wait{}},
+ {"reverting with next finish: finish", bound(StateReverting, 0), withNext(tv(StateReverting), VerbFinish), at(1), Post{Verb: VerbFinish}},
+ {"reverting, next empty: wait", bound(StateReverting, 0), tv(StateReverting), at(1), Wait{}},
+ {"no move, last is ours and done: exit 0", bound(StateFinishing, 0), none(&Outcome{ID: tID, Outcome: OutcomeDone}), at(1), Done{Exit: ExitDone, Reason: ReasonDone}},
+ {"no move, last is ours and aborted: exit 3", bound(StateReverting, 0), none(&Outcome{ID: tID, Outcome: OutcomeAborted}), at(1), Done{Exit: ExitAborted, Reason: ReasonAborted}},
+ {"no move, last is another's: stop", bound(StateFinishing, 0), none(&Outcome{ID: tOther, Outcome: OutcomeDone}), at(1), Done{Exit: ExitStopped, Reason: ReasonMoveGone}},
+ {"a move on the host, nothing bound, no --resume: stop", NewMemory(""), staging(5, true, 0), 0, Done{Exit: ExitStopped, Reason: ReasonHostHasMove}},
+ {"our stage wrote nothing: stop", func() Memory { m := NewMemory(""); m.stagePosts = 1; return m }(), none(nil), at(2), Done{Exit: ExitStopped, Reason: ReasonStageNotWritten}},
+ {"a state this glue does not know: stop", bound(StateStaging, 0), tv("offline-somethingnew"), at(1), Done{Exit: ExitStopped, Reason: ReasonUnexpectedState}},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ got, _ := Decide(c.v, p, c.m, c.now)
+ if !reflect.DeepEqual(got, c.want) {
+ t.Fatalf("Decide = %#v, want %#v", got, c.want)
+ }
+ })
+ }
+}
+
+// step is one tick of a sequence: the view read at now and what Decide must
+// answer.
+type step struct {
+ now time.Duration
+ v View
+ want Action
+}
+
+// play runs steps through Decide in order, carrying memory, and returns it.
+func play(t *testing.T, p Policy, m Memory, steps []step) Memory {
+ t.Helper()
+ for i, s := range steps {
+ var got Action
+ got, m = Decide(s.v, p, m, s.now)
+ if !reflect.DeepEqual(got, s.want) {
+ t.Fatalf("step %d (at %v, %s): Decide = %#v, want %#v", i, s.now, s.v.State, got, s.want)
+ }
+ }
+ return m
+}
+
+func TestDecideHappyPath(t *testing.T) {
+ p := DefaultPolicy()
+ m := play(t, p, NewMemory(""), []step{
+ {0, none(nil), Post{Verb: VerbStage}},
+ {at(2), staging(5, false, 0), Wait{}},
+ {at(4), staging(5, true, 50*mib), Post{Verb: VerbStage}},
+ {at(6), staging(6, false, 50*mib), Wait{}},
+ {at(8), withNext(staging(6, true, 10), VerbStart), Post{Verb: VerbStart}},
+ {at(10), tv(StateStopping), Wait{}},
+ {at(12), withNext(tv(StateStopping), VerbSeal), Post{Verb: VerbSeal}},
+ {at(14), tv(StateSealing), Wait{}},
+ {at(16), withNext(tv(StateSealed), VerbFlip), Post{Verb: VerbFlip}},
+ {at(18), tv(StateLanding), Wait{}},
+ {at(20), withNext(tv(StateLanded), VerbOpen), Post{Verb: VerbOpen}},
+ {at(22), withNext(tv(StateOpen), VerbFinish), Probe{}},
+ })
+ if m.Bound() != tID {
+ t.Fatalf("bound id = %q, want %q", m.Bound(), tID)
+ }
+ m = m.Probed(true)
+ play(t, p, m, []step{
+ {at(24), withNext(tv(StateOpen), VerbFinish), Post{Verb: VerbFinish}},
+ {at(26), tv(StateFinishing), Wait{}},
+ {at(28), withNext(tv(StateFinishing), VerbFinish), Post{Verb: VerbFinish}},
+ {at(30), none(&Outcome{ID: tID, Outcome: OutcomeDone}), Done{Exit: ExitDone, Reason: ReasonDone}},
+ })
+}
+
+func TestDecideSmallRoundWatched(t *testing.T) {
+ p := DefaultPolicy()
+ // Watched pending, then answered small: start while fresh, stage once
+ // the 60 s freshness has passed.
+ m := play(t, p, NewMemory(tID), []step{
+ {0, staging(5, false, 0), Wait{}},
+ {at(2), staging(5, true, 10), Wait{}},
+ })
+ play(t, p, m, []step{
+ {at(61), withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStart}},
+ })
+ play(t, p, m, []step{
+ {at(62), withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStage}},
+ })
+ // A round first seen answered was not watched: stage first.
+ play(t, p, NewMemory(tID), []step{
+ {0, withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStage}},
+ {at(2), staging(6, false, 10), Wait{}},
+ {at(4), withNext(staging(6, true, 10), VerbStart), Post{Verb: VerbStart}},
+ })
+ // A big round watched finish is not a reason to start.
+ play(t, p, NewMemory(tID), []step{
+ {0, staging(5, false, 0), Wait{}},
+ {at(2), withNext(staging(5, true, mib+1), VerbStart), Post{Verb: VerbStage}},
+ })
+}
+
+func TestDecideStageRoundsCapped(t *testing.T) {
+ p := DefaultPolicy()
+ steps := []step{{0, none(nil), Post{Verb: VerbStage}}}
+ for r := int64(1); r < int64(p.MaxStageRounds); r++ {
+ steps = append(steps,
+ step{at(float64(4 * r)), staging(r, false, 0), Wait{}},
+ step{at(float64(4*r + 2)), staging(r, true, 2*mib), Post{Verb: VerbStage}},
+ )
+ }
+ n := int64(p.MaxStageRounds)
+ steps = append(steps,
+ step{at(float64(4 * n)), staging(n, false, 0), Wait{}},
+ step{at(float64(4*n + 2)), staging(n, true, 2*mib), Post{Verb: VerbAbort, Reason: ReasonStageRounds}},
+ )
+ play(t, p, NewMemory(""), steps)
+}
+
+func TestDecideReadyStepBeatsDeadline(t *testing.T) {
+ p := DefaultPolicy()
+ late := p.Offline + time.Hour
+ cases := []struct {
+ state, verb string
+ }{
+ {StateStopping, VerbSeal},
+ {StateSealed, VerbFlip},
+ {StateLanded, VerbOpen},
+ }
+ for _, c := range cases {
+ t.Run(c.state, func(t *testing.T) {
+ got, _ := Decide(withNext(tv(c.state), c.verb), p, offline(c.state, 0), late)
+ if want := (Post{Verb: c.verb}); got != want {
+ t.Fatalf("Decide = %#v, want %#v", got, want)
+ }
+ })
+ }
+ // Staging: a fresh small round with next start is posted however long
+ // staging took.
+ m := play(t, p, NewMemory(tID), []step{
+ {0, staging(5, false, 0), Wait{}},
+ {late, staging(5, true, 10), Wait{}},
+ })
+ play(t, p, m, []step{{late + at(2), withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStart}}})
+}
+
+func TestDecideIDMismatchWritesNothing(t *testing.T) {
+ p := DefaultPolicy()
+ want := Done{Exit: ExitStopped, Reason: ReasonOtherMove}
+ for _, state := range []string{StateStaging, StateStopping, StateSealing, StateSealed, StateLanding, StateLanded, StateOpen, StateFinishing, StateReverting} {
+ t.Run(state, func(t *testing.T) {
+ v := withNext(View{State: state, ID: tOther, Failed: true}, VerbFinish)
+ // Bound by --resume, by our own stage, and mid-abort: none of
+ // them writes to another move.
+ for _, m := range []Memory{NewMemory(tID), offline(state, 0), func() Memory { m := offline(state, 0); return m.Abort(ReasonInterrupted) }()} {
+ got, _ := Decide(v, p, m, p.Offline+time.Hour)
+ if got != Action(want) {
+ t.Fatalf("Decide = %#v, want %#v", got, want)
+ }
+ }
+ })
+ }
+}
+
+func TestDecideAbortIsSticky(t *testing.T) {
+ p := DefaultPolicy()
+ m := offline(StateSealing, 0)
+ failed := tv(StateSealing)
+ failed.Failed = true
+ play(t, p, m, []step{
+ {at(2), failed, Post{Verb: VerbAbort, Reason: ReasonFailed}},
+ // The abort's reply was lost and the record moved on regardless:
+ // a ready flip is not taken, abort is posted again.
+ {at(4), withNext(tv(StateSealed), VerbFlip), Post{Verb: VerbAbort, Reason: ReasonFailed}},
+ {at(6), withNext(tv(StateLanded), VerbOpen), Post{Verb: VerbAbort, Reason: ReasonFailed}},
+ {at(8), tv(StateReverting), Wait{}},
+ {at(10), withNext(tv(StateReverting), VerbFinish), Post{Verb: VerbFinish}},
+ {at(12), none(&Outcome{ID: tID, Outcome: OutcomeAborted}), Done{Exit: ExitAborted, Reason: ReasonAborted}},
+ })
+ // An interrupt (Ctrl-C) before open is the same sticky abort.
+ m = offline(StateStopping, 0).Abort(ReasonInterrupted)
+ play(t, p, m, []step{
+ {at(2), withNext(tv(StateStopping), VerbSeal), Post{Verb: VerbAbort, Reason: ReasonInterrupted}},
+ {at(4), withNext(tv(StateReverting), VerbFinish), Post{Verb: VerbFinish}},
+ })
+ // Someone opened it by hand: the abort ends there, the open path runs.
+ m = offline(StateLanded, 0).Abort(ReasonInterrupted)
+ play(t, p, m, []step{
+ {at(2), withNext(tv(StateOpen), VerbFinish), Probe{}},
+ })
+}
+
+func TestDecideAfterOpenNeverAborts(t *testing.T) {
+ p := DefaultPolicy()
+ open := withNext(tv(StateOpen), VerbFinish)
+ open.Failed = true
+ m := play(t, p, offline(StateLanded, 0), []step{
+ {at(10), open, Probe{}},
+ {at(10) + p.Probe - time.Second, open, Probe{}},
+ })
+ // Ctrl-C after open asks for an abort; it is not taken.
+ m = m.Abort(ReasonInterrupted)
+ play(t, p, m, []step{
+ {at(10) + p.Probe - time.Millisecond, open, Probe{}},
+ {at(10) + p.Probe, open, Done{Exit: ExitStopped, Reason: ReasonProbeFailed}},
+ })
+ // A run that saw open and then reads a pre-open state (it cannot happen;
+ // abort is refused from open on) stops rather than aborting.
+ m = offline(StateOpen, 0)
+ m.opened = true
+ got, _ := Decide(func() View { v := tv(StateLanded); v.Failed = true; return v }(), p, m, p.Offline+time.Hour)
+ if want := (Done{Exit: ExitStopped, Reason: ReasonUnexpectedState}); got != Action(want) {
+ t.Fatalf("Decide = %#v, want %#v", got, want)
+ }
+}
+
+func TestDecideNoFinish(t *testing.T) {
+ p := DefaultPolicy()
+ p.NoFinish = true
+ m := play(t, p, offline(StateLanded, 0), []step{
+ {at(2), withNext(tv(StateOpen), VerbFinish), Probe{}},
+ })
+ play(t, p, m.Probed(true), []step{
+ {at(4), withNext(tv(StateOpen), VerbFinish), Done{Exit: ExitDone, Reason: ReasonOpenNoFinish}},
+ })
+}
+
+func TestDecideNudge(t *testing.T) {
+ p := DefaultPolicy()
+ sealing := tv(StateSealing)
+ m := play(t, p, offline(StateStopping, 0), []step{
+ {at(100), sealing, Wait{}},
+ {at(128), sealing, Wait{}},
+ {at(130), sealing, Nudge{}},
+ {at(132), sealing, Wait{}},
+ {at(188), sealing, Wait{}},
+ {at(190), sealing, Nudge{}},
+ {at(192), sealing, Wait{}},
+ {at(250), sealing, Nudge{}},
+ })
+ // A change restarts the 30 s.
+ landing := tv(StateLanding)
+ play(t, p, m, []step{
+ {at(252), landing, Wait{}},
+ {at(280), landing, Wait{}},
+ {at(282), landing, Nudge{}},
+ })
+ // Waiting text changing is a change too.
+ w := tv(StateStopping)
+ w.Waiting = "a"
+ w2 := w
+ w2.Waiting = "b"
+ play(t, p, offline(StateStopping, 0), []step{
+ {0, w, Wait{}},
+ {at(29), w2, Wait{}},
+ {at(58), w2, Wait{}},
+ {at(59), w2, Nudge{}},
+ })
+ // Staging and reverting waits nudge as well.
+ play(t, p, NewMemory(tID), []step{
+ {0, staging(5, false, 0), Wait{}},
+ {at(30), staging(5, false, 0), Nudge{}},
+ })
+ play(t, p, bound(StateReverting, 0), []step{
+ {0, tv(StateReverting), Wait{}},
+ {at(30), tv(StateReverting), Nudge{}},
+ })
+}
+
+// TestDecideNamesMatchProvision pins the state and outcome twins to the
+// record's own names.
+func TestDecideNamesMatchProvision(t *testing.T) {
+ pairs := [][2]string{
+ {StateStaging, provision.OfflineStaging},
+ {StateStopping, provision.OfflineStopping},
+ {StateSealing, provision.OfflineSealing},
+ {StateSealed, provision.OfflineSealed},
+ {StateLanding, provision.OfflineLanding},
+ {StateLanded, provision.OfflineLanded},
+ {StateOpen, provision.OfflineOpen},
+ {StateFinishing, provision.OfflineFinishing},
+ {StateReverting, provision.OfflineReverting},
+ {OutcomeDone, provision.OfflineOutcomeDone},
+ {OutcomeAborted, provision.OfflineOutcomeAborted},
+ }
+ for _, p := range pairs {
+ if p[0] != p[1] {
+ t.Errorf("twin %q != provision's %q", p[0], p[1])
+ }
+ }
+}