carlos / platform Public

console: one proof decides every restore (#658)

restoreProof implements the admission table row by row, in order: an
unreadable source (R1, 503), ownership of the mark and the slot (S1),
anything pending (R1), the owner's own valid record (the create's
"instance <host> already exists"), the platform (R2), the retired slot
(R8), the lineage from its origin (R4, R8), the newest retirement as a
committed, restorable normal retirement at the slot's incarnation (R8),
plain shape of the stored body, the request and the built record (R7),
this console's region (R5) and a move's staging (R6). Sources are read
in row order, so nothing past ownership is read for another owner. It
takes no lock and never calls hostSettling or withAppHost.

hostHasStaging lists moves/<host>/ (trailing slash) in the console
region's data bucket with the HA leftover rail's bounded listing, any
object of any name, and returns every error.

R7 is 409: the create door answers ValidateShape failures with 400, not
422 (apiinstances.go handleAPIInstanceCreate), so the 422 case does not
apply.

The approved R1-R8 and C2 strings are message functions beside the
proof, checked against the approved copy deck by TestRestoreCopyApproved.
The proof lives in restore_proof.go: restore.go already holds the app
trash restore.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f2dbba608eb17e51c239b9d35c48aa22d87dd970 parent 6fdc6b1
3 files changed, +1,081 −0
  • internal/console/restore_proof.go +356 −0
  • internal/console/restore_proof_test.go +671 −0
  • internal/console/restore_staging.go +54 −0
