carlos / platform Public

console: restore proof before holder checks, admission first (#658)

Review round 1 of Task 6.

P1: a restore now runs its early restoreProof right after the host is
validated and the app's placement read, before the sibling, holder and
claim checks that can name another app or account. Another owner gets
S1's exact bytes whatever else the host holds. An ordinary create reads
the placement and runs those checks in the same order as before.

P2: in the lifetime create core, a restore's history admission
(gateDataCreate: S5, S4) runs before the deciding restoreProof and not
again at the mark, so the deciding verdict is the last answer before
the mark but a store or bucket error. Ordinary creates are unchanged.

The census entry for createRecordWithLifetimeLocked is re-fingerprinted
(same class and kinds).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e2a33b0a1077021740466735c2c5e1d6054a3735 parent b908ffb
4 files changed, +197 −41
  • internal/console/apiinstances.go +56 −37
  • internal/console/lifetimes_create.go +12 −2
  • internal/console/restore_door_test.go +125 −0
  • internal/provision/instance_restore_658_census_test.go +4 −2
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index db565f34d..b9519bf0b 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -1675,6 +1675,60 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
"invalid host — an instance host is one DNS label followed by ."+m.Domain)
return
}
+ // The app's placement, read once: a restore's early proof needs it, and
+ // every create's region resolution below.
+ var (
+ reg consoleRegistry
+ placed string
+ )
+ readPlacement := func() bool {
+ var err error
+ if reg, err = openRegistry(s.cfg.Registry); err != nil {
+ log.Printf("console: api instances create %s/%s: open registry: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not check this app's placement")
+ return false
+ }
+ if placed, err = s.appPlacement(reg, acct, app); err != nil {
+ log.Printf("console: api instances create %s/%s: check placement: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not check this app's placement")
+ return false
+ }
+ return true
+ }
+ // A restore (instance restore #658, spec §3 item 1): ownership, then
+ // eligibility, right after the host is validated and the app's own
+ // placement and pool are read, and before the sibling, holder and claim
+ // checks or anything else that could name another owner, region
+ // resolution, the leftover rail or any history-dependent check. Another
+ // owner is answered S1 whatever else is wrong with the request. Every
+ // check below still runs once ownership has passed. This call holds no
+ // lock and is advisory: the deciding one runs under the create core's
+ // locks (createRecordWithLifetimeLocked), and its verdict alone decides.
+ // An ordinary create keeps its order exactly.
+ var restore *restoreAsk
+ restoreRegion := ""
+ if req.Restore {
+ if !readPlacement() {
+ return
+ }
+ 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)
+ }
if err := s.demoRecordReservation(r.Context(), provision.Record{Host: host}); err != nil {
jsonError(w, http.StatusConflict, demoCopy["DEMO-POLICY"])
return
@@ -1798,49 +1852,14 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// "fleet/<name>" value would fail provision.ValidRegion's shape anyway
// (no "/"), which is exactly why this has to be a check made BEFORE
// that validation, not alongside it.
- reg, err := openRegistry(s.cfg.Registry)
- if err != nil {
- log.Printf("console: api instances create %s/%s: open registry: %v", acct.Sqid, app, err)
- jsonError(w, http.StatusBadGateway, "could not check this app's placement")
- return
- }
- placed, err := s.appPlacement(reg, acct, app)
- if err != nil {
- log.Printf("console: api instances create %s/%s: check placement: %v", acct.Sqid, app, err)
- jsonError(w, http.StatusBadGateway, "could not check this app's placement")
+ // A restore read it already, before its early proof.
+ if restore == nil && !readPlacement() {
return
}
if s.cfg.Demo.Fleet != "" && placed == "fleet/"+s.cfg.Demo.Fleet {
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
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go
index aa00b1354..ad0a5dbf8 100644
--- a/internal/console/lifetimes_create.go
+++ b/internal/console/lifetimes_create.go
@@ -103,6 +103,14 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi
ask, restoring := restoreFrom(ctx)
var restored restoreVerdict
if restoring {
+ // The history's admission (S5, S4) first, and only here for a
+ // restore: nothing between the deciding evaluation and the mark may
+ // answer for it but a store or bucket error. Both stay fail-closed.
+ if rec.DataKind() {
+ if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil {
+ return nil, &hostsUsedError{*ref}
+ }
+ }
ask.Account, ask.App, ask.Host, ask.AccountID, ask.Lifetime = rec.Account, rec.App, host, acct.ID, life.Lifetime
shape := rec
ask.Shape = &shape
@@ -156,8 +164,10 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi
// nothing behind.
var obs markObservation
if rec.DataKind() {
- if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil {
- return nil, &hostsUsedError{*ref}
+ if !restoring { // a restore was admitted before its deciding evaluation
+ if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil {
+ return nil, &hostsUsedError{*ref}
+ }
}
var ref *doorRefusal
obs, ref = s.markForCreate(ctx, recordUse(rec))
diff --git a/internal/console/restore_door_test.go b/internal/console/restore_door_test.go
index 822b867e8..117db3dea 100644
--- a/internal/console/restore_door_test.go
+++ b/internal/console/restore_door_test.go
@@ -12,6 +12,7 @@ import (
"encoding/json"
"errors"
"net/http"
+ "net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
@@ -787,3 +788,127 @@ func TestCreateWithoutRestoreUnchanged(t *testing.T) {
})
}
}
+
+// s1Bytes is the exact answer S1 is: its status and body as the door
+// writes them.
+func s1Bytes() (int, string) {
+ w := httptest.NewRecorder()
+ jsonError(w, http.StatusConflict, msgHostUsed(ltOne))
+ return w.Code, w.Body.String()
+}
+
+// TestRestoreForeignOwnerSeesS1BeforeHolders (review round 1, P1): the
+// early proof answers another owner S1 before the sibling, holder and
+// claim checks, which name the app or account holding the host. Each setup
+// is one the stranger's ordinary create meets as a holder refusal (that
+// order is unchanged); the stranger's restore gets S1's exact bytes and
+// writes nothing.
+func TestRestoreForeignOwnerSeesS1BeforeHolders(t *testing.T) {
+ route := func(t *testing.T, d *doorFx) {
+ t.Helper()
+ reg, err := registry.Open(d.fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(registry.Route{Host: ltOne, Kind: "instance", App: ltApp, Account: "bab"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cases := []struct {
+ name string
+ who stranger
+ build func(t *testing.T) *doorFx
+ after func(t *testing.T, d *doorFx, url string)
+ }{
+ {"another account, a remaining route", strangers[0], newDoorFx, func(t *testing.T, d *doorFx, _ string) { route(t, d) }},
+ {"another app, a remaining route", strangers[1], newDoorFx, func(t *testing.T, d *doorFx, _ string) { route(t, d) }},
+ {"another app, the owner's live sibling record", strangers[1],
+ func(t *testing.T) *doorFx { return doorOver(t, newProofBase(t)) }, func(*testing.T, *doorFx, string) {}},
+ // Another account's records are not this account's siblings: under
+ // lifetimes only the owner's own live record, by its route, can be.
+ {"another account, the owner's live record and its route", strangers[0],
+ func(t *testing.T) *doorFx { return doorOver(t, newProofBase(t)) }, func(t *testing.T, d *doorFx, _ string) { route(t, d) }},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ d := c.build(t)
+ url := c.who.url(t, d)
+ c.after(t, d, url)
+ allocs := len(allocRows(t, d.fx.st, ltOne))
+ ordCode, _, ordOut := rawReq(t, http.MethodPost, url, d.member, ordinaryBody(""))
+ if ordCode != http.StatusConflict || !strings.Contains(ltErr(ordOut), " already ") {
+ t.Fatalf("fixture: the stranger's ordinary create = %d %s, want a holder refusal", ordCode, ordOut)
+ }
+ wantCode, want := s1Bytes()
+ code, _, out := rawReq(t, http.MethodPost, url, d.member, restoreBody(""))
+ if code != wantCode || out != want {
+ t.Fatalf("the stranger's restore = %d %q, want S1's exact %d %q", code, out, wantCode, want)
+ }
+ d.requireNoRestoreWrite(t, allocs)
+ })
+ }
+}
+
+// TestRestoreAdmissionBeforeDecidingCall (review round 1, P2): for a
+// restore the history's admission (S5, S4) runs in the core before the
+// deciding evaluation and not after it, so the deciding verdict is the
+// last answer before the mark. S4 and S5 stay fail-closed.
+func TestRestoreAdmissionBeforeDecidingCall(t *testing.T) {
+ // A box in the home region that activation did not record, as in
+ // TestEveryDoorPassesTheWholeAdmission.
+ joinHome := func(t *testing.T, d *doorFx) { putHostsEdges(t, d.fx.rel, "home-1", "", "") }
+ requireS4 := func(t *testing.T, code int, out string) {
+ t.Helper()
+ if code != http.StatusConflict || !strings.HasPrefix(ltErr(out), "New instances can't be created on ") {
+ t.Fatalf("restore = %d %s, want 409 S4", code, out)
+ }
+ }
+ t.Run("an unexamined home target", func(t *testing.T) {
+ d := newDoorFx(t)
+ joinHome(t, d)
+ code, out := d.restore(t, "")
+ requireS4(t, code, out)
+ d.requireNoRecord(t)
+ d.requireNoRestoreWrite(t, 1)
+ })
+ t.Run("an unexamined home target, and staging between the evaluations", func(t *testing.T) {
+ // The deciding evaluation would answer R6; the admission before it
+ // answers first.
+ d := newDoorFx(t)
+ joinHome(t, d)
+ 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")
+ requireS4(t, a.code, a.out)
+ d.requireNoRecord(t)
+ d.requireNoRestoreWrite(t, 1)
+ })
+ t.Run("the history no longer active 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")
+ forceHostsState(t, d.fx.srv, provision.HostsState{Mode: provision.HostsModeIncomplete})
+ g.open()
+ a := awaitAnswer(t, ch, "the restore")
+ requireAnswer(t, a.code, a.out, http.StatusConflict, msgRestoreUnavailable(ltOne), "the restore")
+ d.requireNoRecord(t)
+ d.requireNoRestoreWrite(t, 1)
+ })
+ t.Run("the history invalidated between the evaluations", func(t *testing.T) {
+ // Fail-closed: S5, from the admission, before any deciding verdict.
+ d := newDoorFx(t)
+ g := parkFirst(t, instanceCreateAfterRestoreProof)
+ ch := d.async(d.url(), restoreBody(""))
+ await(t, g.entered, "the restore past its early proof")
+ forceHostsState(t, d.fx.srv, provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: "test"})
+ g.open()
+ a := awaitAnswer(t, ch, "the restore")
+ requireAnswer(t, a.code, a.out, http.StatusServiceUnavailable, msgHostsInvalidated, "the restore")
+ d.requireNoRecord(t)
+ 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 828f63947..bab816d79 100644
--- a/internal/provision/instance_restore_658_census_test.go
+++ b/internal/provision/instance_restore_658_census_test.go
@@ -16,7 +16,9 @@ package provision
// 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.
+// For a restore, gateDataCreate (S5, S4) runs before the deciding
+// restoreProof and not again at the mark (review round 1, P2); reads
+// only. 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.
@@ -30,7 +32,7 @@ package provision
func instanceRestore658WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), regionHAG2FixesWriteCensusInventory()...)
replacements := []censusEntry{
- {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "ca9f9c54e694a3ed7664327e8c353f9c3bf1f00f17600284259944c478d9cd0b"},
+ {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "e338351f788f6cded8733a1abaa02e1c87befcd04e54594d62f4e2f22a4928dc"},
{"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"},
}