carlos / platform Public

moves: offline run binds only a move its create-only stage made

Astra branch review round 1, finding 1 (P1, ownership). The first stage
run sends is create-only ("new": true): the stage and start doors then
never restage or start a move that is there, and go straight to the
begin transition, which refuses any move on the record under the record
write's compare-and-set. Its 202 says "new": true. Without the flag the
doors are as before.

run binds only from that reply's id. A 4xx on the first stage is a
refusal (exit 5) whatever the next view shows; a lost or 5xx reply, or
one that does not say it created the move, stops with exit 4 and OR27
with the id it sees, never adopting it.

Witnesses: console create-only door (incl. a stage landing between the
door's read and write), CLI and two-box runs where a hand stages between
run's GET and POST (refused, their move untouched) and where the first
stage's reply is lost (exit 4, no further POST). The simulation now
injects hand POSTs between run's read and its POST.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5b6e62c1993952e0697fa1cde28e3f3822c4ecd2 parent 93d831b
11 files changed, +510 −109
  • internal/console/apiinstancemove_offline.go +46 −30
  • internal/console/apiinstancemove_offline_stage_test.go +85 −0
  • internal/host/movesoffline_e2e_test.go +137 −10
  • internal/moves/offlinerun/decide.go +35 −16
  • internal/moves/offlinerun/decide_test.go +43 −17
  • internal/moves/offlinerun/run.go +13 −11
  • internal/moves/offlinerun/run_test.go +31 −0
  • move.go +3 −0
  • move_offline_run.go +34 −16
  • move_offline_run_test.go +78 −7
  • move_test.go +5 −2
diff --git a/internal/console/apiinstancemove_offline.go b/internal/console/apiinstancemove_offline.go
index 11728701a..d3dd80ab0 100644
--- a/internal/console/apiinstancemove_offline.go
+++ b/internal/console/apiinstancemove_offline.go
@@ -601,66 +601,74 @@ func (s *Server) offlineClaimEvidence(ctx context.Context, d offlineDoor) *offli
// code and the fleet it read, or false once it has answered the request.
// A staged move is checked again in full when it starts: the fleet and the
// claims may have changed since the stage.
-func (s *Server) offlineBeginChecks(w http.ResponseWriter, r *http.Request, d offlineDoor) (string, offlineFleet, bool) {
+//
+// createOnly is the body's "new": true (plan 2026-11-15-offline-move-run,
+// Astra branch round 1, finding 1): the caller wants a move created and
+// nothing else. The door then never restages or starts a move that is
+// there; it goes straight to offlineBegin, whose transition refuses any
+// move on the record under the record write's compare-and-set. Without it
+// the door is as it was.
+func (s *Server) offlineBeginChecks(w http.ResponseWriter, r *http.Request, d offlineDoor) (to string, fleet offlineFleet, createOnly, ok bool) {
rec, host := d.rec, d.host
if s.refuseSeedMove(w, rec) || s.refuseRootfsMove(w, rec) {
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if rec.Role != "" {
jsonError(w, http.StatusBadRequest, "a replica does not move. delete it and create one in the new region")
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if len(rec.Replicas) > 0 {
jsonError(w, http.StatusBadRequest, "a home with replicas does not move. remove its replicas first")
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if rec.Steering != "" || rec.Unit != "" {
jsonError(w, http.StatusBadRequest, fmt.Sprintf("%s is steered or runs under a unit. offline moves cannot carry either yet", host))
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
ctx := r.Context()
if ref := s.offlineClaimEvidence(ctx, d); ref != nil {
writeRefusal(w, ref)
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
var req struct {
Region string `json:"region"`
ID string `json:"id"`
+ New bool `json:"new"`
}
if !readJSON(w, r, &req) {
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if !s.offlineMoveIs(w, d, req.ID) {
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
region := strings.TrimSpace(req.Region)
- to := s.homeRegionIn(region)
+ to = s.homeRegionIn(region)
if region == "" || !provision.ValidRegion(to) {
jsonError(w, http.StatusBadRequest, "invalid region")
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if block := s.haTransferRegion(rec, to); block != "" {
jsonError(w, http.StatusConflict, haMoveSentence(block))
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if to == rec.Region {
jsonError(w, http.StatusConflict, "the instance is already in "+region)
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
m, err := provision.GetManifest(ctx, s.cfg.Releases, d.acct.Sqid, d.app)
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Printf("console: offline move %s: manifest: %v", host, err)
jsonError(w, http.StatusServiceUnavailable, "could not read the app's instances manifest. try again")
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if m != nil && !s.moveRegionAllowed(m.Regions, to) {
jsonError(w, http.StatusBadRequest, "region "+region+" is not one of this app's regions: "+strings.Join(m.Regions, ", "))
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
- fleet, ok := s.readOfflineFleet(ctx)
+ fleet, ok = s.readOfflineFleet(ctx)
if !ok {
jsonError(w, http.StatusConflict, "the fleet's edges files could not all be read. try again")
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if to == "" || rec.Region == "" {
// A box that sets CARLOS_REGION to the home's name is home to this
@@ -669,19 +677,19 @@ func (s *Server) offlineBeginChecks(w http.ResponseWriter, r *http.Request, d of
for _, f := range fleet.snap.Files {
if f.Placement != "" && homePlacementCode(s.moveHomeName(), f.Placement) == "" {
jsonError(w, http.StatusConflict, f.Box+" sets CARLOS_REGION, so it cannot take a move into the home region")
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
}
}
if ref := s.offlineSelect(ctx, fleet, host, rec.Region, to); ref != nil {
writeRefusal(w, ref)
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
if ref := offlineBoxFacts(fleet, host, to); ref != nil {
writeRefusal(w, ref)
- return "", offlineFleet{}, false
+ return "", offlineFleet{}, false, false
}
- return to, fleet, true
+ return to, fleet, req.New, true
}
// offlineStagedFor is the refusal of a start or a stage that names another
@@ -740,13 +748,13 @@ func (s *Server) handleAPIInstanceOfflineStart(w http.ResponseWriter, r *http.Re
if !ok {
return
}
- to, fleet, ok := s.offlineBeginChecks(w, r, d)
+ to, fleet, createOnly, ok := s.offlineBeginChecks(w, r, d)
if !ok {
return
}
// A staged instance starts the move it is staged for: staging to
// stopping, the instance offline from now. The lock is the stage's.
- if mv, staged := offlineStaged(d.rec); staged {
+ if mv, staged := offlineStaged(d.rec); staged && !createOnly {
if to != mv.To {
writeRefusal(w, s.offlineStagedFor(d.host, mv.To))
return
@@ -762,7 +770,7 @@ func (s *Server) handleAPIInstanceOfflineStart(w http.ResponseWriter, r *http.Re
s.offlineAdvance(w, r, d, provision.OfflineStartStaged(mv.ID, d.addr, time.Now()))
return
}
- s.offlineBegin(w, r, d, func(id string) func(*provision.Record) error {
+ s.offlineBegin(w, r, d, createOnly, func(id string) func(*provision.Record) error {
return provision.OfflineStart(id, d.rec.Region, to, d.addr, time.Now())
})
}
@@ -772,17 +780,18 @@ func (s *Server) handleAPIInstanceOfflineStart(w http.ResponseWriter, r *http.Re
// under the same one-move lock, and the source region's stager runs one
// round on the serial bump. On a record already staging for that region it
// moves staged_at forward (OfflineRestage), so the stager runs one more
-// round; each round copies only what is new (the receipts).
+// round; each round copies only what is new (the receipts). With "new":
+// true it only ever creates (offlineBeginChecks).
func (s *Server) handleAPIInstanceOfflineStage(w http.ResponseWriter, r *http.Request) {
d, ok := s.offlineGate(w, r)
if !ok {
return
}
- to, fleet, ok := s.offlineBeginChecks(w, r, d)
+ to, fleet, createOnly, ok := s.offlineBeginChecks(w, r, d)
if !ok {
return
}
- if mv, staged := offlineStaged(d.rec); staged {
+ if mv, staged := offlineStaged(d.rec); staged && !createOnly {
if to != mv.To {
writeRefusal(w, s.offlineStagedFor(d.host, mv.To))
return
@@ -821,15 +830,17 @@ func (s *Server) handleAPIInstanceOfflineStage(w http.ResponseWriter, r *http.Re
}
}
st := provision.StageTarget{Stager: moves.OfflineStager(names), Bucket: tgt.DataBucket, Region: tgt.DataBucketRegion}
- s.offlineBegin(w, r, d, func(id string) func(*provision.Record) error {
+ s.offlineBegin(w, r, d, createOnly, func(id string) func(*provision.Record) error {
return provision.OfflineStage(id, d.rec.Region, to, d.addr, st, time.Now())
})
}
// offlineBegin mints the move's id and writes the transition begin makes
// with it (OfflineStart or OfflineStage) under the one-move lock, then
-// bumps the serial and answers 202 with the status view.
-func (s *Server) offlineBegin(w http.ResponseWriter, r *http.Request, d offlineDoor, begin func(id string) func(*provision.Record) error) {
+// bumps the serial and answers 202 with the status view. A create-only
+// request (offlineBeginChecks) gets "new": true in that view: the move it
+// names is the one this request created.
+func (s *Server) offlineBegin(w http.ResponseWriter, r *http.Request, d offlineDoor, createOnly bool, begin func(id string) func(*provision.Record) error) {
ctx := r.Context()
host := d.host
id, err := moves.NewMoveID(rand.Reader)
@@ -871,7 +882,9 @@ func (s *Server) offlineBegin(w http.ResponseWriter, r *http.Request, d offlineD
return
}
s.bumpSerial(ctx)
- writeJSON(w, http.StatusAccepted, s.offlineViewOf(ctx, got))
+ v := s.offlineViewOf(ctx, got)
+ v.New = createOnly
+ writeJSON(w, http.StatusAccepted, v)
}
// offlineStartWrite bounds the start door's record write.
@@ -1453,6 +1466,9 @@ type offlineView struct {
Reports []offlineReportView `json:"reports,omitempty"`
Items []offlineItemView `json:"items,omitempty"`
Last *provision.MoveOutcome `json:"last,omitempty"`
+ // New is set only on the reply to a create-only stage or start
+ // ("new": true in the request): this request created the move.
+ New bool `json:"new,omitempty"`
}
// offlineStageView is the pre-copy's progress, from the latest stager
diff --git a/internal/console/apiinstancemove_offline_stage_test.go b/internal/console/apiinstancemove_offline_stage_test.go
index b6217a446..9bf70f68b 100644
--- a/internal/console/apiinstancemove_offline_stage_test.go
+++ b/internal/console/apiinstancemove_offline_stage_test.go
@@ -2,13 +2,16 @@ package console
import (
"context"
+ "crypto/rand"
"net/http"
"slices"
+ "strings"
"testing"
"time"
"github.com/carlosframework/platform/internal/moves"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
)
// The pre-copy door (offline-staging), in-process against the offline
@@ -418,3 +421,85 @@ func TestOfflineStageAndStartRefuseAStaleLiveLinkOnTheTarget(t *testing.T) {
w3.ok("", `{"region":"uk"}`, provision.OfflineStopping)
}
}
+
+// stageRaceStore writes, once, a move of someone else's into the record
+// just as the door takes the one-move lock: after the door read the record
+// at rest, before its own write. It stands for a second operator whose
+// stage lands between the two.
+type stageRaceStore struct {
+ release.Store
+ race func()
+}
+
+func (s *stageRaceStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if key == moves.OfflineActiveKey && s.race != nil {
+ race := s.race
+ s.race = nil
+ race()
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+// TestOfflineStageCreateOnly is the stage door's create-only condition
+// (plan 2026-11-15-offline-move-run, Astra branch round 1, finding 1):
+// "new": true creates a move or refuses, and never restages one that is
+// there. The refusal is the begin transition's own sentence, checked under
+// the record write's compare-and-set, so a move staged by someone else
+// after the door read the record is refused too, and theirs is left as
+// they wrote it. Without the flag the door restages as it always has.
+func TestOfflineStageCreateOnly(t *testing.T) {
+ t.Run("at rest: created, and the reply says so", func(t *testing.T) {
+ w := newOfflineWorld(t, ieOff("ie-box"), ukOff("uk-box"))
+ code, out := w.req(http.MethodPost, "/stage", `{"region":"uk","new":true}`)
+ if code != http.StatusAccepted || !strings.Contains(out, `"new":true`) {
+ t.Fatalf("stage new = %d %s", code, out)
+ }
+ if v := w.view(code, out); v.State != provision.OfflineStaging || v.ID == "" || w.record().Move.ID != v.ID {
+ t.Fatalf("stage new answered %+v", v)
+ }
+ })
+ t.Run("staging: refused, nothing written", func(t *testing.T) {
+ w := newOfflineWorld(t, ieOff("ie-box"), ukOff("uk-box"))
+ w.stage()
+ w.refused(http.MethodPost, "/stage", `{"region":"uk","new":true}`, http.StatusConflict, "a move to uk is already "+provision.OfflineStaging)
+ // The id of the move that is there changes nothing: still refused.
+ w.refused(http.MethodPost, "/stage", `{"region":"uk","new":true,"id":"`+w.id+`"}`, http.StatusConflict, "a move to uk is already "+provision.OfflineStaging)
+ // The start door honours the flag the same way: it does not start
+ // the staged move.
+ w.refused(http.MethodPost, "", `{"region":"uk","new":true}`, http.StatusConflict, "a move to uk is already "+provision.OfflineStaging)
+ // Without the flag the door restages, and its reply has no "new".
+ code, out := w.req(http.MethodPost, "/stage", `{"region":"uk"}`)
+ if code != http.StatusAccepted || strings.Contains(out, `"new"`) {
+ t.Fatalf("restage = %d %s", code, out)
+ }
+ })
+ t.Run("someone stages between the door's read and its write", func(t *testing.T) {
+ w := newOfflineWorld(t, ieOff("ie-box"), ukOff("uk-box"))
+ theirs, err := moves.NewMoveID(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ inner := w.fx.srv.cfg.Releases
+ var theirRaw []byte
+ w.fx.srv.cfg.Releases = &stageRaceStore{Store: inner, race: func() {
+ st := provision.StageTarget{Stager: "ie-box", Bucket: "data-uk", Region: "eu-west-2"}
+ if _, err := provision.SetRecordMove(context.Background(), inner, "bab", "shop", offlineHost,
+ provision.OfflineStage(theirs, "ie", "uk", "bob@keymail.dev", st, time.Now())); err != nil {
+ t.Fatal(err)
+ }
+ theirRaw, _, _ = inner.Get(context.Background(), provision.RecordKey("bab", "shop", offlineHost))
+ }}
+ code, out := w.req(http.MethodPost, "/stage", `{"region":"uk","new":true}`)
+ if code != http.StatusConflict || errorText(out) != "a move to uk is already "+provision.OfflineStaging {
+ t.Fatalf("stage new over their stage = %d %s", code, out)
+ }
+ rec := w.record()
+ if rec.Move == nil || rec.Move.ID != theirs {
+ t.Fatalf("the record carries %+v, want their move %s", rec.Move, theirs)
+ }
+ raw, _, err := inner.Get(context.Background(), provision.RecordKey("bab", "shop", offlineHost))
+ if err != nil || string(raw) != string(theirRaw) {
+ t.Fatalf("their record changed after the refusal:\n%s\nwas\n%s", raw, theirRaw)
+ }
+ })
+}
diff --git a/internal/host/movesoffline_e2e_test.go b/internal/host/movesoffline_e2e_test.go
index c448834a0..e7f7de403 100644
--- a/internal/host/movesoffline_e2e_test.go
+++ b/internal/host/movesoffline_e2e_test.go
@@ -1997,6 +1997,10 @@ type e2eRunDoors struct {
posts []e2eRunPost
lose func(verb string) bool
accepted func(verb string) // called after a POST the door accepted
+ // beforeRunPost, when set, runs as the run is about to send verb:
+ // after its status read, before its POST (a second operator's hand in
+ // between, Astra branch round 1, finding 1).
+ beforeRunPost func(verb string)
}
// e2eToken is a CLI login's token and the requests it has made. The
@@ -2036,11 +2040,16 @@ func (d *e2eRunDoors) Status(context.Context) (offlinerun.View, error) {
}
// post sends one door, by the run (hand false) or by a second operator.
+// The run's first stage (no id yet) is create-only, as the CLI sends it;
+// a hand's is not, as the hand verbs send it.
func (d *e2eRunDoors) post(hand bool, verb, id string) (int, string) {
- body := map[string]string{}
+ body := map[string]any{}
if id != "" {
body["id"] = id
}
+ if !hand && verb == offlinerun.VerbStage && id == "" {
+ body["new"] = true
+ }
if verb == offlinerun.VerbStage || verb == offlinerun.VerbStart {
body["region"] = "uk"
}
@@ -2061,13 +2070,21 @@ func (d *e2eRunDoors) post(hand bool, verb, id string) (int, string) {
}
func (d *e2eRunDoors) answer(code int, out string) offlinerun.Answer {
- if p := d.posts[len(d.posts)-1]; p.lost {
+ p := d.posts[len(d.posts)-1]
+ if p.lost {
return offlinerun.Answer{}
}
switch {
case code >= 200 && code <= 299:
- var v offlinerun.View
+ var v struct {
+ offlinerun.View
+ New bool `json:"new"`
+ }
_ = json.Unmarshal([]byte(out), &v)
+ if p.verb == offlinerun.VerbStage && p.id == "" && !v.New {
+ // A first stage binds only to a move its reply says it created.
+ return offlinerun.Answer{Accepted: true}
+ }
return offlinerun.Answer{Accepted: true, ID: v.ID}
case code >= 400 && code <= 499:
return offlinerun.Answer{Refused: true}
@@ -2076,6 +2093,9 @@ func (d *e2eRunDoors) answer(code int, out string) offlinerun.Answer {
}
func (d *e2eRunDoors) Post(_ context.Context, verb, id string) offlinerun.Answer {
+ if d.beforeRunPost != nil {
+ d.beforeRunPost(verb)
+ }
return d.answer(d.post(false, verb, id))
}
@@ -2368,6 +2388,60 @@ func TestOfflineMoveRunE2E(t *testing.T) {
t.Fatalf("the run's move %q, the record's %q", mine, theirs)
}
})
+ // A second operator stages between the run's first status read and its
+ // stage. The run's stage is create-only: the door refuses it, their
+ // move is left exactly as they wrote it, and the run ends with exit 5
+ // having sent nothing else.
+ t.Run("a second operator stages between the run's read and its stage", func(t *testing.T) {
+ w := newE2EWorld(t, landOpts{})
+ r := w.newRun(nil)
+ r.doors.beforeRunPost = func(verb string) {
+ if verb == offlinerun.VerbStage && w.snap().id == "" {
+ if code, out := r.doors.post(true, offlinerun.VerbStage, ""); code != http.StatusAccepted {
+ t.Fatalf("hand stage = %d %s", code, out)
+ }
+ }
+ }
+ done := r.run(20)
+ if done.Exit != offlinerun.ExitRefused {
+ t.Fatalf("the run ended %+v; POSTs %v", done, r.doors.runVerbs())
+ }
+ if got := strings.Join(r.doors.runVerbs(), ","); got != "stage" {
+ t.Fatalf("the run posted %s", got)
+ }
+ hand, mine := r.doors.posts[0], r.doors.posts[1]
+ if !hand.hand || mine.hand || mine.code != http.StatusConflict {
+ t.Fatalf("POSTs %+v", r.doors.posts)
+ }
+ if mine.before.raw != mine.after.raw || mine.after.id != hand.after.id {
+ t.Fatalf("the run's refused stage changed their move: %s -> %s", mine.before, mine.after)
+ }
+ })
+ // The run's first stage commits and its reply is lost. The next read
+ // shows a move the run cannot prove is its own: it stops with exit 4
+ // and sends nothing more, for the operator to resume by id.
+ t.Run("the run's first stage reply is lost", func(t *testing.T) {
+ w := newE2EWorld(t, landOpts{})
+ r := w.newRun(nil)
+ lost := false
+ r.doors.lose = func(verb string) bool {
+ if verb == offlinerun.VerbStage && !lost {
+ lost = true
+ return true
+ }
+ return false
+ }
+ done := r.run(20)
+ if done.Exit != offlinerun.ExitStopped || done.Reason != offlinerun.ReasonStageUncertain {
+ t.Fatalf("the run ended %+v; POSTs %v", done, r.doors.runVerbs())
+ }
+ if got := strings.Join(r.doors.runVerbs(), ","); got != "stage" {
+ t.Fatalf("the run posted %s", got)
+ }
+ if end := w.snap(); end.id == "" || end.id != r.doors.posts[0].after.id || end.state != provision.OfflineStaging {
+ t.Fatalf("the record is %s", end)
+ }
+ })
// Without the nudge (NudgeAfter past every budget) the same miss stalls
// the stop: nothing moves until the stop's budget aborts the move, and
// the abort's bump reverts it.
@@ -2444,7 +2518,7 @@ 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.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) {
t.Fatalf("the seeds did not exercise every fault and ending: %+v", all)
}
}
@@ -2459,10 +2533,16 @@ const (
simMissWake = 0.2
simHandDoor = 0.04
simTakeOver = 0.005
+ // simHandBeforePost is a hand POST between the run's read and its POST;
+ // simHandStagesFirst a hand stage before the run's first stage.
+ simHandBeforePost = 0.04
+ simHandStagesFirst = 0.06
+ simLoseFirstStage = 0.03
)
type offlineRunSimTally struct {
done, aborted, stopped int
+ refused int
lost, missed, handPosts int
handWrites, nudges, ticks int
runAborts int
@@ -2472,6 +2552,7 @@ func (a *offlineRunSimTally) add(b offlineRunSimTally) {
a.done += b.done
a.aborted += b.aborted
a.stopped += b.stopped
+ a.refused += b.refused
a.lost += b.lost
a.missed += b.missed
a.handPosts += b.handPosts
@@ -2485,9 +2566,29 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally {
rng := rand.New(rand.NewPCG(seed, 0x0ff11e))
w := newE2EWorld(t, landOpts{})
r := w.newRun(func(*offBox) bool { return rng.Float64() < simMissWake })
- r.doors.lose = func(string) bool { return rng.Float64() < simLoseReply }
+ r.doors.lose = func(string) bool {
+ // The first stage's lost reply ends the run at once (exit 4, it
+ // never adopts the move it then reads), so it is kept rarer than
+ // the rest, which the run rides out.
+ if len(r.doors.runVerbs()) == 0 {
+ return rng.Float64() < simLoseFirstStage
+ }
+ return rng.Float64() < simLoseReply
+ }
hands := []string{offlinerun.VerbStage, offlinerun.VerbStart, offlinerun.VerbSeal, offlinerun.VerbFlip,
offlinerun.VerbOpen, offlinerun.VerbFinish, offlinerun.VerbAbort}
+ // A hand between the run's status read and its POST, on the read's
+ // view: the case finding 1 of the branch review found the simulation
+ // never reached.
+ r.doors.beforeRunPost = func(string) {
+ switch x := rng.Float64(); {
+ case len(r.doors.runVerbs()) == 0 && x < simHandStagesFirst:
+ // Someone stages between the run's first read and its stage.
+ r.doors.post(true, offlinerun.VerbStage, "")
+ case x < simHandBeforePost:
+ r.doors.post(true, hands[rng.IntN(len(hands))], "")
+ }
+ }
r.between = func() {
switch x := rng.Float64(); {
case x < simTakeOver:
@@ -2536,17 +2637,33 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally {
t.Fatalf("seed %d: %s\nended %+v after %d ticks\n%s", seed, fmt.Sprintf(format, args...), done, r.ticks, strings.Join(trail, "\n"))
}
- // The run's own move: its first POST is the stage that made it.
+ // The run's own move: its first POST is the create-only stage. When
+ // it created a move, that is the run's; when it was refused (someone
+ // staged between the run's read and its POST) it wrote nothing, and
+ // the run posts nothing after it.
var mine string
+ first := -1
opened := map[string]bool{}
written := map[string]bool{}
for i, p := range r.doors.posts {
- if !p.hand && mine == "" {
- if i != 0 || p.verb != offlinerun.VerbStage || p.id != "" || p.before.state != "none" || p.after.id == "" {
+ switch {
+ case p.hand:
+ case first < 0:
+ first = i
+ if p.verb != offlinerun.VerbStage || p.id != "" {
fail("the run's first POST is %s %q on %s", p.verb, p.id, p.before)
}
- mine = p.after.id
- } else if !p.hand && p.id != mine {
+ if p.code == http.StatusAccepted {
+ if p.before.state != "none" || p.after.id == "" {
+ fail("the run's create-only stage was accepted on %s, leaving %s", p.before, p.after)
+ }
+ mine = p.after.id
+ } else if p.before.raw != p.after.raw {
+ fail("the run's refused stage (%d) wrote the record: %s -> %s", p.code, p.before, p.after)
+ }
+ case mine == "":
+ fail("the run posted %s %q after a stage that made no move of its own", p.verb, p.id)
+ case p.id != mine:
fail("the run posted %s naming %q; its move is %s", p.verb, p.id, mine)
}
if !p.hand && p.verb == offlinerun.VerbAbort {
@@ -2600,11 +2717,21 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally {
if rt := w.ie.row(offHost); rt == nil || rt.HoldOp != "" || !w.ie.lists(offHost) {
fail("aborted, but ie-box's row is %+v (listed %v)", rt, w.ie.lists(offHost))
}
+ case offlinerun.ExitRefused:
+ tally.refused++
+ if runs := r.doors.runVerbs(); len(runs) != 1 || mine != "" {
+ fail("exit 5 after the run posted %v (its move %q)", runs, mine)
+ }
case offlinerun.ExitStopped:
tally.stopped++
+ runs := len(r.doors.runVerbs())
switch {
case done.Reason == offlinerun.ReasonOtherMove && end.id != "" && end.id != mine:
case done.Reason == offlinerun.ReasonProbeFailed && end.id == mine && end.state == provision.OfflineOpen:
+ // The first stage's reply was lost: the run stopped without
+ // 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 == "":
default:
fail("exit 4 (%s) with the record %s", done.Reason, end)
}
diff --git a/internal/moves/offlinerun/decide.go b/internal/moves/offlinerun/decide.go
index 7b07ebbb7..974b2b0f3 100644
--- a/internal/moves/offlinerun/decide.go
+++ b/internal/moves/offlinerun/decide.go
@@ -58,11 +58,15 @@ const (
// 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"
+ ReasonDone = "done"
+ ReasonAborted = "aborted"
+ ReasonOpenNoFinish = "open-no-finish"
+ ReasonOtherMove = "other-move"
+ ReasonHostHasMove = "host-has-move"
+ // ReasonStageUncertain: the first stage's reply was lost or named no
+ // move it created, and the next view shows a move. It may be the run's
+ // or someone else's; the run never adopts it (exit 4).
+ ReasonStageUncertain = "stage-uncertain"
ReasonStageNotWritten = "stage-not-written"
ReasonMoveGone = "move-gone"
ReasonUnexpectedState = "unexpected-state"
@@ -248,18 +252,29 @@ func (m Memory) Probed(ok bool) Memory {
return m
}
-// Refused records that the POST just made got a non-2xx answer from the
-// console, with the console's sentence (may be empty). Call it before the
-// follow-up status read's Decide; a POST lost on the network is not a
-// refusal and does not call it. Decide consumes it on its next call: when
-// that view shows no move and nothing is bound after our first stage, the
-// run ends with ExitRefused and the sentence as Reason. Otherwise the view
+// Refused records that the POST just made was refused by the console (a
+// 4xx: nothing was written), with the console's sentence (may be empty).
+// Call it before the follow-up status read's Decide; a POST lost on the
+// network, or answered with a 5xx, is not a refusal and does not call it.
+// Decide consumes it on its next call: after our first stage, with nothing
+// bound, the run ends with ExitRefused and the sentence as Reason, whatever
+// that view shows (a move there is someone else's). Otherwise the view
// decides, as for any POST that was not a clean 2xx.
func (m Memory) Refused(sentence string) Memory {
m.refused, m.refusal = true, sentence
return m
}
+// bindTo binds the run to the move its first stage created, as that
+// stage's reply named it (Step). It is the only way a run that did not
+// --resume is bound: never from a view.
+func (m Memory) bindTo(id string) Memory {
+ if m.id == "" && m.stagePosts > 0 && id != "" {
+ m.id = id
+ }
+ 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.
@@ -361,12 +376,14 @@ func Decide(v View, p Policy, m Memory, now time.Duration) (Action, Memory) {
m.refused, m.refusal = false, ""
m = m.observe(v, now)
+ if m.id == "" && m.stagePosts > 0 && refused {
+ // The console refused our first stage: nothing was written, so
+ // nothing is ours and nothing to abort, whatever the view shows.
+ // Its sentence is the reason.
+ return Done{Exit: ExitRefused, Reason: refusal}, m
+ }
if v.State == StateNone {
switch {
- case m.id == "" && m.stagePosts > 0 && refused:
- // The console refused our stage and no move exists: nothing
- // is bound and nothing to abort. Its sentence is the reason.
- return Done{Exit: ExitRefused, Reason: refusal}, m
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).
@@ -396,7 +413,9 @@ func Decide(v View, p Policy, m Memory, now time.Duration) (Action, Memory) {
// A move this run did not stage: never adopted without --resume.
return Done{Exit: ExitStopped, Reason: ReasonHostHasMove}, m
}
- m.id = v.ID
+ // Our stage's reply did not bind us (lost, or it named no move
+ // it created): whose move this is cannot be known from a view.
+ return Done{Exit: ExitStopped, Reason: ReasonStageUncertain}, m
}
if v.ID != m.id {
return Done{Exit: ExitStopped, Reason: ReasonOtherMove}, m
diff --git a/internal/moves/offlinerun/decide_test.go b/internal/moves/offlinerun/decide_test.go
index f8d2ed52b..f4229baff 100644
--- a/internal/moves/offlinerun/decide_test.go
+++ b/internal/moves/offlinerun/decide_test.go
@@ -141,8 +141,9 @@ func play(t *testing.T, p Policy, m Memory, steps []step) Memory {
func TestDecideHappyPath(t *testing.T) {
p := DefaultPolicy()
- m := play(t, p, NewMemory(""), []step{
- {0, none(nil), Post{Verb: VerbStage}},
+ m := play(t, p, NewMemory(""), []step{{0, none(nil), Post{Verb: VerbStage}}})
+ // Step binds the run to the move its stage's reply names.
+ m = play(t, p, m.bindTo(tID), []step{
{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{}},
@@ -201,8 +202,8 @@ func TestDecideSmallRoundWatched(t *testing.T) {
// cap aborts a healthy move.
func TestDecideFastRoundIsWatched(t *testing.T) {
p := DefaultPolicy()
- play(t, p, NewMemory(""), []step{
- {0, none(nil), Post{Verb: VerbStage}},
+ m := play(t, p, NewMemory(""), []step{{0, none(nil), Post{Verb: VerbStage}}})
+ play(t, p, m.bindTo(tID), []step{
{at(2), withNext(staging(5, true, 10), VerbStart), Post{Verb: VerbStart}},
})
// A restage answered at once is watched the same way.
@@ -220,7 +221,8 @@ func TestDecideFastRoundIsWatched(t *testing.T) {
func TestDecideStageRoundsCapped(t *testing.T) {
p := DefaultPolicy()
- steps := []step{{0, none(nil), Post{Verb: VerbStage}}}
+ m := play(t, p, NewMemory(""), []step{{0, none(nil), Post{Verb: VerbStage}}}).bindTo(tID)
+ var steps []step
for r := int64(1); r < int64(p.MaxStageRounds); r++ {
steps = append(steps,
step{at(float64(4 * r)), staging(r, false, 0), Wait{}},
@@ -232,7 +234,7 @@ func TestDecideStageRoundsCapped(t *testing.T) {
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)
+ play(t, p, m, steps)
}
func TestDecideReadyStepBeatsDeadline(t *testing.T) {
@@ -437,8 +439,9 @@ func TestDecideNamesMatchProvision(t *testing.T) {
}
// TestDecideStageRefused: a refused first stage ends the run with exit 5
-// and the console's sentence, with no retry; the refusal is consumed by
-// the next Decide, so it never colours a later tick.
+// and the console's sentence, with no retry, whatever the next view shows:
+// a refusal wrote nothing, so a move there is someone else's. The refusal
+// is consumed by the next Decide, so it never colours a later tick.
func TestDecideStageRefused(t *testing.T) {
p := DefaultPolicy()
m := play(t, p, NewMemory(""), []step{{0, none(nil), Post{Verb: VerbStage}}})
@@ -446,16 +449,39 @@ func TestDecideStageRefused(t *testing.T) {
if want := (Done{Exit: ExitRefused, Reason: "the instance is not in a region"}); got != Action(want) {
t.Fatalf("Decide = %#v, want %#v", got, want)
}
- // A refused POST whose follow-up read shows the move after all (a
- // committed write answered with an error): the view wins, no exit 5.
+ // Someone staged between the run's read and its stage, so the door
+ // refused the run's create-only stage: their move is not adopted.
m2 := play(t, p, NewMemory(""), []step{{0, none(nil), Post{Verb: VerbStage}}})
- got, m2 = Decide(staging(5, false, 0), p, m2.Refused("timeout"), at(2))
- if got != Action(Wait{}) {
- t.Fatalf("Decide = %#v, want Wait", got)
- }
- // The refusal was consumed: a later none reads as the move gone.
- got, _ = Decide(none(nil), p, m2, at(4))
- if want := (Done{Exit: ExitStopped, Reason: ReasonMoveGone}); got != Action(want) {
+ theirs := View{State: StateStaging, ID: tOther, StagedAt: 5}
+ got, m2 = Decide(theirs, p, m2.Refused("a move to uk is already offline-staging"), at(2))
+ if want := (Done{Exit: ExitRefused, Reason: "a move to uk is already offline-staging"}); got != Action(want) {
t.Fatalf("Decide = %#v, want %#v", got, want)
}
+ if m2.Bound() != "" {
+ t.Fatalf("bound to %q after a refused stage", m2.Bound())
+ }
+}
+
+// TestDecideNeverAdoptsAfterItsStage: the run binds only from its stage's
+// reply (Step). When that reply was lost or could not be read, a move the
+// next view shows may be the run's or someone else's: the run stops (exit
+// 4) and writes nothing, for an operator to resume by id.
+func TestDecideNeverAdoptsAfterItsStage(t *testing.T) {
+ p := DefaultPolicy()
+ for _, v := range []View{
+ staging(5, false, 0),
+ staging(5, true, 10),
+ withNext(staging(5, true, 10), VerbStart),
+ tv(StateStopping),
+ withNext(tv(StateReverting), VerbFinish),
+ } {
+ m := play(t, p, NewMemory(""), []step{{0, none(nil), Post{Verb: VerbStage}}})
+ got, m := Decide(v, p, m, at(2))
+ if want := (Done{Exit: ExitStopped, Reason: ReasonStageUncertain}); got != Action(want) {
+ t.Fatalf("%s: Decide = %#v, want %#v", v.State, got, want)
+ }
+ if m.Bound() != "" {
+ t.Fatalf("%s: bound to %q", v.State, m.Bound())
+ }
+ }
}
diff --git a/internal/moves/offlinerun/run.go b/internal/moves/offlinerun/run.go
index 4328bce5a..d2e82d447 100644
--- a/internal/moves/offlinerun/run.go
+++ b/internal/moves/offlinerun/run.go
@@ -20,17 +20,19 @@ const ReasonStoppedWatching = "stopped-watching"
type Answer struct {
// Accepted is a 2xx.
Accepted bool
- // Refused: the console answered, with something other than a 2xx. It
- // is taken at its word (Memory.Refused). With neither flag no answer
- // arrived, or none that could be read: the write may or may not have
- // happened, and the next status read says which. Neither case is
- // ever sent again blindly.
+ // Refused: the console refused it (a 4xx, nothing written). It is
+ // taken at its word (Memory.Refused). With neither flag no answer
+ // arrived, or none that could be read, or a 5xx: the write may or may
+ // not have happened, and the next status read says which. Neither case
+ // is ever sent again blindly.
Refused bool
// Sentence is the console's own sentence for a refusal, when the
// Doors can carry it; "" otherwise.
Sentence string
// ID is the move the door's view names, for an accepted POST ("" when
- // the Doors cannot read it). An accepted stage binds the run to it.
+ // the Doors cannot read it). An accepted first stage binds the run to
+ // it, so for that stage the Doors set it only when the door says it
+ // created that move (the create-only stage's "new" in its reply).
ID string
}
@@ -111,11 +113,11 @@ func (r *Runner) Step(ctx context.Context, m Memory) (Memory, *Done, error) {
if !ans.Accepted && ans.Refused {
m = m.Refused(ans.Sentence)
}
- if a.Verb == VerbStage && ans.Accepted && ans.ID != "" && m.id == "" {
- // Bound to the move this stage made, not to whatever the next
- // view shows: someone may have ended it and staged their own
- // before that read.
- m.id = ans.ID
+ 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 || !ans.Refused) {
r.openSent = true
diff --git a/internal/moves/offlinerun/run_test.go b/internal/moves/offlinerun/run_test.go
index 60be43806..7778ff408 100644
--- a/internal/moves/offlinerun/run_test.go
+++ b/internal/moves/offlinerun/run_test.go
@@ -259,3 +259,34 @@ func TestRunBindsTheMoveItsStageMade(t *testing.T) {
t.Fatalf("calls %q, want %q", d.log, want)
}
}
+
+// TestRunFirstStageUncertainNeverAdopts: the first stage's reply was lost
+// (or accepted with no move it created named): the next view's move is
+// not adopted, and nothing more is sent (exit 4). A stage refused because
+// someone staged first ends with exit 5, and nothing more is sent either.
+func TestRunFirstStageUncertainNeverAdopts(t *testing.T) {
+ theirs := View{State: StateStaging, ID: tOther, StagedAt: 5}
+ for name, c := range map[string]struct {
+ ans Answer
+ want Done
+ }{
+ "reply lost": {Answer{}, Done{Exit: ExitStopped, Reason: ReasonStageUncertain}},
+ "accepted, no move id": {Answer{Accepted: true}, Done{Exit: ExitStopped, Reason: ReasonStageUncertain}},
+ "refused": {Answer{Refused: true, Sentence: "a move to uk is already offline-staging"}, Done{Exit: ExitRefused, Reason: "a move to uk is already offline-staging"}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ d := &fakeDoors{views: []View{none(nil), theirs}, answer: func(string) Answer { return c.ans }}
+ r, _ := testRunner(d, func() int { return 200 })
+ done, m, err := r.Run(context.Background(), NewMemory(""), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if done != c.want || m.Bound() != "" {
+ t.Fatalf("done %#v bound %q, want %#v", done, m.Bound(), c.want)
+ }
+ if want := []string{"status", "stage ", "status"}; !reflect.DeepEqual(d.log, want) {
+ t.Fatalf("calls %q, want %q", d.log, want)
+ }
+ })
+ }
+}
diff --git a/move.go b/move.go
index 3bdd4ed46..beeefc2db 100644
--- a/move.go
+++ b/move.go
@@ -1124,6 +1124,9 @@ type offlineView struct {
RequestedAt int64 `json:"requested_at"`
UpdatedAt int64 `json:"updated_at"`
OpenedAt int64 `json:"opened_at"`
+ // New: the reply to a create-only stage says this request created the
+ // move (offline run's first stage).
+ New bool `json:"new"`
// Failed: a box's report says the step cannot finish (the status view's
// own flag; the CLI says MV-O6 or MV-O9 for it).
Failed bool `json:"failed"`
diff --git a/move_offline_run.go b/move_offline_run.go
index bbf63250a..d498fbf57 100644
--- a/move_offline_run.go
+++ b/move_offline_run.go
@@ -123,7 +123,7 @@ func (m *mover) offlineRun(ctx context.Context, a moveArgs, d moveDeps) int {
doors := &runDoors{w: w, region: a.to, code: -1}
start := now()
watch := &runWatcher{w: w, doors: doors, now: now, policy: policy,
- resume: a.resume, url: "https://" + m.host + path}
+ resume: a.resume, bound: a.resume, url: "https://" + m.host + path}
watch.clock = func() time.Duration { return now().Sub(start) }
r := &offlinerun.Runner{
Doors: doors,
@@ -240,12 +240,18 @@ func (d *runDoors) Status(ctx context.Context) (offlinerun.View, error) {
}
// body is a door's request: the move's id once bound, and the region for
-// stage and start (the bound move's own, once a view of it named one).
-func (d *runDoors) body(verb, id string) map[string]string {
- b := map[string]string{}
+// stage and start (the bound move's own, once a view of it named one). The
+// first stage, sent before anything is bound, is create-only ("new"): the
+// door refuses it if the host already has a move, rather than restaging
+// someone else's (Astra branch round 1, finding 1).
+func (d *runDoors) body(verb, id string) map[string]any {
+ b := map[string]any{}
if id != "" {
b["id"] = id
}
+ if verb == offlinerun.VerbStage && id == "" {
+ b["new"] = true
+ }
if verb == offlinerun.VerbStage || verb == offlinerun.VerbStart {
region := d.region
if v := d.last.v; id != "" && v.ID == id && v.To != "" {
@@ -261,19 +267,22 @@ func (d *runDoors) Post(ctx context.Context, verb, id string) offlinerun.Answer
if verb == offlinerun.VerbStart {
tail = "" // start is the offline door itself
}
- return d.answer(d.w.m.send(ctx, http.MethodPost, tail, d.body(verb, id)))
+ b := d.body(verb, id)
+ return d.answer(d.w.m.send(ctx, http.MethodPost, tail, b), b["new"] == true)
}
func (d *runDoors) Nudge(ctx context.Context, id string) offlinerun.Answer {
- return d.answer(d.w.m.send(ctx, http.MethodPost, "/nudge", d.body("nudge", id)))
+ return d.answer(d.w.m.send(ctx, http.MethodPost, "/nudge", d.body("nudge", id)), false)
}
// answer reads a POST's reply. A 2xx is accepted (and its view teaches the
-// move's id and regions); a reply with the console's sentence, or a 4xx, is
-// a refusal; anything else (no reply, a redirect, an unreadable body, a 5xx
-// with no sentence) says nothing about the write, and the next status read
-// decides.
-func (d *runDoors) answer(r moveReply) offlinerun.Answer {
+// move's id and regions); a 4xx is a refusal (the doors write nothing
+// before they answer one); anything else (no reply, a redirect, an
+// unreadable body, a 5xx with or without a sentence) says nothing about the
+// write, and the next status read decides. A create-only stage's reply
+// names the move only when it says this request created it ("new"), so the
+// run is never bound to a move it did not make.
+func (d *runDoors) answer(r moveReply, createOnly bool) offlinerun.Answer {
d.reply = r
switch {
case r.failed || r.moved != "":
@@ -283,8 +292,11 @@ func (d *runDoors) answer(r moveReply) offlinerun.Answer {
if json.Unmarshal(r.body, &v) == nil {
d.w.learn(v)
}
+ if createOnly && !v.New {
+ return offlinerun.Answer{Accepted: true}
+ }
return offlinerun.Answer{Accepted: true, ID: v.ID}
- case r.refused, r.status >= 400 && r.status <= 499:
+ case r.status >= 400 && r.status <= 499:
return offlinerun.Answer{Refused: true}
}
return offlinerun.Answer{}
@@ -301,6 +313,7 @@ type runWatcher struct {
url string // the probe's
posted bool // a POST went out
+ bound string // the move the run is bound to (--resume's, or its stage's reply's)
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
@@ -314,9 +327,9 @@ func (rw *runWatcher) column(step string) {
}
// sayHeader is M-C1 and OR10, once, when a view first names the move this
-// run is carrying: the one it staged, or --resume's.
+// run is bound to: the one its stage created, or --resume's.
func (rw *runWatcher) sayHeader(v offlineView) {
- if rw.id != "" || v.ID == "" || (rw.resume != "" && v.ID != rw.resume) || (rw.resume == "" && !rw.posted) {
+ if rw.id != "" || v.ID == "" || v.ID != rw.bound {
return
}
rw.id = v.ID
@@ -421,7 +434,9 @@ func (rw *runWatcher) sayAnswer(verb string, ans offlinerun.Answer) {
runPiece(out, "Offline from now.")
}
runSep(out, "\n")
- case ans.Refused && r.refused:
+ case r.refused:
+ // The console's own sentence: a refusal, or a 5xx that says why
+ // (whose write the next status read decides).
runPiece(out, "refused: ")
saySpoken(out, r.refusal)
case ans.Refused:
@@ -433,6 +448,7 @@ func (rw *runWatcher) sayAnswer(verb string, ans offlinerun.Answer) {
}
func (rw *runWatcher) Acted(a offlinerun.Action, res offlinerun.Result, m offlinerun.Memory) {
+ rw.bound = m.Bound()
switch a := a.(type) {
case offlinerun.Post:
rw.sayAnswer(a.Verb, res.Answer)
@@ -506,7 +522,9 @@ func (rw *runWatcher) end(d offlinerun.Done) int {
} else {
moveSay(rw.out(), fmt.Sprintf("%s now has a different move (%s). This run sent nothing for that move and stopped.", host, v.ID))
}
- case offlinerun.ReasonHostHasMove:
+ case offlinerun.ReasonHostHasMove, offlinerun.ReasonStageUncertain:
+ // A move this run did not stage, or one it cannot tell is its own
+ // (its first stage's reply was lost): never adopted.
moveSay(rw.out(), fmt.Sprintf("%s already has a move in flight (%s). See where it is, then carry it on:", host, v.ID))
sayRunCommand(rw.out(), "status", host)
sayRunCommand(rw.out(), "run", host, " --resume ", v.ID)
diff --git a/move_offline_run_test.go b/move_offline_run_test.go
index fc0d7c809..4a2126e53 100644
--- a/move_offline_run_test.go
+++ b/move_offline_run_test.go
@@ -35,6 +35,9 @@ type offlineSim struct {
nudged bool
started int64 // requested_at
updated int64 // updated_at
+ // beforePost, when set, runs as a POST arrives, before the door acts:
+ // a second operator's hand between the run's status read and its POST.
+ beforePost func(s *offlineSim, verb string)
}
const simEpoch = int64(1794724320) // 2026-11-15T06:32:00Z
@@ -136,11 +139,16 @@ func (s *offlineSim) get() frame {
}
// post is one POST of a door: its answer, and whether the reply is lost.
-func (s *offlineSim) post(tail string) (int, any, bool) {
+// createOnly is the body's "new": a stage that creates or is refused, as
+// the console's door does; its reply says "new" when it created.
+func (s *offlineSim) post(tail string, createOnly bool) (int, any, bool) {
verb := strings.TrimPrefix(tail, "/")
if tail == "" {
verb = "start"
}
+ if s.beforePost != nil {
+ s.beforePost(s, verb)
+ }
if why, ok := s.refuse[verb]; ok {
return http.StatusConflict, frame{"error": why}, false
}
@@ -159,7 +167,14 @@ func (s *offlineSim) post(tail string) (int, any, bool) {
switch s.state {
case "", "none":
s.enter("offline-staging")
- case "offline-staging":
+ case "offline-staging", "offline-stopping", "offline-sealing", "offline-sealed", "offline-landing", "offline-landed",
+ "offline-open", "offline-finishing", "offline-reverting":
+ if createOnly {
+ return http.StatusConflict, frame{"error": "a move to uk is already " + s.state}, false
+ }
+ if s.state != "offline-staging" {
+ return wrong()
+ }
s.reads = 0
default:
return wrong()
@@ -219,7 +234,11 @@ func (s *offlineSim) post(tail string) (int, any, bool) {
if drop {
s.drop = ""
}
- return http.StatusAccepted, s.view(), drop
+ v := s.view()
+ if createOnly {
+ v["new"] = true
+ }
+ return http.StatusAccepted, v, drop
}
// runSeams is what a run test controls: the probe's answers and Ctrl-C.
@@ -323,9 +342,9 @@ func TestMoveOfflineRunHappyPath(t *testing.T) {
if got := doorsOf(posts); got != "stage,start,seal,flip,open,finish,finish" {
t.Fatalf("doors %s\n%s", got, out)
}
- // The first stage names no move (there is none yet); every later POST
- // names this one, and start carries the region too.
- if posts[0] != `/stage {"region":"uk"}` {
+ // The first stage names no move (there is none yet) and is create-only;
+ // every later POST names this one, and start carries the region too.
+ if posts[0] != `/stage {"new":true,"region":"uk"}` {
t.Errorf("first POST %q", posts[0])
}
if posts[1] != ` {"id":"`+tMoveID+`","region":"uk"}` {
@@ -703,7 +722,7 @@ func TestMoveOfflineRunBindsTheMoveItsStageMade(t *testing.T) {
c := &fakeOfflineConsole{
moveID: "mv_theirs", // the record's move, which the doors check ids against
gets: []frame{{"host": oHost, "state": "none"}, theirs},
- posts: map[string][]offPost{"/stage": {{202, offView("offline-staging", frame{"staged_at": 4})}}},
+ posts: map[string][]offPost{"/stage": {{202, offView("offline-staging", frame{"staged_at": 4, "new": true})}}},
}
code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk")
if code != 4 {
@@ -714,3 +733,55 @@ func TestMoveOfflineRunBindsTheMoveItsStageMade(t *testing.T) {
}
wantLines(t, out, "acme.shop.example.com now has a different move (mv_theirs). This run sent nothing for that move and stopped.")
}
+
+// TestMoveOfflineRunStagedByHandBeforeItsStage: a second operator stages
+// between the run's first status read and its stage. The run's stage is
+// create-only, so the door refuses it and their move is left as they made
+// it: exit 5, the console's sentence, nothing more sent.
+func TestMoveOfflineRunStagedByHandBeforeItsStage(t *testing.T) {
+ var theirs offlineSim
+ sim := &offlineSim{beforePost: func(s *offlineSim, verb string) {
+ if verb == "stage" && s.recordID() == "" {
+ s.enter("offline-staging")
+ s.stagedAt = 7
+ s.beforePost = nil
+ theirs = *s
+ }
+ }}
+ c := &fakeOfflineConsole{sim: sim}
+ code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk")
+ if code != 5 {
+ t.Fatalf("exit %d:\n%s", code, out)
+ }
+ if got := doorsOf(c.postsSent()); got != "stage" {
+ t.Fatalf("doors %s:\n%s", got, out)
+ }
+ if out != "06:12:00Z stage sent, refused: a move to uk is already offline-staging\n" {
+ t.Fatalf("output:\n%s", out)
+ }
+ if sim.state != theirs.state || sim.stagedAt != theirs.stagedAt || sim.updated != theirs.updated {
+ t.Fatalf("their move changed: %+v, was %+v", *sim, theirs)
+ }
+}
+
+// TestMoveOfflineRunLostFirstStageReply: the first stage committed and its
+// reply was lost. The next read shows a move, which the run cannot tell is
+// its own: it stops (exit 4) with OR27 and the two commands, and sends
+// nothing more.
+func TestMoveOfflineRunLostFirstStageReply(t *testing.T) {
+ c := &fakeOfflineConsole{sim: &offlineSim{drop: "stage"}}
+ code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk")
+ if code != 4 {
+ t.Fatalf("exit %d:\n%s", code, out)
+ }
+ if got := doorsOf(c.postsSent()); got != "stage" {
+ t.Fatalf("doors %s:\n%s", got, out)
+ }
+ want := "06:12:00Z stage sent, no answer, checking where the move stands\n" +
+ "acme.shop.example.com already has a move in flight (" + tMoveID + "). See where it is, then carry it on:\n" +
+ " carlos move offline status --host acme.shop.example.com\n" +
+ " carlos move offline run --host acme.shop.example.com --resume " + tMoveID + "\n"
+ if out != want {
+ t.Fatalf("output:\n%s\nwant:\n%s", out, want)
+ }
+}
diff --git a/move_test.go b/move_test.go
index 501b289f8..9038adb5e 100644
--- a/move_test.go
+++ b/move_test.go
@@ -1163,11 +1163,14 @@ func (c *fakeOfflineConsole) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if c.n == nil {
c.n = map[string]int{}
}
+ createOnly := false
if r.Method == http.MethodPost {
var req struct {
- ID string `json:"id"`
+ ID string `json:"id"`
+ New bool `json:"new"`
}
_ = json.Unmarshal(body, &req)
+ createOnly = req.New
record := c.moveID
if c.sim != nil {
record = c.sim.recordID()
@@ -1184,7 +1187,7 @@ func (c *fakeOfflineConsole) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
c.n[tail]++
- code, v, drop := c.sim.post(tail)
+ code, v, drop := c.sim.post(tail, createOnly)
if drop {
// The write committed; the reply is lost on the way back.
if hj, ok := w.(http.Hijacker); ok {