design: storage generations rev 2 (Astra R1: copy, drain, fence)
Answers Astra round 1's four P1s: the base is a server-side copy of exact versions (no version references, so no noncurrent expiry and moves need no remap); a clean release proves every replica request answered (lease runs the compaction/snapshot/retention passes itself) and continues its generation; old binaries still read every lock as HA and refuse it, plus an unknown-field refusal shipped ahead as slice 0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+145
−100
docs/superpowers/reviews/ASTRA-BRIEF-ha-generations.md+22 −0docs/superpowers/reviews/ASTRA-FINDINGS-ha-generations-R1.md+19 −0docs/superpowers/specs/2026-11-12-region-ha-storage-generations-design.md+104 −100
CI cancelled — superseded by a newer push — run details
Intent
Attributed to this commit: 16.8 g CO₂e (2,194,956 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-ha-generations, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/reviews/ASTRA-BRIEF-ha-generations.md b/docs/superpowers/reviews/ASTRA-BRIEF-ha-generations.md| new file mode 100644 |
| index 000000000..7cd83cd8c |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-BRIEF-ha-generations.md |
| @@ -0,0 +1,22 @@ |
| +# Astra design review: region HA per-holder storage generations (round N of max 3) |
| + |
| +Worktree /home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-generations, branch design-ha-generations. |
| +Spec: docs/superpowers/specs/2026-11-12-region-ha-storage-generations-design.md (read the commit named in the prompt). |
| +Reading only: no edits. Leave GOCACHE unset if you build anything. |
| + |
| +Context: this is your wake-race review's option 2 (~/.cache/ha-flakes/wake-race/FINDINGS.md). Paul ruled |
| +(2026-11-12): containment now (branch ha-unclean-marker-waits, region HA spec rev 6.7), this spec now, build |
| +after G6. Fixed decisions, do not re-argue: generations are per holder; build after G6; clean markers keep the |
| +drain's fast handover. The three questions in spec section 10 are open for Paul: give your recommendation. |
| + |
| +Review question: does the design guarantee G1-G5 (spec section 2) for every writer and reader, so that no |
| +successor's history can contain or be replaced by a write an earlier holder sent, without any time wait? Check |
| +against the code: the take protocol (section 4) and its races, Litestream 0.5.14 behaviour on a restored database |
| +with the union client (section 5.1, db.go checkDatabaseBehindReplica, Replica.Sync, compaction, retention), the |
| +reader inventory (section 6.1; is any reader missing?), PITR (6.2), moves (6.3), files (7), retention and the |
| +7-day noncurrent expiry (8), the old-binary fence and gate (9: verify old HAOn/ParseOwner really refuse). |
| +A mechanism that is named, bounded and assigned to a slice is complete at spec level; do not ask for plan detail. |
| +If this is round 2 or 3: first a disposition table of the previous round's findings, then only new findings. |
| + |
| +Output: findings P1/P2/P3 with file:line or spec section citations; verdict READY / READY AFTER FIXES / NOT READY. |
| +Concise. |
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-ha-generations-R1.md b/docs/superpowers/reviews/ASTRA-FINDINGS-ha-generations-R1.md| new file mode 100644 |
| index 000000000..5f8b0026c |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-FINDINGS-ha-generations-R1.md |
| @@ -0,0 +1,19 @@ |
| +Round 1, commit `b31a503b`. **Four P1 findings.** |
| + |
| +1. **P1 — A snapshot-only base resets replication to TXID 1.** |
| + **Family: history continuity; §§3.1, 5.1.** The usual clean-handover base contains only L9. Both `checkDatabaseBehindReplica` ([db.go:1414](/home/paulca/go/pkg/mod/github.com/benbjohnson/litestream@v0.5.14/db.go:1414)) and `Replica.calcPos` ([replica.go:210](/home/paulca/go/pkg/mod/github.com/benbjohnson/litestream@v0.5.14/replica.go:210)) inspect **L0 only**. On a cold restore, neither establishes `base.txid`; the first local sync starts at 1. With a base snapshot through TXID 100, successor writes below 100 are then skipped by restore in favour of that snapshot. This is data loss, not merely extra snapshot bandwidth. Specify a bootstrap mechanism that establishes both local and replica positions at the pinned boundary, including snapshot-only and compacted-only bases. |
| + |
| +2. **P1 — The six-hour snapshot target does not guarantee pin survival.** |
| + **Family: G5, referenced-version lifetime; §§5.3, 8.** A predecessor’s late overwrite makes a pinned version noncurrent. If its successor crashes before becoming self-contained and receives no wake for seven days, lifecycle can permanently delete the only baseline. Repeated short generations can also inherit an already-aged pin; their new take times do not restart its expiry. Historical restores still need earlier bases after the current generation becomes self-contained. The bucket’s [unconditional lifecycle rule](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-generations/infra/modules/deployment-buckets/main.tf:106) does not consult references. An alarm cannot enforce G5. Specify storage protection or durable immutable copies covering every live and historical dependency, including sleeping instances. |
| + |
| +3. **P1 — The old-binary fence opens the legacy acquire path.** |
| + **Family: ownership compatibility boundary; §9.** The proposed formats correctly make old `HAOn` false and make `ParseOwner` reject `;gen=1`. However, [takeLegacy](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-generations/internal/lease/legacytake.go:61) accepts an expired lock precisely when `HAOn` is false. Thus an old legacy-route wake or [move checkpoint](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-generations/internal/lease/lease.go:531) can take a v2 release marker immediately and write the root layout. Preserve old HA recognition while making old HA acquisition refuse the payload. Test both acquisition paths, not just `DecideAcquire`. |
| + |
| +4. **P1 — Moving only the current generation loses retained restore history.** |
| + **Family: G4/G5, history across relocation; §§6.2–6.3.** A self-contained current snapshot removes dependencies for latest restore only. Copying `head.json` and that generation omits earlier generations and historical head versions still required by `history`. Cross-bucket copies also receive new version IDs; copying JSON does not translate its pins. After landing, an otherwise valid `--at` request into a previous generation cannot resolve. Specify either copying and remapping the retained dependency graph, or retaining explicitly addressed source history until its restore window closes. |
| + |
| +For §10: **Q1:** prefer references once G5 has enforceable protection. **Q2:** remove the termination expiry wait once the complete fence works. **Q3:** keep one generation per holder; measure before considering coalescing. |
| + |
| +Source review only; no files changed, tests run, or oldest-live-binary verification performed. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
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| index ac5f9da99..5c40181c4 100644 |
| --- 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 |
| @@ -1,8 +1,15 @@ |
| # 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**. |
| +Design, 2026-11-12, **rev 2** (Astra round 1 answered; 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`). |
| +Sources: the wake-race review (`~/.cache/ha-flakes/wake-race/FINDINGS.md`, Astra, 2026-11-11; its options 1 and 2 combined are 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 whose shapes this reuses (`internal/genselect`, `internal/hostbox/restore.go`, `internal/moves/source.go`, `internal/lease/claimgeneration.go`). |
| + |
| +**Rev 2** answers Astra round 1 (`docs/superpowers/reviews/ASTRA-FINDINGS-ha-generations-R1.md`), four P1s: |
| +- **(gen-1.1)** a snapshot-only base reset Litestream to TXID 1: the base is now a server-side **copy** of the predecessor's files into the new generation, the newest L0 included, so the new prefix looks exactly like a restored prefix does today (§4 step 4, §5.1); |
| +- **(gen-1.2)** pinned versions could expire under the bucket's noncurrent rule: nothing references a version id after the take; the copy is made from exact versions and then owned (§4, §8); |
| +- **(gen-1.3)** the old-binary fence opened the legacy acquire: old binaries now still read every lock as HA and refuse it (§9); |
| +- **(gen-1.4)** a move dropped history: generations are self-contained prefixes under `<loc>/`, so today's whole-prefix mirror copies all of them, and head.json names generations, not versions (§6.3). |
| +- Rev 1's per-take generation would copy the database on every wake. Rev 2 starts a generation only when the predecessor did not release cleanly, and makes "clean" mean every replica request was answered (§5.2, Astra option 1). This answers rev 1 §10 Q3 and changes Q1. |
| ## 1. The problem, and what this retires |
| @@ -13,10 +20,10 @@ Today time is the only fence: |
| - 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; |
| +**Goal.** A successor never writes into a prefix 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, into a new generation; |
| - 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. |
| +- the clean marker's monitor exposure closes, because clean now proves every request was answered. |
| 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`). |
| @@ -24,21 +31,21 @@ Out of scope: hung but live boxes (still terminated by the group, RHA §9.5); th |
| | 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. | |
| +| G1 | **No shared writing.** A holder writes replica objects only into its generation prefix `<loc>/g-<id>/`. It continues an existing generation only after a **drained** clean release (§5.2), when no earlier request can still land. Otherwise it starts a new one. Nothing it does writes, compacts or deletes outside its generation. | The replica client the lease package builds (§5.1); the take decision (§4). | |
| +| G2 | **One authority.** `<loc>/head.json` names the one current generation and changes only by a conditional write of the lock holder. | §4 step 5, `If-Match`. | |
| +| G3 | **Frozen start.** A new generation starts as a server-side copy of exact object versions of its predecessor, taken at the take. A later write anywhere in the predecessor prefix cannot change the copy. | `CopyObject` with a source version id (§4 step 4). | |
| +| G4 | **One reader.** Every reader of an instance's replica resolves it through head.json, by one function. | §6, and a test that no caller builds a replica client at `<loc>` directly. | |
| +| G5 | **Self-contained generations.** No generation, and no head, refers to another generation's object versions after its take. Each generation restores from its own prefix alone. | §4 (copy, not reference); §8 retention touches whole generations only. | |
| ## 3. Layout |
| -- `<loc>/lock.json`: unchanged (the lease, release markers). |
| +- `<loc>/lock.json`: the lease and release markers (format in §9). |
| - `<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). |
| +- `<loc>/g-<id>/<level>/<min>-<max>.ltx`: one generation's Litestream files, the tree Litestream writes today, one level down. `<id>` is the lock generation of the take that created it, zero-padded to 20 digits (`g-00000000000000000042`). The lock's conditional take makes it unique, and it sorts. |
| +- `<loc>/` root LTX files: the **root generation** (`@root`, as `hostclaim.RootGeneration` names it). A predecessor only; never written once head.json exists. |
| +- `<loc>/files/0/`: unchanged (§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. |
| +The claim code uses the same `<location>/g-<gen>/` shape (`BindGeneration`, `claimgeneration.go:31`; `moves.ReplicaSource`; `genselect`). Its three prefix twins (`hostbox.GenerationPrefix`, `moves.GenerationPrefix`, `genselect.prefix`) fold into one helper. |
| ### 3.1 head.json |
| @@ -46,150 +53,147 @@ The claim code already uses `<location>/g-<gen>/` (`BindGeneration`, `claimgener |
| { |
| "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>"} ] |
| + "created_by": {"lock_generation": 42, "box": "box-a", "iid": "i-0abc", "lifetime": "<incarnation>", "at": "2026-11-12T10:00:00Z"}, |
| + "start_txid": 1234, |
| + "predecessor": "g-00000000000000000037", |
| + "history": [ {"generation": "g-00000000000000000037", "start_txid": 900, "created_at": "...", "ended_at": "2026-11-12T10:00:00Z"} ] |
| } |
| ``` |
| -- `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. |
| +- `start_txid` is the TXID the copy ends at; the generation's own writes begin after it. |
| +- `history` lists earlier generations still inside the restore window, newest first, with the time each stopped being current (`ended_at`). PITR uses it (§6.2); §8 trims it. |
| +- No version ids, so a move can copy head.json as it is (§6.3). |
| ## 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). |
| +The HA acquire is unchanged up to its conditional take of `lock.json` (RHA §9.4, `hafresh.DecideAcquire`). N is the lock generation the take wrote. Then, before the instance starts: |
| + |
| +1. **Read head.json** with its ETag `E` (absent: the current generation is `@root`; step 5 uses `If-None-Match: *`). |
| +2. **Continue or start.** Continue the current generation G only if the lock the take replaced was a **drained clean** marker naming G (§5.2). Everything else starts a new generation `g-N`: an unclean marker, a clean marker from before the drain existed, a crash or termination takeover, a same-box recovery, `@root` (the migration, §9), a staged move (§6.3). |
| +3. **Continue:** restore from G as today's restore does (the keep rule, RHA §5.3, unchanged), then step 6. head.json is unchanged. |
| +4. **Start:** list G with versions (`ListObjectVersions` under G's prefix; a paged listing that fails fails the wake). Compute Litestream's restore plan over G's **current** versions to the highest contiguous TXID `T`, and add G's newest L0 file at or below `T` (Litestream reads positions from L0 only, `db.go:1414`, `replica.go:210`). Then `CopyObject` each planned file, by its exact version id, to the same level and name under `g-N/`. Copies run in parallel and are server-side: no download, no upload from the box. |
| + - A clean marker of G records its TXID. `T` below it means a file the marker covers is missing: refuse the wake (`genselect.ErrPinnedMissing`'s meaning). `T` above it means G wrote more before its marker: those files are G's history and are copied. |
| + - An unclean marker or a crash: `T` is what G managed to store. Anything G sent that is not visible now is lost, as today (RHA §5.2), and never enters `g-N` (G3). |
| + - An empty plan on a host with data is a refusal, never a fresh boot. |
| + - If G holds no L0 at or below `T` (only compacted levels remain), the new generation needs a position file: the take restores locally, then lets Litestream write its baseline into `g-N` before step 5 (its "database behind replica" path). Slice 1 proves which of the two holds for 0.5.14 with witnesses for a snapshot-only, a compacted-only and a drain-snapshot predecessor; a full snapshot upload from the box is the fallback for that case only. |
| +5. **Switch.** Restore locally from `g-N` (the keep rule still applies: a drained clean marker naming this box with an unchanged local record keeps the local copy and skips the download). Then write head.json for `g-N` (`predecessor` G, `history` = G prepended, trimmed by §8), `If-Match: E`, with the lease healthy (`Held.Err()` nil). |
| + - **412:** head changed since step 1. Only a holder of an older lock generation can have written it, so its own switch was in flight when N took over, and it never served. N abandons: it deletes nothing (its `g-N` objects are unreferenced and §8 removes them), releases through a settled marker (it never replicated) and the wake retries once from the acquire. |
| - Any other failure: a failed wake, released settled. |
| -6. **Replicate** into `<loc>/g-N/` (§5) and serve. |
| +6. **Replicate** into the current generation (§5.1) 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. |
| +A late switch PUT from a holder that lost its lock lands either before N's step 1 (then N copies from that generation: right, its switch was real) or after it (then one of the two conditional writes gets 412). 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. |
| +**Cost per take.** Continue (the common case: sleep then wake after a clean release): one GET of head.json more than today. Start: one GET, the listing, one `CopyObject` per planned file (the plan is typically one snapshot, a few compacted files and some L0), one PUT. Copy time is S3-internal; it grows with the database (a multipart copy above 5 GB). |
| ## 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. |
| +`Held.Replicate` builds a generation client (the existing `generationClient`, `claimgeneration.go:90`, widened): |
| +- every request (`WriteLTXFile`, `LTXFiles`, `OpenLTXFile`, `DeleteLTXFiles`) is confined to `<loc>/<generation>/`; a key outside it is refused; |
| +- 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. |
| +Because a started generation holds a copy of the predecessor's plan plus its newest L0, Litestream sees exactly what it sees today after a restore: a replica at `T` with an L0 position. Retention and compaction work inside the generation as today, including on the copied files. |
| -### 5.2 Compaction |
| +### 5.2 Clean means drained |
| -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`. |
| +A clean release (RHA §5.2) additionally proves that every replica request the holder sent was answered: |
| +- the lease package runs compaction, snapshot and L0-retention passes itself, by calling `Store.CompactDB`, `Store.EnforceSnapshotRetention` and `DB.EnforceL0RetentionByTime` from its own scheduler, with Litestream's monitors off (`CompactionMonitorEnabled = false`, `L0RetentionCheckInterval = 0`, snapshot level driven by the same scheduler). The passes keep today's intervals (`lease.go` `compactionLevels`, `SnapshotInterval`); |
| +- at release, the scheduler stops starting passes and waits, up to a bound (10 s), for the pass in flight to return. Then the final sync, then `Store.Close` (which now has no monitor to cancel); |
| +- a pass that returns an error, a pass still running at the bound, or a final sync that fails makes the release unclean. |
| -### 5.3 Becoming self-contained |
| +The marker records `drained: true` only then. A clean marker without it (a binary before this design) starts a new generation (§4 step 2), so a rollout needs no flag day. |
| -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.3 Release and the acquire table |
| -### 5.4 Release |
| +- **Drained clean:** the successor continues the generation (fast, as today; the drain's `FinishSnapshot` still leaves one L9 for its restore). |
| +- **Anything else** (unclean, crash, G6's fence, an old clean marker): the successor starts a new generation. Whatever the old holder sent late lands in its own generation, which is no longer current. |
| -- **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). |
| +`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 no longer waits for expiry. These table changes ship only with the gate (§9), in slice 4. |
| ## 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): |
| +`lease.ResolveReplica(ctx, store, loc) (Replica, error)` reads head.json (absent: `@root`) and returns a read-only Litestream client confined to the current generation, plus head's ETag. 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 | |
| +| Wake restore: `backend_exec.go:1074` `restorePlain`, `hawake.go:553` `restoreHA` → `lease.Restore` (`lease.go:636`) | root levels | §4; 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 the 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>` | |
| +| Restore drill `ops/hibernate_verify.go:139/385`, `lease.VerifyReplica` (`check.go:215/248`) | root | resolver | |
| +| Create leftovers `createleftovers.go:71-99` `hostHoldsReplicaData` | root levels | also refuses on head.json or any `g-*/` (`hacreate.go:29`'s whole-prefix check already does) | |
| +| First-wake `prefixEmpty` (`ha.go:264`) | whole prefix | unchanged (sees `g-*`: safe refusal) | |
| +| Legacy moves `movespass.go:1505-1630`; offline stage, seal, land (`movesoffline_*.go`) | whole-prefix mirror; `newestLTX` parses root keys | §6.3 | |
| +| Promote staged replica `backend_exec.go:4105` (`MirrorPrefix` onto `<loc>`) | exact mirror, deletes extras | §6.3 | |
| | Seed deletes `seedfinish.go:271`, `seedwiring.go:243` | delete `<loc>/` | unchanged (whole prefix, lock-checked) | |
| +| Park sweep `park/sweep.go:227`, `park/remote.go:547` | `instances/<host>/` exact versions | unchanged: whole prefix, so every generation | |
| | 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. |
| +`--at T` (#262): if T is at or after the current generation's `created_by.at`, read the current generation. Otherwise walk `history` to the entry whose `created_at` ≤ T < `ended_at` and read that generation alone, with today's CreatedAt rule. Each generation is self-contained (G5), so this needs no other generation. Files a generation's holder wrote after its successor's copy (a late write, or writes lost in an unclean release) are visible to a T inside that holder's tenure, because that is what that holder had at T. Documented as such. A T older than every `history` entry still inside the restore window is refused, as a T before the oldest retained file is today. |
| ### 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. |
| +Generations are ordinary prefixes under `<loc>/`, and head.json names them by name only. So: |
| +- **Legacy and offline moves** keep their whole-prefix mirror (`MirrorPrefix`), which copies head.json, every generation and the root. The landing side reads head.json through the resolver. `newestLTX` and `replicaPosition` (`movesoffline_seal.go:391/432/488`, `movesreport.go:599`) read the resolved current generation instead of parsing root keys. |
| +- **Promote staged replica** stops exact-mirroring onto a live `<loc>`. The staged prefix becomes the predecessor of a §4 start: its resolved generation is copied into a new `g-N` under `<loc>` and head.json switches to it, with the staged head's `history` carried over (the copied history generations come along by the same mirror). Nothing under the live `<loc>` is deleted by a move. |
| +- **Claim moves** already copy one generation with a keep function (`moves/source.go:30`); unchanged. |
| ## 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. |
| +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). 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 not part of 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). |
| +The data bucket is versioned; noncurrent versions expire after `data_noncurrent_days` (7, `infra/modules/deployment-buckets`). Nothing here depends on a noncurrent version surviving: each take's copy is made at the take, and every later read uses current versions of a generation's own files (G5). |
| -- **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. |
| +- **Inside a generation:** Litestream retention as today (snapshot retention, L0 retention), run by the §5.2 scheduler. |
| +- **History:** a `history` entry stays while its `ended_at` is inside the restore window (7 days, #263). At each switch (§4 step 5) the new head drops the expired entries. |
| +- **Retirement:** after its switch, the new holder deletes the current objects of generations that left `history`, and of abandoned `g-*` prefixes no head names (a §4 step 5 412), older than one day. Their versions then expire by lifecycle. The park sweep already covers the whole prefix. |
| +- **Storage:** a new generation copies one restore plan (about one database's size, compressed) and exists only after an unclean release, a crash, a fence or a move, so the steady cost is near zero; it is bounded by those events inside 7 days. |
| ## 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: |
| +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. Three layers: |
| -- **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. |
| +- **Gate.** A pool turns generations on only when every box serving it publishes capability `replica-generations-1` (as `offline-move-1`). With the gate on, nothing places on a box without it. The release that adds the capability is the **floor**: no HA box goes below it. |
| +- **Old binaries still see HA, and refuse.** Today's `HAOn` is true for a lock with `carlos_release`, an owner starting `released/v1;`, or a parsable `;ha=1` owner (`hafresh/lock.go:94`); an HA lock is never taken by the legacy acquire (`legacytake.go:61`). Today's `DecideAcquire` refuses (ReasonBadMarker) an owner starting `released/v1;` with no `carlos_release` record (`acquire.go:89-93`). So a generations host's locks use: |
| + - release markers: owner `released/v1;ref=<box>;iid=<iid>;gen=1`, record field `carlos_release_g` (not `carlos_release`). Old HA acquire: bad marker, refused. Old legacy acquire: HA, refused. |
| + - held locks: owner `box/v1;ref=…;iid=…;pid=…;ha=1`, unchanged, plus record field `carlos_generation` written into the lock body by the take. An old box's HA acquire would treat it as an ordinary HA lock: it waits for expiry and termination proof, then takes, and would then restore the root. That case is closed by the gate and the floor only, and by slice 0 below. |
| +- **Slice 0, ahead of everything (rides an early release):** `DecideAcquire` and the legacy take refuse any lock carrying a field they do not know from a fixed list (`carlos_generation`, `carlos_release_g`, and any future `carlos_*`). Every binary at or above the floor then refuses a generations lock outright, held or released. Verify against the oldest binary on any HA box when the gate turns on. |
| +- **Migration:** no copy job. A host's first take on the new code starts `g-N` from `@root` (§4) and writes head.json. The root files are then retired with §8 (as a `history` entry named `@root`). |
| ## 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). |
| +1. **How does a new generation get its start?** Recommended: a server-side copy of the predecessor's restore plan (§4 step 4): seconds for typical databases, no upload from the box, and nothing ever refers back to another generation. Rejected: references to pinned versions (rev 1), because the bucket's noncurrent expiry could delete a referenced version (gen-1.2); a full snapshot upload from the box before serving, because it adds the upload time (over a minute at 1.6 GB) to every failover. |
| +2. **Drop N-HA9's expiry wait once this is live?** Recommended: yes, for confirmed-terminated owners and same-box recovery (§5.3). The wait exists only because storage had no fence. Hung boxes are unchanged. Astra round 1 agreed. |
| +3. **Continue the generation after a drained clean release?** Recommended: yes (§5.2): sleep and wake, and planned handovers, then cost nothing extra, and the clean exposure is closed by the drain instead of a copy per wake. The alternative, a generation per take, copies the database on every wake. |
| -## 11. Slices (after G6) |
| +## 11. Slices (after G6, except slice 0) |
| -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. |
| +0. **Unknown-field refusal** (§9), now: small, inert, rides the next release, so the floor exists when slice 1 needs it. |
| +1. **Lease core:** head.json, the take (§4) with copy and switch, the confined client (§5.1), the drained release (§5.2), the resolver with wake restore and seed placement (§6.1), the files fence (§7), the gate and lock formats (§9). Behind the gate; dev only. |
| +2. **Readers:** door, backups, seed copy, db reads, drill, leftovers (§6.1), PITR (§6.2). |
| +3. **Moves** (§6.3) and retirement (§8). |
| +4. **Table change:** drop the rev 6.7 wait and N-HA9's expiry clause (§5.3), with RHA §21's drills 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. |
| +- The late-write witness (`unclean_marker_test.go`) with no wait: B takes at once into a new generation; A's held upload lands afterwards in A's generation; B's restore, PITR and compaction never see it. |
| - 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. |
| +- Head races: two takes; a late switch PUT before and after the successor's read (§4 step 5); the 412 path leaves no head change and an unreferenced prefix §8 removes. |
| +- The copy is immune: overwrite a copied source key after step 4, and restore of the new generation is unchanged. |
| +- Litestream continues at `T + 1` with no gap after a start from a snapshot-only, a compacted-only and a drain-snapshot predecessor (§4 step 4). |
| +- The drain: a pass in flight at release is waited for; one past the bound makes the release unclean and the next take starts a generation. |
| +- Old binaries: the oldest live release refuses a `released/v1;…;gen=1` marker without `carlos_release`; a slice-0 binary refuses a held lock with `carlos_generation`. Both the HA and the legacy acquire. |
| - 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. |
| +- Moves: whole-prefix mirror then resolve on landing; promote creates a new generation and deletes nothing live. |
| +- Retirement removes only generations outside `history` and abandoned prefixes over a day old. |
| +- Simulation: model generations; I1 becomes "no late write lands in the current generation", with rules for §4 steps 2 to 5 and §5.2, and a witness 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. |
| +At most three Astra rounds (memory round-limit-anti-spin). This is rev 2 after round 1. A P1 in round three cuts scope or goes to Paul. |