carlos / platform Public

moves: refuse rootfs instances in every move transition and at carlos apps place

A record with any runtime (rootfs-v1, or one this build does not know)
never moves. rootfsMoveRefusal sits beside seedMoveRefusal in every
transition that moves a record (MoveRequest, MoveStartTransition,
offlineBegin for OfflineStart and OfflineStage, SetRecordRegion when the
region changes), and WriteRecord's runtime guard refuses any write that
changes such a record's region or gives it a move, whoever built the body.
Guard tests pin the seedMoveRefusal callers, the move starts and the
region writers, and the console doors that answer refuseSeedMove.

The move doors (legacy, Phase 1, offline start and stage) answer RFS-3-C23;
carlos apps place answers RFS-3-C24 before it writes anything, from the one
strict read it already made, and under the CAS for a late record.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 8c14abe5981aacea12d18c1097550856240d7384 parent 7f0e6be
10 files changed, +700 −33
  • approved_rootfs_copy_test.go +3 −0
  • internal/console/apiinstancemove.go +10 −3
  • internal/console/apiinstancemove_offline.go +4 −1
  • internal/console/fleets.go +15 −7
  • internal/console/rootfs_move_test.go +174 −0
  • internal/console/seedmove.go +73 −12
  • internal/provision/offline_move.go +7 −4
  • internal/provision/provision.go +13 −0
  • internal/provision/rootfs_move_test.go +348 −0
  • internal/provision/runtime.go +53 −6
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go
index 7794547bc..cc615c67e 100644
--- a/approved_rootfs_copy_test.go
+++ b/approved_rootfs_copy_test.go
@@ -187,6 +187,9 @@ var rootfsCopyBuilt = []string{
// Plan 3 Task 8: the resident restart event (internal/rolloutwords/words.go)
// and the resident backoff's 503 body (internal/activator/activator.go)
"RFS-3-C11", "RFS-3-C16",
+ // Plan 3 Task 13: the move doors and carlos apps place refuse rootfs
+ // instances (internal/console/seedmove.go)
+ "RFS-3-C23", "RFS-3-C24",
}
func mustParseRootfsRecord(t *testing.T) []copyRow {
diff --git a/internal/console/apiinstancemove.go b/internal/console/apiinstancemove.go
index 5a51c6cb9..f729a6bd4 100644
--- a/internal/console/apiinstancemove.go
+++ b/internal/console/apiinstancemove.go
@@ -89,7 +89,10 @@ func (s *Server) moveGate(w http.ResponseWriter, r *http.Request) (acct *Account
jsonError(w, http.StatusBadRequest, c.pool)
return nil, "", "", nil, false
}
- if !rec.HibernateOrDefault() {
+ // A record with a runtime runs under the activator whatever its
+ // hibernation. It never moves, and the move doors say so
+ // (refuseRootfsMove), so this rail does not answer for it.
+ if !rec.HibernateOrDefault() && rec.Runtime == "" {
jsonError(w, http.StatusBadRequest, c.hibernate)
return nil, "", "", nil, false
}
@@ -359,6 +362,10 @@ func (s *Server) moveTransitionSaying(w http.ResponseWriter, r *http.Request, ac
return
}
rec, err := provision.SetRecordMove(ctx, s.cfg.Releases, acct.Sqid, app, host, mut)
+ if msg := rootfsMoveRefused(err); msg != "" {
+ jsonError(w, http.StatusConflict, msg)
+ return
+ }
if errors.Is(err, provision.ErrMoveConflict) {
jsonError(w, http.StatusConflict, conflict(err))
return
@@ -413,7 +420,7 @@ func (s *Server) legacyHandleAPIInstanceMoveRequest(w http.ResponseWriter, r *ht
if !ok {
return
}
- if s.refuseSeedMove(w, rec) {
+ if s.refuseSeedMove(w, rec) || s.refuseRootfsMove(w, rec) {
return
}
// A replica is refused at the request only (G14): moveGate also fronts
@@ -569,7 +576,7 @@ func (s *Server) handleAPIInstanceMoveRequest(w http.ResponseWriter, r *http.Req
if !ok {
return
}
- if s.refuseSeedMove(w, rec) {
+ if s.refuseSeedMove(w, rec) || s.refuseRootfsMove(w, rec) {
return
}
// Host-claim consoles start the move under the app's admission: the
diff --git a/internal/console/apiinstancemove_offline.go b/internal/console/apiinstancemove_offline.go
index 21c2341c7..2211150ed 100644
--- a/internal/console/apiinstancemove_offline.go
+++ b/internal/console/apiinstancemove_offline.go
@@ -154,6 +154,9 @@ func writeRefusal(w http.ResponseWriter, ref *offlineRefusal) {
// error's own text: phase1Conflict passes only recorded sentences and
// answers a fixed one for anything else.
func offlineConflict(err error) string {
+ if msg := rootfsMoveRefused(err); msg != "" {
+ return msg
+ }
msg := strings.TrimPrefix(err.Error(), provision.ErrMoveConflict.Error()+": ")
switch {
// The offline transitions' own recorded sentences (MV-O34 to MV-O43).
@@ -495,7 +498,7 @@ func (s *Server) offlineClaimEvidence(ctx context.Context, d offlineDoor) *offli
// claims may have changed since the stage.
func (s *Server) offlineBeginChecks(w http.ResponseWriter, r *http.Request, d offlineDoor) (string, offlineFleet, bool) {
rec, host := d.rec, d.host
- if s.refuseSeedMove(w, rec) {
+ if s.refuseSeedMove(w, rec) || s.refuseRootfsMove(w, rec) {
return "", offlineFleet{}, false
}
if rec.Role != "" {
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index 206269f4c..b295642d1 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -607,15 +607,20 @@ func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target
}
}
- // A place re-homes every record of the app, so a seed that may not move
- // yet (spec §5.8) refuses it, before any write. A record that cannot be
- // read refuses it too. SetRecordRegion refuses such a seed again under
- // its CAS, for a record created after this read.
- switch block, err := placeSeedBlock(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct.Sqid, app); {
- case err != nil:
+ // A place re-homes every record of the app, so a record with a runtime
+ // (which never moves) and a seed that may not move yet (spec §5.8)
+ // refuse it, before any write. A record that cannot be read refuses it
+ // too. SetRecordRegion refuses both again under its CAS, for a record
+ // created after this read.
+ recs, err := placeRecords(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct.Sqid, app)
+ if err != nil {
log.Printf("console: place %s/%s: read instances: %v", acct.Sqid, app, err)
return http.StatusBadGateway, placeSeedReadFailed
- case block != "":
+ }
+ if placeRootfsBlock(recs) {
+ return http.StatusConflict, rootfsPlaceWords
+ }
+ if block := placeSeedBlock(recs); block != "" {
return http.StatusConflict, provision.SeedMoveSentence(block)
}
@@ -705,6 +710,9 @@ func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target
if msg := seedMoveConflict(err); msg != "" {
return http.StatusConflict, msg
}
+ if msg := rootfsMoveConflict(err); msg != "" {
+ return http.StatusConflict, msg
+ }
log.Printf("console: place %s/%s: stamp instance %s: %v", acct.Sqid, app, host, err)
return http.StatusBadGateway, "could not update every instance — try again"
}
diff --git a/internal/console/rootfs_move_test.go b/internal/console/rootfs_move_test.go
new file mode 100644
index 000000000..839fee007
--- /dev/null
+++ b/internal/console/rootfs_move_test.go
@@ -0,0 +1,174 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "net/http"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Rootfs apps Plan 3 Task 13: the move doors and carlos apps place give the
+// words (RFS-3-C23, RFS-3-C24) for a record with a runtime, before the
+// provision transition, which refuses it anyway, would.
+
+const rootfsMoveHost = "bab.example.com"
+
+// putRuntimeRecord creates an instance record of the shop app in region
+// with the given runtime (and, as any record with a runtime has, its
+// hibernation stated: always awake).
+func putRuntimeRecord(t *testing.T, st release.Store, acct, host, region, runtime string) {
+ t.Helper()
+ putRuntimeRecordHibernating(t, st, acct, host, region, runtime, false)
+}
+
+func putRuntimeRecordHibernating(t *testing.T, st release.Store, acct, host, region, runtime string, h bool) {
+ t.Helper()
+ rec := provision.Record{Schema: 1, Host: host, Slug: strings.SplitN(host, ".", 2)[0], App: "shop", Account: acct,
+ Region: region, Channel: "stable", CreatedAt: time.Now().UTC(), Runtime: runtime, Hibernate: &h}
+ if err := provision.CreateRecord(context.Background(), st, rec); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func wantRootfsMoveWords(host string) string {
+ return fmt.Sprintf("%s is a rootfs instance, and a rootfs instance does not move. create a new instance where you want it", host)
+}
+
+// POST .../move (the legacy door and the Phase 1 door) and the offline
+// door (start and stage) answer 409 with C23 for a rootfs instance,
+// hibernating or always awake, and write nothing.
+func TestMoveDoorsRefuseRootfs(t *testing.T) {
+ for _, door := range []struct {
+ name string
+ phase1 bool
+ hibernate bool
+ }{{"legacy", false, false}, {"legacy", false, true}, {"phase 1", true, false}, {"phase 1", true, true}} {
+ fx, token := seedMoveFixture(t, "code-rootfs-move", door.phase1)
+ putRuntimeRecordHibernating(t, fx.rel, release.OpsAccount, rootfsMoveHost, "ie", provision.RuntimeRootfsV1, door.hibernate)
+ key := provision.RecordKey(release.OpsAccount, "shop", rootfsMoveHost)
+ stored, _, err := fx.rel.Get(context.Background(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ code, _, raw := rawReq(t, http.MethodPost, instancesURL(fx, release.OpsAccount, "shop")+"/"+rootfsMoveHost+"/move", token, `{"region":"uk"}`)
+ if code != http.StatusConflict || errorText(raw) != wantRootfsMoveWords(rootfsMoveHost) {
+ t.Fatalf("%s door = %d %s", door.name, code, raw)
+ }
+ if got, _, err := fx.rel.Get(context.Background(), key); err != nil || string(got) != string(stored) {
+ t.Fatalf("%s door: a refused move wrote the record: %s, %v", door.name, got, err)
+ }
+ if claim := claimBytes(t, fx, rootfsMoveHost); claim != "" {
+ t.Fatalf("%s door: a refused move wrote a claim: %s", door.name, claim)
+ }
+ }
+
+ for _, h := range []bool{false, true} {
+ w := newOfflineWorld(t, ieOff("box-ie"), ukOff("box-uk"))
+ rec := w.record()
+ rec.Runtime, rec.Hibernate, rec.Seed, rec.Pool, rec.Addr, rec.Addrs = provision.RuntimeRootfsV1, &h, nil, "", "", nil
+ body, err := json.Marshal(rec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ offlinePut(t, w.fx.rel, provision.RecordKey("bab", "shop", offlineHost), body)
+ for _, path := range []string{"", "/stage"} {
+ w.refused(http.MethodPost, path, `{"region":"uk"}`, http.StatusConflict, wantRootfsMoveWords(offlineHost))
+ }
+ }
+}
+
+// carlos apps place refuses an app with any rootfs instance with C24
+// before it writes the app's placement or any record.
+func TestPlaceRefusesAnAppWithRootfsInstances(t *testing.T) {
+ const want = "this app's instances are rootfs instances, which do not move. create new instances where you want them"
+ fx, token := placeSeedFixture(t, "code-place-rootfs")
+ putRuntimeRecord(t, fx.rel, fx.sqid, "plain.example.com", "ie", "")
+ putRuntimeRecord(t, fx.rel, fx.sqid, rootfsMoveHost, "ie", provision.RuntimeRootfsV1)
+ code, _, raw := rawReq(t, http.MethodPost, placeURL(fx, "shop"), token, `{"target":"fleet/pi"}`)
+ if code != http.StatusConflict || errorText(raw) != want {
+ t.Fatalf("place = %d %s", code, raw)
+ }
+ assertNotPlaced(t, fx, "plain.example.com", rootfsMoveHost)
+
+ // The backstop: a rootfs record created after the place's read is
+ // refused under SetRecordRegion's CAS, and the place answers C24.
+ fx, token = placeSeedFixture(t, "code-place-rootfs-backstop")
+ putRuntimeRecord(t, fx.rel, fx.sqid, "plain.example.com", "ie", "")
+ fx.srv.cfg.Releases = &createOnSecondListStore{Store: fx.rel, prefix: provision.RecordsPrefix(fx.sqid, "shop"), create: func(st release.Store) {
+ putRuntimeRecord(t, st, fx.sqid, rootfsMoveHost, "ie", provision.RuntimeRootfsV1)
+ }}
+ code, _, raw = rawReq(t, http.MethodPost, placeURL(fx, "shop"), token, `{"target":"fleet/pi"}`)
+ if code != http.StatusConflict || errorText(raw) != want {
+ t.Fatalf("place = %d %s", code, raw)
+ }
+ got, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "shop", rootfsMoveHost)
+ if err != nil || got.Region != "ie" {
+ t.Fatalf("the late rootfs record was re-homed: %+v, %v", got, err)
+ }
+}
+
+// rootfsMoveDoors is every function of the package that answers a move
+// with refuseSeedMove: each answers refuseRootfsMove as well, so a door
+// added later gives the words too. (The transitions refuse regardless.)
+var rootfsMoveDoors = []string{"handleAPIInstanceMoveRequest", "legacyHandleAPIInstanceMoveRequest", "offlineBeginChecks"}
+
+func TestEverySeedMoveDoorRefusesRootfs(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ seed, rootfs := map[string]bool{}, map[string]bool{}
+ for _, f := range files {
+ if strings.HasSuffix(f, "_test.go") {
+ continue
+ }
+ file, err := parser.ParseFile(fset, f, nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range file.Decls {
+ fn, ok := d.(*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
+ }
+ if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
+ switch sel.Sel.Name {
+ case "refuseSeedMove":
+ seed[fn.Name.Name] = true
+ case "refuseRootfsMove":
+ rootfs[fn.Name.Name] = true
+ }
+ }
+ return true
+ })
+ }
+ }
+ var doors []string
+ for name := range seed {
+ doors = append(doors, name)
+ if !rootfs[name] {
+ t.Errorf("%s answers refuseSeedMove and not refuseRootfsMove", name)
+ }
+ }
+ slices.Sort(doors)
+ if !slices.Equal(doors, rootfsMoveDoors) {
+ t.Errorf("the seed move doors are %v, pinned %v", doors, rootfsMoveDoors)
+ }
+}
diff --git a/internal/console/seedmove.go b/internal/console/seedmove.go
index f4412dcde..69b4877a0 100644
--- a/internal/console/seedmove.go
+++ b/internal/console/seedmove.go
@@ -31,17 +31,19 @@ func (s *Server) refuseSeedMove(w http.ResponseWriter, rec *provision.Record) bo
// placement is written keeps main's sentence (placeInstancesFailed).
const placeSeedReadFailed = "could not update this app's instances. Try again."
-// placeSeedBlock is carlos apps place's seed rule (preflight M8(a)): a
-// place re-homes every record of the app, so it is a move of each. It reads
-// the app's records strictly, under judge (a record its slot no longer
-// vouches for is not one of them; nil reads as today), and returns the first record's MoveBlock, ""
-// when none blocks. A record it cannot read could be anything, so it is an
-// error and the place is refused. A record deleted between the listing and
-// its read (the race the place's own walk skips) is read again once.
+// placeRecords is carlos apps place's read of the app's records, before
+// any write (preflight M8(a)): a place re-homes every record of the app,
+// so it is a move of each, and the move rules (placeRootfsBlock,
+// placeSeedBlock) judge what it reads. It reads the app's records
+// strictly, under judge (a record its slot no longer vouches for is not one
+// of them; nil reads as today). A record it cannot read could be anything,
+// so it is an error and the place is refused. A record deleted between the
+// listing and its read (the race the place's own walk skips) is read again
+// once.
//
// No cap: the place walks every record of the app, and a cap would refuse
// a large app's place for good.
-func placeSeedBlock(ctx context.Context, st release.Store, judge *provision.LifetimeJudge, acct, app string) (string, error) {
+func placeRecords(ctx context.Context, st release.Store, judge *provision.LifetimeJudge, acct, app string) ([]provision.Record, error) {
ctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout)
defer cancel()
recs, unreadable, err := provision.ListRecordsStrictJudged(ctx, st, judge, acct, app, math.MaxInt)
@@ -49,7 +51,7 @@ func placeSeedBlock(ctx context.Context, st release.Store, judge *provision.Life
recs, unreadable, err = provision.ListRecordsStrictJudged(ctx, st, judge, acct, app, math.MaxInt)
}
if err != nil {
- return "", err
+ return nil, err
}
if len(unreadable) > 0 {
hosts := make([]string, 0, len(unreadable))
@@ -57,14 +59,73 @@ func placeSeedBlock(ctx context.Context, st release.Store, judge *provision.Life
hosts = append(hosts, h)
}
slices.Sort(hosts)
- return "", fmt.Errorf("records that do not read: %v", hosts)
+ return nil, fmt.Errorf("records that do not read: %v", hosts)
}
+ return recs, nil
+}
+
+// placeSeedBlock is the place's seed rule: the first record's MoveBlock,
+// "" when none blocks.
+func placeSeedBlock(recs []provision.Record) string {
for _, rec := range recs {
if b := rec.Seed.MoveBlock(); b != "" {
- return b, nil
+ return b
}
}
- return "", nil
+ return ""
+}
+
+// placeRootfsBlock is the place's runtime rule: true when any record of the
+// app has a runtime (rootfs-v1, or one this build does not know), which
+// never moves. The place then writes nothing, so no placement is left
+// half-applied.
+func placeRootfsBlock(recs []provision.Record) bool {
+ for _, rec := range recs {
+ if rec.Runtime != "" {
+ return true
+ }
+ }
+ return false
+}
+
+// rootfsMoveWords is RFS-3-C23, the move doors' sentence for an instance
+// with a runtime, filled with its host.
+const rootfsMoveWords = "%s is a rootfs instance, and a rootfs instance does not move. create a new instance where you want it"
+
+// rootfsPlaceWords is RFS-3-C24, carlos apps place's sentence for an app
+// with any instance with a runtime.
+const rootfsPlaceWords = "this app's instances are rootfs instances, which do not move. create new instances where you want them"
+
+// refuseRootfsMove answers a move of an instance with a runtime with C23.
+// Every move door calls it beside refuseSeedMove, after its gate and before
+// its transition, which refuses the record again under its CAS
+// (provision.RootfsMoveError).
+func (s *Server) refuseRootfsMove(w http.ResponseWriter, rec *provision.Record) bool {
+ if rec.Runtime != "" {
+ jsonError(w, http.StatusConflict, fmt.Sprintf(rootfsMoveWords, rec.Host))
+ return true
+ }
+ return false
+}
+
+// rootfsMoveRefused is a move door's sentence (C23) for a transition the
+// record's runtime refused under its CAS, "" for any other error.
+func rootfsMoveRefused(err error) string {
+ var refusal *provision.RootfsMoveError
+ if errors.As(err, &refusal) {
+ return fmt.Sprintf(rootfsMoveWords, refusal.Host)
+ }
+ return ""
+}
+
+// rootfsMoveConflict is carlos apps place's sentence (C24) for a write the
+// record's runtime refused under its CAS, "" for any other error.
+func rootfsMoveConflict(err error) string {
+ var refusal *provision.RootfsMoveError
+ if errors.As(err, &refusal) {
+ return rootfsPlaceWords
+ }
+ return ""
}
// seedMoveConflict is the sentence of a write the record's seed refused
diff --git a/internal/provision/offline_move.go b/internal/provision/offline_move.go
index 2ddc0dcbe..9176e8f99 100644
--- a/internal/provision/offline_move.go
+++ b/internal/provision/offline_move.go
@@ -146,10 +146,10 @@ func offlineIs(rec *Record, id string) error {
// OfflineStart begins an offline move from region `from` to region `to`
// (either may be "", the home placement). It carries MoveRequest's refusals:
-// a seeded record, an open run, a move already in flight, the same region and
-// a replica. It also refuses a `from` that is not the record's region, and a
-// malformed id. It stamps kind, id, from, to, state, requested_by and
-// requested_at; it does not touch the region.
+// a seeded record, a record with a runtime, an open run, a move already in
+// flight, the same region and a replica. It also refuses a `from` that is
+// not the record's region, and a malformed id. It stamps kind, id, from,
+// to, state, requested_by and requested_at; it does not touch the region.
func OfflineStart(id, from, to, by string, now time.Time) func(*Record) error {
return offlineBegin(id, from, to, by, now, OfflineStopping)
}
@@ -182,6 +182,9 @@ func offlineBegin(id, from, to, by string, now time.Time, state string) func(*Re
if err := seedMoveRefusal(rec); err != nil {
return err
}
+ if err := rootfsMoveRefusal(rec); err != nil {
+ return err
+ }
if rec.ActiveRun.Open() {
return &MoveRunOpenError{Run: *rec.ActiveRun}
}
diff --git a/internal/provision/provision.go b/internal/provision/provision.go
index c613899a1..f05c4fb89 100644
--- a/internal/provision/provision.go
+++ b/internal/provision/provision.go
@@ -1001,6 +1001,10 @@ func CreateRecord(ctx context.Context, s release.Store, rec Record) error {
// would keep the region they were created under forever, silently exempt
// from the placement a caller was just told had taken effect.
//
+// A change of region is a move, so it carries the move rules of the seed
+// (seedMoveRefusal) and the runtime (rootfsMoveRefusal); a write that
+// leaves the region as it is never refuses for either.
+//
// Not-found is returned verbatim (os.ErrNotExist-wrapped): a caller walking
// a key list that has gone stale between listing and this call should see
// the record is gone, not a manufactured success for a write that touched
@@ -1011,6 +1015,9 @@ func SetRecordRegion(ctx context.Context, s release.Store, acct, app, host, regi
if err := seedMoveRefusal(rec); err != nil {
return err
}
+ if err := rootfsMoveRefusal(rec); err != nil {
+ return err
+ }
}
rec.Region = region
return nil
@@ -1454,6 +1461,9 @@ func MoveRequest(to string, now time.Time) func(*Record) error {
if err := seedMoveRefusal(rec); err != nil {
return err
}
+ if err := rootfsMoveRefusal(rec); err != nil {
+ return err
+ }
if rec.ActiveRun.Open() {
return &MoveRunOpenError{Run: *rec.ActiveRun}
}
@@ -1491,6 +1501,9 @@ func MoveStartTransition(p MoveStart) func(*Record) error {
if err := seedMoveRefusal(rec); err != nil {
return err
}
+ if err := rootfsMoveRefusal(rec); err != nil {
+ return err
+ }
if rec.ActiveRun.Open() {
return &MoveRunOpenError{Run: *rec.ActiveRun}
}
diff --git a/internal/provision/rootfs_move_test.go b/internal/provision/rootfs_move_test.go
new file mode 100644
index 000000000..6d6d17ccb
--- /dev/null
+++ b/internal/provision/rootfs_move_test.go
@@ -0,0 +1,348 @@
+package provision
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "go/ast"
+ "go/parser"
+ "go/printer"
+ "go/token"
+ "os"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Rootfs apps Plan 3 Task 13: a record with a runtime does not move. Every
+// transition that starts a move, and SetRecordRegion when the region
+// changes, refuses it with a RootfsMoveError (an ErrMoveConflict), beside
+// the seed rule; WriteRecord refuses any write that changes such a
+// record's region or gives it a move, whoever wrote the mutation.
+
+const rootfsMoveID = "mv_abcdefghijklmnopqrstuvwxyz"
+
+// rootfsMoveStarts is every transition that starts a move, as the doors
+// call them, for a record in ie moving to uk.
+func rootfsMoveStarts(now time.Time) map[string]func(*Record) error {
+ return map[string]func(*Record) error{
+ "MoveRequest": MoveRequest("uk", now),
+ "MoveStartTransition": MoveStartTransition(MoveStart{ID: rootfsMoveID, Incarnation: strings.Repeat("a", 64),
+ From: "ie", To: "uk", Cut: "auto", By: "op@example.com", Now: now}),
+ "OfflineStart": OfflineStart(rootfsMoveID, "ie", "uk", "op@example.com", now),
+ "OfflineStage": OfflineStage(rootfsMoveID, "ie", "uk", "op@example.com",
+ StageTarget{Stager: "box-a", Bucket: "uk-data", Region: "eu-west-2"}, now),
+ }
+}
+
+func wantRootfsMoveError(t *testing.T, what string, err error, host string) {
+ t.Helper()
+ var refusal *RootfsMoveError
+ if !errors.As(err, &refusal) || refusal.Host != host {
+ t.Fatalf("%s: err = %v, want a RootfsMoveError for %s", what, err, host)
+ }
+ if !errors.Is(err, ErrMoveConflict) {
+ t.Fatalf("%s: err = %v, want an ErrMoveConflict", what, err)
+ }
+}
+
+func TestMoveTransitionsRefuseRootfs(t *testing.T) {
+ now := time.Now()
+ // The transitions themselves, on a record in memory: a binary record
+ // starts each (the control), and any runtime, rootfs-v1 or one this
+ // build does not know, is refused and left as it was.
+ for name := range rootfsMoveStarts(now) {
+ bin := rootfsTestRecord(rootfsHost, false)
+ bin.Runtime, bin.Hibernate = "", nil
+ if err := rootfsMoveStarts(now)[name](&bin); err != nil || bin.Move == nil {
+ t.Fatalf("%s on a binary record: %v, move %+v", name, err, bin.Move)
+ }
+ for _, runtime := range []string{RuntimeRootfsV1, "rootfs-v9"} {
+ rec := rootfsTestRecord(rootfsHost, false)
+ rec.Runtime = runtime
+ before := mustJSON(t, rec)
+ wantRootfsMoveError(t, name+" on "+runtime, rootfsMoveStarts(now)[name](&rec), rootfsHost)
+ if !bytes.Equal(mustJSON(t, rec), before) {
+ t.Fatalf("%s on %s changed the record: %s", name, runtime, mustJSON(t, rec))
+ }
+ }
+ }
+
+ // Through the record writer: refused, and the stored bytes unchanged.
+ s, sqid := rootfsSetup(t)
+ if err := CreateRecord(ctx, s, rootfsRecord(sqid, rootfsHost, false)); err != nil {
+ t.Fatal(err)
+ }
+ key := RecordKey(sqid, "shop", rootfsHost)
+ stored, _, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, start := range rootfsMoveStarts(now) {
+ _, err := SetRecordMove(ctx, s, sqid, "shop", rootfsHost, start)
+ wantRootfsMoveError(t, name+" through SetRecordMove", err, rootfsHost)
+ if got, _, err := s.Get(ctx, key); err != nil || !bytes.Equal(got, stored) {
+ t.Fatalf("%s: the stored record changed: %s, %v", name, got, err)
+ }
+ }
+
+ // [pf 2.3] The held mint is a move participant's: a box's Hold answers
+ // only for a record that carries a move. The refused record carries
+ // none, so a pass that would hold any moving record mints its row ready.
+ reg := regWith(t)
+ cfg := rootfsCfg(nil)
+ cfg.Hold = func(rec Record) (string, string, bool) {
+ if rec.Host == rootfsHost && rec.Move != nil {
+ t.Errorf("the hold was asked about a rootfs record with a move: %+v", rec.Move)
+ }
+ if rec.Move == nil {
+ return "", "", false
+ }
+ return "moving", rec.Move.ID, true
+ }
+ reconcileOnce(t, s, reg, cfg)
+ got := mustGet(t, reg, rootfsHost)
+ if got.Status != "ready" || got.HoldOp != "" {
+ t.Fatalf("the rootfs row was minted held: status %q hold_op %q", got.Status, got.HoldOp)
+ }
+}
+
+func TestSetRecordRegionRefusesARootfsMove(t *testing.T) {
+ s, sqid := rootfsSetup(t)
+ if err := CreateRecord(ctx, s, rootfsRecord(sqid, rootfsHost, false)); err != nil {
+ t.Fatal(err)
+ }
+ key := RecordKey(sqid, "shop", rootfsHost)
+ stored, _, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, target := range []string{"uk", "fleet/pi", ""} {
+ wantRootfsMoveError(t, "SetRecordRegion to "+target, SetRecordRegion(ctx, s, sqid, "shop", rootfsHost, target), rootfsHost)
+ if got, _, err := s.Get(ctx, key); err != nil || !bytes.Equal(got, stored) {
+ t.Fatalf("to %q: the stored record changed: %s, %v", target, got, err)
+ }
+ }
+ // A placement that leaves the instance where it is still succeeds.
+ if err := SetRecordRegion(ctx, s, sqid, "shop", rootfsHost, "ie"); err != nil {
+ t.Fatalf("same region: %v", err)
+ }
+}
+
+// The invariant in one place: WriteRecord refuses a write that changes the
+// region of a stored record with a runtime, or gives it a move, whichever
+// writer built the body (hostops, a console door, a transition this test
+// has not heard of). A write that leaves both alone, and the tombstone,
+// pass; a binary record moves as before.
+func TestWriteRecordKeepsARootfsRecordInPlace(t *testing.T) {
+ s, sqid := rootfsSetup(t)
+ if err := CreateRecord(ctx, s, rootfsRecord(sqid, rootfsHost, false)); err != nil {
+ t.Fatal(err)
+ }
+ key := RecordKey(sqid, "shop", rootfsHost)
+ write := func(mut func(*Record)) error {
+ raw, etag, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec, err := DecodeRecord(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mut(&rec)
+ _, _, err = WriteRecord(WithRecordSequence(ctx), s, key, raw, mustJSON(t, rec), etag)
+ return err
+ }
+ refused := map[string]func(*Record){
+ "region": func(r *Record) { r.Region = "uk" },
+ "region home": func(r *Record) { r.Region = "" },
+ "legacy move": func(r *Record) { r.Move = &MoveState{To: "uk", State: MovePreparing, RequestedAt: time.Now().UTC()} },
+ "offline move": func(r *Record) {
+ r.Move = &MoveState{Kind: MoveKindOffline, ID: rootfsMoveID, From: "ie", To: "uk", State: OfflineStaging}
+ },
+ }
+ for name, mut := range refused {
+ wantRootfsMoveError(t, name, write(mut), rootfsHost)
+ }
+ if err := write(func(r *Record) { r.Channel = "edge" }); err != nil {
+ t.Fatalf("a write that moves nothing: %v", err)
+ }
+ raw, etag, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tomb, err := TombstoneBody(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := WriteRecord(WithRecordSequence(ctx), s, key, raw, tomb, etag); err != nil {
+ t.Fatalf("the tombstone: %v", err)
+ }
+
+ bin := rootfsRecord(sqid, "plain.shop.example.com", false)
+ bin.Runtime, bin.Hibernate = "", nil
+ if err := CreateRecord(ctx, s, bin); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetRecordRegion(ctx, s, sqid, "shop", bin.Host, "uk"); err != nil {
+ t.Fatalf("a binary record's region: %v", err)
+ }
+}
+
+// rootfsRefusalCallers is every function of the package that calls
+// seedMoveRefusal: the writes that move a record. Each calls
+// rootfsMoveRefusal on the same record. A new move write joins this list,
+// and so gets the runtime rule, in the commit that adds it.
+var rootfsRefusalCallers = []string{"MoveRequest", "MoveStartTransition", "SetRecordRegion", "offlineBegin"}
+
+// rootfsMoveStartWriters is every function that writes a new MoveState onto
+// a record (a move's start), and rootfsRegionWriters every function that
+// assigns a record's region. A start is a refusal caller. A region writer
+// is SetRecordRegion or a continuation of a move already on the record,
+// which no record with a runtime ever carries; WriteRecord refuses the
+// write either way.
+var (
+ rootfsMoveStartWriters = []string{"MoveRequest", "MoveStartTransition", "offlineBegin"}
+ rootfsRegionWriters = []string{"MoveComplete", "MoveFlip", "MoveRollBack", "OfflineAbort", "OfflineFlip", "SetRecordRegion"}
+)
+
+func TestEverySeedMoveRefusalSiteRefusesRootfs(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ render := func(e ast.Expr) string {
+ var b bytes.Buffer
+ if err := printer.Fprint(&b, fset, e); err != nil {
+ t.Fatal(err)
+ }
+ return b.String()
+ }
+ seedArgs, rootfsArgs := map[string][]string{}, map[string][]string{}
+ var starts, regions []string
+ for _, f := range files {
+ if strings.HasSuffix(f, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ file, err := parser.ParseFile(fset, f, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range file.Decls {
+ fn, ok := d.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ name := fn.Name.Name
+ var start, region bool
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.CallExpr:
+ id, ok := n.Fun.(*ast.Ident)
+ if !ok || len(n.Args) != 1 {
+ return true
+ }
+ switch id.Name {
+ case "seedMoveRefusal":
+ seedArgs[name] = append(seedArgs[name], render(n.Args[0]))
+ case "rootfsMoveRefusal":
+ rootfsArgs[name] = append(rootfsArgs[name], render(n.Args[0]))
+ }
+ case *ast.AssignStmt:
+ for i, lhs := range n.Lhs {
+ sel, ok := lhs.(*ast.SelectorExpr)
+ if !ok || i >= len(n.Rhs) {
+ continue
+ }
+ switch sel.Sel.Name {
+ case "Region":
+ region = true
+ case "Move":
+ if u, ok := n.Rhs[i].(*ast.UnaryExpr); ok {
+ if lit, ok := u.X.(*ast.CompositeLit); ok && render(lit.Type) == "MoveState" {
+ start = true
+ }
+ }
+ }
+ }
+ }
+ return true
+ })
+ if start {
+ starts = append(starts, name)
+ }
+ if region {
+ regions = append(regions, name)
+ }
+ }
+ }
+ var callers []string
+ for name, args := range seedArgs {
+ callers = append(callers, name)
+ for _, a := range args {
+ if !slices.Contains(rootfsArgs[name], a) {
+ t.Errorf("%s calls seedMoveRefusal(%s) and not rootfsMoveRefusal(%s)", name, a, a)
+ }
+ }
+ }
+ for _, list := range []*[]string{&callers, &starts, &regions} {
+ sort.Strings(*list)
+ }
+ pinned := slices.Clone(rootfsRefusalCallers)
+ sort.Strings(pinned)
+ if !slices.Equal(callers, pinned) {
+ t.Errorf("seedMoveRefusal's callers are %v, pinned %v", callers, pinned)
+ }
+ for _, s := range starts {
+ if !slices.Contains(rootfsRefusalCallers, s) {
+ t.Errorf("%s starts a move and is not a refusal caller", s)
+ }
+ }
+ if want := sortedClone(rootfsMoveStartWriters); !slices.Equal(starts, want) {
+ t.Errorf("move starts are %v, pinned %v", starts, want)
+ }
+ if want := sortedClone(rootfsRegionWriters); !slices.Equal(regions, want) {
+ t.Errorf("region writers are %v, pinned %v", regions, want)
+ }
+}
+
+func sortedClone(s []string) []string {
+ c := slices.Clone(s)
+ sort.Strings(c)
+ return c
+}
+
+// The record body WriteRecord's guard reads is the one every reader
+// decodes: a region or move under another key spelling is the same field
+// to encoding/json, so the guard and the readers agree on it.
+func TestRootfsMoveGuardReadsTheDecodedFields(t *testing.T) {
+ s, sqid := rootfsSetup(t)
+ if err := CreateRecord(ctx, s, rootfsRecord(sqid, rootfsHost, false)); err != nil {
+ t.Fatal(err)
+ }
+ key := RecordKey(sqid, "shop", rootfsHost)
+ raw, etag, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &m); err != nil {
+ t.Fatal(err)
+ }
+ delete(m, "region")
+ m["REGION"] = json.RawMessage(`"uk"`)
+ body, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _, err = WriteRecord(ctx, s, key, raw, body, etag)
+ wantRootfsMoveError(t, "REGION", err, rootfsHost)
+}
diff --git a/internal/provision/runtime.go b/internal/provision/runtime.go
index 0b974a2c0..07cd40fc0 100644
--- a/internal/provision/runtime.go
+++ b/internal/provision/runtime.go
@@ -71,8 +71,11 @@ var ErrRuntimeProtected = errors.New("provision: an instance's runtime, and a ro
// the record gets; protectedSpellings first makes sure there is only one
// key it could have matched.
type runtimeFields struct {
- Runtime string `json:"runtime"`
- Hibernate *bool `json:"hibernate"`
+ Runtime string `json:"runtime"`
+ Hibernate *bool `json:"hibernate"`
+ Host string `json:"host"`
+ Region string `json:"region"`
+ Move json.RawMessage `json:"move"`
}
// protectedKeys are the fields runtimeFixed protects.
@@ -103,9 +106,10 @@ func protectedSpellings(fields map[string]json.RawMessage) error {
// fence or a supersede writes the stored bytes again, even a record that
// would not pass below), and the exact tombstone of before (retirement
// ends the life; the hostname's next life is a new mint). Otherwise the
-// runtime must be byte-equal, and a stored rootfs-v1 record's hibernate
-// must be present in both and equal. A body that does not decode is
-// ErrRecordSequence, as RecordSequence answers it.
+// runtime must be byte-equal, a stored rootfs-v1 record's hibernate must
+// be present in both and equal, and a stored record with a runtime keeps
+// its region and gets no move (rootfsStaysPut, a RootfsMoveError). A body
+// that does not decode is ErrRecordSequence, as RecordSequence answers it.
func runtimeFixed(before, body []byte) error {
prior, _, err := RecordSequence(before)
if err != nil {
@@ -137,7 +141,7 @@ func runtimeFixed(before, body []byte) error {
if was.Runtime == RuntimeRootfsV1 && (was.Hibernate == nil || now.Hibernate == nil || *was.Hibernate != *now.Hibernate) {
return ErrRuntimeProtected
}
- return nil
+ return rootfsStaysPut(was, now)
}
// isTombstoneOf reports whether next, a body's fields, is
@@ -185,3 +189,46 @@ func sameJSON(a, b []byte) bool {
}
return bytes.Equal(ca.Bytes(), cb.Bytes())
}
+
+// RootfsMoveError is a move a record's runtime refuses: a record minted
+// with a runtime (rootfs-v1, or one this build does not know, which is
+// fixed and inert) never moves. It wraps ErrMoveConflict, as SeedMoveError
+// does, so a door that meets it under a CAS can answer its own sentence.
+type RootfsMoveError struct{ Host string }
+
+func (e *RootfsMoveError) Error() string {
+ return ErrMoveConflict.Error() + ": " + e.Host + " has a runtime, and a record with a runtime does not move"
+}
+
+func (e *RootfsMoveError) Unwrap() error { return ErrMoveConflict }
+
+// rootfsMoveRefusal is the runtime rule of every write that moves a record
+// (the move-start transitions and SetRecordRegion), beside seedMoveRefusal
+// at each of its call sites, under the record CAS. Any non-empty runtime
+// refuses. WriteRecord holds the same rule on the bytes it stores
+// (rootfsStaysPut), for a writer that bypasses the transitions.
+func rootfsMoveRefusal(rec *Record) error {
+ if rec.Runtime != "" {
+ return &RootfsMoveError{Host: rec.Host}
+ }
+ return nil
+}
+
+// rootfsStaysPut is runtimeFixed's move rule, after its create, write-back
+// and tombstone exemptions: a stored record with a runtime keeps its region
+// and is never given a move (a move it somehow already carries may only be
+// left as it is or cleared).
+func rootfsStaysPut(was, now runtimeFields) error {
+ if was.Runtime == "" {
+ return nil
+ }
+ if now.Region != was.Region || (moveSet(now.Move) && !(moveSet(was.Move) && sameJSON(was.Move, now.Move))) {
+ return &RootfsMoveError{Host: was.Host}
+ }
+ return nil
+}
+
+// moveSet reports whether a record body's move field carries a move.
+func moveSet(raw json.RawMessage) bool {
+ return len(raw) > 0 && !bytes.Equal(bytes.TrimSpace(raw), []byte("null"))
+}