carlos / platform Public

notes #658 Task 1: retirement inventory, sibling warm file, account ids

Step 1: every record_retirements writer and data-kind record remover
either reaches the normal-retirement steps (takes spec 5's rule) or
writes no restorable row; none does neither, so Task 4 is not blocked.
Step 2: the sibling-box warm file is real for non-HA hibernating
instances in multi-box regions; draft discussion included, not posted.
Step 3: marks, allocations, slots and retirements all hold the sqid.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev bbfacc8123203c4edb38215ef14d8c9ccc46595d parent e6930ba
1 file changed, +350 −0
  • docs/superpowers/notes/instance-restore-658-task1.md +350 −0
diff --git a/docs/superpowers/notes/instance-restore-658-task1.md b/docs/superpowers/notes/instance-restore-658-task1.md
new file mode 100644
index 000000000..2e08ddb8a
--- /dev/null
+++ b/docs/superpowers/notes/instance-restore-658-task1.md
@@ -0,0 +1,350 @@
+# Instance restore (#658), plan Task 1: inventories
+
+Read from branch `design-instance-restore-658` at e6930bae. No code changed.
+Spec: docs/superpowers/specs/2026-11-07-instance-restore-658-design.md §4-§6.
+All paths are under `internal/` unless they say otherwise.
+
+Summary of the three answers:
+
+1. Every writer of `record_retirements`, and every path that removes a
+ data-kind record, either goes through the normal-retirement steps (and so
+ can take §5's rule), or writes no row / only orphan, cleanup, void or
+ refused outcomes. **No path does neither.** Task 4 can go ahead. Five
+ implementation points for Tasks 3 to 5 are in §1.5, and one gap that
+ crosses modes (claims on, then off) is in §1.6.
+2. **Yes, the sibling-box warm file is real** for a non-HA, unlabelled,
+ unseeded hibernating instance in a platform region with more than one box
+ serving its pool. The code says so itself (activator/activator.go:2900-2907).
+ A draft discussion is at the end. Restore is not changed.
+3. `HostUse.Account`, `Allocation.Account`, the slot's `Account` and
+ `Retirement.Account` all hold the **account sqid** (`acct.Sqid`). Only the
+ apps row is keyed by the numeric id. `restoreProof` compares `acct.Sqid`
+ with the stored strings, and reads L with `AppLife(acct.ID, app)`.
+
+---
+
+## 1. Step 1: writers of `record_retirements` and removers of data-kind records
+
+### 1.1 Every SQL writer of the table
+
+Searched every non-test `.go` file for `record_retirements`. The only SQL
+writes are in console/lifetimes_store.go. Nothing deletes rows (no
+`DELETE FROM record_retirements` anywhere). store.go:487 is the `CREATE TABLE`.
+store_gate.go:241 only lists the table for the claim SQL gate
+(`{Sqid: "account", App: "app"}`). hostsused_store.go:9 reads it.
+
+| Writer | Where | What it writes | Callers |
+|---|---|---|---|
+| `BeginRetirement` | lifetimes_store.go:208 | INSERT, kind normal / orphan / cleanup, state pending, `cancels` always "" | lifetimes_retire.go:173 (normal), :198 (cleanup); lifetimes_create.go:524 (orphan) |
+| `BeginCancellingRetirement` | lifetimes_store.go:228 | INSERT of an **orphan** row plus void of the allocation, in one tx | lifetimes_create.go:526, only reached from lifetimes_recovery.go:208 (recovery cancelling an allocation whose app lifetime is gone) |
+| `ConvertRetirementKind` | lifetimes_store.go:261 | UPDATE normal to cleanup **and replaces `record_etag`** | lifetimes_retire.go:298 only |
+| `SetRetirementState` | lifetimes_store.go:270 | UPDATE state | lifetimes_retire.go:308 (void), :331 (refused); `settleRetirement` lifetimes_create.go:556 (void or committed) |
+
+Only `retirementStepsLocked` (lifetimes_retire.go:230) can produce a normal
+row that ends committed with its own tombstone. Its outcomes, against §5:
+
+| Branch | Line | §5 |
+|---|---|---|
+| N1 write lands (`WriteRecord` err == nil) | lifetimes_retire.go:323 | **restorable** (N1's own write) |
+| N1 response lost; next round sees `rec.Retired && rec.Incarnation == r.Incarnation` | :302 | **restorable** only if `record_seq` = candidate + 1 |
+| slot already retired on first look | :266 | not restorable |
+| record absent under the live slot | :288 | not restorable |
+| corrupt body: quarantine, convert to cleanup | :294-301 | not restorable |
+| another incarnation: fence, void | :306-316 | not restorable |
+| same incarnation, other ETag: fence, refused | :328-339 | not restorable |
+| successor slot: void | :264-265 | not restorable |
+
+Orphan rows (`orphanStepsLocked`, lifetimes_create.go:537) and cleanup rows
+never become restorable under §5.
+
+N1 writes with `provision.WithRecordSequence(ctx)` (lifetimes_retire.go:323).
+`TombstoneBody` keeps `record_seq` (provision/lifetime.go:157), and
+`WriteRecord` advances it by exactly one (`AdvanceRecordSequence`,
+provision/record_sequence.go:83-99; it refuses unless the candidate's counter
+equals the before's). A legacy body with no counter reads as 0 and its
+tombstone gets 1, so the "+1" proof holds for those too.
+
+### 1.2 Paths that reach a normal retirement (they take §5's rule)
+
+Every one goes through `retireRecordWithLifetimeLocked`
+(lifetimes_retire.go:102), so N1/N2/N3 and the table above apply. Under the
+rule each can leave a restorable row. The last column says what still stops a
+restore that should not happen. That is §4's other items, not §5.
+
+| Path | Entry | Expectation | What else refuses a wrong restore |
+|---|---|---|---|
+| Delete door, claims off | apiinstances.go:3247 `refuseImportDelete` → apiinstanceimport.go:1109 `deleteRead` | `retireExpectETag(etag)` | none needed: this is the case restore is for |
+| Delete door, record absent | apiinstanceimport.go:997 | `retireExpectAbsent` | only reaches the orphan branch (lifetimes_retire.go:131) or nothing |
+| Import / seed / demo-claim rollback finish | seedfinish.go:134-143 (`finishSeedOnce`, state rolled-back only) | `retireExpectETag` | stored body has `Seed` (R7); Task 3 never sets an origin for a seeded create |
+| Committed import or `--from` seed deleted | apiinstanceimport.go:1012-1013 → `deleteRead` | `retireExpectETag` | `Seed` stays on the record for good (provision/provision.go:123-128: "it stays on the record after placement as provenance"; nothing sets `Seed = nil`) → R7; no origin |
+| Domain detach, first route, lifetimes on | domainattach.go:393, apidomains.go:1194 → `detachRetireLocked` domainattach.go:452 | `retireAny` | the record is `Kind: "static"` (domainattach.go:692), so it is not a data kind and gets no mark and no origin; R7 |
+| Attach rollback, lifetimes on | domainattach.go:635 → `retireInstanceRecord` → hostclaimops.go:24-28 | `retireAny` | static, as above |
+| Create undo after a sibling label appears | apiinstances.go:2556-2563 | `retireExpectIncarnation(rec.Incarnation)` | same owner's few-second-old record; a restore runs the create's sibling-label recheck again |
+| App purge door | ownership.go:605 → `purgeAppWithLifetimes` lifetimes_purge.go:40 → `purgeHostLocked` :130 | incarnation, or ETag | the app is trashed (create refuses, lifetimes_create.go:186) or purged; a recreated app has a new `apps.lifetime`, so its allocations don't match L → R4 |
+| Expiry pass early purge | expirypass.go:249 | same | same |
+| Trash sweep | lifetimes_purge.go:245 | same | same |
+| Demo expiry / retire purge | demo_expiry.go:335 | same | stored body has `Demo` (R7) |
+| Retire of a legacy (incarnation 0) record | lifetimes_retire.go:142-159: migrate first, then normal | as the caller's | a migrated record has no allocation at its incarnation → R8 (§4 item 3) |
+
+### 1.3 Paths that remove a data-kind record with no restorable row
+
+| Path | Where | Row written |
+|---|---|---|
+| Orphan retirement (live slot, no record) | lifetimes_create.go:516; callers lifetimes_retire.go:132, lifetimes_create.go:260, lifetimes_purge.go:134, lifetimes_recovery.go:208 | orphan |
+| Cleanup retirement (stale/corrupt body beside own live slot) | lifetimes_retire.go:191-201, lifetimes_create.go:249 | cleanup |
+| Stale body, not under this key's live slot | lifetimes_retire.go:203 `deleteRecordIfMatch` | none |
+| Create step 5: stale body under this key / previous owner | lifetimes_create.go:358, :366; recovery lifetimes_create.go:408 | none (body the slot does not vouch for) |
+| `deleteUnderRetiredSlot` | lifetimes_create.go:600-615; called lifetimes_retire.go:268, lifetimes_create.go:546, lifetimes_recovery.go:127 | none of its own; it is N3 / C2 / the orphan's tail of an existing row and does not touch `restorable` |
+| Migration quarantine (corrupt body, no slot) | lifetimes_migrate.go:233-246 | none (row in `record_migrations`, superseded) |
+| Lifetimes-off delete door | apiinstanceimport.go:1111 `release.DeleteIfMatch` | none |
+| Lifetimes-off seed finish | seedfinish.go:145 | none |
+| Lifetimes-off detach / rollback / undo / claim-console delete door | hostclaimops.go:33 → provision/retirement.go:64-68 → `DeleteRecord` provision/provision.go:2947 | none |
+| Lifetimes-off purges | ownership.go:607 `release.PurgeApp`; expirypass.go:251 and lifetimes_purge.go:248 `PurgeAppIfTrashedAt`; demo_expiry.go:337 `PurgeAppExcept` | none |
+| Claims on: every instance removal | hostclaimops.go:21-23 → `retireClaimHostRecord` claim_retire.go:33; claim purge claim_purge.go; hostops | none (claims-on consoles write no lifetime rows: lifetimes_recovery.go:30-32) |
+| Sidecar delete | apisidecars.go:549 → `retireHostRecord` with Family "sidecar" | none (sidecar record key, not an instance record) |
+
+Not removers, checked: app trash writes only the marker (release/trash.go:44-51,
+`claimRawTrashApp`); trash restore deletes only the marker
+(claim_restore.go:184); demo claim transfer's purge keeps every record key
+(demo_claim_transfer.go:879, `keep = provision.IsRecordKey`);
+`purgeAppWithLifetimes`'s final sweep keeps instance record keys
+(lifetimes_purge.go:94-96); account deletion refuses an account that still
+has apps (ownership.go:752), and the console never deletes `accounts` rows.
+
+### 1.4 Verdict for Step 4
+
+No path does neither. Every remover either goes through
+`retirementStepsLocked` (and can take §5's rule there), or writes no row, or
+writes only an orphan, cleanup, void or refused row. **Task 4 is not blocked.**
+
+### 1.5 Points for Tasks 3 to 5 (found while reading; not findings against §5)
+
+1. **"Restorable" must mean `kind = normal AND state = committed AND
+ restorable`.** Once N1 has landed, the same row can still turn into a
+ cleanup (:294-301, which also replaces `record_etag`), void (:306, :264) or
+ refused (:328) if another writer replaces the tombstone before N2/N3.
+ Either clear `restorable` in `ConvertRetirementKind` and in the void/refused
+ branches, or have `restoreProof` require all three fields. The second is
+ simpler and safe on its own.
+2. **Persist `restorable` before N2, and treat a failed write as pending.**
+ The lost-response proof (:302) can only be made while the tombstone is
+ still there. After N3 deletes it, recovery takes the :266 branch, which
+ can prove nothing. If the flag is written before N2, a crash between N2
+ and the flag write cannot drop a provable row. A failed flag write that
+ goes on anyway only costs R8, which is the safe side.
+3. **N1 throws away what it wrote.** lifetimes_retire.go:323 is
+ `_, _, err = provision.WriteRecord(...)`. Task 4 needs the candidate's
+ `record_seq` from `RecordSequence(obs.Raw)` for the "+1" check.
+4. **Stored body after a migration.** On the legacy branch,
+ lifetimes_retire.go:143 throws away the migrated raw bytes
+ (`mrec, _, metag, state, err := s.migrateHostLifetimeLocked(...)`), so the
+ body to store with `BeginRetirement` is not to hand there. Such a record is
+ R8 anyway (no allocation at its incarnation). Storing no body there is fine.
+5. **Task 3 import marker.** `createRecordWithLifetimeLocked` has six
+ callers: the create door apiinstances.go:2513; the seed and import doors
+ apiinstanceseed.go:86 (import sets `rec.Seed.Kind = seeds.KindImport` at
+ apiinstanceimport.go:172; `--from` sets `seeds.KindReplica` at
+ apiinstanceseed.go:359); demo claim demo_claim_seed.go:191
+ (`Seed.Kind = seeds.KindDemoClaim`, :189); demo publish demo_publish.go:218
+ (`rec.Demo` set, :193, and ctx carries `demoRecordCreateKey{}`); and the
+ first-route attach domainattach.go:698 (static, so it never marks). The
+ markers on the record: `rec.Seed != nil` (any kind: `Seed.Import()`,
+ `Seed.DemoClaim()`, replica), `rec.Demo != nil`, `rec.DemoClaim != nil`.
+ Recommendation: set `restore_origin` only on an explicit flag from the
+ create door's own call (apiinstances.go:2513), and also require
+ `rec.Seed == nil && rec.Demo == nil && rec.DemoClaim == nil` as a second
+ check. Don't rely on the record content alone.
+
+### 1.6 A gap across modes (not a §5 path; for the controller)
+
+Claims-on removals write no row (§1.3), and claims-on creates do not mark:
+`gateDataCreate`/`markForCreate`/`markBeforeCreate` are called only from the
+lifetime create (lifetimes_create.go:139-142) and the lifetimes-off create
+(hostsused.go:710-713, sidecars :736-740). The claim create
+(apiinstances.go:2500-2509, `finishClaimCreate` at :2506) marks nothing and writes no
+slot. The tripwire (hostsused_tripwire.go:61) only fires for an unmarked
+host. So in principle: A/P deletes H with claims off (restorable row at N).
+The console then runs claims on, and another owner creates H, writes data
+and deletes it. Claims go off again. Now A's mark, slot, allocations and
+newest row all still pass. R2 checks only the current mode. I have not shown
+that a claims-on create of an already-marked host is accepted end to end
+(the claim system has its own hostname ownership), and claims have been
+shelved since 2026-10-25. Two possible cheap closes: a ruling that claims on
+is one-way, or restore requiring that no claim object for H ever existed. Or
+leave it as the R2 non-goal.
+
+---
+
+## 2. Step 2: the sibling-box warm file (§6)
+
+**Answer: yes, for a hibernated instance.** In a platform region with two or
+more boxes serving the instance's pool, a box other than the last one to
+serve a host can hold a file at that host's derived path. A wake there uses
+that file and never looks at the newer replica.
+
+Evidence:
+
+- **Every box in the region takes the record.** `inScope`
+ (provision/reconcile.go:524-537) admits on pool, then `region == cfg.Region`.
+ `ownsRecord` (:549-557) returns true off a fleet ("a platform box's scope is
+ its region and pool alone"). So each such box mints the route at the same
+ derived path, `DefaultDBPath(dataDir, host)` = `<dataDir>/<host>.db`
+ (provision/provision.go:3187).
+- **Sleep leaves the file.** activator/activator.go:478 ("asleep (local DB
+ left as a warm cache)"), :4724. Delete removes only the route, and boxes
+ purge nothing. The only local-data removers are import/seed/demo-claim
+ rollback (`RemoveLocal`, provision/seedrollback.go:162, :279;
+ provision/demo_claim_seed.go:157, :250) and a move's cut
+ (`PurgeLocalDBArtifacts(.., true)`, activator/backend_exec.go:3810-3829).
+- **Any box can wake a non-HA host.** Non-HA hosts are not forwarded
+ (activator/haforward.go:149-150:
+ `if !rt.HA { return edge.ForwardDecision{Unavailable: !eligible}, true }`).
+ The multi-box owner layer was dropped ("mesh (multi-box placement:
+ gossip/HRW, peer proxying) dropped for single-box v1",
+ activator/activator.go:12-15). The legacy lease is a plain single-writer
+ lock with no "who held it last" check (activator/hawake.go:285-294,
+ `acquireLegacy`; lease/lease.go:1-11). Pool eligibility is only "serves the
+ pool" (activator/backend_exec.go:3920-3921).
+- **The wake prefers the local file.** `restorePlain`
+ (activator/backend_exec.go:965-1001): with no HA, no seed obligation, an
+ unlabelled row (`reconcileAssignment` acts only on labelled rows, :980-987)
+ and no seed marker, `os.Stat(dbPath) == nil` returns "warm" at :991-998.
+ `restoreReplica` (:1031) is never reached.
+- **The code already says this assumption breaks with two boxes.**
+ activator/activator.go:2900-2907: "When it's still on disk it is the warm
+ cache: on one box, with the lease held, the local copy can only be what we
+ ourselves checkpointed at the last sleep. That holds only while a region
+ has one box. Claim ruling R6 ends it ... once wakes are admitted by
+ hostclaim's AdmitWriter". Claims are shelved, so R6 is not in force. Other
+ doors already guard against it: the offline move refuses
+ "<host> keeps local data on more than one box"
+ (console/apiinstancemove_offline.go:1062-1063); imports refuse multi-box
+ regions (console/seedfloor.go:28-29, :98); moves refuse them
+ (host/movesphase1.go:517, console/apiinstancemove.go:740).
+
+What's out of scope: HA hosts (`restoreHA`, backend_exec.go:968-972), fleet
+rows labelled for a box (`reconcileAssignment`), seeded rows (seed marker),
+demos (`restoreDemoLocal`). Restore's §4 item 5 already excludes all of these.
+
+I did not establish which box a request for a non-HA host reaches in a
+multi-box region. That is DNS and ingress (`CONSOLE_REGION_INGRESS`,
+console/regioningress.go; the edge-IP fold, console/server.go:1631-1658),
+outside the wake path. The hazard needs requests for one host to reach two
+boxes over time. Nothing in the activator or reconcile stops that.
+
+As §6 says, restore gives the same guarantee as waking the never-deleted
+instance. This is a property of every hibernating non-HA instance in a
+multi-box region, so it is filed on its own (below) and restore is unchanged.
+
+## Draft discussion
+
+Type: Issue. Not posted; the controller posts it.
+
+**Title:** A non-HA instance in a region with two boxes can wake on an older local copy
+
+**Body:**
+
+A hibernating instance that is not HA can come back with old data if its
+region has more than one platform box serving its pool. When a box wakes it,
+the box uses any database file it already holds for that hostname and skips
+the replica, even when another box has written newer data to the replica
+since.
+
+Scenario (hibernated instance, nothing deleted):
+
+1. Region R has two platform boxes, X1 and X2, both serving the shared pool.
+ Instance `shop.example.com` is not HA.
+2. A request reaches X2. X2 wakes the host, it serves and writes, then
+ sleeps. X2 keeps `<data>/shop.example.com.db` as its warm cache.
+3. Later a request reaches X1. X1 has no local file, so it restores from the
+ replica, serves, writes newer rows, sleeps and checkpoints to the replica.
+4. A request reaches X2 again. The lease is free. X2 finds its own file from
+ step 2 and starts on it. The rows written in step 3 are not there, and X2's
+ replication then carries on from the older file.
+
+Why it happens:
+
+- Every platform box in the region mints the route
+ (provision/reconcile.go:524 `inScope`, :549 `ownsRecord`).
+- Non-HA hosts are never forwarded to the box that last held them
+ (activator/haforward.go:149), and the legacy lease has no "last holder"
+ check (activator/hawake.go:285).
+- `restorePlain` uses any local file before the replica
+ (activator/backend_exec.go:991).
+- activator/activator.go:2900-2907 already notes that the warm-cache trust
+ "holds only while a region has one box" and was to end with claim ruling
+ R6. Claims are shelved, so it has not ended.
+
+Existing guards elsewhere show the shape is known: the offline move refuses
+a host that "keeps local data on more than one box", and imports and moves
+refuse multi-box regions.
+
+Who is exposed: non-HA, unlabelled, unseeded hibernating instances in any
+platform region with more than one box serving their pool. That includes
+records made before HA stamping in a region that later became HA, and any
+classic region that gains a box. HA hosts, fleet rows labelled for a box,
+seeded rows and demos take other paths.
+
+Restore (#658) gives the same guarantee as this wake and does not change it.
+
+Questions:
+
+- Which live regions have more than one box serving the shared pool today,
+ and do they hold non-HA hibernating instances?
+- Possible fixes: record the last holder in the lease or the replica, and
+ have a wake set aside (never delete) a local file that doesn't match the
+ replica's latest generation. Or, in a multi-box region, keep the warm cache
+ only on the box that last released the lease.
+
+---
+
+## 3. Step 3: which account identifier
+
+All of them hold the **sqid** (`Account.Sqid`, a string).
+
+- The create door builds the record with `Account: acct.Sqid`
+ (console/apiinstances.go:2096).
+- Mark: `recordUse` (console/hostsused.go:668-670) is
+ `provision.HostUse{Host: rec.Host, Account: rec.Account, ...}`, so it is the
+ sqid. The recovery mark (hostsused.go:577) uses `a.Account`, also the sqid.
+ The sidecar mark (:739) uses `rec.Account`, also the sqid. Activation's
+ inventory marks carry **no account** (hostsused_activate.go:443,
+ `HostUse{Host: h, Kind: "inventory", ...}`), so they always fail stage 1
+ and answer S1, as §4 means.
+- Allocation: `createRecordWithLifetimeLocked` (console/lifetimes_create.go:128)
+ sets `Allocation{..., Account: rec.Account, ...}`, the sqid. The same step
+ passes `rec.Account` to `AccountBySqid` (lifetimes_create.go:83 →
+ `lifetimeAppCheck` :165), which only works on a sqid. The claim gate
+ declares it too: store_gate.go:240-242,
+ `"host_allocations": {Sqid: "account", ...}` and the same for
+ `record_retirements`.
+- Slot: `allocationSlot` (lifetimes_create.go:292-295) uses `a.Account`, the
+ sqid. Ownership is plain string equality, `slotOwnedBy`
+ (console/lifetimes.go:260-262).
+- Retirement: every caller passes `acct.Sqid` (for example
+ apiinstanceimport.go:1109, lifetimes_purge.go:130), and the row takes it
+ (lifetimes_retire.go:171).
+- App lifetime: the apps row is keyed by the **numeric id**,
+ `s.store.AppLife(acct.ID, app)` (lifetimes_create.go:172; tempstore.go:52).
+ `Allocation.AppLifetime` is `life.Lifetime` (lifetimes_create.go:130).
+
+**`restoreProof` must use:** with `acct` the door's `*Account` and `app` the
+name,
+
+- `mark.Account == acct.Sqid && mark.App == app`
+- `slot.Account == acct.Sqid && slot.App == app` (`slotOwnedBy(slot, acct.Sqid, app)`)
+- for every non-void allocation: `a.Account == acct.Sqid && a.App == app && a.AppLifetime == L`
+- newest retirement: `r.Account == acct.Sqid && r.App == app`
+- where `L = s.store.AppLife(acct.ID, app).Lifetime`
+
+No normalising is needed.
+
+The sqid is a pure function of the id (console/account.go:24,
+`domains.Sqid(id)`), and `accounts.id` is `INTEGER PRIMARY KEY` without
+AUTOINCREMENT (store.go:218-223). The console never deletes `accounts` rows,
+so a sqid is not reused today. A console restored to an older snapshot could
+hand an old id, and so an old sqid, to a new account. But the
+`host_allocations` rows from the same snapshot go with it, and `apps.lifetime`
+is a fresh random value per apps row (`mintLifetime`, lifetimes_store.go:358-364). So the
+app-lifetime comparison, not the sqid, is what closes that case. Keep it in
+the proof.