diff --git a/internal/console/restore_proof.go b/internal/console/restore_proof.go
new file mode 100644
index 000000000..30c191972
--- /dev/null
+++ b/internal/console/restore_proof.go
@@ -0,0 +1,356 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Instance restore (#658, spec docs/superpowers/specs/2026-11-07-instance-
+// restore-658-design.md §3-§4; plan "The admission table"). One function,
+// restoreProof, decides every restore: the create door's early call, the
+// mark step's deciding call and C2 all ask it, and nothing else does.
+
+// The approved strings (docs/superpowers/notes/instance-restore-658-copy.json).
+func msgRestoreUnchecked(host string) string { // R1
+ return "Could not check whether " + host + " can be restored. Try again."
+}
+
+func msgRestoreUnavailable(host string) string { // R2
+ return host + " can't be restored on this platform yet. Ask an operator."
+}
+
+func msgRestoreEarlierApp(host, app string) string { // R4
+ return host + " belonged to an earlier app named " + app + ", so it can't be restored into this one."
+}
+
+func msgRestoreRegion(host, region string) string { // R5
+ return host + " can only be restored from the console in " + region + "."
+}
+
+func msgRestoreStaging(host string) string { // R6
+ return host + " has a move's copy waiting, so it can't be restored. Ask an operator."
+}
+
+func msgRestoreNotPlain(host string) string { // R7
+ return host + " can't be restored: restore works for plain instances only."
+}
+
+func msgRestoreTooOld(host string) string { // R8
+ return host + " was created or deleted before restore was available, so it can't be restored."
+}
+
+// msgRestoreHint is C2: S1's text for an ordinary create when a restore of
+// the same request would pass both stages.
+func msgRestoreHint(host string) string { // C2
+ return host + " held this app's data before. To bring it back, create it with --restore."
+}
+
+// msgInstanceExists is the create door's own answer to a record that
+// already stands under its key.
+func msgInstanceExists(host string) string {
+ return "instance " + host + " already exists"
+}
+
+// restoreAsk is one restore as the proof needs it. Account is the account's
+// sqid (the identifier the mark, slot, allocations and retirements hold;
+// Task 1 note §3) and AccountID its numeric id, the key of its apps row.
+// Lifetime is the app's current apps.lifetime, as the door read it
+// (AppLife(AccountID, App)). Region is the request's, normalized with
+// homeRegionIn, so naming the home region is "". Kind, Role and Addrs are
+// the request's; Placement is appPlacement's answer and Pool the manifest's
+// pool. Shape is nil at the door's early call and the record actually being
+// written at the deciding call.
+type restoreAsk struct {
+ Account, App, Lifetime, Host, Region string
+ AccountID int64
+ Kind, Role, Placement, Pool string
+ Addrs []string
+ Shape *provision.Record
+ From, Import bool
+}
+
+// restoreVerdict is the proof's answer.
+//
+// - Owner false: the mark or the slot does not name the account and app,
+// and the door answers S1 (Refusal carries it), unless Refusal is R1 (a
+// source could not be read). Another owner never sees anything else.
+// - Duplicate: the owner's valid record stands under the key; Refusal is
+// the create's ordinary "instance <host> already exists" (409).
+// - Otherwise Refusal nil is eligible: Region is the record region to
+// write (the stored body's, "" for home), RetirementOp the retirement
+// restored, and Body the record as it was retired. Any other Refusal is
+// the owner's detailed answer: R1, R2 or R4 to R8.
+type restoreVerdict struct {
+ Owner, Duplicate bool
+ Refusal *doorRefusal
+ Region string
+ RetirementOp string
+ Body *provision.Record
+}
+
+// restoreProof answers ask by the admission table, the first row that
+// applies, in this order:
+//
+// 1. a source it reads cannot be read: R1 (503)
+// 2. the mark or the slot does not name the account and app: S1
+// 3. an allocation, retirement or migration of the host is pending: R1
+// 4. a valid record of this account and app stands under the key: duplicate
+// 5. the history mode is not active, lifetimes are off, or claims are on: R2
+// 6. the slot is not retired: R8
+// 7. a lineage row of this account and app is bound to another lifetime: R4
+// 8. no origin, a row with neither flag, the lowest row not the origin, a
+// row naming anyone else, or no row at the slot's incarnation: R8
+// 9. the newest retirement is not the slot's incarnation, names someone
+// else, or is not a committed, restorable normal retirement: R8
+// 10. the stored body, the request or the built record is not plain: R7
+// 11. the stored body is not in this console's region, or the request
+// names another region: R5
+// 12. any object under moves/<host>/: R6
+// 13. otherwise eligible.
+//
+// Sources are read in row order, and row 1 fires at the read that fails:
+// the mark and the slot before row 2 decides, the pending count for row 3,
+// the record for row 4, the mode for row 5, the lineage for rows 7-8, the
+// newest retirement for row 9, and the staging list for row 12. So nothing
+// past ownership is read for another owner (spec §3 item 1), and an
+// unreadable source is never a pass.
+//
+// It takes no lock: the early call holds none, and the deciding call runs
+// under the app lock and the hostname exclusion the create core already
+// holds (lifetimes_create.go). It never calls hostSettling or withAppHost,
+// which are not reentrant; PendingForHost is the same count without them.
+func (s *Server) restoreProof(ctx context.Context, ask restoreAsk) restoreVerdict {
+ host := ask.Host
+ tag := ask.Account + "/" + ask.App + "/" + host
+ unchecked := func(owner bool, what string, err error) restoreVerdict {
+ log.Printf("console: restore %s: %s: %v (refused, try again)", tag, what, err)
+ return restoreVerdict{Owner: owner, Refusal: &doorRefusal{Status: http.StatusServiceUnavailable, Msg: msgRestoreUnchecked(host)}}
+ }
+ refuse := func(msg, why string) restoreVerdict {
+ log.Printf("console: restore %s: refused: %s", tag, why)
+ return restoreVerdict{Owner: true, Refusal: &doorRefusal{Status: http.StatusConflict, Msg: msg}}
+ }
+ tooOld := func(why string) restoreVerdict { return refuse(msgRestoreTooOld(host), why) }
+
+ // Stage 1, ownership (rows 1-2): the mark and the slot, both read
+ // before either decides.
+ if s.cfg.Releases == nil {
+ return unchecked(false, "read the mark", errors.New("no control store on this console"))
+ }
+ mark, err := readHostMark(ctx, s, host)
+ if err != nil {
+ return unchecked(false, "read the mark", err)
+ }
+ slot, _, err := provision.ReadHostIncarnation(ctx, s.cfg.Releases, host)
+ if err != nil {
+ return unchecked(false, "read the slot", err)
+ }
+ if ask.Account == "" || ask.App == "" || mark == nil || mark.Host != host ||
+ mark.Account != ask.Account || mark.App != ask.App || !slotOwnedBy(slot, ask.Account, ask.App) {
+ return restoreVerdict{Refusal: &doorRefusal{Status: http.StatusConflict, Msg: msgHostUsed(host)}}
+ }
+
+ // Row 3: anything pending for the host is settling; try again.
+ n, err := s.store.PendingForHost(host, "")
+ if err != nil {
+ return unchecked(true, "count pending operations", err)
+ }
+ if n > 0 {
+ return unchecked(true, "pending operations", fmt.Errorf("%d pending", n))
+ }
+
+ // Row 4: the owner's own record stands, as a retry after success finds.
+ obs := s.judge.Observe(ctx, s.cfg.Releases, ask.Account, ask.App, host)
+ if obs.Verdict == provision.LifetimeUnreadable {
+ return unchecked(true, "read the record", obs.Err)
+ }
+ if validRecord(obs) {
+ return restoreVerdict{Owner: true, Duplicate: true,
+ Refusal: &doorRefusal{Status: http.StatusConflict, Msg: msgInstanceExists(host)}}
+ }
+
+ // Stage 2, eligibility. Row 5: the platform.
+ mode, err := s.hostsMode(ctx)
+ if err != nil {
+ return unchecked(true, "read the history mode", err)
+ }
+ if mode != provision.HostsModeActive || !s.lifetimesOn() || s.cfg.HostClaim {
+ return refuse(msgRestoreUnavailable(host), fmt.Sprintf("mode %q, lifetimes on %v, claims %v", mode, s.lifetimesOn(), s.cfg.HostClaim))
+ }
+
+ // Row 6: the slot.
+ if slot.State != provision.SlotRetired {
+ return tooOld("the slot is " + slot.State)
+ }
+
+ // Rows 7-8: the lineage, from its origin.
+ rows, err := s.store.HostLineage(host)
+ if err != nil {
+ return unchecked(true, "read the lineage", err)
+ }
+ for _, a := range rows {
+ if a.Account == ask.Account && a.App == ask.App && a.AppLifetime != ask.Lifetime {
+ return refuse(msgRestoreEarlierApp(host, ask.App), "allocation "+a.OpID+" is of another app lifetime")
+ }
+ }
+ if why := lineageGap(rows, ask, slot.Incarnation); why != "" {
+ return tooOld(why)
+ }
+
+ // Row 9: the newest retirement, and the body it kept.
+ e, err := s.store.NewestRetirement(host)
+ if err != nil {
+ return unchecked(true, "read the newest retirement", err)
+ }
+ body, why := retiredBody(e, ask, slot.Incarnation)
+ if why != "" {
+ return tooOld(why)
+ }
+
+ // Row 10: plain, old and new.
+ if !restorePlain(body) || !ask.plainRequest() || (ask.Shape != nil && !restorePlain(*ask.Shape)) {
+ return refuse(msgRestoreNotPlain(host), "not a plain instance")
+ }
+
+ // Row 11: this console's own region.
+ if body.Region != s.cfg.Region || (ask.Region != "" && ask.Region != s.cfg.Region) ||
+ (ask.Shape != nil && ask.Shape.Region != body.Region) {
+ return refuse(msgRestoreRegion(host, s.restoreRegionName(body.Region)),
+ fmt.Sprintf("stored region %q, requested %q, console %q", body.Region, ask.Region, s.cfg.Region))
+ }
+
+ // Row 12: a move's staged copy.
+ staged, err := s.hostHasStaging(ctx, host)
+ if err != nil {
+ return unchecked(true, "list the staging prefix", err)
+ }
+ if staged {
+ return refuse(msgRestoreStaging(host), "a move's staging is under moves/"+host+"/")
+ }
+
+ return restoreVerdict{Owner: true, Region: body.Region, RetirementOp: e.OpID, Body: &body}
+}
+
+// readHostMark is host's mark body, nil when there is none. A body that
+// does not decode is an error: an unreadable mark is never "absent".
+func readHostMark(ctx context.Context, s *Server, host string) (*provision.HostUse, error) {
+ key := provision.HostsUsedKey(host)
+ if key == "" {
+ return nil, fmt.Errorf("%q is not a hostname", host)
+ }
+ raw, _, err := s.cfg.Releases.Get(ctx, key)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ var u provision.HostUse
+ if err := json.Unmarshal(raw, &u); err != nil {
+ return nil, fmt.Errorf("decode %s: %w", key, err)
+ }
+ return &u, nil
+}
+
+// lineageGap is row 8 (spec §4 stage 2 item 3): among the host's non-void
+// allocations, the lowest carries restore_origin and nothing else, every
+// other carries restore_of and no origin, every one names the account, app
+// and lifetime, and one has the slot's incarnation. It answers why not, ""
+// when the lineage holds.
+func lineageGap(rows []Allocation, ask restoreAsk, incarnation uint64) string {
+ if len(rows) == 0 {
+ return "no allocation"
+ }
+ if ask.Lifetime == "" {
+ return "no app lifetime to compare"
+ }
+ atSlot := false
+ for i, a := range rows {
+ switch {
+ case a.Account != ask.Account || a.App != ask.App:
+ return "allocation " + a.OpID + " names another account or app"
+ case a.AppLifetime != ask.Lifetime:
+ return "allocation " + a.OpID + " is of another app lifetime"
+ case i == 0 && (!a.RestoreOrigin || a.RestoreOf != ""):
+ return "the lowest allocation " + a.OpID + " is not the origin"
+ case i > 0 && (a.RestoreOrigin || a.RestoreOf == ""):
+ return "allocation " + a.OpID + " is neither the origin nor a restore"
+ }
+ if a.Incarnation == incarnation {
+ atSlot = true
+ }
+ }
+ if !atSlot {
+ return fmt.Sprintf("no allocation at the slot's incarnation %d", incarnation)
+ }
+ return ""
+}
+
+// retiredBody is row 9 (spec §4 stage 2 item 4; controller's ruling 1): the
+// newest retirement is a committed, restorable normal retirement of this
+// account and app at the slot's incarnation, and the body it kept is this
+// host's record of the same. It answers the body, or why not.
+func retiredBody(e *RetirementEvidence, ask restoreAsk, incarnation uint64) (provision.Record, string) {
+ switch {
+ case e == nil:
+ return provision.Record{}, "no retirement"
+ case e.Kind != retireNormal || e.State != lifetimeCommitted || !e.Restorable:
+ return provision.Record{}, fmt.Sprintf("the newest retirement %s is %s %s, restorable %v", e.OpID, e.Kind, e.State, e.Restorable)
+ case e.Incarnation != incarnation:
+ return provision.Record{}, fmt.Sprintf("the newest retirement %s is of incarnation %d, the slot's is %d", e.OpID, e.Incarnation, incarnation)
+ case e.Account != ask.Account || e.App != ask.App:
+ return provision.Record{}, "the newest retirement " + e.OpID + " names another account or app"
+ case len(e.RecordBody) == 0:
+ return provision.Record{}, "the newest retirement " + e.OpID + " kept no body"
+ }
+ body, err := provision.DecodeRecord(e.RecordBody)
+ if err != nil {
+ return provision.Record{}, "the newest retirement " + e.OpID + " kept a body that does not decode"
+ }
+ if body.Host != ask.Host || body.Account != ask.Account || body.App != ask.App || body.Retired || body.Incarnation != e.Incarnation {
+ return provision.Record{}, "the newest retirement " + e.OpID + " kept a body of another record"
+ }
+ return body, ""
+}
+
+// restorePlain reports whether rec is a plain instance (spec §4 stage 2 item
+// 5): kind instance with derived paths, and no HA, runtime, pool, fleet
+// placement, fleet box, replica role, assignment or replica state, seed,
+// demo or demo claim.
+func restorePlain(rec provision.Record) bool {
+ if rec.KindOrDefault() != "instance" || !rec.DerivesPaths() {
+ return false
+ }
+ if _, fleet := registry.FleetPlacement(rec.Region); fleet {
+ return false
+ }
+ return !rec.HA && rec.Runtime == "" && rec.Pool == "" && rec.FleetBox == "" && rec.Role == "" &&
+ rec.ReplicaAssignment == nil && rec.Coordinator == nil && rec.ReplicaDeploy == nil &&
+ rec.Seed == nil && rec.Demo == nil && rec.DemoClaim == nil
+}
+
+// plainRequest is row 10's request half, known before the region block:
+// kind instance, no addrs, no role, no from or import, no app placement and
+// no manifest pool.
+func (a restoreAsk) plainRequest() bool {
+ return (a.Kind == "" || a.Kind == "instance") && len(a.Addrs) == 0 && a.Role == "" &&
+ !a.From && !a.Import && a.Placement == "" && a.Pool == ""
+}
+
+// restoreRegionName is R5's <region>: the region as a person would type it,
+// the home region's name for "" (homeRegionOut), or the console's own label
+// for the home when no home is named.
+func (s *Server) restoreRegionName(region string) string {
+ if name := s.homeRegionOut(region); name != "" {
+ return name
+ }
+ return s.offlinePlace(region)
+}
diff --git a/internal/console/restore_proof_test.go b/internal/console/restore_proof_test.go
new file mode 100644
index 000000000..114e68b66
--- /dev/null
+++ b/internal/console/restore_proof_test.go
@@ -0,0 +1,671 @@
+package console
+
+// restoreProof (instance restore #658, plan Task 5; the admission table):
+// one proof decides every restore. Driven over a real claims-off console
+// with lifetimes on and the history active: one.shop.example.com created
+// through the door (its origin recorded) and deleted through the door (a
+// committed, restorable normal retirement), then one input changed per row.
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// stagingStore is the console region's data bucket: a DirStore whose
+// bounded listing records each prefix asked and can be made to fail.
+type stagingStore struct {
+ *release.DirStore
+ mu sync.Mutex
+ fail error
+ listed []string
+}
+
+func (s *stagingStore) ListPage(ctx context.Context, prefix, startAfter string, limit int) ([]string, error) {
+ s.mu.Lock()
+ s.listed = append(s.listed, prefix)
+ fail := s.fail
+ s.mu.Unlock()
+ if fail != nil {
+ return nil, fail
+ }
+ return s.DirStore.ListPage(ctx, prefix, startAfter, limit)
+}
+
+// proofFx is the restore's world: the console, its data bucket, the ask
+// the rightful owner makes, and the bytes before the delete.
+type proofFx struct {
+ ltOn
+ data *stagingStore
+ ask restoreAsk
+ recBefore []byte
+ slotBefore []byte
+}
+
+// newProofBase creates ltOne through the door with the history active and
+// gives the console a data bucket and a home region's name. Nothing is
+// deleted yet.
+func newProofBase(t *testing.T) *proofFx {
+ t.Helper()
+ ctx := context.Background()
+ l := newLtOn(t)
+ forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive})
+ l.mustCreate(t, ltOne)
+ recBefore, _ := rawOf(t, l.fx.rel, ltApp, ltOne)
+ slotBefore, _, err := l.fx.rel.Get(ctx, provision.HostIncarnationKey(ltOne))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rows := lineage(t, l.fx.st, ltOne); len(rows) != 1 || !rows[0].RestoreOrigin {
+ t.Fatalf("fixture: lineage %+v, want one row with the origin", rows)
+ }
+ // After the create, so its leftover rail stays as the fixture had it.
+ data := &stagingStore{DirStore: release.NewDirStore(t.TempDir())}
+ srv := l.fx.srv
+ srv.cfg.SeedData, srv.cfg.HibernateBucket, srv.cfg.HomeRegion = data, "data-test", "ie"
+ acct := l.acct(t)
+ life, err := l.fx.st.AppLife(acct.ID, ltApp)
+ if err != nil || life == nil {
+ t.Fatalf("apps row: %+v %v", life, err)
+ }
+ return &proofFx{ltOn: l, data: data, recBefore: recBefore, slotBefore: slotBefore,
+ ask: restoreAsk{Account: acct.Sqid, AccountID: acct.ID, App: ltApp, Lifetime: life.Lifetime, Host: ltOne}}
+}
+
+// newProofFx is newProofBase with ltOne deleted through the door: the
+// state in which the owner's restore is eligible.
+func newProofFx(t *testing.T) *proofFx {
+ t.Helper()
+ p := newProofBase(t)
+ if code, body := p.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent {
+ t.Fatalf("delete = %d %s", code, body)
+ }
+ requireRetired(t, p.fx.rel, ltApp, ltOne, 1)
+ if e := evidenceOf(t, p.fx.st, ltOne); !restoreGrade(e) {
+ t.Fatalf("fixture: retirement %+v, want normal committed restorable", e)
+ }
+ return p
+}
+
+func (p *proofFx) prove() restoreVerdict {
+ return p.fx.srv.restoreProof(context.Background(), p.ask)
+}
+
+// overwrite replaces key's body in the bucket, bypassing the hooks.
+func (p *proofFx) overwrite(t *testing.T, key string, body []byte) {
+ t.Helper()
+ ctx := context.Background()
+ if err := p.fx.rel.Delete(ctx, key); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.fx.rel.Put(ctx, key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (p *proofFx) overwriteJSON(t *testing.T, key string, v any) {
+ t.Helper()
+ b, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p.overwrite(t, key, b)
+}
+
+func (p *proofFx) setMark(t *testing.T, u provision.HostUse) {
+ t.Helper()
+ p.overwriteJSON(t, provision.HostsUsedKey(ltOne), u)
+}
+
+func (p *proofFx) setSlot(t *testing.T, slot provision.HostIncarnation) {
+ t.Helper()
+ p.overwriteJSON(t, provision.HostIncarnationKey(ltOne), slot)
+}
+
+// slotLive puts the slot back as the create left it: live at 1.
+func (p *proofFx) slotLive(t *testing.T) {
+ t.Helper()
+ p.overwrite(t, provision.HostIncarnationKey(ltOne), p.slotBefore)
+}
+
+// reviveRecord puts the record and its live slot back: the owner's valid
+// record stands under the key, as after a restore that succeeded.
+func (p *proofFx) reviveRecord(t *testing.T) {
+ t.Helper()
+ p.slotLive(t)
+ p.overwrite(t, recKey(ltApp, ltOne), p.recBefore)
+}
+
+func (p *proofFx) exec(t *testing.T, q string, args ...any) {
+ t.Helper()
+ if _, err := p.fx.st.db.Exec(q, args...); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// setBody replaces the newest retirement's stored body with the deleted
+// record changed by mutate.
+func (p *proofFx) setBody(t *testing.T, mutate func(*provision.Record)) {
+ t.Helper()
+ rec := decodeRec(t, p.recBefore)
+ mutate(&rec)
+ b, err := json.Marshal(rec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p.exec(t, `UPDATE record_retirements SET record_body = ? WHERE host = ?`, b, ltOne)
+}
+
+// failGets fails every read of key through the console's bucket.
+func (p *proofFx) failGets(key string) {
+ p.bucket.setHook(failNth("get", key, 1, true))
+}
+
+func (p *proofFx) stage(t *testing.T, key string) {
+ t.Helper()
+ if _, err := p.data.Put(context.Background(), key, []byte("x"), ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// commitAllocation adds a committed allocation of ltOne at incarnation n.
+func (p *proofFx) commitAllocation(t *testing.T, a Allocation) {
+ t.Helper()
+ a.Host, a.State = ltOne, lifetimePending
+ if a.Account == "" {
+ a.Account, a.App, a.AppLifetime = p.ask.Account, ltApp, p.ask.Lifetime
+ }
+ if err := p.fx.st.BeginAllocation(a); err != nil {
+ t.Fatal(err)
+ }
+ if err := p.fx.st.SetAllocationState(a.OpID, lifetimeCommitted); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// deleted is the record as the delete retired it.
+func (p *proofFx) deleted(t *testing.T) provision.Record {
+ t.Helper()
+ return decodeRec(t, p.recBefore)
+}
+
+// requireVerdict holds v to one answer of the table. class is R1-pre (an
+// unreadable source before ownership), R1, S1, dup, R2, R4 to R8, or ok;
+// region is R5's <region>.
+func (p *proofFx) requireVerdict(t *testing.T, v restoreVerdict, class, region string) {
+ t.Helper()
+ host := ltOne
+ type answer struct {
+ owner, dup bool
+ status int
+ msg string
+ }
+ want := map[string]answer{
+ "R1-pre": {false, false, http.StatusServiceUnavailable, msgRestoreUnchecked(host)},
+ "R1": {true, false, http.StatusServiceUnavailable, msgRestoreUnchecked(host)},
+ "S1": {false, false, http.StatusConflict, msgHostUsed(host)},
+ "dup": {true, true, http.StatusConflict, msgInstanceExists(host)},
+ "R2": {true, false, http.StatusConflict, msgRestoreUnavailable(host)},
+ "R4": {true, false, http.StatusConflict, msgRestoreEarlierApp(host, ltApp)},
+ "R5": {true, false, http.StatusConflict, msgRestoreRegion(host, region)},
+ "R6": {true, false, http.StatusConflict, msgRestoreStaging(host)},
+ "R7": {true, false, http.StatusConflict, msgRestoreNotPlain(host)},
+ "R8": {true, false, http.StatusConflict, msgRestoreTooOld(host)},
+ }
+ if class == "ok" {
+ if v.Refusal != nil || !v.Owner || v.Duplicate {
+ t.Fatalf("verdict = %s, want eligible", describeVerdict(v))
+ }
+ e := evidenceOf(t, p.fx.st, ltOne)
+ if v.Region != region || v.RetirementOp != e.OpID || v.Body == nil || !reflect.DeepEqual(*v.Body, p.deleted(t)) {
+ t.Fatalf("eligible verdict = region %q op %q body %+v, want region %q op %q and the deleted record", v.Region, v.RetirementOp, v.Body, region, e.OpID)
+ }
+ return
+ }
+ w, ok := want[class]
+ if !ok {
+ t.Fatalf("no class %q", class)
+ }
+ if v.Refusal == nil || v.Owner != w.owner || v.Duplicate != w.dup || v.Refusal.Status != w.status || v.Refusal.Msg != w.msg {
+ t.Fatalf("verdict = %s, want %s: owner %v duplicate %v %d %q", describeVerdict(v), class, w.owner, w.dup, w.status, w.msg)
+ }
+ if v.Body != nil || v.Region != "" || v.RetirementOp != "" {
+ t.Fatalf("a refusal carries a body, region or op: %s", describeVerdict(v))
+ }
+}
+
+func describeVerdict(v restoreVerdict) string {
+ ref := "nil"
+ if v.Refusal != nil {
+ ref = fmt.Sprintf("%d %q", v.Refusal.Status, v.Refusal.Msg)
+ }
+ return fmt.Sprintf("{owner %v duplicate %v refusal %s region %q op %q}", v.Owner, v.Duplicate, ref, v.Region, v.RetirementOp)
+}
+
+// TestRestoreProof is the table, one input changed per case.
+func TestRestoreProof(t *testing.T) {
+ plainShape := func(p *proofFx, mutate func(*provision.Record)) *provision.Record {
+ rec := decodeRec(t, p.recBefore)
+ rec.Incarnation, rec.RecordSeq = 2, 0
+ mutate(&rec)
+ return &rec
+ }
+ cases := []struct {
+ name string
+ apply func(t *testing.T, p *proofFx)
+ class string
+ region string
+ }{
+ // Stage 1: ownership.
+ {"a mark of another account", func(t *testing.T, p *proofFx) {
+ p.setMark(t, provision.HostUse{Host: ltOne, Account: "zzz", App: ltApp, Kind: "instance", Source: "create"})
+ }, "S1", ""},
+ {"a mark of another app", func(t *testing.T, p *proofFx) {
+ p.setMark(t, provision.HostUse{Host: ltOne, Account: "bab", App: "blog", Kind: "instance", Source: "create"})
+ }, "S1", ""},
+ {"a slot of another app", func(t *testing.T, p *proofFx) {
+ p.setSlot(t, provision.HostIncarnation{Incarnation: 1, State: provision.SlotRetired, Account: "bab", App: "blog"})
+ }, "S1", ""},
+ {"a slot of another account", func(t *testing.T, p *proofFx) {
+ p.setSlot(t, provision.HostIncarnation{Incarnation: 1, State: provision.SlotRetired, Account: "zzz", App: ltApp})
+ }, "S1", ""},
+ {"an inventory mark with no owner", func(t *testing.T, p *proofFx) {
+ p.setMark(t, provision.HostUse{Host: ltOne, Kind: "inventory", Source: "activation"})
+ }, "S1", ""},
+ {"no mark", func(t *testing.T, p *proofFx) {
+ if err := p.fx.rel.Delete(context.Background(), provision.HostsUsedKey(ltOne)); err != nil {
+ t.Fatal(err)
+ }
+ }, "S1", ""},
+ {"no slot", func(t *testing.T, p *proofFx) {
+ if err := p.fx.rel.Delete(context.Background(), provision.HostIncarnationKey(ltOne)); err != nil {
+ t.Fatal(err)
+ }
+ }, "S1", ""},
+ {"an unreadable mark", func(t *testing.T, p *proofFx) { p.failGets(provision.HostsUsedKey(ltOne)) }, "R1-pre", ""},
+ {"a mark that does not decode", func(t *testing.T, p *proofFx) {
+ p.overwrite(t, provision.HostsUsedKey(ltOne), []byte("{"))
+ }, "R1-pre", ""},
+ {"an unreadable slot", func(t *testing.T, p *proofFx) { p.failGets(provision.HostIncarnationKey(ltOne)) }, "R1-pre", ""},
+ {"a malformed slot", func(t *testing.T, p *proofFx) {
+ p.overwrite(t, provision.HostIncarnationKey(ltOne), []byte(`{"incarnation":0}`))
+ }, "R1-pre", ""},
+ {"an unreadable slot behind a foreign mark", func(t *testing.T, p *proofFx) {
+ p.setMark(t, provision.HostUse{Host: ltOne, Account: "zzz", App: ltApp})
+ p.failGets(provision.HostIncarnationKey(ltOne))
+ }, "R1-pre", ""},
+ // Row 3 is TestRestoreProofPendingRetirement; a migration here.
+ {"a pending migration", func(t *testing.T, p *proofFx) {
+ if err := p.fx.st.BeginMigration(Migration{OpID: "m1", Account: "bab", App: ltApp, Host: ltOne}); err != nil {
+ t.Fatal(err)
+ }
+ }, "R1", ""},
+ // Row 4.
+ {"the owner's valid record and nothing pending", func(t *testing.T, p *proofFx) { p.reviveRecord(t) }, "dup", ""},
+ {"an unreadable record", func(t *testing.T, p *proofFx) { p.failGets(recKey(ltApp, ltOne)) }, "R1", ""},
+ // Row 5.
+ {"the history incomplete", func(t *testing.T, p *proofFx) {
+ forceHostsState(t, p.fx.srv, provision.HostsState{Mode: provision.HostsModeIncomplete})
+ }, "R2", ""},
+ {"the history invalidated", func(t *testing.T, p *proofFx) {
+ forceHostsState(t, p.fx.srv, provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: "test"})
+ }, "R2", ""},
+ {"an unreadable history mode", func(t *testing.T, p *proofFx) {
+ p.fx.srv.hosts.reset()
+ p.failGets(provision.HostsModeKey)
+ }, "R1", ""},
+ {"lifetimes off", func(t *testing.T, p *proofFx) { p.fx.srv.cutover = newCutoverGate(lifetimesNow) }, "R2", ""},
+ {"claims on", func(t *testing.T, p *proofFx) { p.fx.srv.cfg.HostClaim = true }, "R2", ""},
+ // Row 6.
+ {"the slot live with no valid record", func(t *testing.T, p *proofFx) { p.slotLive(t) }, "R8", ""},
+ // Row 7.
+ {"a lineage row on another app lifetime", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE host_allocations SET app_lifetime = 'feedfacefeedface' WHERE host = ?`, ltOne)
+ }, "R4", ""},
+ {"an earlier lifetime's row before a missing origin", func(t *testing.T, p *proofFx) {
+ p.commitAllocation(t, Allocation{OpID: "a2", Incarnation: 2, Account: "bab", App: ltApp, AppLifetime: "feedfacefeedface"})
+ p.exec(t, `UPDATE host_allocations SET restore_origin = 0 WHERE host = ?`, ltOne)
+ }, "R4", ""},
+ // Row 8.
+ {"no origin row", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE host_allocations SET restore_origin = 0 WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"no allocation at all", func(t *testing.T, p *proofFx) {
+ p.exec(t, `DELETE FROM host_allocations WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"a lineage row with neither flag", func(t *testing.T, p *proofFx) {
+ p.commitAllocation(t, Allocation{OpID: "a2", Incarnation: 2})
+ }, "R8", ""},
+ {"a lineage row with both flags", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE host_allocations SET restore_of = 'r0' WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"a lower row that is not the origin", func(t *testing.T, p *proofFx) {
+ // a0 below the origin, carrying restore_of: the origin at the
+ // slot's incarnation stays, so only "lowest is the origin" fails.
+ p.commitAllocation(t, Allocation{OpID: "a0", Incarnation: 1, RestoreOf: "r0"})
+ p.exec(t, `UPDATE host_allocations SET incarnation = 0 WHERE op_id = 'a0'`)
+ }, "R8", ""},
+ {"a lineage row of another account", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE host_allocations SET account = 'zzz' WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"no row at the slot's incarnation", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE host_allocations SET incarnation = 5 WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"a void row is not lineage", func(t *testing.T, p *proofFx) {
+ p.commitAllocation(t, Allocation{OpID: "a-void", Incarnation: 1})
+ p.exec(t, `UPDATE host_allocations SET state = 'void', incarnation = 0 WHERE op_id = 'a-void'`)
+ }, "ok", ""},
+ // Row 9.
+ {"the newest retirement not restorable", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE record_retirements SET restorable = 0 WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"the newest retirement a cleanup", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE record_retirements SET kind = ? WHERE host = ?`, retireCleanup, ltOne)
+ }, "R8", ""},
+ {"the newest retirement void", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE record_retirements SET state = ? WHERE host = ?`, lifetimeVoid, ltOne)
+ }, "R8", ""},
+ {"the newest retirement of another incarnation", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE record_retirements SET incarnation = 2 WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"the newest retirement of another app", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE record_retirements SET app = 'blog' WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"the newest retirement kept no body", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE record_retirements SET record_body = NULL WHERE host = ?`, ltOne)
+ }, "R8", ""},
+ {"the stored body of another host", func(t *testing.T, p *proofFx) {
+ p.setBody(t, func(r *provision.Record) { r.Host = ltFresh })
+ }, "R8", ""},
+ {"a newer unproven retirement hides an older restorable one", func(t *testing.T, p *proofFx) {
+ if err := p.fx.st.BeginRetirement(Retirement{OpID: "r2", Kind: retireOrphan, Account: "bab", App: ltApp, Host: ltOne, Incarnation: 1}); err != nil {
+ t.Fatal(err)
+ }
+ if err := p.fx.st.SetRetirementState("r2", lifetimeCommitted); err != nil {
+ t.Fatal(err)
+ }
+ p.exec(t, `UPDATE record_retirements SET created_at = created_at + 10 WHERE op_id = 'r2'`)
+ }, "R8", ""},
+ // Row 10.
+ {"a seeded stored body", func(t *testing.T, p *proofFx) {
+ p.setBody(t, func(r *provision.Record) { r.Seed = &provision.SeedSource{ID: "s1", Kind: "replica"} })
+ }, "R7", ""},
+ {"an HA stored body", func(t *testing.T, p *proofFx) { p.setBody(t, func(r *provision.Record) { r.HA = true }) }, "R7", ""},
+ {"a pooled stored body", func(t *testing.T, p *proofFx) { p.setBody(t, func(r *provision.Record) { r.Pool = "p1" }) }, "R7", ""},
+ {"an addr-backed stored body", func(t *testing.T, p *proofFx) {
+ p.setBody(t, func(r *provision.Record) { r.Addrs = []string{"127.0.0.1:9000"} })
+ }, "R7", ""},
+ {"a fleet-placed stored body", func(t *testing.T, p *proofFx) {
+ p.setBody(t, func(r *provision.Record) { r.Region = "fleet/acme" })
+ }, "R7", ""},
+ {"a replica stored body", func(t *testing.T, p *proofFx) { p.setBody(t, func(r *provision.Record) { r.Role = "replica" }) }, "R7", ""},
+ {"a rootfs stored body", func(t *testing.T, p *proofFx) {
+ p.setBody(t, func(r *provision.Record) { r.Runtime = provision.RuntimeRootfsV1 })
+ }, "R7", ""},
+ {"ask.From", func(t *testing.T, p *proofFx) { p.ask.From = true }, "R7", ""},
+ {"ask.Import", func(t *testing.T, p *proofFx) { p.ask.Import = true }, "R7", ""},
+ {"ask.Addrs", func(t *testing.T, p *proofFx) { p.ask.Addrs = []string{"127.0.0.1:9000"} }, "R7", ""},
+ {"ask.Role", func(t *testing.T, p *proofFx) { p.ask.Role = "replica" }, "R7", ""},
+ {"ask.Placement", func(t *testing.T, p *proofFx) { p.ask.Placement = "fleet/acme" }, "R7", ""},
+ {"ask.Pool", func(t *testing.T, p *proofFx) { p.ask.Pool = "p1" }, "R7", ""},
+ {"ask.Shape with a pool", func(t *testing.T, p *proofFx) {
+ p.ask.Shape = plainShape(p, func(r *provision.Record) { r.Pool = "p1" })
+ }, "R7", ""},
+ {"ask.Shape with HA", func(t *testing.T, p *proofFx) {
+ p.ask.Shape = plainShape(p, func(r *provision.Record) { r.HA = true })
+ }, "R7", ""},
+ {"ask.Shape plain", func(t *testing.T, p *proofFx) {
+ p.ask.Shape = plainShape(p, func(*provision.Record) {})
+ }, "ok", ""},
+ // Row 11.
+ {"the stored body in another region", func(t *testing.T, p *proofFx) {
+ p.setBody(t, func(r *provision.Record) { r.Region = "uk" })
+ }, "R5", "uk"},
+ {"the request naming another region", func(t *testing.T, p *proofFx) { p.ask.Region = "uk" }, "R5", "ie"},
+ {"ask.Shape in another region", func(t *testing.T, p *proofFx) {
+ p.ask.Shape = plainShape(p, func(r *provision.Record) { r.Region = "uk" })
+ }, "R5", "ie"},
+ {"the request naming the home region", func(t *testing.T, p *proofFx) {
+ p.ask.Region = p.fx.srv.homeRegionIn("ie")
+ }, "ok", ""},
+ // Row 12.
+ {"a move's build-state.json", func(t *testing.T, p *proofFx) {
+ p.stage(t, "moves/"+ltOne+"/build-state.json")
+ }, "R6", ""},
+ {"a move's replica level", func(t *testing.T, p *proofFx) {
+ p.stage(t, "moves/"+ltOne+"/0000/0000000000000001-0000000000000001.ltx")
+ }, "R6", ""},
+ {"staging of a longer hostname only", func(t *testing.T, p *proofFx) {
+ p.stage(t, "moves/"+ltOne+".au/build-state.json")
+ }, "ok", ""},
+ {"a staging list error", func(t *testing.T, p *proofFx) { p.data.fail = errBucketDown }, "R1", ""},
+ {"no data bucket", func(t *testing.T, p *proofFx) { p.fx.srv.cfg.SeedData = nil }, "R1", ""},
+ // Row 13.
+ {"all good", func(*testing.T, *proofFx) {}, "ok", ""},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ p := newProofFx(t)
+ c.apply(t, p)
+ p.requireVerdict(t, p.prove(), c.class, c.region)
+ })
+ }
+}
+
+// TestRestoreProofListsTheWholeStagingPrefix: the staging list asks for
+// moves/<host>/ with its trailing slash, in the data bucket.
+func TestRestoreProofListsTheWholeStagingPrefix(t *testing.T) {
+ p := newProofFx(t)
+ p.requireVerdict(t, p.prove(), "ok", "")
+ if want := []string{"moves/" + ltOne + "/"}; !reflect.DeepEqual(p.data.listed, want) {
+ t.Fatalf("listed %q, want %q", p.data.listed, want)
+ }
+}
+
+// TestRestoreProofStrangerReadsNothingMore: another owner is answered S1
+// from the mark alone; nothing past ownership is read for it (spec §3
+// item 1), so a failing staging list or record cannot change its answer.
+func TestRestoreProofStrangerReadsNothingMore(t *testing.T) {
+ p := newProofFx(t)
+ p.setMark(t, provision.HostUse{Host: ltOne, Account: "zzz", App: ltApp})
+ p.data.fail = errBucketDown
+ p.failGets(recKey(ltApp, ltOne))
+ p.requireVerdict(t, p.prove(), "S1", "")
+ if len(p.data.listed) != 0 {
+ t.Fatalf("listed %q for another owner, want nothing", p.data.listed)
+ }
+}
+
+// TestRestoreProofPendingRetirement (Review Focus 3): a delete pending
+// before N1 with the record still valid, after N1, and after N2 is R1 each
+// time, never the duplicate; once recovery settles it, the restore is
+// eligible.
+func TestRestoreProofPendingRetirement(t *testing.T) {
+ for _, step := range []string{"begin", "n1", "n2"} {
+ t.Run(step, func(t *testing.T) {
+ p := newProofBase(t)
+ r := p.pendingRetire(t, step)
+ if step == "begin" {
+ raw, _ := rawOf(t, p.fx.rel, ltApp, ltOne)
+ obs := p.fx.srv.judge.Observe(context.Background(), p.fx.rel, "bab", ltApp, ltOne)
+ if raw == nil || !validRecord(obs) {
+ t.Fatalf("fixture: before N1 the record is %s (%v), want it valid", raw, obs.Verdict)
+ }
+ }
+ p.requireVerdict(t, p.prove(), "R1", "")
+ p.recoveredTo(t, r.OpID, lifetimeCommitted)
+ p.requireVerdict(t, p.prove(), "ok", "")
+ })
+ }
+}
+
+// TestRestoreProofStaticKind: a request for a static or service route is
+// R7 at the early call, before any shape is built.
+func TestRestoreProofStaticKind(t *testing.T) {
+ for _, kind := range []string{"static", "service"} {
+ t.Run(kind, func(t *testing.T) {
+ p := newProofFx(t)
+ p.ask.Kind = kind
+ p.requireVerdict(t, p.prove(), "R7", "")
+ })
+ }
+ t.Run("instance", func(t *testing.T) {
+ p := newProofFx(t)
+ p.ask.Kind = "instance"
+ p.requireVerdict(t, p.prove(), "ok", "")
+ })
+}
+
+// TestRestoreProofTakesNoLocks: the proof answers while the caller holds
+// the app lock and the hostname exclusion for the same host, as the
+// deciding call does, and asks for no lock of its own.
+func TestRestoreProofTakesNoLocks(t *testing.T) {
+ p := newProofFx(t)
+ srv := p.fx.srv
+ unlockApp := srv.lockApp("bab", ltApp)
+ unlockHost := srv.lockHostname(ltOne)
+ defer unlockApp()
+ defer unlockHost()
+ var mu sync.Mutex
+ var events []string
+ hook := func(kind, key, event string) {
+ mu.Lock()
+ events = append(events, kind+" "+key+" "+event)
+ mu.Unlock()
+ }
+ lifetimeLockHook.Store(&hook)
+ defer lifetimeLockHook.Store(nil)
+ done := make(chan restoreVerdict, 1)
+ go func() { done <- p.prove() }()
+ select {
+ case v := <-done:
+ p.requireVerdict(t, v, "ok", "")
+ case <-time.After(time.Second):
+ t.Fatal("the proof did not answer within 1 s under the caller's locks")
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if len(events) != 0 {
+ t.Fatalf("the proof took locks: %q", events)
+ }
+}
+
+// proofRow is one row of the admission table as a state builder: apply
+// makes the row's condition hold on an otherwise eligible fixture, and
+// class is the row's answer. TestRestoreProofPrecedence composes them.
+type proofRow struct {
+ n int
+ name string
+ class string
+ region string
+ apply func(t *testing.T, p *proofFx)
+}
+
+// proofRows is the admission table, rows 1 to 12, in its order. Each
+// builder touches its own input, so any two compose.
+func proofRows() []proofRow {
+ return []proofRow{
+ {1, "the mark cannot be read", "R1-pre", "", func(t *testing.T, p *proofFx) { p.failGets(provision.HostsUsedKey(ltOne)) }},
+ {2, "the mark names another account", "S1", "", func(t *testing.T, p *proofFx) {
+ p.setMark(t, provision.HostUse{Host: ltOne, Account: "zzz", App: ltApp, Kind: "instance", Source: "create"})
+ }},
+ {3, "a migration is pending", "R1", "", func(t *testing.T, p *proofFx) {
+ if err := p.fx.st.BeginMigration(Migration{OpID: "m1", Account: "bab", App: ltApp, Host: ltOne}); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ {4, "the owner's record stands", "dup", "", func(t *testing.T, p *proofFx) { p.reviveRecord(t) }},
+ {5, "the history is incomplete", "R2", "", func(t *testing.T, p *proofFx) {
+ forceHostsState(t, p.fx.srv, provision.HostsState{Mode: provision.HostsModeIncomplete})
+ }},
+ {6, "the slot is live", "R8", "", func(t *testing.T, p *proofFx) { p.slotLive(t) }},
+ {7, "a lineage row of another app lifetime", "R4", "", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE host_allocations SET app_lifetime = 'feedfacefeedface' WHERE host = ?`, ltOne)
+ }},
+ {8, "no origin", "R8", "", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE host_allocations SET restore_origin = 0 WHERE host = ?`, ltOne)
+ }},
+ {9, "the newest retirement is not restorable", "R8", "", func(t *testing.T, p *proofFx) {
+ p.exec(t, `UPDATE record_retirements SET restorable = 0 WHERE host = ?`, ltOne)
+ }},
+ {10, "the request is a seed", "R7", "", func(t *testing.T, p *proofFx) { p.ask.From = true }},
+ {11, "the request names another region", "R5", "ie", func(t *testing.T, p *proofFx) { p.ask.Region = "uk" }},
+ {12, "a move's staging", "R6", "", func(t *testing.T, p *proofFx) { p.stage(t, "moves/"+ltOne+"/build-state.json") }},
+ }
+}
+
+// TestRestoreProofPrecedence: for every pair of rows i < j, a state where
+// both apply answers row i. Each row alone answers itself too.
+func TestRestoreProofPrecedence(t *testing.T) {
+ rows := proofRows()
+ for i, row := range rows {
+ if row.n != i+1 {
+ t.Fatalf("row %d is numbered %d", i+1, row.n)
+ }
+ t.Run(fmt.Sprintf("%d alone", row.n), func(t *testing.T) {
+ p := newProofFx(t)
+ row.apply(t, p)
+ p.requireVerdict(t, p.prove(), row.class, row.region)
+ })
+ }
+ for i := range rows {
+ for j := i + 1; j < len(rows); j++ {
+ ri, rj := rows[i], rows[j]
+ t.Run(fmt.Sprintf("%d over %d", ri.n, rj.n), func(t *testing.T) {
+ p := newProofFx(t)
+ rj.apply(t, p)
+ ri.apply(t, p)
+ p.requireVerdict(t, p.prove(), ri.class, ri.region)
+ })
+ }
+ }
+}
+
+// TestRestoreCopyApproved: every restore string is the approved text
+// (docs/superpowers/notes/instance-restore-658-copy.json), placeholders
+// filled.
+func TestRestoreCopyApproved(t *testing.T) {
+ raw, err := os.ReadFile("../../docs/superpowers/notes/instance-restore-658-copy.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var deck struct {
+ Strings []struct{ ID, Text string }
+ }
+ if err := json.Unmarshal(raw, &deck); err != nil {
+ t.Fatal(err)
+ }
+ approved := map[string]string{}
+ for _, s := range deck.Strings {
+ approved[s.ID] = s.Text
+ }
+ fill := strings.NewReplacer("<host>", "h.example.com", "<app>", "shop", "<region>", "ie")
+ for id, got := range map[string]string{
+ "restore.R1": msgRestoreUnchecked("h.example.com"),
+ "restore.R2": msgRestoreUnavailable("h.example.com"),
+ "restore.R4": msgRestoreEarlierApp("h.example.com", "shop"),
+ "restore.R5": msgRestoreRegion("h.example.com", "ie"),
+ "restore.R6": msgRestoreStaging("h.example.com"),
+ "restore.R7": msgRestoreNotPlain("h.example.com"),
+ "restore.R8": msgRestoreTooOld("h.example.com"),
+ "restore.C2": msgRestoreHint("h.example.com"),
+ } {
+ text, ok := approved[id]
+ if !ok {
+ t.Fatalf("no approved string %s", id)
+ }
+ if want := fill.Replace(text); got != want {
+ t.Errorf("%s = %q, want %q", id, got, want)
+ }
+ }
+}
diff --git a/internal/console/restore_staging.go b/internal/console/restore_staging.go
new file mode 100644
index 000000000..724385fb0
--- /dev/null
+++ b/internal/console/restore_staging.go
@@ -0,0 +1,54 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// hostHasStaging is a restore's staging check (instance restore #658, spec
+// §3 item 3): whether host's move staging prefix moves/<host>/ in this
+// console region's data bucket holds any object at all, of any name. It is
+// the boundary promotion mirrors (activator backend_exec.go
+// promoteStagedReplica lists MovesPrefix(host) and copies all of it), so a
+// build-state.json alone counts, unlike the leftover rail's LTX-only test
+// (hostHoldsReplicaData). The trailing slash keeps app.example.co from
+// seeing app.example.com's keys.
+//
+// The listing is the bounded one the HA leftover rail uses on the same
+// bucket (firstHALeftover): one key, then stop. Every error is returned,
+// never read as empty, and a console with no data bucket cannot check.
+func (s *Server) hostHasStaging(ctx context.Context, host string) (bool, error) {
+ if !provision.ValidHostShape(host) {
+ return false, fmt.Errorf("%q is not a hostname", host)
+ }
+ if s.cfg.SeedData == nil || s.cfg.HibernateBucket == "" {
+ return false, errors.New("no data bucket on this console")
+ }
+ pages, ok := s.cfg.SeedData.(release.PageLister)
+ if !ok {
+ return false, errors.New("the data bucket has no bounded listing")
+ }
+ prefix := activator.MovesPrefix(host)
+ if !strings.HasSuffix(prefix, "/") {
+ return false, fmt.Errorf("staging prefix %q has no trailing slash", prefix)
+ }
+ ctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout)
+ defer cancel()
+ keys, err := pages.ListPage(ctx, prefix, "", 1)
+ if err != nil {
+ return false, err
+ }
+ if len(keys) == 0 {
+ return false, nil
+ }
+ if !strings.HasPrefix(keys[0], prefix) {
+ return false, errors.New("the staging listing returned a key outside the prefix")
+ }
+ return true, nil
+}