carlos / platform Public

ops, lease: carlos ops ha-generations list, verify and point

Task 14 of the region HA storage generations build: the by-hand
restore of a host whose wake was refused (ha_generation_refused).

- lease.ListGenerations and lease.VerifyGeneration only read:
  head.json, the lock, each generation's newest L0, and a restore of
  one generation pinned at its newest L0, integrity-checked.
- lease.PointGeneration is the one function that writes head.json
  and lock.json for an operator. It refuses a live held lock, an
  absent or unknown-field lock, a missing or unplannable generation,
  a TXID that is not the generation's newest L0, and a failed
  verify, all before any write. With Write it rewrites head.json
  first (If-Match, or create-only), then lowers the lock's take
  bound (clean TXID, min_txid, carlos_min_txid) to the TXID
  (If-Match), keeping the marker format, owner and generation.
  head.json times are the store's (the Date of a lock read just
  before the writes).
- carlos ops ha-generations list|verify|point: point is a dry run
  unless --yes and prints exactly the documents it writes and the
  loss. Refuses root. Per invocation only, no polling.
- parity: box-ops row and cli.tsv list the three leaves.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 003e44eca62470dce6b3157ae1a5812ceff04427 parent 59bafaa
11 files changed, +1,891 −10
  • docs/parity.md +1 −1
  • internal/lease/genpoint.go +584 −0
  • internal/lease/genpoint_test.go +380 −0
  • internal/lease/head.go +18 −8
  • internal/lease/legacytake.go +9 −0
  • internal/lease/storeclock.go +8 −0
  • internal/ops/hagenerations.go +410 −0
  • internal/ops/hagenerations_test.go +469 −0
  • internal/ops/ops.go +8 −0
  • parity/cli.tsv +3 −0
  • parity/parity.tsv +1 −1
