design: region HA per-holder storage generations (rev 1)
Spec only, nothing built: per-holder replica prefixes g-<lockgen>, a head.json pointer switched by If-Match, a version-pinned base instead of a bulk copy, one resolver for every reader, moves, retention, an old-binary fence and the gate. Retires the rev 6.7 wait and N-HA9's expiry wait once built (after G6). Astra review to follow, max three rounds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+195
−0
docs/superpowers/specs/2026-11-12-region-ha-storage-generations-design.md+195 −0
CI passed — run details
Intent
Human
<task-notification> <task-id>bke82ipe0</task-id> <tool-use-id>toolu_01PN14upVprZLj2PHcywBvoi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/18c2ef37-6ec3-4dcd-8be8-7eed9ce0123f/tasks/bke82ipe0.output</output-file> <status>completed</status> <summary>Background command "Run the Astra (codex) read-only review of the containment" completed (exit code 0)</summary> </task-notification>
diff --git a/docs/superpowers/specs/2026-11-12-region-ha-storage-generations-design.md b/docs/superpowers/specs/2026-11-12-region-ha-storage-generations-design.md| new file mode 100644 |
| index 000000000..ac5f9da99 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-12-region-ha-storage-generations-design.md |
| @@ -0,0 +1,195 @@ |
| +# Region HA: per-holder storage generations |
| + |
| +Design, 2026-11-12, **rev 1** (draft for Astra review; max three rounds). Branch `design-ha-generations`. Nothing here is built. Paul's ruling (2026-11-12, HA session, #421): contain the unclean-release late write now (branch `ha-unclean-marker-waits`, region HA spec rev 6.7), spec storage generations now, **build after G6**. |
| + |
| +Sources: the wake-race review (`~/.cache/ha-flakes/wake-race/FINDINGS.md`, Astra, 2026-11-11; its option 2 is this design), the containment review (`docs/superpowers/reviews/ASTRA-FINDINGS-ha-unclean-containment-R1.md`), region HA without claims (**RHA**, `2026-10-26-region-ha-without-claims-design.md`, §5, §9.4, N-HA9), and the dormant claim machinery this reuses (`internal/genselect`, `internal/hostbox/restore.go`, `internal/moves/source.go`, `internal/lease/claimgeneration.go`). |
| + |
| +## 1. The problem, and what this retires |
| + |
| +Every holder of an HA instance's lease writes its Litestream replica into one shared prefix, `<loc>/` (`instances/<host>/`), with no ownership condition on the write (`litestream@v0.5.14/s3/replica_client.go:702`). Litestream's close cancels requests without proof that S3 did not receive them. So a request an earlier holder sent can be applied after a successor has restored and started its own history under the same keys. The late object replaces the successor's, and history diverges silently (wake-race P1 B; witness `internal/lease/unclean_marker_test.go`, adapted from 8e8a00a0). |
| + |
| +Today time is the only fence: |
| +- N-HA9: a terminated owner's lock is taken only after it expires (up to 15 minutes); |
| +- rev 6.7: an unclean release after replication waits a lease term from its marker; |
| +- a clean release opens at once, and still carries the exposure for cancelled compaction, snapshot and retention requests (containment R1 A). Paul kept that for the drain's fast handover. |
| + |
| +**Goal.** A successor never appends to, or replaces, anything an earlier holder can still write. Late writes may land; they land where nobody reads them as current. With that in place: |
| +- the rev 6.7 wait goes: an unclean marker opens at once; |
| +- N-HA9's expiry wait goes: a confirmed-terminated owner's lock is taken on the proof alone (RHA §9.8 totals become 1 to 5 minutes, not 15); |
| +- the clean marker's monitor exposure closes. |
| + |
| +Out of scope: hung but live boxes (still terminated by the group, RHA §9.5); the process single-writer rule (I1's cgroup and termination proofs stay); legacy non-HA hosts and the box-wide Litestream (`internal/ops/litestream.go`). |
| + |
| +## 2. Invariants |
| + |
| +| ID | Invariant | Enforced by | |
| +|---|---|---| |
| +| G1 | **Own prefix.** A holder writes replica objects only under its own generation prefix `<loc>/g-<id>/`. Nothing it does writes, compacts or deletes under another generation. | The replica client the lease package builds (§5), refusing any key outside the bound prefix. | |
| +| G2 | **One authority.** `<loc>/head.json` names the one current generation, and changes only by a conditional write made by the lock holder whose generation it names. | §4 take protocol, `If-Match`. | |
| +| G3 | **Frozen base.** A generation's history is: its base (exact object versions of its predecessor, pinned at take) then its own files. A later write anywhere in the predecessor prefix cannot change what the base resolves to. | Version-pinned reads (§5). | |
| +| G4 | **One reader.** Every reader of an instance's replica (wake, door, PITR, drill, seed copy, leftovers, moves) resolves it through head.json, by one function. | §6, and a census-style test that no caller builds a replica client at `<loc>` directly. | |
| +| G5 | **Pins outlive their use.** A pinned version is never deleted or expired while a head (or a PITR chain entry inside the restore window) references it. | §8 retention rules and the bucket's noncurrent window. | |
| + |
| +## 3. Layout |
| + |
| +- `<loc>/lock.json`: unchanged (the lease, release markers). |
| +- `<loc>/head.json`: the pointer (§3.1). Absent means the legacy root layout. |
| +- `<loc>/g-<id>/<level>/<min>-<max>.ltx`: one generation's Litestream files, the same tree Litestream writes today, one level down. `<id>` is the lock generation the holder took, zero-padded to 20 digits (`g-00000000000000000042`). The lock's conditional take makes it unique per holder, and it sorts. |
| +- `<loc>/` root LTX files: the **root generation** (`@root`, as `hostclaim.RootGeneration` names it). Read as a predecessor only, never written once head.json exists. |
| +- `<loc>/files/0/`: unchanged in slice 1 (§7). |
| + |
| +The claim code already uses `<location>/g-<gen>/` (`BindGeneration`, `claimgeneration.go:31`, `moves.ReplicaSource`, `genselect`). This design keeps that shape and its three prefix twins (`hostbox.GenerationPrefix`, `moves.GenerationPrefix`, `genselect.prefix`), and folds them into one helper. |
| + |
| +### 3.1 head.json |
| + |
| +```json |
| +{ |
| + "v": 1, |
| + "generation": "g-00000000000000000042", |
| + "lock_generation": 42, |
| + "box": "box-a", "iid": "i-0abc", "lifetime": "<incarnation>", |
| + "taken_at": "2026-11-12T10:00:00Z", |
| + "base": { |
| + "generation": "g-00000000000000000041", |
| + "txid": 1234, |
| + "files": [ {"key": "<loc>/g-...41/0009/...ltx", "version": "<s3 version id>", "level": 9, "min": 1, "max": 1200}, |
| + {"key": "...", "version": "...", "level": 0, "min": 1201, "max": 1234} ] |
| + }, |
| + "self_contained_txid": 0, |
| + "history": [ {"generation": "g-...41", "start_txid": 900, "taken_at": "...", "base_head_version": "<version id of the head that named it>"} ] |
| +} |
| +``` |
| + |
| +- `base` is the predecessor's restore plan at take time, as exact versions (§4 step 3). A clean drain release leaves one L9 at the final TXID (RHA §25.4), so a planned handover's base is usually one file. |
| +- `self_contained_txid` is set once the generation holds its own snapshot (L9) at a TXID at or above `base.txid` (§5.3). From then on, restoring the current generation needs no base. |
| +- `history` lists earlier generations inside the restore window, newest first, for PITR (§6.2). Entries leave it as §8 retires them. |
| + |
| +## 4. The take |
| + |
| +The HA acquire is unchanged up to its conditional take of `lock.json` (RHA §9.4, `hafresh.DecideAcquire`). Generation N is the lock generation the take wrote. Then, before the instance starts: |
| + |
| +1. **Read head.json** with its ETag `E` (absent: the predecessor is `@root`, and the write in step 5 is `If-None-Match: *`). |
| +2. **List the predecessor** `P = head.generation` with versions (`ListObjectVersions` under `<loc>/g-P/`, or the root levels for `@root`). A paged listing that fails is a failed wake: no partial plan. |
| +3. **Plan and pin.** If P is self-contained or has a base, the plan starts from its base pins, then P's own current versions. Compute Litestream's restore plan over that set to the highest contiguous TXID `T` (litestream's own `CalcRestorePlan`, given a client that serves exactly these versions). Record each file as key and version id. Delete markers and gaps follow `genselect`'s errors (`ErrDeleteMarker`, `ErrGap`). An empty plan on a host with data is a refusal, never a fresh boot. |
| + - A **clean** release marker of P records its TXID. If `T` is below it, a file the marker covers is missing: refuse the wake (`ErrPinnedMissing`), as today's keep proof would. If `T` is above it, the extra files were written by P before its marker: they are part of P's history and stay in the plan. |
| + - An unclean marker, or a crash: `T` is what P managed to store. Anything P sent that is not visible now is lost, as today (RHA §5.2), and can never enter N's history (G3). |
| +4. **Restore** into the clean tree from the pinned set (`hostbox.ColdRestore`'s `pinnedClient` shape). The local keep rule (RHA §5.3) still applies: a clean marker naming this box, with `T` equal to its TXID and the local record unchanged, keeps the local copy and skips the download, but the pins are still written. |
| +5. **Switch.** Write head.json for N (`base` = the pins, `history` = P's head entry prepended, trimmed by §8), `If-Match: E`. The lease must still be healthy (`Held.Err()` nil) before the PUT. |
| + - **412:** head changed since step 1. Only a holder of an older lock generation can have written it (G2: N holds the lock), so its switch was in flight when N took over and it never served. N writes nothing more, releases through a settled marker (it never replicated) and the wake retries from the acquire (one retry, then a failed wake). |
| + - Any other failure: a failed wake, released settled. |
| +6. **Replicate** into `<loc>/g-N/` (§5) and serve. |
| + |
| +Nothing is written under `g-N/` before step 5 lands, so an abandoned take leaves no objects. A late step 5 PUT of a holder that lost its lock to N+1 lands either before N+1's step 1 (N+1 then takes N as its predecessor: correct, N's switch was real) or after it (N+1's own switch then gets 412 or wins first; the late one gets 412). Either way exactly one switch per ETag. |
| + |
| +**Cost per take:** one GET (head), one or more `ListObjectVersions` pages of one generation (today's restore already lists the levels), one PUT. No bulk copy: the base is a reference. |
| + |
| +## 5. Writing a generation |
| + |
| +### 5.1 The replica client |
| + |
| +`Held.Replicate` builds a **generation client** (the existing `generationClient`, `claimgeneration.go:90`, widened): |
| +- **Writes** (`WriteLTXFile`) go to `<loc>/g-N/` only. |
| +- **Reads and listings** (`LTXFiles`, `OpenLTXFile`) return the union of the base pins (served by version id, at or below `base.txid`) and `g-N`'s own files. Litestream therefore sees a replica at `base.txid` and continues at `base.txid + 1` (`checkDatabaseBehindReplica`, `db.go:1406`, sees no gap). |
| +- **Deletes** (`DeleteLTXFiles`, retention) apply to `g-N` keys only. A delete naming a base file is dropped, not an error, so Litestream's retention keeps working on its own files. |
| +- Every request first checks the lease's health, as `BindGeneration`'s check does. |
| + |
| +To verify in the plan, with a witness: that Litestream 0.5.14 started on the restored database against this client uploads L0 from `base.txid + 1` and does not insist on a fresh snapshot first. If it does insist, the snapshot upload runs while the instance serves; the base keeps the generation restorable meanwhile, so durability is unchanged, only bandwidth. |
| + |
| +### 5.2 Compaction |
| + |
| +Compaction runs inside the generation. An L1 window that spans `base.txid` reads base files and writes the compacted file into `g-N`, which is allowed: base files are frozen, and the output belongs to N. No compaction ever writes outside `g-N`. |
| + |
| +### 5.3 Becoming self-contained |
| + |
| +Once `g-N` holds an L9 at a TXID at or above `base.txid` (the snapshot monitor, 24 h; or the drain's `FinishSnapshot` at release), the holder rewrites head.json with `self_contained_txid`, `If-Match` its own last ETag. After that, restoring N reads no base. The holder also forces one snapshot within **6 hours** of the take if the monitor has not (§8, G5). A holder that cannot write it keeps serving; the base stays referenced and the §8 alarm fires before any pin could expire. |
| + |
| +### 5.4 Release |
| + |
| +- **Clean** (RHA §5.2): unchanged, plus the marker records `generation`. The drain's snapshot makes the successor's base one file. |
| +- **Unclean, crash, fence (G6):** unchanged. The marker no longer delays anyone: whatever N sent late lands in `g-N`, which N+1 has already pinned. |
| + |
| +`hafresh.DecideAcquire` then drops the rev 6.7 row (an unclean marker is taken at once) and N-HA9's expiry clause (a confirmed-terminated owner is taken at once). Same-box recovery still needs the emptiness proof, and now no expiry. These table changes ship only with the gate (§9). |
| + |
| +## 6. Readers |
| + |
| +### 6.1 One resolver |
| + |
| +`lease.ResolveReplica(ctx, store, loc) (Replica, error)` reads head.json (absent: `@root`) and returns a read-only Litestream client over the current generation's base pins plus its current files, and the head's ETag and version for callers that need a stable view. Every reader below switches to it (G4). Inventory (2026-11-12, at 08aed1c1): |
| + |
| +| Reader | Today | With generations | |
| +|---|---|---| |
| +| Wake restore: `backend_exec.go:1074` `restorePlain`, `hawake.go:553` `restoreHA` → `lease.Restore` (`lease.go:636`) | root levels | §4 (pinned plan); a non-HA host keeps today's root restore | |
| +| Seed placement `seedplace.go:173` `HasReplica` (`check.go:405`) | root levels | resolver; "no replica" only when head is absent and root is empty | |
| +| Console DB door `apidb.go:73/171/503`, backups `backups.go:182`, seed copy `apiinstanceseed.go:286`, box db reads `dbreads/read.go:166` | `ReadReplicaClient` at root | resolver | |
| +| Restore drill `ops/hibernate_verify.go:139/385`, `lease.VerifyReplica` (`check.go:215/248`) | root | resolver; the drill also checks §8's pin ages | |
| +| Create leftovers `createleftovers.go:71-99` `hostHoldsReplicaData` | root levels | also refuses on any head.json or `g-*/` (today's whole-prefix check `hacreate.go:29` already does) | |
| +| First-wake `prefixEmpty` (`ha.go:264`) | whole prefix | unchanged (sees `g-*`, safe) | |
| +| Legacy moves `movespass.go:1505-1630`, offline stage/seal/land (`movesoffline_*.go`) | whole-prefix mirror, `newestLTX` root parse | §6.3 | |
| +| Promote staged replica `backend_exec.go:4105` (`MirrorPrefix` onto `<loc>`) | exact mirror, deletes extras | lands into a fresh generation (§6.3); never an exact mirror over `<loc>` | |
| +| Seed deletes `seedfinish.go:271`, `seedwiring.go:243` | delete `<loc>/` | unchanged (whole prefix, lock-checked) | |
| +| Claim paths (`apidbclaim.go`, `genselect`, claim moves) | generation-aware | unchanged; share the prefix helper | |
| + |
| +### 6.2 Point-in-time reads |
| + |
| +`--at T` (RHA, #262): walk head then `history`, newest first, to the generation whose `taken_at` is at or before T. Restore that generation's base pins plus its own files created before T (the CreatedAt rule, truncated to the second as today). A generation's files after its successor's base TXID are history that never became current (late writes, or writes lost in an unclean release); a read at a T inside that generation's tenure includes them, because that is what that holder had at T. Documented as such. |
| + |
| +### 6.3 Moves |
| + |
| +A move copies one instance's replica to another prefix or region. With generations it copies the **resolved** replica: |
| +1. under the source lease (today's checkpoint), force a snapshot into the current generation and mark it self-contained (§5.3); |
| +2. mirror `head.json` and that one generation, with `MirrorPrefixKeep` (the claim moves' keep function, `moves/source.go:30`); |
| +3. the landing side writes its own head (lock generation of its own first take) whose base pins the copied snapshot. |
| + |
| +The landing side never exact-mirrors over a live `<loc>`. `promoteStagedReplica` becomes "pin the staged generation as base" (§4 with the staged prefix as predecessor). Offline-move `newestLTX` reads the resolved generation, not the root. |
| + |
| +## 7. Files, wake state and other colocated objects |
| + |
| +Files objects are immutable and the manifest moves by compare-and-swap (RHA §8.2), so a late write cannot replace a successor's object. A late manifest CAS can still land between the successor's read and its first publish; the successor's CAS then gets 412 and its publisher errs (containment R1 A, last paragraph). Slice 1 adds one fence: at take step 5, the successor rewrites the manifest unchanged with its lock generation in it, `If-Match` the ETag it restored from. A late CAS conditioned on that ETag then fails. Build state, rootfs and demo markers (`rootfsmarker.go:74`, `buildstate.go:82`, `demo_durability.go:186`) are written outside the wake's history and stay at the root. |
| + |
| +## 8. Retention and retirement |
| + |
| +The data bucket is versioned; noncurrent versions expire after `data_noncurrent_days` (7, `infra/modules/deployment-buckets`). Litestream's own retention deletes inside the current generation only (§5.1). |
| + |
| +- **Pins (G5).** A base pin can become noncurrent the moment the predecessor rewrites that key, and then expires 7 days later. The successor becomes self-contained within 6 hours (§5.3), far inside that. The restore drill and an alarm (`ha_generation_base_age`) fire when a current head has carried a base for 24 hours. |
| +- **PITR history.** A `history` entry stays while its successor's `taken_at` is inside the restore window (7 days, #263). Its generation's objects stay until it leaves `history`. |
| +- **Retirement.** At each take, after step 5, the new holder deletes the objects of generations that left `history` (current versions; their noncurrent versions expire by lifecycle). The park sweep (`park/sweep.go:227`) learns that `g-*` under `instances/<host>/` are part of the instance, and archives exact versions as today. A generation is never deleted while any head, `history` entry or moves staging names it. |
| +- **Storage.** Each generation adds at most one full snapshot (its self-contained L9) plus its own L0 to L3 tail. Today's single prefix already keeps a daily snapshot, so the steady extra is one snapshot per take inside the window. A host that wakes many times a day gets one generation per wake: retirement keeps only those inside 7 days, and §10 Q3 asks whether to coalesce. |
| + |
| +## 9. Rollout and the old-binary fence |
| + |
| +A binary that predates this design reads and writes the root. Once a host has head.json, such a binary would restore stale root data and append to it. So: |
| + |
| +- **Gate.** A pool turns generations on only when every box serving it publishes capability `replica-generations-1` (the same pattern as `offline-move-1`). A pool with the gate on never places on a box without it. |
| +- **Old-binary refusal.** From the first switch, the host's release markers use owner prefix `released/v2;` and the record field `carlos_release_v2`. An old binary reads no `carlos_release`, no `released/v1;` owner and no parsable box owner, so `HAOn` is false and its acquire refuses the lock as a leftover (`hafresh/acquire.go`, ReasonLeftoverLock). Held locks already use an owner old binaries parse; the owner gains `;gen=1`, which old `ParseOwner` rejects (strict parser), so an old box also refuses a held lock instead of treating it as another box's HA lease. Verify both against the oldest binary still on any HA box. |
| +- **Migration.** No copy. A host's first take on the new code pins the root files as its base (`@root`) and writes head.json. The root files then age out with §8. |
| +- **No downgrade** below the gate release on an HA box. The release floor records it. |
| + |
| +## 10. Questions for Paul |
| + |
| +1. **Base by reference, or a full upload before serving?** Recommended: by reference (§4). A full snapshot upload before serving is simpler to reason about, but it adds the database's upload time to every wake (1.6 GB took over a minute in the move timings) and to every failover. |
| +2. **Drop N-HA9's expiry wait once this is live?** Recommended: yes, for terminated owners (§5.4). The wait exists only because storage had no fence; this is the fence. Hung boxes are unchanged. |
| +3. **Coalesce frequent wakes?** A host that sleeps and wakes every few minutes makes a generation each time. Recommended: no special case in slice 1; measure the object count on dev, then decide (a clean marker from the same box could continue its generation). |
| + |
| +## 11. Slices (after G6) |
| + |
| +1. **Lease core:** head.json, the take protocol (§4), the generation client (§5.1), self-contained switch (§5.3), resolver (§6.1) with wake restore and seed placement, files fence (§7), gate and old-binary fence (§9). Behind the gate; dev only. |
| +2. **Readers:** door, backups, seed copy, db reads, drill, leftovers (§6.1 table), PITR (§6.2). |
| +3. **Moves** (§6.3) and park/retirement (§8). |
| +4. **Table change:** drop the rev 6.7 wait and N-HA9's expiry clause (§5.4), with the drills of RHA §21 rerun and timed. |
| + |
| +## 12. Tests and witnesses |
| + |
| +- The late-write witness (`unclean_marker_test.go`) without any wait: B takes at once, A's held upload lands after B's writes, and B's history (restore, PITR, compaction) never contains A's object. |
| +- Crash takeover on termination proof alone, with an upload landing a minute later. |
| +- Head races: two takes, a late switch PUT before and after the successor's read (§4 step 5). |
| +- Pinned base after the predecessor's key is overwritten and the old version made noncurrent. |
| +- Litestream continuation at `base.txid + 1` with no gap and no forced snapshot (§5.1). |
| +- An old binary refuses a v2 marker and a `;gen=1` owner (§9), run against the oldest live release. |
| +- PITR across a generation boundary, inside and outside a predecessor's late tail (§6.2). |
| +- Moves: resolved copy, landing pin, no exact mirror over a live prefix. |
| +- Retirement never deletes a referenced generation; the base-age alarm fires. |
| +- Simulation: model generations; I1 becomes "no late write lands in the current generation", with rules for each step of §4 and witnesses for each. |
| + |
| +## 13. Review budget |
| + |
| +At most three Astra rounds (memory round-limit-anti-spin). A P1 in round three cuts scope or goes to Paul. |