carlos / platform Public

console: restore a deleted instance through the create door (#658)

The instance create body gains "restore": true. Right after the app's
placement and pool are read, the door asks restoreProof (no lock,
advisory): another owner gets S1, the owner R1, the duplicate or the
detailed refusal. An eligible restore takes the stored body's region,
skips the app-region default and the leftover rail, and meets every
other region and placement check unchanged.

In createRecordWithLifetimeLocked, right after the regional recheck and
before admission and planning, whatever the record's kind, the deciding
restoreProof runs under the held locks about the record being written.
Its verdict alone decides: a duplicate is ErrCASConflict, a refusal a
hostsUsedError, and eligible lets markForCreate's S1 pass and records
restore_of. A restore never carries the origin flag.

C2: an ordinary create from the instance door whose mark step answers
S1 asks restoreProof about its record; only when a restore would pass
does the message become the restore hint. The answer of a restore
carries "restore": true. The census layer's entry for
createRecordWithLifetimeLocked is re-fingerprinted (same class).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b908ffb953a85477b91d8694b98c44cc5f8ce4f2 parent 5522942
5 files changed, +975 −27
  • internal/console/apiinstances.go +79 −25
  • internal/console/lifetimes_create.go +33 −1
  • internal/console/restore_door.go +65 −0
  • internal/console/restore_door_test.go +789 −0
  • internal/provision/instance_restore_658_census_test.go +9 −1
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 940b18c09..db565f34d 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -68,6 +68,9 @@ const (
// instanceCreateAfterClaimCheck: the door's holder and claim checks
// have been judged and admitted the host; no lock is held.
instanceCreateAfterClaimCheck = "after-claim-check"
+ // instanceCreateAfterRestoreProof: a restore's early restoreProof was
+ // eligible (instance restore #658); no lock is held.
+ instanceCreateAfterRestoreProof = "after-restore-proof"
// instanceCreateAfterRecordWrite: the record write returned with the
// record written, still inside the app lock and the host exclusion
// (createRecordMarked, createRecordWithLifetime).
@@ -1458,6 +1461,10 @@ type apiRecordView struct {
// RegionLabel is the record's region label (region labels spec §4),
// on every create, a fleet-placed one included ("fleet <name>").
RegionLabel string `json:"region_label,omitempty"`
+ // Restore says the create door accepted this record as a restore
+ // (instance restore #658, spec §3). It does not claim data came back:
+ // the first wake finds whatever the replica holds.
+ Restore bool `json:"restore,omitempty"`
}
func recordView(rec provision.Record) apiRecordView {
@@ -1618,6 +1625,10 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// naming it. Ignored for an unowned environment. A team credential
// sends none; the scoped registration already decided its reach.
Scope string `json:"scope"`
+ // Restore brings a deleted instance back over its own hostname
+ // (instance restore #658, spec §3): the same create, decided by
+ // restoreProof at the door and again under the core's locks.
+ Restore bool `json:"restore"`
}
if !readJSON(w, r, &req) {
return
@@ -1803,16 +1814,47 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
jsonError(w, http.StatusConflict, demoCopy["DEMO-POLICY"])
return
}
+ // A restore (instance restore #658, spec §3 item 1): ownership, then
+ // eligibility, before region resolution, the leftover rail or any other
+ // history-dependent check. Another owner is answered S1 whatever else
+ // is wrong with the request. This call holds no lock and is advisory:
+ // the deciding one runs under the create core's locks
+ // (createRecordWithLifetimeLocked), and its verdict alone decides.
+ var restore *restoreAsk
+ restoreRegion := ""
+ if req.Restore {
+ ask := restoreAsk{Account: acct.Sqid, App: app, Lifetime: lifetime, Host: host,
+ Region: s.homeRegionIn(strings.TrimSpace(req.Region)), RegionSpecified: strings.TrimSpace(req.Region) != "",
+ AccountID: acct.ID, Kind: strings.TrimSpace(req.Kind), Role: strings.TrimSpace(req.Role),
+ Placement: placed, Pool: m.Pool, Addrs: req.Addrs, From: req.From != nil, Import: req.Import != nil}
+ v := s.restoreProof(ctx, ask)
+ if v.Refusal != nil {
+ writeDoorRefusalJSON(w, r, v.Refusal)
+ return
+ }
+ // Row 5 as this request was admitted: a unit admitted before the
+ // cutover never reaches the lifetime create, so it cannot restore.
+ if !lifetimesUnit(r.Context()) {
+ jsonError(w, http.StatusConflict, msgRestoreUnavailable(host))
+ return
+ }
+ restore, restoreRegion = &ask, v.Region
+ instanceCreateStage(instanceCreateAfterRestoreProof, host)
+ }
// The app's region is the default for a create that names none
// (nearest-region spec §7, R2). It runs BEFORE every check an explicit
// region meets, and never for a fleet-placed app, a replica, or anything
// but a socket-backed instance. Named pools need explicit HA membership.
+ // A restore takes the stored body's region instead (spec §3 item 2) and
+ // meets every check after this one unchanged.
raw := strings.TrimSpace(req.Region)
regionFrom := ""
if raw != "" {
regionFrom = "request"
}
- if raw == "" && placed == "" && strings.TrimSpace(req.Role) == "" &&
+ if restore != nil {
+ raw = restoreRegion
+ } else if raw == "" && placed == "" && strings.TrimSpace(req.Role) == "" &&
(provision.Record{Kind: strings.TrimSpace(req.Kind), Addrs: req.Addrs}).DerivesPaths() {
appRegion, _, err := s.appRegion(acct.ID, app)
if err != nil {
@@ -2292,28 +2334,34 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// the new record cannot inherit that database. Last of the checks, after
// every validation above, and BEFORE the store walk below, so a refused
// create never provisions a bucket either.
- if ref := s.leftoverReplicaRefusal(r.Context(), leftoverCreate{
- HAData: s.shouldStampHA(rec) && !seeded && rec.DerivesPaths(),
- logTag: "api instances create " + acct.Sqid + "/" + app,
- host: host, region: region, pool: rec.Pool,
- exists: func(ctx context.Context) (bool, error) {
- // Judged when admitted on (a nil judge is GetRecord): a stale
- // body is no record, and the create replaces it.
- _, _, err := s.readRecord(ctx, acct.Sqid, app, host)
- if errors.Is(err, os.ErrNotExist) {
- return false, nil
- }
- return err == nil, err
- },
- // The same two answers the CreateRecord call below gives.
- duplicate: doorRefusal{Status: http.StatusConflict, Msg: "instance " + host + " already exists"},
- readFailed: doorRefusal{Status: http.StatusBadGateway, Msg: "could not create the instance — try again"},
- taken: host + " still holds data from a deleted instance. Choose another address, or ask an operator to purge it.",
- unsure: "could not check whether " + host + " is free. Try again.",
- }); ref != nil {
- setNoCapacityRetryAfter(w, ref)
- jsonError(w, ref.Status, ref.Msg)
- return
+ //
+ // A restore never asks it (spec §3 item 4): the replica under its own
+ // hostname is the data it brings back, and its duplicate and staging
+ // answers are restoreProof's (the admission table's rows 4 and 12).
+ if restore == nil {
+ if ref := s.leftoverReplicaRefusal(r.Context(), leftoverCreate{
+ HAData: s.shouldStampHA(rec) && !seeded && rec.DerivesPaths(),
+ logTag: "api instances create " + acct.Sqid + "/" + app,
+ host: host, region: region, pool: rec.Pool,
+ exists: func(ctx context.Context) (bool, error) {
+ // Judged when admitted on (a nil judge is GetRecord): a stale
+ // body is no record, and the create replaces it.
+ _, _, err := s.readRecord(ctx, acct.Sqid, app, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ return err == nil, err
+ },
+ // The same two answers the CreateRecord call below gives.
+ duplicate: doorRefusal{Status: http.StatusConflict, Msg: "instance " + host + " already exists"},
+ readFailed: doorRefusal{Status: http.StatusBadGateway, Msg: "could not create the instance — try again"},
+ taken: host + " still holds data from a deleted instance. Choose another address, or ask an operator to purge it.",
+ unsure: "could not check whether " + host + " is free. Try again.",
+ }); ref != nil {
+ setNoCapacityRetryAfter(w, ref)
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
}
// Plain, seeded and imported creates hold the account lock even without
// plans: fleet key replacement checks their records under the same lock.
@@ -2510,10 +2558,15 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// Dispatch by the admitted unit (lifetimes.go): the lifetime
// create, which answers the record as written. A seeded or imported
// create left this handler above; this plain one may record a
- // restore origin (restore_origin.go), and only for this call.
+ // restore origin (restore_origin.go), and only for this call. A
+ // restore carries its intent instead, never the origin: the core
+ // decides it again under its locks (restore_door.go).
var created *provision.Record
originCtx := ctx
- if req.From == nil && req.Import == nil {
+ switch {
+ case restore != nil:
+ originCtx = withRestore(ctx, *restore)
+ case req.From == nil && req.Import == nil:
originCtx = withOriginEligible(ctx)
}
if created, recordWriteErr = s.createRecordWithLifetime(originCtx, rec, lifetime); recordWriteErr == nil {
@@ -2600,6 +2653,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
out := recordView(rec)
out.PrivateStoreBucket = privateBucket
out.RegionFrom = regionFrom
+ out.Restore = restore != nil
// Every non-fleet placement is named, replicas included (codex
// plan-R3 6); a fleet-placed record's Region is the fleet itself.
if placed == "" {
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go
index 3a345a182..aa00b1354 100644
--- a/internal/console/lifetimes_create.go
+++ b/internal/console/lifetimes_create.go
@@ -95,6 +95,25 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi
if err := s.regionalRecheck(ctx, rec); err != nil {
return nil, err
}
+ // A restore's deciding evaluation (instance restore #658, spec §3 items
+ // 1 and 5): both stages again, under the app lock and the hostname
+ // exclusion held here, about the record about to be written, and before
+ // anything below may answer for it, whatever the record's kind. Its
+ // verdict alone decides the restore for the rest of this hold.
+ ask, restoring := restoreFrom(ctx)
+ var restored restoreVerdict
+ if restoring {
+ ask.Account, ask.App, ask.Host, ask.AccountID, ask.Lifetime = rec.Account, rec.App, host, acct.ID, life.Lifetime
+ shape := rec
+ ask.Shape = &shape
+ restored = s.restoreProof(ctx, ask)
+ switch {
+ case restored.Duplicate:
+ return nil, fmt.Errorf("console: lifetimes: restore %s: a record of this lifetime exists: %w", host, release.ErrCASConflict)
+ case restored.Refusal != nil:
+ return nil, &hostsUsedError{*restored.Refusal}
+ }
+ }
// Step 1.
if err := s.admit(host, ""); err != nil {
return nil, err
@@ -141,7 +160,17 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi
return nil, &hostsUsedError{*ref}
}
var ref *doorRefusal
- if obs, ref = s.markForCreate(ctx, recordUse(rec)); ref != nil {
+ obs, ref = s.markForCreate(ctx, recordUse(rec))
+ switch {
+ case ref == nil:
+ case markConflicted(ref, host) && restoring:
+ // The mark is this lineage's own: the deciding evaluation read
+ // it naming this account and app, and found the restore
+ // eligible. Nothing else passes a conflicting mark.
+ case markConflicted(ref, host):
+ // C2: S1, unless a restore of this same request would pass.
+ return nil, &hostsUsedError{s.restoreHint(ctx, rec, acct.ID, life.Lifetime, *ref)}
+ default:
return nil, &hostsUsedError{*ref}
}
}
@@ -152,6 +181,9 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi
// check, never the first. A restore never sets it (it sets RestoreOf).
a.RestoreOrigin = originEligible(ctx) && rec.DataKind() && obs.fresh && obs.active && s.lifetimesOn() &&
rec.Seed == nil && rec.Demo == nil && rec.DemoClaim == nil
+ if restoring {
+ a.RestoreOf = restored.RetirementOp
+ }
if err := s.store.BeginAllocation(a); err != nil {
return nil, fmt.Errorf("console: lifetimes: begin allocation of %s: %w", host, err)
}
diff --git a/internal/console/restore_door.go b/internal/console/restore_door.go
new file mode 100644
index 000000000..1a11dc122
--- /dev/null
+++ b/internal/console/restore_door.go
@@ -0,0 +1,65 @@
+package console
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The restore intent (instance restore #658, spec §3). Only the instance
+// door (handleAPIInstanceCreate) sets it, on the context it hands the
+// lifetime create core for a request with "restore": true whose early
+// restoreProof was eligible, and only for that one call. The core then runs
+// the deciding restoreProof under its locks and acts on that verdict alone.
+// A restore never carries the origin flag (restore_origin.go): its
+// allocation records restore_of instead.
+
+type restoreKey struct{}
+
+// withRestore marks ctx as a restore asked as ask. Its Shape is ignored: the
+// core asks about the record it is about to write.
+func withRestore(ctx context.Context, ask restoreAsk) context.Context {
+ ask.Shape = nil
+ return context.WithValue(ctx, restoreKey{}, ask)
+}
+
+// restoreFrom is the restore ctx carries, if it carries one.
+func restoreFrom(ctx context.Context) (restoreAsk, bool) {
+ ask, ok := ctx.Value(restoreKey{}).(restoreAsk)
+ return ask, ok
+}
+
+// markConflicted reports whether ref is the refusal markForCreate answers
+// for a mark already there once the history is active (S1). It is the only
+// 409 markForCreate answers; markHost's own refusals are 503s.
+func markConflicted(ref *doorRefusal, host string) bool {
+ return ref != nil && ref.Status == http.StatusConflict && ref.Msg == msgHostUsed(host)
+}
+
+// restoreHint is C2 (spec §3, §7): an ordinary create whose mark step
+// answered S1 is told how to restore when a restore of the same request
+// would pass both stages, and only then. It asks restoreProof about the
+// record the create was about to write, under the locks the core holds.
+// Only the instance door's plain create can be the same request with
+// --restore (a seed or import is never plain, row 10), so any other caller
+// keeps S1 without asking. Every other verdict, another owner's above all,
+// keeps s1 byte for byte.
+func (s *Server) restoreHint(ctx context.Context, rec provision.Record, accountID int64, lifetime string, s1 doorRefusal) doorRefusal {
+ if !originEligible(ctx) {
+ return s1
+ }
+ placement := ""
+ if _, fleet := registry.FleetPlacement(rec.Region); fleet {
+ placement = rec.Region
+ }
+ shape := rec
+ v := s.restoreProof(ctx, restoreAsk{Account: rec.Account, App: rec.App, Lifetime: lifetime, Host: rec.Host,
+ Region: rec.Region, RegionSpecified: true, AccountID: accountID,
+ Kind: rec.Kind, Role: rec.Role, Placement: placement, Pool: rec.Pool, Addrs: rec.Addrs, Shape: &shape})
+ if v.Refusal != nil || !v.Owner || v.Duplicate {
+ return s1
+ }
+ return doorRefusal{Status: s1.Status, Msg: msgRestoreHint(rec.Host)}
+}
diff --git a/internal/console/restore_door_test.go b/internal/console/restore_door_test.go
new file mode 100644
index 000000000..822b867e8
--- /dev/null
+++ b/internal/console/restore_door_test.go
@@ -0,0 +1,789 @@
+package console
+
+// The restore door (instance restore #658, plan Task 6; spec §3). Driven
+// through the real create and delete doors of a claims-off console with
+// lifetimes on and the history active (newProofFx: one.shop.example.com
+// created with its origin, then deleted), over the ltStore bucket and the
+// stagingStore data bucket, with the leftover rail reading real litestream
+// replicas on disk.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ lsfile "github.com/benbjohnson/litestream/file"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// doorFx is a proofFx whose leftover rail reads replicas under root.
+type doorFx struct {
+ *proofFx
+ root string
+}
+
+// doorOver gives p's console a replica root for the leftover rail and the
+// instances prefix, as a deployment with a data bucket has.
+func doorOver(t *testing.T, p *proofFx) *doorFx {
+ t.Helper()
+ root := t.TempDir()
+ srv := p.fx.srv
+ srv.cfg.HibernatePrefix = "instances"
+ srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
+ }
+ return &doorFx{proofFx: p, root: root}
+}
+
+// newDoorFx is the eligible state: ltOne created and deleted through the
+// doors.
+func newDoorFx(t *testing.T) *doorFx {
+ t.Helper()
+ return doorOver(t, newProofFx(t))
+}
+
+func restoreBody(extra string) string {
+ return `{"host":"` + ltOne + `","restore":true` + extra + `}`
+}
+
+func ordinaryBody(extra string) string {
+ return `{"host":"` + ltOne + `"` + extra + `}`
+}
+
+// post sends body to the owner's instance door.
+func (d *doorFx) post(t *testing.T, body string) (int, string) {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodPost, instancesURL(d.fx, "bab", ltApp), d.member, body)
+ return code, out
+}
+
+func (d *doorFx) restore(t *testing.T, extra string) (int, string) {
+ t.Helper()
+ return d.post(t, restoreBody(extra))
+}
+
+// async sends body to url without blocking; the answer arrives on the channel.
+func (d *doorFx) async(url, body string) <-chan rdAnswer {
+ done := make(chan rdAnswer, 1)
+ go func() { done <- rdDo(http.MethodPost, url, d.member, body) }()
+ return done
+}
+
+func (d *doorFx) url() string { return instancesURL(d.fx, "bab", ltApp) }
+
+// leaveReplica writes a real litestream replica where the deleted record's
+// activator left it: instances/<host>.
+func (d *doorFx) leaveReplica(t *testing.T) {
+ t.Helper()
+ dbdoortest.Replicate(t, filepath.Join(d.root, activator.HibernatePrefix("instances", ltOne)), 1)
+}
+
+// requireAnswer fails unless the door answered status with msg as its error.
+func requireAnswer(t *testing.T, code int, out string, status int, msg, what string) {
+ t.Helper()
+ if code != status || ltErr(out) != msg {
+ t.Fatalf("%s = %d %s, want %d %q", what, code, out, status, msg)
+ }
+}
+
+// requireNoRestoreWrite: the only allocation of ltOne is the origin, and no
+// record stands under the key.
+func (d *doorFx) requireNoRestoreWrite(t *testing.T, allocs int) {
+ t.Helper()
+ if rows := allocRows(t, d.fx.st, ltOne); len(rows) != allocs {
+ t.Fatalf("allocations of %s = %+v, want %d", ltOne, rows, allocs)
+ }
+}
+
+func (d *doorFx) requireNoRecord(t *testing.T) {
+ t.Helper()
+ if raw, _ := rawOf(t, d.fx.rel, ltApp, ltOne); raw != nil {
+ t.Fatalf("a record stands under %s: %s", ltOne, raw)
+ }
+}
+
+// requireRestored: the door answered 201 with "restore": true; the record
+// under the key is the deleted one's host and region at incarnation n; and
+// the newest allocation carries restore_of naming the newest retirement,
+// and no origin.
+func (d *doorFx) requireRestored(t *testing.T, code int, out string, n uint64) provision.Record {
+ t.Helper()
+ if code != http.StatusCreated {
+ t.Fatalf("restore = %d %s, want 201", code, out)
+ }
+ var reply map[string]any
+ if err := json.Unmarshal([]byte(out), &reply); err != nil {
+ t.Fatalf("restore answer %s: %v", out, err)
+ }
+ if reply["restore"] != true {
+ t.Fatalf("restore answer %s, want \"restore\": true", out)
+ }
+ raw, _ := rawOf(t, d.fx.rel, ltApp, ltOne)
+ if raw == nil {
+ t.Fatal("no record after a 201 restore")
+ }
+ rec := decodeRec(t, raw)
+ deleted := d.deleted(t)
+ if rec.Host != deleted.Host || rec.Region != deleted.Region || rec.Incarnation != n || rec.Retired {
+ t.Fatalf("restored record = host %q region %q incarnation %d retired %v, want %q %q %d live",
+ rec.Host, rec.Region, rec.Incarnation, rec.Retired, deleted.Host, deleted.Region, n)
+ }
+ if reply["host"] != rec.Host {
+ t.Fatalf("restore answer names %v, want %s", reply["host"], rec.Host)
+ }
+ rows := lineage(t, d.fx.st, ltOne)
+ last := rows[len(rows)-1]
+ e := evidenceOf(t, d.fx.st, ltOne)
+ if last.Incarnation != n || last.RestoreOf != e.OpID || last.RestoreOrigin || last.State != lifetimeCommitted {
+ t.Fatalf("the restore's allocation = %+v, want committed at %d, restore_of %s, no origin", last, n, e.OpID)
+ }
+ return rec
+}
+
+// parkFirst holds the first create of ltOne that reaches stage until the
+// gate opens; every later one passes.
+func parkFirst(t *testing.T, stage string) *pauseGate {
+ t.Helper()
+ g := newPauseGate()
+ var first atomic.Bool
+ h := func(s, host string) {
+ if s != stage || host != ltOne || !first.CompareAndSwap(false, true) {
+ return
+ }
+ close(g.entered)
+ select {
+ case <-g.release:
+ case <-time.After(10 * time.Second):
+ t.Errorf("timed out releasing the create parked at %s", stage)
+ }
+ }
+ instanceCreateHook.Store(&h)
+ t.Cleanup(func() {
+ g.open()
+ instanceCreateHook.Store(nil)
+ })
+ return g
+}
+
+func awaitAnswer(t *testing.T, ch <-chan rdAnswer, what string) rdAnswer {
+ t.Helper()
+ a := await(t, ch, what)
+ if a.err != nil {
+ t.Fatalf("%s: %v", what, a.err)
+ }
+ return a
+}
+
+func TestRestoreRoundTrip(t *testing.T) {
+ d := newDoorFx(t)
+ d.leaveReplica(t) // the deleted instance's replica rows, keyed by host alone
+ code, out := d.restore(t, "")
+ d.requireRestored(t, code, out, 2)
+ if rows := lineage(t, d.fx.st, ltOne); len(rows) != 2 || !rows[0].RestoreOrigin {
+ t.Fatalf("lineage = %+v, want the origin then the restore", rows)
+ }
+ slot, _ := slotOf(t, d.fx.rel, ltOne)
+ if slot == nil || slot.Incarnation != 2 || slot.State != provision.SlotLive || slot.Account != "bab" || slot.App != ltApp {
+ t.Fatalf("slot = %+v, want live at 2 for bab/%s", slot, ltApp)
+ }
+}
+
+// TestRestoreTwice (Review Focus 4): delete, restore, delete, restore.
+func TestRestoreTwice(t *testing.T) {
+ d := newDoorFx(t)
+ code, out := d.restore(t, "")
+ d.requireRestored(t, code, out, 2)
+ if code, body := d.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent {
+ t.Fatalf("second delete = %d %s", code, body)
+ }
+ requireRetired(t, d.fx.rel, ltApp, ltOne, 2)
+ code, out = d.restore(t, "")
+ d.requireRestored(t, code, out, 3)
+ if rows := lineage(t, d.fx.st, ltOne); len(rows) != 3 {
+ t.Fatalf("lineage = %+v, want the origin and two restores", rows)
+ }
+}
+
+// TestRestoreRetriedAfterSuccess (Review Focus 2): the retry of a restore
+// that succeeded gets the create's duplicate answer, not R8.
+func TestRestoreRetriedAfterSuccess(t *testing.T) {
+ d := newDoorFx(t)
+ _, _ = d.restore(t, "") // the response is lost
+ code, out := d.restore(t, "")
+ requireAnswer(t, code, out, http.StatusConflict, msgInstanceExists(ltOne), "the retried restore")
+ d.requireNoRestoreWrite(t, 2)
+ if rec := decodeRec(t, mustRaw(t, d)); rec.Incarnation != 2 {
+ t.Fatalf("record at %d, want the first restore's 2", rec.Incarnation)
+ }
+}
+
+func mustRaw(t *testing.T, d *doorFx) []byte {
+ t.Helper()
+ raw, _ := rawOf(t, d.fx.rel, ltApp, ltOne)
+ if raw == nil {
+ t.Fatal("no record")
+ }
+ return raw
+}
+
+// TestRestoreRecordAppearsBetweenEvaluations: a record lands after the
+// early proof; the deciding one, under the locks, answers the duplicate.
+func TestRestoreRecordAppearsBetweenEvaluations(t *testing.T) {
+ d := newDoorFx(t)
+ g := parkFirst(t, instanceCreateAfterRestoreProof)
+ ch := d.async(d.url(), restoreBody(""))
+ await(t, g.entered, "the restore past its early proof")
+ d.reviveRecord(t)
+ g.open()
+ a := awaitAnswer(t, ch, "the restore")
+ requireAnswer(t, a.code, a.out, http.StatusConflict, msgInstanceExists(ltOne), "the restore")
+ d.requireNoRestoreWrite(t, 1)
+ if raw := mustRaw(t, d); string(raw) != string(d.recBefore) {
+ t.Fatalf("the record that landed was changed: %s", raw)
+ }
+}
+
+// TestRestorePendingAppearsBetweenEvaluations: something for the host goes
+// pending after the early proof; the deciding one answers R1 and writes no
+// allocation.
+func TestRestorePendingAppearsBetweenEvaluations(t *testing.T) {
+ t.Run("another restore's allocation, pending with no record", func(t *testing.T) {
+ d := newDoorFx(t)
+ g := parkFirst(t, instanceCreateAfterRestoreProof)
+ ch := d.async(d.url(), restoreBody(""))
+ await(t, g.entered, "the first restore past its early proof")
+ d.bucket.setHook(failNth("put", provision.HostIncarnationKey(ltOne), 1, false))
+ code, out := d.restore(t, "")
+ d.bucket.setHook(nil)
+ requireAnswer(t, code, out, http.StatusBadGateway, msgLifetimeCreatePending, "the second restore")
+ d.requireNoRecord(t)
+ rows := allocRows(t, d.fx.st, ltOne)
+ if len(rows) != 2 || rows[1].State != lifetimePending {
+ t.Fatalf("allocations = %+v, want the origin and one pending", rows)
+ }
+ g.open()
+ a := awaitAnswer(t, ch, "the first restore")
+ requireAnswer(t, a.code, a.out, http.StatusServiceUnavailable, msgRestoreUnchecked(ltOne), "the first restore")
+ d.requireNoRestoreWrite(t, 2)
+ d.requireNoRecord(t)
+ })
+ t.Run("a completed restore whose delete is pending before N1", func(t *testing.T) {
+ d := newDoorFx(t)
+ g := parkFirst(t, instanceCreateAfterRestoreProof)
+ ch := d.async(d.url(), restoreBody(""))
+ await(t, g.entered, "the first restore past its early proof")
+ code, out := d.restore(t, "")
+ d.requireRestored(t, code, out, 2)
+ d.pendingRetire(t, "begin")
+ raw := mustRaw(t, d)
+ g.open()
+ a := awaitAnswer(t, ch, "the first restore")
+ requireAnswer(t, a.code, a.out, http.StatusServiceUnavailable, msgRestoreUnchecked(ltOne), "the first restore")
+ d.requireNoRestoreWrite(t, 2)
+ if now := mustRaw(t, d); string(now) != string(raw) {
+ t.Fatalf("the record changed under a pending delete: %s", now)
+ }
+ })
+}
+
+// newUKDoorFx is newDoorFx on a console in uk whose home is ie: ltOne
+// created in uk through the door, then deleted.
+func newUKDoorFx(t *testing.T) *doorFx {
+ t.Helper()
+ l := newLtOn(t)
+ srv := l.fx.srv
+ srv.cfg.Region, srv.cfg.HomeRegion = "uk", "ie"
+ forceHostsState(t, srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"region:uk"}})
+ if code, _, out := rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", ltApp), l.member, ordinaryBody(`,"region":"uk"`)); code != http.StatusCreated {
+ t.Fatalf("create in uk = %d %s", code, out)
+ }
+ recBefore, _ := rawOf(t, l.fx.rel, ltApp, ltOne)
+ if code, body := l.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent {
+ t.Fatalf("delete = %d %s", code, body)
+ }
+ data := &stagingStore{DirStore: release.NewDirStore(t.TempDir())}
+ srv.cfg.SeedData, srv.cfg.HibernateBucket = data, "data-test"
+ 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 doorOver(t, &proofFx{ltOn: l, data: data, recBefore: recBefore,
+ ask: restoreAsk{Account: acct.Sqid, AccountID: acct.ID, App: ltApp, Lifetime: life.Lifetime, Host: ltOne}})
+}
+
+// TestRestoreRegion (Review Focus 5).
+func TestRestoreRegion(t *testing.T) {
+ for _, c := range []struct{ name, extra string }{
+ {"no region", ""},
+ {"the home region named", `,"region":"ie"`},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ d := newDoorFx(t)
+ code, out := d.restore(t, c.extra)
+ d.requireRestored(t, code, out, 2)
+ })
+ }
+ // A console outside the home restores what it holds, and only that.
+ for _, c := range []struct{ name, extra string }{
+ {"a uk console, no region", ""},
+ {"a uk console, its own region named", `,"region":"uk"`},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ d := newUKDoorFx(t)
+ code, out := d.restore(t, c.extra)
+ if rec := d.requireRestored(t, code, out, 2); rec.Region != "uk" {
+ t.Fatalf("restored into %q, want uk", rec.Region)
+ }
+ })
+ }
+ t.Run("a uk console, the home region named", func(t *testing.T) {
+ d := newUKDoorFx(t)
+ code, out := d.restore(t, `,"region":"ie"`)
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreRegion(ltOne, "uk"), "a restore naming ie on uk")
+ d.requireNoRecord(t)
+ })
+ t.Run("another region", func(t *testing.T) {
+ d := newDoorFx(t)
+ code, out := d.restore(t, `,"region":"uk"`)
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreRegion(ltOne, "ie"), "a restore naming uk")
+ d.requireNoRestoreWrite(t, 1)
+ d.requireNoRecord(t)
+ })
+ t.Run("the app's default region elsewhere", func(t *testing.T) {
+ d := newDoorFx(t)
+ d.fx.srv.appRegionOf = func(int64, string) (string, string, error) { return "uk", "", nil }
+ code, out := d.restore(t, "")
+ if rec := d.requireRestored(t, code, out, 2); rec.Region != "" {
+ t.Fatalf("restored into %q, want the stored body's home region", rec.Region)
+ }
+ })
+}
+
+// TestRestoreRefusesPlacedApp: a fleet placement or a manifest pool, gained
+// after the delete, is R7.
+func TestRestoreRefusesPlacedApp(t *testing.T) {
+ t.Run("fleet placement", func(t *testing.T) {
+ d := newDoorFx(t)
+ // Written directly: the placement door refuses a change while the
+ // history is active (fleets.go).
+ if err := d.fx.st.SetAppPlacement(d.ask.AccountID, ltApp, "fleet/acme"); err != nil {
+ t.Fatal(err)
+ }
+ code, out := d.restore(t, "")
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreNotPlain(ltOne), "a restore on a placed app")
+ d.requireNoRecord(t)
+ })
+ t.Run("manifest pool", func(t *testing.T) {
+ d := newDoorFx(t)
+ enableInstances(t, d.fx, ltApp, provision.Manifest{Schema: 1, App: ltApp, Domain: "shop.example.com", Channel: "stable", Pool: "p1"})
+ code, out := d.restore(t, "")
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreNotPlain(ltOne), "a restore on a pooled app")
+ d.requireNoRecord(t)
+ })
+}
+
+// TestRestoreKeepsRegionPolicy: the manifest's allow-list still applies,
+// with the ordinary create's own refusal.
+func TestRestoreKeepsRegionPolicy(t *testing.T) {
+ d := newDoorFx(t)
+ enableInstances(t, d.fx, ltApp, provision.Manifest{Schema: 1, App: ltApp, Domain: "shop.example.com", Channel: "stable", Regions: []string{"uk"}})
+ code, out := d.restore(t, "")
+ ordCode, _, ordOut := rawReq(t, http.MethodPost, d.url(), d.member, `{"host":"`+ltFresh+`"}`)
+ if ordCode != http.StatusBadRequest || !strings.Contains(ordOut, "not one this app runs in") {
+ t.Fatalf("fixture: an ordinary create = %d %s, want the region refusal", ordCode, ordOut)
+ }
+ if code != ordCode || out != ordOut {
+ t.Fatalf("restore = %d %s, want the ordinary create's %d %s", code, out, ordCode, ordOut)
+ }
+ d.requireNoRecord(t)
+}
+
+// TestRestoreStaticKindRefused: a static or service restore is R7 at the
+// door, and the core's deciding call cannot be skipped by a record that is
+// not a data kind.
+func TestRestoreStaticKindRefused(t *testing.T) {
+ for _, extra := range []string{`,"kind":"static"`, `,"kind":"service","addrs":["127.0.0.1:9000"]`} {
+ t.Run(extra, func(t *testing.T) {
+ d := newDoorFx(t)
+ code, out := d.restore(t, extra)
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreNotPlain(ltOne), "the restore")
+ d.requireNoRecord(t)
+ d.requireNoRestoreWrite(t, 1)
+ })
+ }
+ t.Run("the core, a static record", func(t *testing.T) {
+ d := newDoorFx(t)
+ rec := d.deleted(t)
+ rec.Kind = "static"
+ ctx := withRestore(onCtx(t, d.fx.srv), d.ask)
+ _, err := d.fx.srv.createRecordWithLifetime(ctx, rec, d.ask.Lifetime)
+ var used *hostsUsedError
+ if !errors.As(err, &used) || used.ref.Status != http.StatusConflict || used.ref.Msg != msgRestoreNotPlain(ltOne) {
+ t.Fatalf("the core's static restore = %v, want R7", err)
+ }
+ d.requireNoRecord(t)
+ d.requireNoRestoreWrite(t, 1)
+ })
+}
+
+// TestRestoreStagingRefused: any object under moves/<host>/ is R6, a
+// listing error R1, and staging that appears after the early proof is R6
+// from the deciding one.
+func TestRestoreStagingRefused(t *testing.T) {
+ for _, key := range []string{"moves/" + ltOne + "/build-state.json", "moves/" + ltOne + "/0000/0000000000000001-0000000000000001.ltx"} {
+ t.Run(key, func(t *testing.T) {
+ d := newDoorFx(t)
+ d.stage(t, key)
+ code, out := d.restore(t, "")
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreStaging(ltOne), "the restore")
+ d.requireNoRecord(t)
+ })
+ }
+ t.Run("a listing error", func(t *testing.T) {
+ d := newDoorFx(t)
+ d.data.fail = errBucketDown
+ code, out := d.restore(t, "")
+ requireAnswer(t, code, out, http.StatusServiceUnavailable, msgRestoreUnchecked(ltOne), "the restore")
+ d.requireNoRecord(t)
+ })
+ t.Run("staging between the evaluations", func(t *testing.T) {
+ d := newDoorFx(t)
+ g := parkFirst(t, instanceCreateAfterRestoreProof)
+ ch := d.async(d.url(), restoreBody(""))
+ await(t, g.entered, "the restore past its early proof")
+ d.stage(t, "moves/"+ltOne+"/build-state.json")
+ g.open()
+ a := awaitAnswer(t, ch, "the restore")
+ requireAnswer(t, a.code, a.out, http.StatusConflict, msgRestoreStaging(ltOne), "the restore")
+ d.requireNoRecord(t)
+ d.requireNoRestoreWrite(t, 1)
+ })
+}
+
+// TestRestoreSkipsLeftoverRailOnlyForOwnReplica: the rail does not refuse
+// a restore over the host's own replica; an ordinary create over the same
+// leftovers is refused by it as before.
+func TestRestoreSkipsLeftoverRailOnlyForOwnReplica(t *testing.T) {
+ t.Run("restore", func(t *testing.T) {
+ d := newDoorFx(t)
+ d.leaveReplica(t)
+ code, out := d.restore(t, "")
+ d.requireRestored(t, code, out, 2)
+ })
+ t.Run("ordinary create", func(t *testing.T) {
+ d := newDoorFx(t)
+ d.leaveReplica(t)
+ code, out := d.post(t, ordinaryBody(""))
+ requireAnswer(t, code, out, http.StatusConflict,
+ ltOne+" still holds data from a deleted instance. Choose another address, or ask an operator to purge it.", "the ordinary create")
+ d.requireNoRecord(t)
+ })
+}
+
+// stranger is someone else asking for ltOne: another account, or another
+// app of this one, each with its own app named on shop.example.com.
+type stranger struct {
+ name string
+ url func(t *testing.T, d *doorFx) string
+}
+
+var strangers = []stranger{
+ {"another account", func(t *testing.T, d *doorFx) string {
+ t.Helper()
+ id := testAccountID()
+ sqid := accountSqid(id)
+ now := time.Now()
+ if err := d.fx.st.CreateAccount(id, sqid, "other", "sam@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := d.fx.st.AddMember(id, "alice@keymail.dev", RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := d.fx.st.CreateAppIn(id, ltApp, "sam@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(context.Background(), d.fx.rel, sqid, ltApp,
+ provision.Manifest{Schema: 1, App: ltApp, Domain: "shop.example.com", Channel: "stable"}); err != nil {
+ t.Fatal(err)
+ }
+ return instancesURL(d.fx, sqid, ltApp)
+ }},
+ {"another app", func(t *testing.T, d *doorFx) string {
+ t.Helper()
+ if _, err := d.fx.st.CreateAppIn(OpsAccountID, "blog", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ enableInstances(t, d.fx, "blog", provision.Manifest{Schema: 1, App: "blog", Domain: "shop.example.com", Channel: "stable"})
+ return instancesURL(d.fx, "bab", "blog")
+ }},
+}
+
+// eligibilitySetups are four states that refuse the owner's restore: a
+// region named elsewhere, a move's staging, a retirement with no body, and
+// a lineage row of an older app lifetime. extra is the body's addition.
+var eligibilitySetups = []struct {
+ name, extra, class string
+ apply func(t *testing.T, d *doorFx)
+}{
+ {"a conflicting region", `,"region":"uk"`, "R5", func(*testing.T, *doorFx) {}},
+ {"staging", "", "R6", func(t *testing.T, d *doorFx) { d.stage(t, "moves/"+ltOne+"/build-state.json") }},
+ {"a missing body", "", "R8", func(t *testing.T, d *doorFx) {
+ d.exec(t, `UPDATE record_retirements SET record_body = NULL WHERE host = ?`, ltOne)
+ }},
+ {"an older app lifetime", "", "R4", func(t *testing.T, d *doorFx) {
+ d.exec(t, `UPDATE host_allocations SET app_lifetime = 'feedfacefeedface' WHERE host = ?`, ltOne)
+ }},
+}
+
+// TestRestoreForeignOwnerSeesOnlyS1: another owner's restore answers the
+// exact bytes another owner's ordinary create gets (S1), whatever else is
+// wrong with it.
+func TestRestoreForeignOwnerSeesOnlyS1(t *testing.T) {
+ for _, who := range strangers {
+ for _, c := range eligibilitySetups {
+ t.Run(who.name+", "+c.name, func(t *testing.T) {
+ d := newDoorFx(t)
+ url := who.url(t, d)
+ s1Code, _, s1 := rawReq(t, http.MethodPost, url, d.member, ordinaryBody(""))
+ requireAnswer(t, s1Code, s1, http.StatusConflict, msgHostUsed(ltOne), "the stranger's ordinary create")
+ c.apply(t, d)
+ code, _, out := rawReq(t, http.MethodPost, url, d.member, restoreBody(c.extra))
+ if code != s1Code || out != s1 {
+ t.Fatalf("the stranger's restore = %d %s, want S1's bytes %d %s", code, out, s1Code, s1)
+ }
+ d.requireNoRestoreWrite(t, 1)
+ })
+ }
+ }
+}
+
+// TestRestoreOwnerSeesDetail: the rightful owner gets the detailed answer.
+func TestRestoreOwnerSeesDetail(t *testing.T) {
+ msgs := map[string]string{
+ "R4": msgRestoreEarlierApp(ltOne, ltApp),
+ "R5": msgRestoreRegion(ltOne, "ie"),
+ "R6": msgRestoreStaging(ltOne),
+ "R8": msgRestoreTooOld(ltOne),
+ }
+ for _, c := range eligibilitySetups {
+ t.Run(c.name, func(t *testing.T) {
+ d := newDoorFx(t)
+ c.apply(t, d)
+ code, out := d.restore(t, c.extra)
+ requireAnswer(t, code, out, http.StatusConflict, msgs[c.class], c.class)
+ d.requireNoRestoreWrite(t, 1)
+ })
+ }
+ t.Run("R2", func(t *testing.T) {
+ d := newDoorFx(t)
+ forceHostsState(t, d.fx.srv, provision.HostsState{Mode: provision.HostsModeIncomplete})
+ code, out := d.restore(t, "")
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreUnavailable(ltOne), "R2")
+ d.requireNoRecord(t)
+ })
+ t.Run("R7", func(t *testing.T) {
+ d := newDoorFx(t)
+ code, out := d.restore(t, `,"kind":"static"`)
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreNotPlain(ltOne), "R7")
+ d.requireNoRecord(t)
+ })
+}
+
+// TestOrdinaryCreateHintsRestore: C2 for the owner when a restore would
+// pass; S1 for anyone else, and for the owner when it would not.
+func TestOrdinaryCreateHintsRestore(t *testing.T) {
+ t.Run("the owner", func(t *testing.T) {
+ d := newDoorFx(t)
+ code, out := d.post(t, ordinaryBody(""))
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreHint(ltOne), "the owner's ordinary create")
+ d.requireNoRestoreWrite(t, 1)
+ d.requireNoRecord(t)
+ })
+ for _, who := range strangers {
+ t.Run(who.name, func(t *testing.T) {
+ d := newDoorFx(t)
+ code, _, out := rawReq(t, http.MethodPost, who.url(t, d), d.member, ordinaryBody(""))
+ requireAnswer(t, code, out, http.StatusConflict, msgHostUsed(ltOne), "the stranger's ordinary create")
+ })
+ }
+ t.Run("the owner, staging holding only build-state.json", func(t *testing.T) {
+ d := newDoorFx(t)
+ d.stage(t, "moves/"+ltOne+"/build-state.json")
+ code, out := d.post(t, ordinaryBody(""))
+ requireAnswer(t, code, out, http.StatusConflict, msgHostUsed(ltOne), "the owner's ordinary create")
+ })
+ t.Run("the owner, the staging list failing", func(t *testing.T) {
+ d := newDoorFx(t)
+ d.data.fail = errBucketDown
+ code, out := d.post(t, ordinaryBody(""))
+ requireAnswer(t, code, out, http.StatusConflict, msgHostUsed(ltOne), "the owner's ordinary create")
+ })
+}
+
+// TestRestoreRacesOrdinaryCreate (Review Focus 1): one wins, the other
+// answers its normal refusal, and there is never a second record.
+func TestRestoreRacesOrdinaryCreate(t *testing.T) {
+ requireOneRestore := func(t *testing.T, d *doorFx) {
+ t.Helper()
+ if rec := decodeRec(t, mustRaw(t, d)); rec.Incarnation != 2 {
+ t.Fatalf("record at %d, want the restore's 2", rec.Incarnation)
+ }
+ d.requireNoRestoreWrite(t, 2)
+ }
+ t.Run("the ordinary create inside the restore's window", func(t *testing.T) {
+ d := newDoorFx(t)
+ g := parkFirst(t, instanceCreateAfterRestoreProof)
+ ch := d.async(d.url(), restoreBody(""))
+ await(t, g.entered, "the restore past its early proof")
+ code, out := d.post(t, ordinaryBody(""))
+ requireAnswer(t, code, out, http.StatusConflict, msgRestoreHint(ltOne), "the ordinary create")
+ g.open()
+ a := awaitAnswer(t, ch, "the restore")
+ d.requireRestored(t, a.code, a.out, 2)
+ requireOneRestore(t, d)
+ })
+ t.Run("the restore inside the ordinary create's window", func(t *testing.T) {
+ d := newDoorFx(t)
+ g := parkFirst(t, instanceCreateAfterClaimCheck)
+ ch := d.async(d.url(), ordinaryBody(""))
+ await(t, g.entered, "the ordinary create past its claim check")
+ code, out := d.restore(t, "")
+ d.requireRestored(t, code, out, 2)
+ g.open()
+ a := awaitAnswer(t, ch, "the ordinary create")
+ requireAnswer(t, a.code, a.out, http.StatusConflict, msgInstanceExists(ltOne), "the ordinary create")
+ requireOneRestore(t, d)
+ })
+ for i := 0; i < 3; i++ {
+ t.Run("together", func(t *testing.T) {
+ d := newDoorFx(t)
+ restore := d.async(d.url(), restoreBody(""))
+ ordinary := d.async(d.url(), ordinaryBody(""))
+ r, o := awaitAnswer(t, restore, "the restore"), awaitAnswer(t, ordinary, "the ordinary create")
+ d.requireRestored(t, r.code, r.out, 2)
+ if msg := ltErr(o.out); o.code != http.StatusConflict || (msg != msgRestoreHint(ltOne) && msg != msgInstanceExists(ltOne)) {
+ t.Fatalf("the ordinary create = %d %s, want C2 or the duplicate", o.code, o.out)
+ }
+ requireOneRestore(t, d)
+ })
+ }
+}
+
+// TestRestoreAfterLegacyLineageRefused (spec §8): a hostname first created
+// with lifetimes off has no origin, and an app purged and recreated under
+// the same name is another lifetime: never restored.
+func TestRestoreAfterLegacyLineageRefused(t *testing.T) {
+ l := newLifetimesFx(t)
+ bucket := &ltStore{Store: l.fx.rel}
+ l.fx.srv.cfg.Releases = bucket
+ forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive})
+ if code, out := createAs(t, l, `{"host":"`+ltOne+`"}`); code != http.StatusCreated {
+ t.Fatalf("legacy create = %d %s", code, out)
+ }
+ turnLifetimesOn(t, l.fx.srv, l.clock)
+ on := ltOn{lifetimesFx: l, bucket: bucket}
+ if code, body := on.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent {
+ t.Fatalf("delete = %d %s", code, body)
+ }
+ data := &stagingStore{DirStore: release.NewDirStore(t.TempDir())}
+ l.fx.srv.cfg.SeedData, l.fx.srv.cfg.HibernateBucket, l.fx.srv.cfg.HomeRegion = data, "data-test", "ie"
+ d := doorOver(t, &proofFx{ltOn: on, data: data})
+ refusedAsOld := func(what string) {
+ t.Helper()
+ code, out := d.restore(t, "")
+ if msg := ltErr(out); code != http.StatusConflict || (msg != msgRestoreTooOld(ltOne) && msg != msgRestoreEarlierApp(ltOne, ltApp)) {
+ t.Fatalf("%s = %d %s, want R4 or R8", what, code, out)
+ }
+ d.requireNoRecord(t)
+ }
+ refusedAsOld("the restore of a legacy lineage")
+ now := time.Now()
+ if err := l.fx.st.TrashAppRow(OpsAccountID, ltApp, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := l.fx.st.PurgeAppRow(OpsAccountID, ltApp); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := l.fx.st.CreateAppIn(OpsAccountID, ltApp, "paul@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ refusedAsOld("the restore into a recreated app")
+}
+
+// TestRestoreAfterManagedEnrolment: a managed fleet's enrolment moves the
+// history's @mode.At after the create; the restore still passes.
+func TestRestoreAfterManagedEnrolment(t *testing.T) {
+ p := newProofBase(t)
+ ctx := context.Background()
+ before, _, err := provision.ReadHostsState(ctx, p.fx.rel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(2 * time.Millisecond)
+ if err := p.fx.srv.admitManagedHistory(ctx, registry.Fleet{Name: "production", Account: "bab", Managed: true, Bucket: "bucket"}, ""); err != nil {
+ t.Fatal(err)
+ }
+ after, _, err := provision.ReadHostsState(ctx, p.fx.rel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !after.At.After(before.At) || after.Mode != provision.HostsModeActive {
+ t.Fatalf("history after enrolment = %+v, before %+v: want active with @mode.At moved", after, before)
+ }
+ if code, body := p.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent {
+ t.Fatalf("delete = %d %s", code, body)
+ }
+ d := doorOver(t, p)
+ code, out := d.restore(t, "")
+ d.requireRestored(t, code, out, 2)
+}
+
+// TestCreateWithoutRestoreUnchanged: a create with no restore, or with
+// "restore": false, is today's create. A fresh host never asks the proof
+// (nothing lists the staging prefix), its allocation carries the origin and
+// no restore_of, and its answer has no "restore" key. The existing S1, S4,
+// S5, leftover-rail and lock-order witnesses run unmodified (Step 4).
+func TestCreateWithoutRestoreUnchanged(t *testing.T) {
+ for _, extra := range []string{"", `,"restore":false`} {
+ t.Run("fresh"+extra, func(t *testing.T) {
+ d := newDoorFx(t)
+ code, _, out := rawReq(t, http.MethodPost, d.url(), d.member, `{"host":"`+ltFresh+`"`+extra+`}`)
+ if code != http.StatusCreated {
+ t.Fatalf("create = %d %s", code, out)
+ }
+ var reply map[string]any
+ if err := json.Unmarshal([]byte(out), &reply); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := reply["restore"]; ok {
+ t.Fatalf("an ordinary create's answer carries restore: %s", out)
+ }
+ if len(d.data.listed) != 0 {
+ t.Fatalf("an ordinary create of a fresh host listed %q", d.data.listed)
+ }
+ rows := lineage(t, d.fx.st, ltFresh)
+ if len(rows) != 1 || !rows[0].RestoreOrigin || rows[0].RestoreOf != "" {
+ t.Fatalf("lineage of %s = %+v, want one origin row", ltFresh, rows)
+ }
+ })
+ t.Run("a host another owner marked"+extra, func(t *testing.T) {
+ d := newDoorFx(t)
+ d.setMark(t, provision.HostUse{Host: ltOne, Account: "zzz", App: "gone", Kind: "instance", Source: "test"})
+ code, out := d.post(t, ordinaryBody(extra))
+ requireAnswer(t, code, out, http.StatusConflict, msgHostUsed(ltOne), "the create")
+ d.requireNoRestoreWrite(t, 1)
+ })
+ }
+}
diff --git a/internal/provision/instance_restore_658_census_test.go b/internal/provision/instance_restore_658_census_test.go
index c2cf72f80..828f63947 100644
--- a/internal/provision/instance_restore_658_census_test.go
+++ b/internal/provision/instance_restore_658_census_test.go
@@ -9,6 +9,14 @@ package provision
// observation (markForCreate now returns it) and sets the allocation's
// restore_origin from it before BeginAllocation. A SQL column only; no
// new bucket write. key-site / key:RecordKey, as before.
+// Task 6 adds a restore's deciding restoreProof after the regional
+// recheck (a duplicate is ErrCASConflict, any refusal a hostsUsedError,
+// nothing written), lets an eligible restore pass markForCreate's S1,
+// sets the allocation's restore_of (SQL), and swaps S1 for C2 on an
+// ordinary create when restoreHint finds a restore would pass. It reads
+// only (the mark, slot, record, SQL rows, the staging list); the record
+// it writes is the same create's, through the same allocation path.
+// key-site / key:RecordKey, as before.
// - Server.retireRecordWithLifetimeLocked (Task 4): passes the captured
// body (obs.Raw at RecordETag; nil after a same-call migration) to
// BeginRetirement as RecordBody. A SQL column only; the same record key.
@@ -22,7 +30,7 @@ package provision
func instanceRestore658WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), regionHAG2FixesWriteCensusInventory()...)
replacements := []censusEntry{
- {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "e05edd5868ab2ba17f7c7bed2669c846facff70d17ae5aaf80a62017dc3abdf8"},
+ {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "ca9f9c54e694a3ed7664327e8c353f9c3bf1f00f17600284259944c478d9cd0b"},
{"internal/console/lifetimes_retire.go", "Server.retireRecordWithLifetimeLocked", "key-site", "key:RecordKey", "e5b8fe974a0c6c21e08e059ec6baab1c569766d90c8a84aff405f02cdc51ba37"},
{"internal/console/lifetimes_retire.go", "Server.retirementStepsLocked", "record-writer", "key:RecordKey,key:WriteRecord", "e5bc1a1ef3ddba02c75217b18a71155f5fdbb82c67494cb60c57021ef05f2252"},
}