diff --git a/docs/parity.md b/docs/parity.md
index 1e117a830..0e12c449a 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -435,7 +435,7 @@ Discussion #742.
| box-routes | box | `add`<br>`remove`<br>`route`<br>`instances` | | This box's own registry routes. |
| box-daemons | box | `edge`<br>`agent`<br>`adopt` | | Run under systemd on a box. |
| box-instance | box | `instance-control`<br>`instance-exec`<br>`instance-exit`<br>`instance-stop`<br>`instance-probe` | | Instance plumbing run under systemd. |
-| box-ops | box | `ops litestream`<br>`ops restore-verify`<br>`ops hibernate-verify` | | Checks run on a box. |
+| box-ops | box | `ops litestream`<br>`ops restore-verify`<br>`ops hibernate-verify`<br>`ops ha-generations list`<br>`ops ha-generations verify`<br>`ops ha-generations point` | | Checks run on a box. |
| release-keygen | box | `release-keygen` | | Mints signing keys; the private key stays local. |
| proof | box | `proof keygen`<br>`proof get`<br>`proof put`<br>`proof history` | | Dev proofs a box needs to adopt. |
| relay-box | box | `relay serve`<br>`relay keygen` | | Runs the relay, or mints a region master key. |
diff --git a/internal/lease/genpoint.go b/internal/lease/genpoint.go
new file mode 100644
index 000000000..7cf8f5a23
--- /dev/null
+++ b/internal/lease/genpoint.go
@@ -0,0 +1,584 @@
+package lease
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ lss3 "github.com/benbjohnson/litestream/s3"
+ "github.com/superfly/ltx"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// The by-hand restore of a storage-generations host whose wake was
+// refused (ha_generation_refused; Task 14, `carlos ops ha-generations`).
+// ListGenerations and VerifyGeneration only read. PointGeneration is the
+// one operator path that accepts data loss, and the only code outside a
+// take or a release that writes head.json or lock.json: it repoints
+// head.json at a complete generation g-N and lowers the lock's take bound
+// to g-N's newest L0 TXID, so the next take starts from g-N and keeps
+// exactly the transactions up to that TXID.
+//
+// Every request is per operator invocation: nothing here polls.
+
+// PointCreator is the box a head.json written by PointGeneration names in
+// created_by: an operator's point, not a take.
+const PointCreator = "carlos-ops-point"
+
+// GenerationInfo is one generation under a location: its name and the
+// highest MaxTXID among its current L0 files (0: none), the position a
+// take would start its successor at.
+type GenerationInfo struct {
+ Name string
+ NewestL0 uint64
+}
+
+// HostGenerations is one read of a host's storage-generations state: its
+// head.json, every generation under its location (replicagen.Root first
+// when the root layout holds LTX files, then each g-* prefix in name
+// order) and its lock with the store's time of that read (the zero time
+// when the store gave none, or the lock is absent).
+type HostGenerations struct {
+ Head Head
+ HeadFound bool
+ Generations []GenerationInfo
+ Lock hafresh.View
+ At time.Time
+}
+
+// pointStores are the clients the operator verbs read and write through,
+// built as the take's are.
+type pointStores struct {
+ st release.Store
+ vs VersionedStore
+ client lss3.S3API
+ region string
+}
+
+func openPointStores(ctx context.Context, bucket, region string) (pointStores, error) {
+ region, err := resolveRegion(ctx, region)
+ if err != nil {
+ return pointStores{}, err
+ }
+ client, region, err := newLeaserClient(ctx, region)
+ if err != nil {
+ return pointStores{}, err
+ }
+ st, err := NewFilesStore(ctx, bucket, region)
+ if err != nil {
+ return pointStores{}, err
+ }
+ vs, err := NewVersionedS3(ctx, map[string]string{bucket: region})
+ if err != nil {
+ return pointStores{}, err
+ }
+ return pointStores{st: st, vs: vs, client: client, region: region}, nil
+}
+
+// ListGenerations reads s3://bucket/loc's head.json and lock.json, lists
+// the location's directories once, and lists each generation's L0
+// directory once (the root's too, when the root layout holds LTX files).
+// It writes nothing.
+func ListGenerations(ctx context.Context, bucket, loc, region string) (HostGenerations, error) {
+ key, err := lockKey(bucket, loc)
+ if err != nil {
+ return HostGenerations{}, err
+ }
+ s, err := openPointStores(ctx, bucket, region)
+ if err != nil {
+ return HostGenerations{}, err
+ }
+ var out HostGenerations
+ var clock storeClock
+ if out.Lock, err = readViewClock(ctx, s.client, bucket, key, &clock); err != nil {
+ return HostGenerations{}, err
+ }
+ out.At = clock.last()
+ if out.Head, _, out.HeadFound, err = ReadHead(ctx, s.st, loc); err != nil {
+ return HostGenerations{}, err
+ }
+ base := loc + "/"
+ dirs, err := s.st.ListDirs(ctx, base)
+ if err != nil {
+ return HostGenerations{}, fmt.Errorf("lease: list %s: %w", base, err)
+ }
+ var gens []string
+ rootLevels := false
+ for _, d := range dirs {
+ name, ok := strings.CutPrefix(d, base)
+ if !ok {
+ continue
+ }
+ name = strings.TrimSuffix(name, "/")
+ switch {
+ case isLevelDir(name):
+ rootLevels = true
+ case name != replicagen.Root && replicagen.Valid(name):
+ gens = append(gens, name)
+ }
+ }
+ sort.Strings(gens)
+ if rootLevels {
+ // The root layout holds LTX files: only its L0 directory says
+ // where it reached.
+ n, err := newestL0(ctx, s.vs, bucket, base, base+"0000/")
+ if err != nil {
+ return HostGenerations{}, err
+ }
+ out.Generations = append(out.Generations, GenerationInfo{Name: replicagen.Root, NewestL0: n})
+ }
+ for _, g := range gens {
+ p := replicagen.Prefix(loc, g)
+ n, err := newestL0(ctx, s.vs, bucket, p, p+"0000/")
+ if err != nil {
+ return HostGenerations{}, err
+ }
+ out.Generations = append(out.Generations, GenerationInfo{Name: g, NewestL0: n})
+ }
+ return out, nil
+}
+
+// newestL0 lists prefix (one ListVersions, the L0 directory of the
+// generation whose prefix is gen) and returns the highest MaxTXID among
+// its current L0 files, 0 when there is none.
+func newestL0(ctx context.Context, vs VersionedStore, bucket, gen, prefix string) (uint64, error) {
+ listed, err := vs.ListVersions(ctx, bucket, prefix)
+ if err != nil {
+ return 0, fmt.Errorf("lease: list %s: %w", prefix, err)
+ }
+ var newest uint64
+ for _, v := range listed {
+ if !v.IsLatest || v.DeleteMarker {
+ continue
+ }
+ if pos, ok := parseLTXKey(gen, v.Key); ok && pos.level == 0 {
+ newest = max(newest, pos.max)
+ }
+ }
+ return newest, nil
+}
+
+// VerifyGeneration restores generation gen of s3://bucket/loc through its
+// read-only client (BindReplica), pinned at its newest L0 TXID (the
+// position a take would start from), into a throwaway file under dir,
+// runs the integrity check (VerifyClientAt: CheckDB) and removes the
+// file. It returns the TXID it restored to. A generation with no current
+// L0 file is an error: there is nothing a take could start from.
+func VerifyGeneration(ctx context.Context, bucket, loc, region, gen, dir string) (uint64, error) {
+ if gen == replicagen.Root || !replicagen.Valid(gen) {
+ return 0, fmt.Errorf("lease: verify: %q is not a generation name", gen)
+ }
+ r, err := BindReplica(ctx, bucket, loc, region, gen)
+ if err != nil {
+ return 0, err
+ }
+ itr, err := r.Client.LTXFiles(ctx, 0, 0, false)
+ if err != nil {
+ return 0, fmt.Errorf("lease: verify %s: list L0: %w", gen, err)
+ }
+ var T ltx.TXID
+ for itr.Next() {
+ T = max(T, itr.Item().MaxTXID)
+ }
+ if err := errors.Join(itr.Err(), itr.Close()); err != nil {
+ return 0, fmt.Errorf("lease: verify %s: list L0: %w", gen, err)
+ }
+ if T == 0 {
+ return 0, fmt.Errorf("lease: verify %s: it holds no L0 file", gen)
+ }
+ if _, err := VerifyClientAt(ctx, r.Client, replicagen.ClientPath(loc, gen), dir, uint64(T)); err != nil {
+ return 0, err
+ }
+ return uint64(T), nil
+}
+
+// PointRequest is one point: repoint s3://Bucket/Loc at Generation,
+// accepting the loss of every transaction after TXID, which must be
+// exactly Generation's newest L0 TXID. Without Write it reads, checks
+// and verifies, and returns the documents it would write. Verify is the
+// integrity check (VerifyGeneration, into a throwaway directory): it
+// returns the TXID it restored to.
+type PointRequest struct {
+ Bucket, Loc, Region string
+ Generation string
+ TXID uint64
+ Write bool
+ Verify func(ctx context.Context, gen string) (uint64, error)
+}
+
+// PointResult is what a point changed, or would change.
+//
+// HeadBody is the exact head.json the point writes, conditional on
+// HeadETag ("" is create-only: there was no head.json); nil when
+// head.json already names Generation. LockBody is the exact lock.json,
+// conditional on LockETag; nil when the lock's take bound is already at
+// most TXID. HeadWritten and LockWritten say which writes landed.
+type PointResult struct {
+ Generation string
+ NewestL0 uint64
+ OldHead Head
+ OldHeadFound bool
+ // OldReached is the newest L0 TXID of the generation head.json named
+ // (the root's when there was no head.json).
+ OldReached uint64
+ // OldBound is the lock's take bound before the point
+ // (hafresh.View.TakeBound).
+ OldBound uint64
+ Lock hafresh.View
+ HeadBody []byte
+ HeadETag string
+ LockBody []byte
+ LockETag string
+ HeadWritten bool
+ LockWritten bool
+}
+
+// Point refusal reasons. Each refuses before any write.
+const (
+ PointLockAbsent = "lock_absent" // no lock.json: there is no lease to take
+ PointLockUnknown = "lock_unknown_fields" // lock.json has carlos_ fields a later release wrote
+ PointLockHeld = "lock_held" // a box holds the lock and it has not expired
+ PointNoStoreTime = "no_store_time" // the store sent no Date: head.json's times would have none
+ PointNoGeneration = "no_generation" // Generation holds no current object
+ PointNotPlannable = "not_plannable" // a take could not start from Generation (Err: its *StartRefusal)
+ PointTXIDAbove = "txid_above_l0" // TXID is above Generation's newest L0
+ PointTXIDMismatch = "txid_not_l0" // TXID is below Generation's newest L0
+ PointVerifyFailed = "verify_failed" // the restore or the integrity check failed
+ PointLockChanged = "lock_changed" // lock.json changed while the point verified
+ PointBadGeneration = "bad_generation" // Generation is not a g-<N> name
+)
+
+// PointRefusal is a point refused before any write: Reason, with what the
+// operator needs to see (the holder and its expiry, the newest L0, the
+// unknown fields) and the cause in Err.
+type PointRefusal struct {
+ Reason string
+ Owner string
+ Until time.Time
+ NewestL0 uint64
+ Fields []string
+ Err error
+}
+
+func (r *PointRefusal) Error() string {
+ s := "lease: point refused: " + r.Reason
+ if r.Err != nil {
+ s += ": " + r.Err.Error()
+ }
+ return s
+}
+
+func (r *PointRefusal) Unwrap() error { return r.Err }
+
+// PointWriteError is a write of a point that did not land, or whose
+// outcome is unknown. Doc is "head.json" or "lock.json"; Conflict says the
+// write's condition failed (412: the document changed since the point
+// read it, so it was not written); otherwise the outcome is unknown.
+// HeadWritten says head.json was rewritten before it: a lock.json failure
+// leaves head.json naming the generation with the lock's bound as it was.
+type PointWriteError struct {
+ Doc string
+ Conflict bool
+ HeadWritten bool
+ Err error
+}
+
+func (e *PointWriteError) Error() string {
+ what := "outcome unknown"
+ if e.Conflict {
+ what = "it changed since it was read"
+ }
+ s := fmt.Sprintf("lease: point: write %s: %s", e.Doc, what)
+ if e.HeadWritten {
+ s += " (head.json was written)"
+ }
+ return s + ": " + e.Err.Error()
+}
+
+func (e *PointWriteError) Unwrap() error { return e.Err }
+
+// PointGeneration repoints s3://Bucket/Loc at Generation. It is the one
+// function that writes head.json and lock.json for an operator, and it
+// writes only with Write:
+//
+// 1. Read lock.json (with the store's Date) and refuse an absent lock,
+// one with carlos_ fields this binary does not know, and a held lock
+// that has not expired by the store's time (lockHeld: expiry plus the
+// renewal margin). Read head.json.
+// 2. Refuse a Generation that holds no current object, one a take could
+// not start from (PlanStart's own refusals), and a TXID that is not
+// exactly its newest L0. Verify it (Verify), which must restore to
+// that same TXID.
+// 3. Read lock.json again: changed since step 1 refuses; its Date is the
+// time head.json records (the store's, never this box's).
+// 4. Build the documents. head.json, unless it already names Generation:
+// Generation current from now, created_by PointCreator with the lock
+// generation its name carries, the previous head (or the root layout,
+// when there was none) prepended to history as ended now, trimmed as a
+// take trims it, and predecessor the generation it replaced, so the
+// next take never reads it as an empty first generation. lock.json,
+// unless its take bound is already at most TXID: the same lock with a
+// clean marker's TXID, the marker's min_txid and a held lock's
+// carlos_min_txid each lowered to TXID when above it; its format
+// (carlos_release_g or carlos_release), owner, generation and expiry
+// unchanged.
+// 5. With Write: head.json first, If-Match the ETag step 1 read
+// (If-None-Match: * when there was none), then lock.json, If-Match the
+// ETag step 3 read. head.json goes first so that a bound is never
+// lowered while head.json still names a generation the operator did
+// not choose. A failed head.json write stops there, nothing written. A
+// failed lock.json write after it leaves head.json naming Generation
+// and the lock's bound as it was (a *PointWriteError with
+// HeadWritten); the next take over that bound is refused again, and
+// the recovery is to read the state again (list) and point again: a
+// point at the generation head.json already names writes only the
+// lock. Neither write is undone.
+//
+// Refusals are *PointRefusal; a write that did not land, or whose outcome
+// is unknown, is *PointWriteError. The result describes what was written,
+// or would be, on every return after step 4.
+func PointGeneration(ctx context.Context, req PointRequest) (PointResult, error) {
+ res := PointResult{Generation: req.Generation}
+ gen := req.Generation
+ if gen == replicagen.Root || !replicagen.Valid(gen) {
+ return res, &PointRefusal{Reason: PointBadGeneration, Err: fmt.Errorf("%q is not a generation name", gen)}
+ }
+ n, err := strconv.ParseInt(strings.TrimPrefix(gen, "g-"), 10, 64)
+ if err != nil || n <= 0 {
+ return res, &PointRefusal{Reason: PointBadGeneration, Err: fmt.Errorf("%q names no lock generation", gen)}
+ }
+ if req.Verify == nil {
+ return res, errors.New("lease: point: a verify is required")
+ }
+ key, err := lockKey(req.Bucket, req.Loc)
+ if err != nil {
+ return res, err
+ }
+ loc := strings.TrimSuffix(req.Loc, "/")
+ s, err := openPointStores(ctx, req.Bucket, req.Region)
+ if err != nil {
+ return res, err
+ }
+
+ // 1. The lock, then head.json.
+ var first storeClock
+ v, err := readViewClock(ctx, s.client, req.Bucket, key, &first)
+ if err != nil {
+ return res, err
+ }
+ res.Lock, res.OldBound = v, v.TakeBound()
+ switch {
+ case v.Absent:
+ return res, &PointRefusal{Reason: PointLockAbsent}
+ case len(v.Unknown) > 0:
+ return res, &PointRefusal{Reason: PointLockUnknown, Fields: v.Unknown}
+ }
+ readAt := first.last()
+ if readAt.IsZero() {
+ return res, &PointRefusal{Reason: PointNoStoreTime, Err: ErrNoStoreTime}
+ }
+ if v.Lock.Release == nil && !strings.HasPrefix(v.Lock.Owner, hafresh.MarkerOwnerPrefix) && lockHeld(v.Lock.ExpiresAt, readAt) {
+ return res, &PointRefusal{Reason: PointLockHeld, Owner: v.Lock.Owner, Until: v.Lock.ExpiresAt}
+ }
+ oldHead, headETag, headFound, err := ReadHead(ctx, s.st, loc)
+ if err != nil {
+ return res, err
+ }
+ res.OldHead, res.OldHeadFound = oldHead, headFound
+ if headFound {
+ res.HeadETag = headETag
+ }
+
+ // 2. The generation: it exists, a take can start from it, TXID is its
+ // newest L0, and it verifies.
+ prefix := replicagen.Prefix(loc, gen)
+ listed, err := s.vs.ListVersions(ctx, req.Bucket, prefix)
+ if err != nil {
+ return res, fmt.Errorf("lease: point: list %s: %w", prefix, err)
+ }
+ if !hasCurrent(listed) {
+ return res, &PointRefusal{Reason: PointNoGeneration, Err: fmt.Errorf("%s holds no object", prefix)}
+ }
+ predecessor := replicagen.Root
+ if headFound {
+ predecessor = oldHead.Generation
+ }
+ // The head the next take reads, as far as PlanStart looks at it: a
+ // predecessor, so a generation that lost its files refuses (no_l0)
+ // instead of starting empty.
+ plan, err := PlanStart(ctx, s.vs, req.Bucket, loc, Head{V: HeadVersion, Generation: gen, Predecessor: predecessor}, true, 0)
+ if err != nil {
+ var sr *StartRefusal
+ if errors.As(err, &sr) {
+ return res, &PointRefusal{Reason: PointNotPlannable, Err: err}
+ }
+ return res, err
+ }
+ res.NewestL0 = plan.T
+ switch {
+ case plan.Empty || plan.T == 0:
+ return res, &PointRefusal{Reason: PointNotPlannable, Err: fmt.Errorf("%s holds no L0 file", gen)}
+ case req.TXID > plan.T:
+ return res, &PointRefusal{Reason: PointTXIDAbove, NewestL0: plan.T}
+ case req.TXID < plan.T:
+ return res, &PointRefusal{Reason: PointTXIDMismatch, NewestL0: plan.T}
+ }
+ oldGen := predecessor
+ oldPrefix := replicagen.Prefix(loc, oldGen)
+ if res.OldReached, err = newestL0(ctx, s.vs, req.Bucket, oldPrefix, oldPrefix+"0000/"); err != nil {
+ return res, err
+ }
+ restored, err := req.Verify(ctx, gen)
+ if err != nil {
+ return res, &PointRefusal{Reason: PointVerifyFailed, NewestL0: plan.T, Err: err}
+ }
+ if restored != plan.T {
+ return res, &PointRefusal{Reason: PointVerifyFailed, NewestL0: plan.T,
+ Err: fmt.Errorf("verify restored %s to transaction %d, its newest L0 is %d", gen, restored, plan.T)}
+ }
+
+ // 3. The lock again: unchanged since step 1, and the store's time now.
+ var second storeClock
+ again, err := readViewClock(ctx, s.client, req.Bucket, key, &second)
+ if err != nil {
+ return res, err
+ }
+ if again.Absent || again.ETag != v.ETag {
+ return res, &PointRefusal{Reason: PointLockChanged}
+ }
+ now := second.last()
+ if now.IsZero() {
+ return res, &PointRefusal{Reason: PointNoStoreTime, Err: ErrNoStoreTime}
+ }
+ // A Date has whole seconds; a take's times are a Date plus the local
+ // monotonic time since it. Never end the old head before it began:
+ // history stays ordered, and every time in it is still the store's.
+ if headFound && now.Before(oldHead.CreatedBy.At) {
+ now = oldHead.CreatedBy.At
+ }
+ res.LockETag = v.ETag
+
+ // 4. The documents.
+ if !headFound || oldHead.Generation != gen {
+ var history []HeadHistory
+ if headFound {
+ history = append(history, HeadHistory{Generation: oldHead.Generation, StartTXID: oldHead.StartTXID, CreatedAt: oldHead.CreatedBy.At, EndedAt: now})
+ history = append(history, oldHead.History...)
+ } else {
+ history = append(history, HeadHistory{Generation: replicagen.Root, EndedAt: now})
+ }
+ head := Head{V: HeadVersion, Generation: gen, CreatedBy: HeadCreator{LockGeneration: n, Box: PointCreator, At: now},
+ StartTXID: recordedStart(oldHead, headFound, gen), Predecessor: predecessor,
+ History: TrimHistory(history, now, SnapshotRetention+RetireGrace)}
+ if res.HeadBody, err = headBody(head); err != nil {
+ return res, err
+ }
+ }
+ if res.OldBound > req.TXID {
+ if res.LockBody, err = json.Marshal(lowerBound(v.Lock, req.TXID)); err != nil {
+ return res, fmt.Errorf("lease: point: encode lock: %w", err)
+ }
+ }
+ if !req.Write {
+ return res, nil
+ }
+
+ // 5. The writes: head.json, then lock.json.
+ if res.HeadBody != nil {
+ if err := putHeadBody(ctx, s.st, loc, res.HeadBody, res.HeadETag); err != nil {
+ return res, &PointWriteError{Doc: headName, Conflict: errors.Is(err, release.ErrCASConflict), Err: err}
+ }
+ res.HeadWritten = true
+ }
+ if res.LockBody != nil {
+ if err := putPointLock(ctx, s.client, req.Bucket, key, res.LockBody, res.LockETag); err != nil {
+ return res, &PointWriteError{Doc: "lock.json", Conflict: conditionFailed(err) || lockAbsent(err), HeadWritten: res.HeadWritten, Err: err}
+ }
+ res.LockWritten = true
+ }
+ return res, nil
+}
+
+// hasCurrent reports whether listed holds a current object.
+func hasCurrent(listed []ObjectVersion) bool {
+ for _, v := range listed {
+ if v.IsLatest && !v.DeleteMarker {
+ return true
+ }
+ }
+ return false
+}
+
+// recordedStart is the start_txid head.json recorded for gen, as its
+// current generation or in its history; 0 when it recorded none.
+func recordedStart(h Head, found bool, gen string) uint64 {
+ if !found {
+ return 0
+ }
+ if h.Generation == gen {
+ return h.StartTXID
+ }
+ for _, e := range h.History {
+ if e.Generation == gen {
+ return e.StartTXID
+ }
+ }
+ return 0
+}
+
+// lowerBound is l with every take bound it carries at most txid: a clean
+// marker's TXID, the marker's min_txid and a held lock's carlos_min_txid.
+// Nothing else changes.
+func lowerBound(l hafresh.Lock, txid uint64) hafresh.Lock {
+ l.MinTXID = min(l.MinTXID, txid)
+ if l.Release != nil {
+ m := *l.Release
+ m.MinTXID = min(m.MinTXID, txid)
+ if m.Clean {
+ m.TXID = min(m.TXID, txid)
+ }
+ l.Release = &m
+ }
+ return l
+}
+
+// putHeadBody writes body, built by headBody, as loc's head.json:
+// If-Match ifMatch, or create-only when it is "". A lost race is
+// release.ErrCASConflict.
+func putHeadBody(ctx context.Context, st release.Store, loc string, body []byte, ifMatch string) error {
+ key, err := headKey(loc)
+ if err != nil {
+ return err
+ }
+ if _, err := st.Put(ctx, key, body, ifMatch); err != nil {
+ return fmt.Errorf("head.json: write %s: %w", key, err)
+ }
+ return nil
+}
+
+// putPointLock writes body at key, If-Match etag: one PUT, the SDK's own
+// retries off, so a lost condition is the operator's to read again.
+func putPointLock(ctx context.Context, client lss3.S3API, bucket, key string, body []byte, etag string) error {
+ _, err := client.PutObject(ctx, &awss3.PutObjectInput{
+ Bucket: aws.String(bucket),
+ Key: aws.String(key),
+ Body: bytes.NewReader(body),
+ ContentType: aws.String("application/json"),
+ IfMatch: aws.String(etag),
+ }, noRetries)
+ if err != nil {
+ return fmt.Errorf("lease: write %s: %w", key, err)
+ }
+ return nil
+}
diff --git a/internal/lease/genpoint_test.go b/internal/lease/genpoint_test.go
new file mode 100644
index 000000000..c5bf65cea
--- /dev/null
+++ b/internal/lease/genpoint_test.go
@@ -0,0 +1,380 @@
+package lease_test
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// Task 14: the by-hand restore (carlos ops ha-generations point) through
+// PointGeneration, the one function that writes head.json and lock.json
+// for it, over the versioned S3 fake through the real clients.
+
+// takeAndWrite is a second holder's whole wake: a take over the current
+// lock (it copies the current generation), its restore and switch, rows
+// more rows written and replicated, then a clean release. It returns the
+// take's generation and the clean TXID.
+func (fx *genFixture) takeAndWrite(t *testing.T, rows int) (string, uint64) {
+ t.Helper()
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(t.TempDir(), "take.db")
+ if ok, err := lease.RestoreTake(ctx, path, tk); err != nil || !ok {
+ t.Fatalf("restore of %s: %v %v", tk.Generation, ok, err)
+ }
+ if err := tk.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ for i := range rows {
+ witnessExec(t, path, fmt.Sprintf(`INSERT INTO t (body) VALUES ('more-%d')`, i))
+ }
+ r, err := h.Replicate(ctx, path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatal(err)
+ }
+ txid, err := r.Finish(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1", TXID: txid, FilesGen: "1:aa", At: time.Now().UTC().Truncate(time.Second), Clean: true}
+ if err := r.ReleaseMarker(ctx, m); err != nil {
+ t.Fatal(err)
+ }
+ return tk.Generation, txid
+}
+
+// truncate rewrites the released marker's clean TXID to txid: a replica
+// whose newest L0 is below the TXID its marker records, which every take
+// refuses (clean_marker_above_l0).
+func (fx *genFixture) truncate(t *testing.T, txid uint64) {
+ t.Helper()
+ v := fx.lockView(t)
+ m := *v.Lock.Release
+ m.TXID = txid
+ body, err := hafresh.MarkerBody(v.Lock.Generation, m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.m.Put(fx.bucket, fx.loc+"/lock.json", body)
+}
+
+// pointVerify is the operator's verify (VerifyGeneration), into a test
+// directory.
+func (fx *genFixture) pointVerify(t *testing.T) func(context.Context, string) (uint64, error) {
+ dir := t.TempDir()
+ return func(ctx context.Context, gen string) (uint64, error) {
+ return lease.VerifyGeneration(ctx, fx.bucket, fx.loc, fx.region, gen, dir)
+ }
+}
+
+func (fx *genFixture) point(t *testing.T, gen string, txid uint64, write bool) (lease.PointResult, error) {
+ t.Helper()
+ return lease.PointGeneration(ctx, lease.PointRequest{Bucket: fx.bucket, Loc: fx.loc, Region: fx.region,
+ Generation: gen, TXID: txid, Write: write, Verify: fx.pointVerify(t)})
+}
+
+// refusedHost is a host refused at its wake: g-1 (the seed, rows 3) and
+// g-2 (a take over it, 4 more rows), head.json naming g-2 with g-1 in its
+// history, and a clean marker recording a TXID above g-2's newest L0. It
+// returns both generations and their newest L0 TXIDs.
+func refusedHost(t *testing.T, fx *genFixture) (g1 string, t1 uint64, g2 string, t2 uint64) {
+ t.Helper()
+ g1, t1 = fx.seed(t, time.Minute, 3)
+ g2, t2 = fx.takeAndWrite(t, 4)
+ if t2 <= t1 {
+ t.Fatalf("fixture: g-2 ends at %d, g-1 at %d", t2, t1)
+ }
+ fx.truncate(t, t2+50)
+ h := fx.acquire(t, time.Minute)
+ _, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L1"})
+ var sr *lease.StartRefusal
+ if !errors.As(err, &sr) || sr.Reason != lease.RefuseCleanMarkerAboveL0 {
+ t.Fatalf("fixture: the wake was not refused: %v", err)
+ }
+ if err := h.Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ return g1, t1, g2, t2
+}
+
+// The end-to-end witness: a refused host, pointed at its earlier
+// generation with --yes, takes again from that generation. head.json names
+// g-1 with g-2 now in its history, the marker's bound is lowered to g-1's
+// newest L0 and nothing else in it changed, and the next take (through
+// StartGeneration) copies g-1 at exactly that TXID and restores g-1's rows,
+// none of g-2's.
+func TestPointThenTakeSucceedsFromThePointedGeneration(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ g1, t1, g2, t2 := refusedHost(t, fx)
+ before := fx.lockView(t)
+ oldHead, _, _ := fx.head(t)
+
+ fx.setPhase("point")
+ res, err := fx.point(t, g1, t1, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !res.HeadWritten || !res.LockWritten || res.NewestL0 != t1 || res.OldReached != t2 || res.OldBound != t2+50 {
+ t.Fatalf("point %+v", res)
+ }
+ var puts []string
+ for _, k := range fx.keys("point", false) {
+ puts = append(puts, strings.TrimPrefix(k, fx.loc+"/"))
+ }
+ if !slices.Equal(puts, []string{"head.json", "lock.json"}) {
+ t.Fatalf("point wrote %v, want head.json then lock.json", puts)
+ }
+ head, _, _ := fx.head(t)
+ if head.Generation != g1 || head.Predecessor != g2 || head.CreatedBy.Box != lease.PointCreator ||
+ head.CreatedBy.LockGeneration != 1 || head.CreatedBy.At.IsZero() {
+ t.Fatalf("head after the point: %+v", head)
+ }
+ if len(head.History) == 0 || head.History[0].Generation != g2 || !head.History[0].CreatedAt.Equal(oldHead.CreatedBy.At) ||
+ head.History[0].StartTXID != oldHead.StartTXID || !head.History[0].EndedAt.Equal(head.CreatedBy.At) {
+ t.Fatalf("history after the point: %+v, want g-2's entry first", head.History)
+ }
+ // History stays ordered, newest first: no entry ends before it began,
+ // nor after the entry before it in the list ended.
+ for i, e := range head.History {
+ if e.EndedAt.Before(e.CreatedAt) || (i > 0 && e.EndedAt.After(head.History[i-1].EndedAt)) {
+ t.Fatalf("history out of order at %d: %+v", i, head.History)
+ }
+ }
+ after := fx.lockView(t)
+ // The refused take released settled, carrying its bound as min_txid:
+ // the point lowers that, and nothing else.
+ want := *before.Lock.Release
+ want.MinTXID = t1
+ if after.Lock.Release == nil || *after.Lock.Release != want || after.Lock.Owner != before.Lock.Owner ||
+ after.Lock.Generation != before.Lock.Generation || !after.Lock.ExpiresAt.Equal(before.Lock.ExpiresAt) || !after.Generations() {
+ t.Fatalf("lock after the point: %+v, want %+v with TXID %d", after.Lock, before.Lock, t1)
+ }
+ if string(res.LockBody) != string(mustCurrent(t, fx, "lock.json")) || string(res.HeadBody) != string(mustCurrent(t, fx, "head.json")) {
+ t.Fatal("the point's result does not carry the documents it wrote")
+ }
+ fx.setPhase("")
+
+ h := fx.acquire(t, time.Minute)
+ tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L1"})
+ if err != nil {
+ t.Fatalf("the take after the point: %v", err)
+ }
+ if tk.Predecessor != g1 || tk.StartTXID != t1 {
+ t.Fatalf("take %+v, want from %s at %d", tk, g1, t1)
+ }
+ path := filepath.Join(t.TempDir(), "after.db")
+ if ok, err := lease.RestoreTake(ctx, path, tk); err != nil || !ok {
+ t.Fatalf("restore: %v %v", ok, err)
+ }
+ if err := tk.Switch(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if n, more := witnessCount(t, path, "1=1"), witnessCount(t, path, "body LIKE 'more-%'"); n != 3 || more != 0 {
+ t.Fatalf("restored %d rows (%d of g-2's), want g-1's 3", n, more)
+ }
+}
+
+func mustCurrent(t *testing.T, fx *genFixture, name string) []byte {
+ t.Helper()
+ b, ok := fx.m.Current(fx.bucket, fx.loc+"/"+name)
+ if !ok {
+ t.Fatalf("no %s", name)
+ }
+ return b
+}
+
+// A point without Write reads, checks and verifies, returns the two
+// documents a write would put, and sends no write at all.
+func TestPointDryRunWritesNothing(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ g1, t1, _, _ := refusedHost(t, fx)
+ before := fx.m.Snapshot()
+ fx.setPhase("dry")
+ res, err := fx.point(t, g1, t1, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if w := fx.keys("dry", false); len(w) != 0 {
+ t.Fatalf("a dry run wrote %v", w)
+ }
+ if fx.m.Snapshot() != before {
+ t.Fatal("a dry run changed the bucket")
+ }
+ if res.HeadWritten || res.LockWritten || len(res.HeadBody) == 0 || len(res.LockBody) == 0 {
+ t.Fatalf("dry run %+v", res)
+ }
+}
+
+// Pointing at the generation head.json already names rewrites only the
+// lock: a clean marker's TXID is lowered to the generation's newest L0 and
+// the marker stays clean. A host with nothing to change writes nothing.
+func TestPointAtTheCurrentGenerationLowersOnlyTheBound(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ fx.seed(t, time.Minute, 3)
+ g2, t2 := fx.takeAndWrite(t, 4)
+ fx.truncate(t, t2+50)
+ before := fx.lockView(t)
+ fx.setPhase("point")
+ res, err := fx.point(t, g2, t2, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.HeadBody != nil || res.HeadWritten || !res.LockWritten {
+ t.Fatalf("point %+v", res)
+ }
+ want := *before.Lock.Release
+ want.TXID = t2
+ if got := fx.lockView(t).Lock.Release; got == nil || *got != want || !got.Clean {
+ t.Fatalf("marker after the point: %+v, want %+v", got, want)
+ }
+ if w := fx.keys("point", false); !slices.Equal(w, []string{fx.loc + "/lock.json"}) {
+ t.Fatalf("wrote %v, want only lock.json", w)
+ }
+ fx.setPhase("again")
+ res, err = fx.point(t, g2, t2, true)
+ if err != nil || res.HeadBody != nil || res.LockBody != nil || res.HeadWritten || res.LockWritten {
+ t.Fatalf("second point %+v %v, want nothing to change", res, err)
+ }
+ if w := fx.keys("again", false); len(w) != 0 {
+ t.Fatalf("a point with nothing to change wrote %v", w)
+ }
+}
+
+// Refusals write nothing: a live held lock, a TXID that is not the
+// generation's newest L0 (above or below), a generation that does not
+// exist, and one that fails verify.
+func TestPointRefusalsWriteNothing(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ g1, t1, _, _ := refusedHost(t, fx)
+ refused := func(t *testing.T, reason string, gen string, txid uint64, verify func(context.Context, string) (uint64, error)) *lease.PointRefusal {
+ t.Helper()
+ before := fx.m.Snapshot()
+ fx.setPhase(t.Name())
+ if verify == nil {
+ verify = fx.pointVerify(t)
+ }
+ _, err := lease.PointGeneration(ctx, lease.PointRequest{Bucket: fx.bucket, Loc: fx.loc, Region: fx.region,
+ Generation: gen, TXID: txid, Write: true, Verify: verify})
+ var pr *lease.PointRefusal
+ if !errors.As(err, &pr) || pr.Reason != reason {
+ t.Fatalf("point: %v, want refusal %s", err, reason)
+ }
+ if w := fx.keys(t.Name(), false); len(w) != 0 || fx.m.Snapshot() != before {
+ t.Fatalf("a refused point wrote %v", w)
+ }
+ return pr
+ }
+ t.Run("above", func(t *testing.T) {
+ if pr := refused(t, lease.PointTXIDAbove, g1, t1+1, nil); pr.NewestL0 != t1 {
+ t.Fatalf("refusal %+v", pr)
+ }
+ })
+ t.Run("below", func(t *testing.T) {
+ if pr := refused(t, lease.PointTXIDMismatch, g1, t1-1, nil); pr.NewestL0 != t1 {
+ t.Fatalf("refusal %+v", pr)
+ }
+ })
+ t.Run("absent", func(t *testing.T) {
+ refused(t, lease.PointNoGeneration, replicagen.Name(9), t1, nil)
+ })
+ t.Run("verify", func(t *testing.T) {
+ refused(t, lease.PointVerifyFailed, g1, t1, func(context.Context, string) (uint64, error) {
+ return 0, errors.New("integrity_check: page 2 is never used")
+ })
+ })
+ t.Run("verify-elsewhere", func(t *testing.T) {
+ refused(t, lease.PointVerifyFailed, g1, t1, func(context.Context, string) (uint64, error) { return t1 - 1, nil })
+ })
+ t.Run("held", func(t *testing.T) {
+ h := fx.acquire(t, time.Minute)
+ defer h.Release(ctx)
+ if pr := refused(t, lease.PointLockHeld, g1, t1, nil); pr.Owner == "" || pr.Until.IsZero() {
+ t.Fatalf("refusal %+v", pr)
+ }
+ })
+}
+
+// A lost condition on either write: head.json changed since the point
+// read it (nothing written), or lock.json changed after head.json was
+// rewritten (head written, lock not; the error says which).
+func TestPointConditionalWrites(t *testing.T) {
+ haBox(t)
+ t.Run("head", func(t *testing.T) {
+ fx := newGenFixture(t)
+ g1, t1, _, _ := refusedHost(t, fx)
+ head := mustCurrent(t, fx, "head.json")
+ lock := mustCurrent(t, fx, "lock.json")
+ fx.setHook(func(r *http.Request, keys []string) func(int) {
+ if r.Method == http.MethodPut && slices.Contains(keys, fx.loc+"/head.json") {
+ fx.m.Put(fx.bucket, fx.loc+"/head.json", append(slices.Clone(head), ' '))
+ }
+ return nil
+ })
+ _, err := fx.point(t, g1, t1, true)
+ var we *lease.PointWriteError
+ if !errors.As(err, &we) || we.Doc != "head.json" || !we.Conflict || we.HeadWritten {
+ t.Fatalf("point: %v, want a head.json conflict", err)
+ }
+ if got := mustCurrent(t, fx, "lock.json"); string(got) != string(lock) {
+ t.Fatal("the lock was written after a head conflict")
+ }
+ })
+ t.Run("lock", func(t *testing.T) {
+ fx := newGenFixture(t)
+ g1, t1, _, _ := refusedHost(t, fx)
+ lock := mustCurrent(t, fx, "lock.json")
+ fx.setHook(func(r *http.Request, keys []string) func(int) {
+ if r.Method == http.MethodPut && slices.Contains(keys, fx.loc+"/lock.json") {
+ fx.m.Put(fx.bucket, fx.loc+"/lock.json", append(slices.Clone(lock), ' '))
+ }
+ return nil
+ })
+ res, err := fx.point(t, g1, t1, true)
+ var we *lease.PointWriteError
+ if !errors.As(err, &we) || we.Doc != "lock.json" || !we.Conflict || !we.HeadWritten || !res.HeadWritten || res.LockWritten {
+ t.Fatalf("point %+v: %v, want a lock.json conflict after head.json was written", res, err)
+ }
+ if h, _, _ := fx.head(t); h.Generation != g1 {
+ t.Fatalf("head names %s, want %s", h.Generation, g1)
+ }
+ })
+}
+
+// list: head.json, every generation with its newest L0, and the lock.
+func TestListGenerations(t *testing.T) {
+ haBox(t)
+ fx := newGenFixture(t)
+ g1, t1, g2, t2 := refusedHost(t, fx)
+ got, err := lease.ListGenerations(ctx, fx.bucket, fx.loc, fx.region)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !got.HeadFound || got.Head.Generation != g2 || got.Lock.Lock.Release == nil || got.Lock.TakeBound() != t2+50 || got.At.IsZero() {
+ t.Fatalf("list %+v", got)
+ }
+ // The refused take's g-3 is empty: it never copied (the plan refused).
+ want := []lease.GenerationInfo{{Name: g1, NewestL0: t1}, {Name: g2, NewestL0: t2}}
+ if !slices.Equal(got.Generations, want) {
+ t.Fatalf("generations %+v, want %+v", got.Generations, want)
+ }
+}
diff --git a/internal/lease/head.go b/internal/lease/head.go
index c83a93e8a..fed2a8639 100644
--- a/internal/lease/head.go
+++ b/internal/lease/head.go
@@ -155,15 +155,9 @@ func PutHeadAt(ctx context.Context, st release.Store, loc string, h Head, ifMatc
if err != nil {
return "", time.Time{}, err
}
- if err := h.validate(); err != nil {
- return "", time.Time{}, err
- }
- if h.History == nil {
- h.History = []HeadHistory{}
- }
- body, err := json.Marshal(h)
+ body, err := headBody(h)
if err != nil {
- return "", time.Time{}, fmt.Errorf("head.json: encode: %w", err)
+ return "", time.Time{}, err
}
var etag string
var at time.Time
@@ -178,6 +172,22 @@ func PutHeadAt(ctx context.Context, st release.Store, loc string, h Head, ifMatc
return etag, at, nil
}
+// headBody is the exact body PutHeadAt writes for h: h validated, with a
+// nil history written as [].
+func headBody(h Head) ([]byte, error) {
+ if err := h.validate(); err != nil {
+ return nil, err
+ }
+ if h.History == nil {
+ h.History = []HeadHistory{}
+ }
+ body, err := json.Marshal(h)
+ if err != nil {
+ return nil, fmt.Errorf("head.json: encode: %w", err)
+ }
+ return body, nil
+}
+
// TrimHistory keeps the entries of h whose EndedAt is after now-window, in
// their order (newest first). It returns a new, non-nil slice and never
// changes h.
diff --git a/internal/lease/legacytake.go b/internal/lease/legacytake.go
index b8a2aa8dc..b2c7724a1 100644
--- a/internal/lease/legacytake.go
+++ b/internal/lease/legacytake.go
@@ -183,6 +183,12 @@ func marshalLock(l *litestream.Lease, genName string, minTXID uint64) ([]byte, e
// NoSuchKey is absence (lockAbsent); an unreadable or oversized body, a
// lock with no expiry, or an answer with no ETag is an error.
func readView(ctx context.Context, client lss3.S3API, bucket, key string) (hafresh.View, error) {
+ return readViewClock(ctx, client, bucket, key, nil)
+}
+
+// readViewClock is readView that, when clock is not nil, records the
+// response's Date (the store's time of the read) in clock.
+func readViewClock(ctx context.Context, client lss3.S3API, bucket, key string, clock *storeClock) (hafresh.View, error) {
out, err := client.GetObject(ctx, &awss3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
if err != nil {
if lockAbsent(err) {
@@ -205,6 +211,9 @@ func readView(ctx context.Context, client lss3.S3API, bucket, key string) (hafre
if err != nil {
return hafresh.View{}, fmt.Errorf("lease: %s: %w", key, err)
}
+ if clock != nil {
+ clock.observeMetadata(out.ResultMetadata)
+ }
return v, nil
}
diff --git a/internal/lease/storeclock.go b/internal/lease/storeclock.go
index 82617645d..bb0dcd1d7 100644
--- a/internal/lease/storeclock.go
+++ b/internal/lease/storeclock.go
@@ -92,3 +92,11 @@ func (c *storeClock) now() (time.Time, error) {
}
return at.Add(time.Since(mono)).UTC(), nil
}
+
+// last is the Date c last recorded, as it was sent (no local time added):
+// the zero time when none was seen.
+func (c *storeClock) last() time.Time {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.at
+}
diff --git a/internal/ops/hagenerations.go b/internal/ops/hagenerations.go
new file mode 100644
index 000000000..1c76c05ea
--- /dev/null
+++ b/internal/ops/hagenerations.go
@@ -0,0 +1,410 @@
+package ops
+
+import (
+ "context"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "os/signal"
+ "slices"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/clireg"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// `carlos ops ha-generations` (Task 14, region HA storage generations):
+// the by-hand restore of a host whose wake was refused
+// (ha_generation_refused). list and verify only read; point repoints the
+// host at a complete generation, a dry run unless --yes, and is the one
+// operator path that accepts data loss. Every write it makes goes through
+// lease.PointGeneration. It runs once per operator invocation: nothing
+// here polls.
+
+// haGenUsage is the verb's usage. Every human-facing sentence in this file
+// goes through a copy pass (Task 14 report).
+const haGenUsage = `usage: carlos ops ha-generations list <host>
+ carlos ops ha-generations verify <host> --gen <g-N>
+ carlos ops ha-generations point <host> --gen <g-N> --accept-loss-after <txid> [--yes]
+
+Restores a region HA host whose wake was refused (ha_generation_refused).
+list and verify only read. point is a dry run unless --yes: it points the
+host at a complete generation and gives up every transaction after <txid>,
+which must be that generation's newest L0 transaction.
+`
+
+// haGenRun is one run of the verb with what it reads from the box named,
+// so a test can run it whole.
+type haGenRun struct {
+ // Root is a run as effective uid 0, which run refuses first of all, as
+ // hibernate-verify does: the verb runs as the carlos user.
+ Root bool
+ // Cfg is the box's hibernation config (activator.ConfigFromEnv): the
+ // bucket, region and prefix the host's replica lives under.
+ Cfg *activator.Config
+ // TmpDir holds verify's throwaway restore, removed before return.
+ TmpDir string
+ Out, Err io.Writer
+}
+
+// haGenSubs are the verb's subcommands, each a command-tree leaf.
+var haGenSubs = []string{"list", "verify", "point"}
+
+// haGenerationsCommand is `carlos ops ha-generations`: a branch whose
+// leaves are its subcommands, handed their arguments unparsed. No word, a
+// help word or a word that names none is haGenFallback.
+func haGenerationsCommand() *clireg.Node {
+ n := &clireg.Node{Name: "ha-generations", Audience: clireg.BoxLocal,
+ Fallback: func(args, _ []string) { os.Exit(haGenFallback(os.Stdout, os.Stderr, args)) }}
+ for _, sub := range haGenSubs {
+ n.Children = append(n.Children, &clireg.Node{Name: sub, Audience: clireg.BoxLocal,
+ Run: clireg.RawArgs(func(args []string) { runHAGenerations(sub, args) })})
+ }
+ return n
+}
+
+// haGenFallback is the branch with no subcommand: usage, exit 2, or exit
+// 0 for a help word.
+func haGenFallback(out, errw io.Writer, args []string) int {
+ if len(args) > 0 {
+ switch args[0] {
+ case "-h", "--help", "help":
+ fmt.Fprint(out, haGenUsage)
+ return 0
+ }
+ fmt.Fprintf(errw, "ha-generations: unknown subcommand %q\n", args[0])
+ }
+ fmt.Fprint(errw, haGenUsage)
+ return 2
+}
+
+func runHAGenerations(sub string, args []string) {
+ cfg, err := activator.ConfigFromEnv()
+ if err != nil {
+ log.Fatalf("ha-generations: %v", err)
+ }
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ r := haGenRun{Root: os.Geteuid() == 0, Cfg: cfg, TmpDir: os.TempDir(), Out: os.Stdout, Err: os.Stderr}
+ if code := r.run(ctx, sub, args); code != 0 {
+ stop()
+ os.Exit(code)
+ }
+}
+
+// errUsage is a mistake in the arguments: usage, exit 2.
+var errUsage = errors.New("usage")
+
+// haGenArgs are a run's parsed arguments.
+type haGenArgs struct {
+ sub, host, gen string
+ txid uint64
+ txidSet, yes bool
+}
+
+// parseHAGenArgs reads subcommand sub's <host> and flags, in any order. A
+// mistake is written to w and returned as errUsage; flag.ErrHelp is a
+// request for help.
+func parseHAGenArgs(w io.Writer, sub string, args []string) (haGenArgs, error) {
+ a := haGenArgs{sub: sub}
+ if !slices.Contains(haGenSubs, sub) {
+ fmt.Fprintf(w, "ha-generations: unknown subcommand %q\n", sub)
+ return a, errUsage
+ }
+ fs := flag.NewFlagSet("ops ha-generations "+a.sub, flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ fs.StringVar(&a.gen, "gen", "", "")
+ txid := fs.String("accept-loss-after", "", "")
+ fs.BoolVar(&a.yes, "yes", false, "")
+ for {
+ if err := fs.Parse(args); err != nil {
+ if errors.Is(err, flag.ErrHelp) {
+ return a, err
+ }
+ fmt.Fprintf(w, "ha-generations %s: %v\n", a.sub, err)
+ return a, errUsage
+ }
+ if fs.NArg() == 0 {
+ break
+ }
+ if a.host != "" {
+ fmt.Fprintf(w, "ha-generations %s: one host at a time, got %q and %q\n", a.sub, a.host, fs.Arg(0))
+ return a, errUsage
+ }
+ a.host, args = fs.Arg(0), fs.Args()[1:]
+ }
+ if a.host == "" {
+ fmt.Fprintf(w, "ha-generations %s: name the host\n", a.sub)
+ return a, errUsage
+ }
+ if *txid != "" {
+ n, err := strconv.ParseUint(*txid, 10, 64)
+ if err != nil || n == 0 {
+ fmt.Fprintf(w, "ha-generations %s: --accept-loss-after %q is not a transaction number\n", a.sub, *txid)
+ return a, errUsage
+ }
+ a.txid, a.txidSet = n, true
+ }
+ switch {
+ case a.sub == "list" && (a.gen != "" || a.txidSet || a.yes):
+ fmt.Fprintf(w, "ha-generations list takes only a host\n")
+ return a, errUsage
+ case a.sub == "verify" && (a.txidSet || a.yes):
+ fmt.Fprintf(w, "ha-generations verify takes a host and --gen\n")
+ return a, errUsage
+ case a.sub != "list" && a.gen == "":
+ fmt.Fprintf(w, "ha-generations %s: --gen is required\n", a.sub)
+ return a, errUsage
+ case a.sub == "point" && !a.txidSet:
+ fmt.Fprintf(w, "ha-generations point: --accept-loss-after is required\n")
+ return a, errUsage
+ }
+ if a.gen != "" && (a.gen == replicagen.Root || !replicagen.Valid(a.gen)) {
+ fmt.Fprintf(w, "ha-generations %s: --gen %q is not a generation name like %s\n", a.sub, a.gen, replicagen.Name(42))
+ return a, errUsage
+ }
+ return a, nil
+}
+
+// run is subcommand sub's body (the command tree chose it); it returns
+// the exit code: 0 done, 1 refused or failed, 2 a usage mistake.
+func (r haGenRun) run(ctx context.Context, sub string, args []string) int {
+ a, err := parseHAGenArgs(r.Err, sub, args)
+ if errors.Is(err, flag.ErrHelp) {
+ fmt.Fprint(r.Out, haGenUsage)
+ return 0
+ }
+ if err != nil {
+ fmt.Fprint(r.Err, haGenUsage)
+ return 2
+ }
+ // Root is refused before anything is read, as hibernate-verify refuses
+ // it (after its flags, as there): the verb runs as the carlos user,
+ // with its credentials.
+ if r.Root {
+ fmt.Fprintln(r.Err, "ha-generations: not run: refusing to run as root. Run it as the carlos user, as carlos-hibernate-verify.service does.")
+ return 1
+ }
+ if r.Cfg == nil {
+ fmt.Fprintln(r.Err, "ha-generations: CARLOS_HIBERNATE_BUCKET is not set, so this box keeps no region HA hosts.")
+ return 1
+ }
+ loc := activator.HibernatePrefix(r.Cfg.Prefix, a.host)
+ switch a.sub {
+ case "list":
+ return r.list(ctx, a.host, loc)
+ case "verify":
+ return r.verify(ctx, loc, a.gen)
+ default:
+ return r.point(ctx, a, loc)
+ }
+}
+
+// stamp is a time as the verb prints it.
+func stamp(t time.Time) string { return t.UTC().Format(time.RFC3339) }
+
+func (r haGenRun) list(ctx context.Context, host, loc string) int {
+ g, err := lease.ListGenerations(ctx, r.Cfg.Bucket, loc, r.Cfg.Region)
+ if err != nil {
+ fmt.Fprintf(r.Err, "ha-generations list: %v\n", err)
+ return 1
+ }
+ w := r.Out
+ fmt.Fprintf(w, "%s (s3://%s/%s)\n", host, r.Cfg.Bucket, loc)
+ if g.HeadFound {
+ h := g.Head
+ fmt.Fprintf(w, "head.json: %s, start_txid %d, created by %s (lock generation %d) at %s\n",
+ h.Generation, h.StartTXID, h.CreatedBy.Box, h.CreatedBy.LockGeneration, stamp(h.CreatedBy.At))
+ for _, e := range h.History {
+ fmt.Fprintf(w, " history: %s, start_txid %d, created %s, ended %s\n", e.Generation, e.StartTXID, stamp(e.CreatedAt), stamp(e.EndedAt))
+ }
+ } else {
+ fmt.Fprintln(w, "head.json: none")
+ }
+ if len(g.Generations) == 0 {
+ fmt.Fprintln(w, "generations: none")
+ } else {
+ fmt.Fprintln(w, "generations:")
+ }
+ for _, gi := range g.Generations {
+ named := ""
+ if g.HeadFound && gi.Name == g.Head.Generation {
+ named = " (head.json names it)"
+ }
+ fmt.Fprintf(w, " %s: newest L0 %d%s\n", gi.Name, gi.NewestL0, named)
+ }
+ v := g.Lock
+ switch {
+ case v.Absent:
+ fmt.Fprintln(w, "lock.json: none")
+ case v.Lock.Release != nil:
+ m := v.Lock.Release
+ format, clean := "ordinary", "unclean"
+ if m.Gen {
+ format = "generations"
+ }
+ if m.Clean {
+ clean = "clean"
+ }
+ fmt.Fprintf(w, "lock.json: released by %s at lock generation %d (%s marker): %s, txid %d, bound %d\n",
+ m.Box, v.Lock.Generation, format, clean, m.TXID, v.TakeBound())
+ default:
+ state := ""
+ if !g.At.IsZero() {
+ state = " (expired)"
+ if !g.At.After(v.Lock.ExpiresAt.Add(lease.RenewMargin)) {
+ state = " (live)"
+ }
+ }
+ fmt.Fprintf(w, "lock.json: held by %s at lock generation %d, expires %s%s, bound %d\n",
+ v.Lock.Owner, v.Lock.Generation, stamp(v.Lock.ExpiresAt), state, v.TakeBound())
+ }
+ if len(v.Unknown) > 0 {
+ fmt.Fprintf(w, "lock.json has fields this binary does not know: %s\n", strings.Join(v.Unknown, ", "))
+ }
+ return 0
+}
+
+// verifyGeneration is VerifyGeneration into a scratch directory of its
+// own under TmpDir, removed before it returns.
+func (r haGenRun) verifyGeneration(ctx context.Context, loc, gen string) (uint64, error) {
+ dir, err := os.MkdirTemp(r.TmpDir, "carlos-ha-generations-")
+ if err != nil {
+ return 0, err
+ }
+ defer os.RemoveAll(dir)
+ return lease.VerifyGeneration(ctx, r.Cfg.Bucket, loc, r.Cfg.Region, gen, dir)
+}
+
+func (r haGenRun) verify(ctx context.Context, loc, gen string) int {
+ txid, err := r.verifyGeneration(ctx, loc, gen)
+ if err != nil {
+ fmt.Fprintf(r.Out, "%s: verify failed: %v\n", gen, err)
+ return 1
+ }
+ fmt.Fprintf(r.Out, "%s: restored to transaction %d; the integrity check passed.\n", gen, txid)
+ return 0
+}
+
+func (r haGenRun) point(ctx context.Context, a haGenArgs, loc string) int {
+ res, err := lease.PointGeneration(ctx, lease.PointRequest{Bucket: r.Cfg.Bucket, Loc: loc, Region: r.Cfg.Region,
+ Generation: a.gen, TXID: a.txid, Write: a.yes,
+ Verify: func(ctx context.Context, gen string) (uint64, error) { return r.verifyGeneration(ctx, loc, gen) }})
+ var pr *lease.PointRefusal
+ if errors.As(err, &pr) {
+ fmt.Fprintf(r.Err, "ha-generations point: refused: %s\n", r.refusal(pr, a, loc))
+ return 1
+ }
+ var we *lease.PointWriteError
+ if err != nil && !errors.As(err, &we) {
+ fmt.Fprintf(r.Err, "ha-generations point: %v\n", err)
+ return 1
+ }
+ w := r.Out
+ if res.HeadBody == nil && res.LockBody == nil {
+ fmt.Fprintf(w, "Nothing to change: head.json names %s and the lock's bound, %d, is not above %d.\n", a.gen, res.OldBound, a.txid)
+ return 0
+ }
+ fmt.Fprintln(w, lossSentence(a.host, res))
+ if !a.yes {
+ docs := "these two documents"
+ if res.HeadBody == nil || res.LockBody == nil {
+ docs = "this document"
+ }
+ fmt.Fprintf(w, "Dry run: nothing written. Run it again with --yes to write %s.\n", docs)
+ }
+ if res.HeadBody == nil {
+ fmt.Fprintf(w, "head.json already names %s; it stays as it is.\n", a.gen)
+ } else if !a.yes {
+ cond := "If-None-Match *"
+ if res.HeadETag != "" {
+ cond = "If-Match " + res.HeadETag
+ }
+ fmt.Fprintf(w, "head.json, %s:\n%s\n", cond, res.HeadBody)
+ } else if res.HeadWritten {
+ fmt.Fprintf(w, "Wrote head.json:\n%s\n", res.HeadBody)
+ }
+ if res.LockBody == nil {
+ fmt.Fprintf(w, "lock.json stays as it is: its bound, %d, is not above %d.\n", res.OldBound, a.txid)
+ } else if !a.yes {
+ fmt.Fprintf(w, "lock.json, If-Match %s:\n%s\n", res.LockETag, res.LockBody)
+ } else if res.LockWritten {
+ fmt.Fprintf(w, "Wrote lock.json:\n%s\n", res.LockBody)
+ }
+ if we != nil {
+ fmt.Fprintf(r.Err, "ha-generations point: %s\n", writeFailure(we, a))
+ return 1
+ }
+ return 0
+}
+
+// lossSentence names what a point keeps and what it gives up.
+func lossSentence(host string, res lease.PointResult) string {
+ recorded := "the marker recorded"
+ if res.Lock.Lock.Release == nil {
+ recorded = "the lock recorded"
+ }
+ before := fmt.Sprintf("the old head reached %d", res.OldReached)
+ if !res.OldHeadFound {
+ before = "there was no head.json"
+ }
+ return fmt.Sprintf("Pointing %s at %s keeps its data up to transaction %d and permanently gives up every transaction after it (%s; %s %d).",
+ host, res.Generation, res.NewestL0, before, recorded, res.OldBound)
+}
+
+// rerun is the recovery every lost write names.
+func rerun(host string) string {
+ return fmt.Sprintf("Run \"carlos ops ha-generations list %s\", then point again.", host)
+}
+
+func writeFailure(we *lease.PointWriteError, a haGenArgs) string {
+ switch {
+ case we.Doc == "head.json" && we.Conflict:
+ return "head.json changed after it was read, so nothing was written. " + rerun(a.host)
+ case we.Doc == "head.json":
+ return fmt.Sprintf("writing head.json failed, and whether it landed is unknown: %v. lock.json was not written. %s", we.Err, rerun(a.host))
+ case we.HeadWritten && we.Conflict:
+ return fmt.Sprintf("head.json now names %s, but lock.json changed after it was read, so it was not written; a box may have taken the lock. %s", a.gen, rerun(a.host))
+ case we.HeadWritten:
+ return fmt.Sprintf("head.json now names %s, but writing lock.json failed, and whether it landed is unknown: %v. %s", a.gen, we.Err, rerun(a.host))
+ case we.Conflict:
+ return "lock.json changed after it was read, so nothing was written. " + rerun(a.host)
+ default:
+ return fmt.Sprintf("writing lock.json failed, and whether it landed is unknown: %v. %s", we.Err, rerun(a.host))
+ }
+}
+
+func (r haGenRun) refusal(pr *lease.PointRefusal, a haGenArgs, loc string) string {
+ switch pr.Reason {
+ case lease.PointLockHeld:
+ return fmt.Sprintf("the lock is held by %s until %s. Point only a host no box holds.", pr.Owner, stamp(pr.Until))
+ case lease.PointLockAbsent:
+ return fmt.Sprintf("%s has no lock.json, so there is no lease for a take to start from.", a.host)
+ case lease.PointLockUnknown:
+ return fmt.Sprintf("lock.json has fields this binary does not know (%s); a newer release wrote it.", strings.Join(pr.Fields, ", "))
+ case lease.PointNoStoreTime:
+ return "the store sent no Date header, and head.json must record the store's time."
+ case lease.PointNoGeneration:
+ return fmt.Sprintf("%s does not exist under s3://%s/%s.", a.gen, r.Cfg.Bucket, loc)
+ case lease.PointNotPlannable:
+ return fmt.Sprintf("a take could not start from %s: %v", a.gen, pr.Err)
+ case lease.PointTXIDAbove:
+ return fmt.Sprintf("--accept-loss-after %d is above %s's newest L0 transaction, %d. The generation holds nothing after %d.", a.txid, a.gen, pr.NewestL0, pr.NewestL0)
+ case lease.PointTXIDMismatch:
+ return fmt.Sprintf("--accept-loss-after %d is not %s's newest L0 transaction, %d. A point keeps everything up to the newest L0, so pass --accept-loss-after %d.", a.txid, a.gen, pr.NewestL0, pr.NewestL0)
+ case lease.PointVerifyFailed:
+ return fmt.Sprintf("%s failed verify: %v", a.gen, pr.Err)
+ case lease.PointLockChanged:
+ return "lock.json changed while the point was verifying. Nothing was written; run it again."
+ default:
+ return pr.Error()
+ }
+}
diff --git a/internal/ops/hagenerations_test.go b/internal/ops/hagenerations_test.go
new file mode 100644
index 000000000..112228659
--- /dev/null
+++ b/internal/ops/hagenerations_test.go
@@ -0,0 +1,469 @@
+package ops
+
+import (
+ "bytes"
+ "context"
+ "crypto/md5"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ lsfile "github.com/benbjohnson/litestream/file"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/clireg"
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/leasetest"
+ "github.com/carlosframework/platform/internal/replicagen"
+)
+
+// `carlos ops ha-generations` (Task 14) against leasetest's versioned S3,
+// reached as production reaches it (CARLOS_S3_ENDPOINT), with the store's
+// clock fixed so every time it prints is known.
+
+const (
+ hgHost = "shop.example.com"
+ hgLoc = "hib/" + hgHost
+)
+
+var hgNow = time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC)
+
+// hgFixture is a refused host: g-5 and g-7, head.json naming g-7 with g-5
+// in its history, and a clean generations marker recording a TXID above
+// g-7's newest L0 (every take refuses: clean_marker_above_l0).
+type hgFixture struct {
+ m *leasetest.VersionedBucket
+ g5, g7 string
+ t5, t7 uint64
+ head lease.Head
+ marker hafresh.Marker
+ tmp string
+ mu sync.Mutex
+ reqs int
+ writes []string // "METHOD key" of every PUT, POST and DELETE
+ beforeW func(r *http.Request, key string)
+}
+
+func newHGFixture(t *testing.T) *hgFixture {
+ t.Helper()
+ fx := &hgFixture{m: leasetest.NewVersionedBucket(), g5: replicagen.Name(5), g7: replicagen.Name(7), tmp: t.TempDir()}
+ fx.m.AddBucket(rsBucket)
+ fx.m.Date = func() time.Time { return hgNow }
+ handler, _ := leasetest.NewS3Server(fx.m)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ key := strings.TrimPrefix(r.URL.Path, "/"+rsBucket+"/")
+ fx.mu.Lock()
+ fx.reqs++
+ hook := fx.beforeW
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ fx.writes = append(fx.writes, r.Method+" "+key)
+ }
+ fx.mu.Unlock()
+ if hook != nil && r.Method == http.MethodPut {
+ hook(r, key)
+ }
+ handler.ServeHTTP(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ t.Setenv("AWS_ACCESS_KEY_ID", "test-key")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret")
+ t.Setenv("AWS_SESSION_TOKEN", "")
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("CARLOS_S3_ENDPOINT", srv.URL)
+
+ fx.t5 = fx.replica(t, fx.g5, 2)
+ fx.t7 = fx.replica(t, fx.g7, 4)
+ if fx.t5 >= fx.t7 {
+ t.Fatalf("fixture: g-5 ends at %d, g-7 at %d", fx.t5, fx.t7)
+ }
+ fx.head = lease.Head{V: 1, Generation: fx.g7, StartTXID: fx.t5, Predecessor: fx.g5,
+ CreatedBy: lease.HeadCreator{LockGeneration: 7, Box: "box-b", IID: "i-b", Lifetime: "L2", At: time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC)},
+ History: []lease.HeadHistory{{Generation: fx.g5, StartTXID: 0, CreatedAt: time.Date(2026, 11, 17, 9, 0, 0, 0, time.UTC), EndedAt: time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC)}}}
+ fx.put(t, "head.json", fx.head)
+ fx.marker = hafresh.Marker{V: 1, Box: "box-b", IID: "i-b", Lifetime: "L2", TXID: fx.t7 + 50, FilesGen: "1:aa",
+ At: time.Date(2026, 11, 18, 11, 0, 0, 0, time.UTC), Clean: true, Gen: true}
+ body, err := hafresh.MarkerBody(7, fx.marker)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.m.Put(rsBucket, hgLoc+"/lock.json", body)
+ return fx
+}
+
+// replica writes a real replica of batches*10 rows into gen and returns
+// its newest L0 TXID.
+func (fx *hgFixture) replica(t *testing.T, gen string, batches int) uint64 {
+ t.Helper()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, batches)
+ if _, err := fx.m.PutFileReplica(rsBucket, replicagen.Prefix(hgLoc, gen), dir); err != nil {
+ t.Fatal(err)
+ }
+ p, err := dbdoor.PlanFrom(context.Background(), lsfile.NewReplicaClient(dir), time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return p.TXID
+}
+
+func (fx *hgFixture) put(t *testing.T, name string, v any) {
+ t.Helper()
+ body, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx.m.Put(rsBucket, hgLoc+"/"+name, body)
+}
+
+func (fx *hgFixture) current(t *testing.T, name string) []byte {
+ t.Helper()
+ b, ok := fx.m.Current(rsBucket, hgLoc+"/"+name)
+ if !ok {
+ t.Fatalf("no %s", name)
+ }
+ return b
+}
+
+func (fx *hgFixture) counts() (reqs int, writes []string) {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return fx.reqs, append([]string(nil), fx.writes...)
+}
+
+func (fx *hgFixture) reset() {
+ fx.mu.Lock()
+ fx.reqs, fx.writes = 0, nil
+ fx.mu.Unlock()
+}
+
+// run is `carlos ops ha-generations args...` as the carlos user.
+func (fx *hgFixture) run(t *testing.T, args ...string) (int, string) {
+ t.Helper()
+ return fx.runAs(t, false, args...)
+}
+
+func (fx *hgFixture) runAs(t *testing.T, root bool, args ...string) (int, string) {
+ t.Helper()
+ var out bytes.Buffer
+ if len(args) == 0 || !slices.Contains(haGenSubs, args[0]) {
+ // The command tree's fallback: no subcommand, or one it does not
+ // name.
+ code := haGenFallback(&out, &out, args)
+ return code, out.String()
+ }
+ r := haGenRun{Root: root, Cfg: &activator.Config{Bucket: rsBucket, Region: "us-east-1", Prefix: "hib"}, TmpDir: fx.tmp, Out: &out, Err: &out}
+ code := r.run(context.Background(), args[0], args[1:])
+ return code, out.String()
+}
+
+func (fx *hgFixture) noScratch(t *testing.T) {
+ t.Helper()
+ left, err := os.ReadDir(fx.tmp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(left) != 0 {
+ t.Fatalf("scratch left behind: %v", left)
+ }
+}
+
+// list prints head.json with its history, every generation with its newest
+// L0 and whether head.json names it, and the lock, and writes nothing.
+func TestHAGenerationsList(t *testing.T) {
+ fx := newHGFixture(t)
+ code, out := fx.run(t, "list", hgHost)
+ want := fmt.Sprintf(`shop.example.com (s3://data/hib/shop.example.com)
+head.json: %[1]s, start_txid %[3]d, created by box-b (lock generation 7) at 2026-11-18T10:00:00Z
+ history: %[2]s, start_txid 0, created 2026-11-17T09:00:00Z, ended 2026-11-18T10:00:00Z
+generations:
+ %[2]s: newest L0 %[3]d
+ %[1]s: newest L0 %[4]d (head.json names it)
+lock.json: released by box-b at lock generation 7 (generations marker): clean, txid %[5]d, bound %[5]d
+`, fx.g7, fx.g5, fx.t5, fx.t7, fx.t7+50)
+ if code != 0 || out != want {
+ t.Fatalf("list exit %d:\n%s\nwant:\n%s", code, out, want)
+ }
+ if _, w := fx.counts(); len(w) != 0 {
+ t.Fatalf("list wrote %v", w)
+ }
+}
+
+// verify restores the generation at its newest L0, checks it, prints the
+// TXID and the result, and leaves no scratch behind; a damaged generation
+// fails it.
+func TestHAGenerationsVerify(t *testing.T) {
+ fx := newHGFixture(t)
+ code, out := fx.run(t, "verify", hgHost, "--gen", fx.g5)
+ if want := fmt.Sprintf("%s: restored to transaction %d; the integrity check passed.\n", fx.g5, fx.t5); code != 0 || out != want {
+ t.Fatalf("verify exit %d: %q, want %q", code, out, want)
+ }
+ fx.noScratch(t)
+ g9 := replicagen.Name(9)
+ fx.m.Put(rsBucket, replicagen.Prefix(hgLoc, g9)+"0000/0000000000000001-0000000000000003.ltx", []byte("not an ltx file"))
+ code, out = fx.run(t, "verify", hgHost, "--gen", g9)
+ if code != 1 || !strings.HasPrefix(out, g9+": verify failed: ") {
+ t.Fatalf("verify of a damaged generation: exit %d: %q", code, out)
+ }
+ fx.noScratch(t)
+ if _, w := fx.counts(); len(w) != 0 {
+ t.Fatalf("verify wrote %v", w)
+ }
+}
+
+// expectedDocs are the two documents a point at g-5 writes, as the dry run
+// must print them.
+func (fx *hgFixture) expectedDocs(t *testing.T) (head, lock []byte) {
+ t.Helper()
+ h := lease.Head{V: 1, Generation: fx.g5, StartTXID: 0, Predecessor: fx.g7,
+ CreatedBy: lease.HeadCreator{LockGeneration: 5, Box: lease.PointCreator, At: hgNow},
+ History: []lease.HeadHistory{{Generation: fx.g7, StartTXID: fx.t5, CreatedAt: fx.head.CreatedBy.At, EndedAt: hgNow}, fx.head.History[0]}}
+ head, err := json.Marshal(h)
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := fx.marker
+ m.TXID = fx.t5
+ if lock, err = hafresh.MarkerBody(7, m); err != nil {
+ t.Fatal(err)
+ }
+ return head, lock
+}
+
+// etagOf is the ETag leasetest's S3 gives body: its MD5, quoted.
+func etagOf(b []byte) string {
+ return fmt.Sprintf(`"%x"`, md5.Sum(b))
+}
+
+// A point without --yes writes nothing (no PUT, POST or DELETE at all) and
+// prints exactly the loss and the two documents it would write.
+func TestHAGenerationsPointDryRun(t *testing.T) {
+ fx := newHGFixture(t)
+ headBefore, lockBefore := fx.current(t, "head.json"), fx.current(t, "lock.json")
+ code, out := fx.run(t, "point", hgHost, "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5))
+ head, lock := fx.expectedDocs(t)
+ want := fmt.Sprintf(`Pointing shop.example.com at %s keeps its data up to transaction %d and permanently gives up every transaction after it (the old head reached %d; the marker recorded %d).
+Dry run: nothing written. Run it again with --yes to write these two documents.
+head.json, If-Match %s:
+%s
+lock.json, If-Match %s:
+%s
+`, fx.g5, fx.t5, fx.t7, fx.t7+50, etagOf(headBefore), head, etagOf(lockBefore), lock)
+ if code != 0 || out != want {
+ t.Fatalf("dry run exit %d:\n%s\nwant:\n%s", code, out, want)
+ }
+ if _, w := fx.counts(); len(w) != 0 {
+ t.Fatalf("a dry run sent %d writes: %v", len(w), w)
+ }
+ fx.noScratch(t)
+}
+
+// point --yes writes exactly the documents the dry run printed, head.json
+// first, and says so.
+func TestHAGenerationsPointYes(t *testing.T) {
+ fx := newHGFixture(t)
+ code, out := fx.run(t, "point", hgHost, "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5), "--yes")
+ head, lock := fx.expectedDocs(t)
+ want := fmt.Sprintf(`Pointing shop.example.com at %s keeps its data up to transaction %d and permanently gives up every transaction after it (the old head reached %d; the marker recorded %d).
+Wrote head.json:
+%s
+Wrote lock.json:
+%s
+`, fx.g5, fx.t5, fx.t7, fx.t7+50, head, lock)
+ if code != 0 || out != want {
+ t.Fatalf("point exit %d:\n%s\nwant:\n%s", code, out, want)
+ }
+ if _, w := fx.counts(); strings.Join(w, ",") != "PUT "+hgLoc+"/head.json,PUT "+hgLoc+"/lock.json" {
+ t.Fatalf("writes %v, want head.json then lock.json", w)
+ }
+ if got := fx.current(t, "head.json"); !bytes.Equal(got, head) {
+ t.Fatalf("head.json %s, want %s", got, head)
+ }
+ if got := fx.current(t, "lock.json"); !bytes.Equal(got, lock) {
+ t.Fatalf("lock.json %s, want %s", got, lock)
+ }
+
+ // Again: head.json names g-5 and the bound is g-5's newest L0.
+ fx.reset()
+ code, out = fx.run(t, "point", hgHost, "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5), "--yes")
+ if want := fmt.Sprintf("Nothing to change: head.json names %s and the lock's bound, %d, is not above %d.\n", fx.g5, fx.t5, fx.t5); code != 0 || out != want {
+ t.Fatalf("second point exit %d: %q, want %q", code, out, want)
+ }
+ if _, w := fx.counts(); len(w) != 0 {
+ t.Fatalf("a point with nothing to change wrote %v", w)
+ }
+}
+
+// Every refusal exits 1, says why, and writes nothing.
+func TestHAGenerationsPointRefusals(t *testing.T) {
+ refused := func(t *testing.T, fx *hgFixture, want string, args ...string) {
+ t.Helper()
+ fx.reset()
+ code, out := fx.run(t, append([]string{"point", hgHost}, args...)...)
+ if code != 1 || out != want {
+ t.Fatalf("exit %d: %q\nwant %q", code, out, want)
+ }
+ if _, w := fx.counts(); len(w) != 0 {
+ t.Fatalf("a refused point wrote %v", w)
+ }
+ fx.noScratch(t)
+ }
+ t.Run("held", func(t *testing.T) {
+ fx := newHGFixture(t)
+ owner := hafresh.OwnerFor(hafresh.Self{Ref: "box-c", IID: "i-c", Account: "111122223333", Region: "eu-west-1"}, 4242, true)
+ until := hgNow.Add(10 * time.Minute)
+ fx.put(t, "lock.json", hafresh.Lock{Generation: 8, ExpiresAt: until, Owner: owner, GenName: replicagen.Name(8)})
+ refused(t, fx, fmt.Sprintf("ha-generations point: refused: the lock is held by %s until 2026-11-19T12:10:00Z. Point only a host no box holds.\n", owner),
+ "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5), "--yes")
+ })
+ t.Run("below", func(t *testing.T) {
+ fx := newHGFixture(t)
+ refused(t, fx, fmt.Sprintf("ha-generations point: refused: --accept-loss-after %d is not %s's newest L0 transaction, %d. A point keeps everything up to the newest L0, so pass --accept-loss-after %d.\n", fx.t5-1, fx.g5, fx.t5, fx.t5),
+ "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5-1), "--yes")
+ })
+ t.Run("above", func(t *testing.T) {
+ fx := newHGFixture(t)
+ refused(t, fx, fmt.Sprintf("ha-generations point: refused: --accept-loss-after %d is above %s's newest L0 transaction, %d. The generation holds nothing after %d.\n", fx.t5+1, fx.g5, fx.t5, fx.t5),
+ "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5+1), "--yes")
+ })
+ t.Run("absent", func(t *testing.T) {
+ fx := newHGFixture(t)
+ g9 := replicagen.Name(9)
+ refused(t, fx, fmt.Sprintf("ha-generations point: refused: %s does not exist under s3://data/hib/shop.example.com.\n", g9),
+ "--gen", g9, "--accept-loss-after", "3", "--yes")
+ })
+ t.Run("verify", func(t *testing.T) {
+ fx := newHGFixture(t)
+ g9 := replicagen.Name(9)
+ fx.m.Put(rsBucket, replicagen.Prefix(hgLoc, g9)+"0000/0000000000000001-0000000000000003.ltx", []byte("not an ltx file"))
+ fx.reset()
+ code, out := fx.run(t, "point", hgHost, "--gen", g9, "--accept-loss-after", "3", "--yes")
+ if prefix := "ha-generations point: refused: " + g9 + " failed verify: "; code != 1 || !strings.HasPrefix(out, prefix) {
+ t.Fatalf("exit %d: %q, want %q...", code, out, prefix)
+ }
+ if _, w := fx.counts(); len(w) != 0 {
+ t.Fatalf("a refused point wrote %v", w)
+ }
+ fx.noScratch(t)
+ })
+}
+
+// A lost condition: head.json changed before its write (nothing written),
+// or lock.json changed after head.json was rewritten (head.json written,
+// the lock not; the output says so and how to recover).
+func TestHAGenerationsPointConflicts(t *testing.T) {
+ t.Run("head", func(t *testing.T) {
+ fx := newHGFixture(t)
+ lockBefore := fx.current(t, "lock.json")
+ moved := fx.head
+ moved.StartTXID++
+ fx.beforeW = func(r *http.Request, key string) {
+ if key == hgLoc+"/head.json" {
+ fx.put(t, "head.json", moved)
+ }
+ }
+ code, out := fx.run(t, "point", hgHost, "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5), "--yes")
+ if !strings.HasSuffix(out, "head.json changed after it was read, so nothing was written. Run \"carlos ops ha-generations list shop.example.com\", then point again.\n") || code != 1 {
+ t.Fatalf("exit %d:\n%s", code, out)
+ }
+ if _, w := fx.counts(); strings.Join(w, ",") != "PUT "+hgLoc+"/head.json" {
+ t.Fatalf("writes %v, want only the refused head.json PUT", w)
+ }
+ if got := fx.current(t, "lock.json"); !bytes.Equal(got, lockBefore) {
+ t.Fatal("lock.json was written after head.json's conflict")
+ }
+ })
+ t.Run("lock", func(t *testing.T) {
+ fx := newHGFixture(t)
+ lockBefore := fx.current(t, "lock.json")
+ fx.beforeW = func(r *http.Request, key string) {
+ if key == hgLoc+"/lock.json" {
+ fx.m.Put(rsBucket, hgLoc+"/lock.json", append(bytes.Clone(lockBefore), ' '))
+ }
+ }
+ code, out := fx.run(t, "point", hgHost, "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5), "--yes")
+ head, _ := fx.expectedDocs(t)
+ want := fmt.Sprintf("Wrote head.json:\n%s\nha-generations point: head.json now names %s, but lock.json changed after it was read, so it was not written; a box may have taken the lock. Run \"carlos ops ha-generations list shop.example.com\", then point again.\n", head, fx.g5)
+ if code != 1 || !strings.HasSuffix(out, want) {
+ t.Fatalf("exit %d:\n%s\nwant suffix:\n%s", code, out, want)
+ }
+ if got := fx.current(t, "head.json"); !bytes.Equal(got, head) {
+ t.Fatalf("head.json %s, want the point's", got)
+ }
+ })
+}
+
+// The verb refuses root before it reads anything.
+func TestHAGenerationsRefusesRoot(t *testing.T) {
+ fx := newHGFixture(t)
+ fx.reset()
+ code, out := fx.runAs(t, true, "point", hgHost, "--gen", fx.g5, "--accept-loss-after", fmt.Sprint(fx.t5), "--yes")
+ if want := "ha-generations: not run: refusing to run as root. Run it as the carlos user, as carlos-hibernate-verify.service does.\n"; code != 1 || out != want {
+ t.Fatalf("exit %d: %q, want %q", code, out, want)
+ }
+ if n, _ := fx.counts(); n != 0 {
+ t.Fatalf("root made %d requests", n)
+ }
+}
+
+// Usage mistakes exit 2 before any request.
+func TestHAGenerationsUsage(t *testing.T) {
+ fx := newHGFixture(t)
+ fx.reset()
+ for _, args := range [][]string{
+ nil,
+ {"undo", hgHost},
+ {"list"},
+ {"verify", hgHost},
+ {"verify", hgHost, "--gen", "g-5"},
+ {"point", hgHost, "--gen", replicagen.Name(5)},
+ {"point", hgHost, "--accept-loss-after", "3"},
+ {"list", hgHost, "other.example.com"},
+ } {
+ if code, out := fx.run(t, args...); code != 2 || !strings.Contains(out, "usage: carlos ops ha-generations") {
+ t.Errorf("%q: exit %d: %q", args, code, out)
+ }
+ }
+ if n, _ := fx.counts(); n != 0 {
+ t.Fatalf("usage mistakes made %d requests", n)
+ }
+ if code, out := fx.run(t, "--help"); code != 0 || out != haGenUsage {
+ t.Fatalf("--help: exit %d: %q", code, out)
+ }
+}
+
+// The command tree routes each subcommand word to its own leaf; the
+// branch with no word, or a word it does not name, is the fallback.
+func TestHAGenerationsCommandTree(t *testing.T) {
+ var n *clireg.Node
+ for _, c := range Commands() {
+ if c.Name == "ha-generations" {
+ n = c
+ }
+ }
+ if n == nil || n.Fallback == nil || n.Audience != clireg.BoxLocal {
+ t.Fatalf("ops ha-generations node %+v", n)
+ }
+ var names []string
+ for _, c := range n.Children {
+ if c.Run == nil || c.Audience != clireg.BoxLocal {
+ t.Errorf("%s: not a box-local leaf", c.Name)
+ }
+ names = append(names, c.Name)
+ }
+ if !slices.Equal(names, []string{"list", "verify", "point"}) {
+ t.Fatalf("subcommands %v", names)
+ }
+}
diff --git a/internal/ops/ops.go b/internal/ops/ops.go
index 15bd44131..2e68cdf94 100644
--- a/internal/ops/ops.go
+++ b/internal/ops/ops.go
@@ -53,6 +53,7 @@ func Commands() []*clireg.Node {
leaf("litestream", runLitestream),
leaf("restore-verify", runRestoreVerify),
leaf("hibernate-verify", runHibernateVerify),
+ haGenerationsCommand(),
}
}
@@ -90,6 +91,13 @@ func usage() {
replication the activator owns under its lease.
Publishes a per-host verdict to the deployment
bucket so the result is readable off-box.
+ carlos ops ha-generations list|verify|point <host>
+ restore by hand a region HA host whose wake was
+ refused (ha_generation_refused): list its
+ storage generations, verify one, or point the
+ host at one. point gives up every transaction
+ after the one you name, and writes nothing
+ without --yes.
No verb for your task? Extend ops in a small PR — never a hand-run sequence
reconstructed from docs.
diff --git a/parity/cli.tsv b/parity/cli.tsv
index cb32f4faf..b86c1f4b6 100644
--- a/parity/cli.tsv
+++ b/parity/cli.tsv
@@ -175,6 +175,9 @@ move offline start customer - - - - -
move offline status customer - - - - -
move resolve customer - - - - -
move status customer - - - - -
+ops ha-generations list box-local - - - - -
+ops ha-generations point box-local - - - - -
+ops ha-generations verify box-local - - - - -
ops hibernate-verify box-local - - - - -
ops host resolve operator - - - - -
ops litestream box-local - - - - -
diff --git a/parity/parity.tsv b/parity/parity.tsv
index 7fcdde519..a8f598a33 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -230,7 +230,7 @@ bootstrap box box-local bootstrap Prepares a host, as root.
box-routes box box-local add ; remove ; route ; instances This box's own registry routes.
box-daemons box box-local edge ; agent ; adopt Run under systemd on a box.
box-instance box box-local instance-control ; instance-exec ; instance-exit ; instance-stop ; instance-probe Instance plumbing run under systemd.
-box-ops box box-local ops litestream ; ops restore-verify ; ops hibernate-verify Checks run on a box.
+box-ops box box-local ops litestream ; ops restore-verify ; ops hibernate-verify ; ops ha-generations list ; ops ha-generations verify ; ops ha-generations point Checks run on a box.
release-keygen box box-local release-keygen Mints signing keys; the private key stays local.
proof box box-local proof keygen ; proof get ; proof put ; proof history Dev proofs a box needs to adopt.
relay-box box box-local relay serve ; relay keygen Runs the relay, or mints a region master key.