ha-generations point: R1 fixes (keep rule, retained, exact bound)
Task 14 fix round 1 (Astra R1 NOT READY, Fable R1 READY AFTER FIXES; controller rulings 1-8). - activator: a wake keeps its local copy only when the take copied from the generation the marker's holder wrote (g-<its lock generation>, or the root with no head.json). Witness: a point at a sibling with the marker's TXID and other rows restores it. - lease.PointGeneration refuses a generation head.json neither names nor keeps in history (not_retained) and a host without head.json (no_head); re-reads head.json beside the lock and refuses head_changed; always writes both documents, head.json first, so the head rewrite fences a switch already in flight; sets the lock's take bound to exactly the accepted TXID (raised or lowered); writes head.json without SDK retries; created_by records the lock's own generation. - ops: list prints created_by iid and lifetime and marks each prefix; loss sentences for a head and a history target; Luna's approved copy; docs/site/cli.md documents the verb.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+553
−212
docs/site/cli.md+19 −0internal/activator/hapoint_test.go+111 −0internal/activator/hawake.go+10 −0internal/lease/genpoint.go+119 −115internal/lease/genpoint_test.go+157 −17internal/lease/gentake.go+20 −1internal/ops/hagenerations.go+70 −48internal/ops/hagenerations_test.go+43 −27internal/ops/ops.go+4 −4
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 6dd60f1d6..14eafc8b4 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -3845,6 +3845,25 @@ the deployment bucket so you can read it off-box. |
| carlos ops restore-verify |
| ``` |
| +`ha-generations` recovers a region HA host whose wake was refused |
| +(`ha_generation_refused`). Run it on a box as the carlos user. `list <host>` |
| +shows the host's head.json, each storage generation with its newest L0 |
| +transaction, and its lock. `verify <host> --gen <g-N>` restores one |
| +generation into a temporary file, integrity-checks it and removes the file. |
| +Both only read. `point <host> --gen <g-N> --accept-loss-after <txid>` points |
| +the host at a generation head.json names or keeps in its history, and |
| +permanently gives up every transaction after `<txid>`, which must be that |
| +generation's newest L0 transaction. It runs the same verify first. Without |
| +`--yes` it is a dry run: it prints what is lost and the two documents it |
| +would write, head.json and then lock.json, and writes nothing. With `--yes` |
| +it writes head.json first. If lock.json then changed before its own write, |
| +point says that head.json was written and lock.json was not; run `list` |
| +again, then point again. |
| + |
| +```sh |
| +carlos ops ha-generations point shop.example.com --gen g-00000000000000000005 --accept-loss-after 120 |
| +``` |
| + |
| ## Everything else |
| `carlos help` belongs to all three roles above. |
diff --git a/internal/activator/hapoint_test.go b/internal/activator/hapoint_test.go| new file mode 100644 |
| index 000000000..e48d7e902 |
| --- /dev/null |
| +++ b/internal/activator/hapoint_test.go |
| @@ -0,0 +1,111 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "testing" |
| + "time" |
| + |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +// Task 14 R1 (Astra P1-1, Fable P2-1): after an operator's point |
| +// (carlos ops ha-generations point) at a sibling generation that reached |
| +// the same TXID as the marker with different contents, the marker's own |
| +// box must not keep its local copy: the wake restores the pointed |
| +// generation. DecideKeep alone passes (the marker's TXID, files generation |
| +// and box are its), and so does the take's TXID, so only the generation |
| +// the take read tells them apart. |
| +func TestHAWakeAfterAPointRestoresThePointedGeneration(t *testing.T) { |
| + t.Setenv("CARLOS_HA_GENERATIONS", "on") |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.insertRows(t, 0, 5) |
| + s.stopForTest(e) |
| + v := s.lockView(t) |
| + m := v.Lock.Release |
| + if m == nil || !m.Clean || !m.Gen || m.TXID == 0 { |
| + t.Fatalf("want a clean generations marker: %+v", v.Lock) |
| + } |
| + if h, _ := s.head(t); h.Generation != replicagen.Name(v.Lock.Generation) { |
| + t.Fatalf("fixture: head names %s, the marker's holder wrote %s", h.Generation, replicagen.Name(v.Lock.Generation)) |
| + } |
| + |
| + // A sibling generation in head.json's history, reaching exactly the |
| + // marker's TXID with other rows. |
| + sib := replicagen.Name(40) |
| + dir := t.TempDir() |
| + dbdoortest.Replicate(t, dir, int(m.TXID)) |
| + p, err := dbdoor.PlanFrom(context.Background(), lsfile.NewReplicaClient(dir), time.Time{}) |
| + if err != nil || p.TXID != m.TXID { |
| + t.Fatalf("fixture: the sibling reaches %d (%v), want the marker's %d", p.TXID, err, m.TXID) |
| + } |
| + putFileReplica(t, s, replicagen.Prefix(s.loc(), sib), dir) |
| + h, _ := s.head(t) |
| + h.History = append(h.History, lease.HeadHistory{Generation: sib, CreatedAt: h.CreatedBy.At.Add(-2 * time.Hour), EndedAt: h.CreatedBy.At.Add(-time.Hour)}) |
| + body, err := json.Marshal(h) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.fx.PutObject(s.headKey(), body) |
| + |
| + verifyDir := t.TempDir() |
| + res, err := lease.PointGeneration(context.Background(), lease.PointRequest{Bucket: s.fx.Bucket, Loc: s.loc(), |
| + Generation: sib, TXID: m.TXID, Write: true, |
| + Verify: func(ctx context.Context, gen string) (uint64, error) { |
| + return lease.VerifyGeneration(ctx, s.fx.Bucket, s.loc(), "", gen, verifyDir) |
| + }}) |
| + if err != nil || !res.HeadWritten || !res.LockWritten { |
| + t.Fatalf("point %+v: %v", res, err) |
| + } |
| + if got := s.lockView(t).Lock.Release; got == nil || got.TXID != m.TXID || got.Box != m.Box || !got.Clean { |
| + t.Fatalf("the point changed the marker's keep fields: %+v", got) |
| + } |
| + |
| + e, err = s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if n, want := countRows(t, s.b.pathsFor(s.rt).dbPath), int(m.TXID)*dbdoortest.Rows; n != want { |
| + t.Fatalf("the wake serves %d rows, want the pointed generation's %d (5 is the kept local copy)", n, want) |
| + } |
| + if h, _ := s.head(t); h.Predecessor != sib { |
| + t.Fatalf("head after the wake %+v, want a take from %s", h, sib) |
| + } |
| + s.stopForTest(e) |
| +} |
| + |
| +// putFileReplica copies a litestream file replica (dir/ltx/<level>/<file>) |
| +// under prefix in the S3 client's layout. |
| +func putFileReplica(t *testing.T, s *haSvc, prefix, dir string) { |
| + t.Helper() |
| + levels, err := os.ReadDir(filepath.Join(dir, "ltx")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, lv := range levels { |
| + level, err := strconv.Atoi(lv.Name()) |
| + if err != nil { |
| + continue |
| + } |
| + files, err := os.ReadDir(filepath.Join(dir, "ltx", lv.Name())) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, f := range files { |
| + body, err := os.ReadFile(filepath.Join(dir, "ltx", lv.Name(), f.Name())) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.fx.PutObject(fmt.Sprintf("%s%04x/%s", prefix, level, f.Name()), body) |
| + } |
| + } |
| +} |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index 97b3a91c5..cb753c124 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -21,6 +21,7 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| ) |
| // Region HA P1a, the wake (spec §5, §7.3): a host born HA (its record's ha, |
| @@ -781,6 +782,15 @@ func (b *ExecBackend) restoreHAGenerations(ctx context.Context, rt registry.Rout |
| } else { |
| log.Printf("activator: %s: %v", host, rerr) |
| } |
| + // The local copy is the marker holder's: it may stand for the |
| + // replica only when the take copied from the generation that |
| + // holder wrote, g-<its lock generation> (or the root layout, with |
| + // no head.json). An operator's point (carlos ops ha-generations) |
| + // can name another generation that reached the same TXID with |
| + // different contents (Task 14 R1). |
| + if read := take.HeadGeneration(); keep && read != replicagen.Root && read != replicagen.Name(v.Lock.Generation) { |
| + keep, reason = false, fmt.Sprintf("head %s, marker holder's %s", read, replicagen.Name(v.Lock.Generation)) |
| + } |
| if keep && take.StartTXID != v.Lock.Release.TXID { |
| keep, reason = false, fmt.Sprintf("take-txid %d, marker %d", take.StartTXID, v.Lock.Release.TXID) |
| } |
diff --git a/internal/lease/genpoint.go b/internal/lease/genpoint.go| index 7cf8f5a23..167c51307 100644 |
| --- a/internal/lease/genpoint.go |
| +++ b/internal/lease/genpoint.go |
| @@ -7,7 +7,6 @@ import ( |
| "errors" |
| "fmt" |
| "sort" |
| - "strconv" |
| "strings" |
| "time" |
| @@ -220,20 +219,20 @@ type PointRequest struct { |
| // 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. |
| +// HeadETag, and LockBody the exact lock.json, conditional on LockETag: a |
| +// point always writes both, head.json first (PointGeneration). 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). |
| + Generation string |
| + NewestL0 uint64 |
| + // OldHead is head.json as the point read it; Generation is its |
| + // generation or one of its history entries. |
| + OldHead Head |
| + // OldReached is the newest L0 TXID of the generation OldHead named. |
| OldReached uint64 |
| // OldBound is the lock's take bound before the point |
| - // (hafresh.View.TakeBound). |
| + // (hafresh.View.TakeBound); after it, the bound is exactly the |
| + // accepted TXID. |
| OldBound uint64 |
| Lock hafresh.View |
| HeadBody []byte |
| @@ -250,12 +249,15 @@ const ( |
| 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 |
| + PointNoHead = "no_head" // there is no head.json: no generation is retained (head_missing) |
| + PointNotRetained = "not_retained" // Generation is neither head.json's generation nor a history entry |
| 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 |
| + PointHeadChanged = "head_changed" // head.json changed while the point verified |
| PointBadGeneration = "bad_generation" // Generation is not a g-<N> name |
| ) |
| @@ -315,35 +317,43 @@ func (e *PointWriteError) Unwrap() error { return e.Err } |
| // 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. |
| +// renewal margin). Read head.json, and refuse a Generation that is not |
| +// its generation or one of its history entries (not_retained; with no |
| +// head.json at all, no_head): retirement never deletes those, while |
| +// an abandoned prefix may still have an earlier holder's deletes in |
| +// flight (Task 14 R1, cut for this slice). |
| // 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 |
| +// 3. Read lock.json and head.json again: either changed since step 1 |
| +// refuses (lock_changed, head_changed). The lock read's 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 |
| +// 4. Build both documents, always. head.json: Generation current from |
| +// now, created_by PointCreator with the lock's own generation, the |
| +// previous head prepended to history as ended now (even when it names |
| +// Generation: the rewrite is the fence below), trimmed as a take trims |
| +// it; predecessor the generation it replaced, or the previous head's |
| +// own predecessor when that was Generation. lock.json: the same lock |
| +// with its effective take bound (hafresh.View.TakeBound) exactly TXID, |
| +// raised or lowered: a marker's min_txid set to TXID and a clean |
| +// marker's TXID lowered to it when above; a held lock's |
| +// carlos_min_txid set to TXID. Its format (carlos_release_g or |
| +// carlos_release), owner, generation and expiry are unchanged. An |
| +// exact bound makes the next take refuse any plan that ends below the |
| +// TXID the operator accepted. |
| +// 5. With Write: head.json first, If-Match the ETag step 1 read, then |
| +// lock.json, If-Match the ETag step 1 read; one PUT each, the SDK's |
| +// retries off. head.json goes first so that a bound is never set while |
| +// head.json still names a generation the operator did not choose, and |
| +// its write always changes head.json's ETag, so a switch an expired |
| +// holder already sent (conditional on the old ETag) can no longer |
| +// land. 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. |
| +// HeadWritten): the next take over a higher bound is refused again, |
| +// and the recovery is to read the state again (list) and point again. |
| +// 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, |
| @@ -354,10 +364,6 @@ func PointGeneration(ctx context.Context, req PointRequest) (PointResult, error) |
| 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") |
| } |
| @@ -395,9 +401,12 @@ func PointGeneration(ctx context.Context, req PointRequest) (PointResult, error) |
| if err != nil { |
| return res, err |
| } |
| - res.OldHead, res.OldHeadFound = oldHead, headFound |
| - if headFound { |
| - res.HeadETag = headETag |
| + if !headFound { |
| + return res, &PointRefusal{Reason: PointNoHead, Err: fmt.Errorf("%s has no head.json", loc)} |
| + } |
| + res.OldHead, res.HeadETag, res.LockETag = oldHead, headETag, v.ETag |
| + if !retained(oldHead, gen) { |
| + return res, &PointRefusal{Reason: PointNotRetained, Err: fmt.Errorf("head.json names %s and keeps %d history entries; %s is none of them", oldHead.Generation, len(oldHead.History), gen)} |
| } |
| // 2. The generation: it exists, a take can start from it, TXID is its |
| @@ -410,14 +419,12 @@ func PointGeneration(ctx context.Context, req PointRequest) (PointResult, error) |
| if !hasCurrent(listed) { |
| return res, &PointRefusal{Reason: PointNoGeneration, Err: fmt.Errorf("%s holds no object", prefix)} |
| } |
| - predecessor := replicagen.Root |
| - if headFound { |
| - predecessor = oldHead.Generation |
| + predecessor := oldHead.Generation |
| + if gen == oldHead.Generation { |
| + predecessor = oldHead.Predecessor |
| } |
| - // 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) |
| + // The head the next take reads, as far as PlanStart looks at it. |
| + plan, err := PlanStart(ctx, s.vs, req.Bucket, loc, Head{V: HeadVersion, Generation: gen, Predecessor: replicagen.Root}, true, 0) |
| if err != nil { |
| var sr *StartRefusal |
| if errors.As(err, &sr) { |
| @@ -434,8 +441,7 @@ func PointGeneration(ctx context.Context, req PointRequest) (PointResult, error) |
| case req.TXID < plan.T: |
| return res, &PointRefusal{Reason: PointTXIDMismatch, NewestL0: plan.T} |
| } |
| - oldGen := predecessor |
| - oldPrefix := replicagen.Prefix(loc, oldGen) |
| + oldPrefix := replicagen.Prefix(loc, oldHead.Generation) |
| if res.OldReached, err = newestL0(ctx, s.vs, req.Bucket, oldPrefix, oldPrefix+"0000/"); err != nil { |
| return res, err |
| } |
| @@ -448,7 +454,8 @@ func PointGeneration(ctx context.Context, req PointRequest) (PointResult, error) |
| 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. |
| + // 3. The lock and head.json 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 { |
| @@ -457,6 +464,11 @@ func PointGeneration(ctx context.Context, req PointRequest) (PointResult, error) |
| if again.Absent || again.ETag != v.ETag { |
| return res, &PointRefusal{Reason: PointLockChanged} |
| } |
| + if _, etag, found, err := ReadHead(ctx, s.st, loc); err != nil { |
| + return res, err |
| + } else if !found || etag != headETag { |
| + return res, &PointRefusal{Reason: PointHeadChanged} |
| + } |
| now := second.last() |
| if now.IsZero() { |
| return res, &PointRefusal{Reason: PointNoStoreTime, Err: ErrNoStoreTime} |
| @@ -464,52 +476,55 @@ func PointGeneration(ctx context.Context, req PointRequest) (PointResult, error) |
| // 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) { |
| + if 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 |
| - } |
| + history := append([]HeadHistory{{Generation: oldHead.Generation, StartTXID: oldHead.StartTXID, CreatedAt: oldHead.CreatedBy.At, EndedAt: now}}, oldHead.History...) |
| + head := Head{V: HeadVersion, Generation: gen, CreatedBy: HeadCreator{LockGeneration: v.Lock.Generation, Box: PointCreator, At: now}, |
| + StartTXID: recordedStart(oldHead, 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 res.LockBody, err = json.Marshal(exactBound(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 |
| + hk, err := headKey(loc) |
| + if err != nil { |
| + return res, err |
| } |
| - 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 |
| + if err := putIfMatch(ctx, s.client, req.Bucket, hk, res.HeadBody, res.HeadETag); err != nil { |
| + return res, &PointWriteError{Doc: headName, Conflict: conditionFailed(err) || lockAbsent(err), Err: err} |
| } |
| + res.HeadWritten = true |
| + if err := putIfMatch(ctx, s.client, req.Bucket, key, res.LockBody, res.LockETag); err != nil { |
| + return res, &PointWriteError{Doc: "lock.json", Conflict: conditionFailed(err) || lockAbsent(err), HeadWritten: true, Err: err} |
| + } |
| + res.LockWritten = true |
| return res, nil |
| } |
| +// retained reports whether h names gen as its generation or keeps it in |
| +// its history. |
| +func retained(h Head, gen string) bool { |
| + if h.Generation == gen { |
| + return true |
| + } |
| + for _, e := range h.History { |
| + if e.Generation == gen { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| // hasCurrent reports whether listed holds a current object. |
| func hasCurrent(listed []ObjectVersion) bool { |
| for _, v := range listed { |
| @@ -521,11 +536,8 @@ func hasCurrent(listed []ObjectVersion) bool { |
| } |
| // 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 |
| - } |
| +// current generation or in its history (the newest entry). |
| +func recordedStart(h Head, gen string) uint64 { |
| if h.Generation == gen { |
| return h.StartTXID |
| } |
| @@ -537,39 +549,31 @@ func recordedStart(h Head, found bool, gen string) uint64 { |
| 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 { |
| +// exactBound is l with its effective take bound (hafresh.View.TakeBound) |
| +// exactly txid, raised or lowered as the format carries it: a marker's |
| +// min_txid set to txid and a clean marker's TXID lowered to txid when |
| +// above it (a lock-level carlos_min_txid on a marker lowered too); a held |
| +// lock's carlos_min_txid set to txid. Nothing else changes. |
| +func exactBound(l hafresh.Lock, txid uint64) hafresh.Lock { |
| + if l.Release == nil { |
| + l.MinTXID = txid |
| + return l |
| + } |
| + m := *l.Release |
| + m.MinTXID = txid |
| + if m.Clean { |
| + m.TXID = min(m.TXID, txid) |
| + } |
| + l.Release = &m |
| 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 { |
| +// putIfMatch writes body at key, If-Match etag: one PUT, the SDK's own |
| +// retries off, so a lost condition, or a response that never came, is the |
| +// operator's to read again (a retried PUT could otherwise report a 412 |
| +// for a write that landed). |
| +func putIfMatch(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), |
diff --git a/internal/lease/genpoint_test.go b/internal/lease/genpoint_test.go| index c5bf65cea..742e89eff 100644 |
| --- a/internal/lease/genpoint_test.go |
| +++ b/internal/lease/genpoint_test.go |
| @@ -1,6 +1,7 @@ |
| package lease_test |
| import ( |
| + "bytes" |
| "context" |
| "errors" |
| "fmt" |
| @@ -143,7 +144,7 @@ func TestPointThenTakeSucceedsFromThePointedGeneration(t *testing.T) { |
| } |
| head, _, _ := fx.head(t) |
| if head.Generation != g1 || head.Predecessor != g2 || head.CreatedBy.Box != lease.PointCreator || |
| - head.CreatedBy.LockGeneration != 1 || head.CreatedBy.At.IsZero() { |
| + head.CreatedBy.LockGeneration != before.Lock.Generation || 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) || |
| @@ -223,45 +224,157 @@ func TestPointDryRunWritesNothing(t *testing.T) { |
| } |
| } |
| -// 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) { |
| +// Pointing at the generation head.json already names still rewrites |
| +// head.json, If-Match the head it read: the rewrite is the fence that |
| +// stops a switch an expired holder already sent (Task 14 R1). head.json |
| +// keeps naming the generation, with the previous head as a history entry |
| +// and created_by refreshed; the clean marker's TXID is lowered to the |
| +// generation's newest L0, its min_txid set to it, and it stays clean. A |
| +// second point writes both again. |
| +func TestPointAtTheCurrentGenerationRewritesBoth(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) |
| + oldHead, oldETag, _ := fx.head(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 { |
| + if !res.HeadWritten || !res.LockWritten || res.HeadETag != oldETag { |
| t.Fatalf("point %+v", res) |
| } |
| + head, etag, _ := fx.head(t) |
| + if head.Generation != g2 || etag == oldETag || head.Predecessor != oldHead.Predecessor || head.StartTXID != oldHead.StartTXID || |
| + head.CreatedBy.Box != lease.PointCreator || len(head.History) != len(oldHead.History)+1 || head.History[0].Generation != g2 { |
| + t.Fatalf("head after the point %+v, was %+v", head, oldHead) |
| + } |
| want := *before.Lock.Release |
| - want.TXID = t2 |
| + want.TXID, want.MinTXID = t2, 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) |
| + if w := fx.keys("point", false); !slices.Equal(w, []string{fx.loc + "/head.json", fx.loc + "/lock.json"}) { |
| + t.Fatalf("wrote %v, want head.json then 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 res, err = fx.point(t, g2, t2, true); err != nil || !res.HeadWritten || !res.LockWritten { |
| + t.Fatalf("second point %+v %v", res, err) |
| + } |
| +} |
| + |
| +// The bound a point leaves is exactly the TXID it accepted, raised as well |
| +// as lowered (Task 14 R1): over an unclean marker with no bound, a point |
| +// at the newest L0 still binds the next take to it, so if that L0 later |
| +// goes (a delete an earlier holder sent lands late), the next take refuses |
| +// a plan that ends below it instead of silently losing the rest. |
| +func TestPointSetsAnExactBound(t *testing.T) { |
| + haBox(t) |
| + fx := newGenFixture(t) |
| + g1, t1 := fx.seedSyncs(t, time.Minute, 3, 3) |
| + v := fx.lockView(t) |
| + m := *v.Lock.Release |
| + m.Clean, m.Settled, m.TXID, m.MinTXID = false, true, 0, 0 |
| + body, err := hafresh.MarkerBody(v.Lock.Generation, m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.m.Put(fx.bucket, fx.loc+"/lock.json", body) |
| + if b := fx.lockView(t).TakeBound(); b != 0 { |
| + t.Fatalf("fixture: bound %d, want 0", b) |
| + } |
| + if _, err := fx.point(t, g1, t1, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + after := fx.lockView(t) |
| + if after.TakeBound() != t1 || after.Lock.Release.MinTXID != t1 || after.Lock.Release.Clean || !after.Lock.Release.Settled { |
| + t.Fatalf("lock after the point %+v, want an unclean settled marker bound at %d", after.Lock.Release, t1) |
| + } |
| + newest := "" |
| + for _, k := range fx.current(t, replicagen.Prefix(fx.loc, g1)+"0000/") { |
| + if strings.HasSuffix(k, fmt.Sprintf("-%016x.ltx", t1)) { |
| + newest = k |
| + } |
| + } |
| + if newest == "" { |
| + t.Fatalf("fixture: no L0 file ends at %d", t1) |
| + } |
| + fx.m.BareDelete(fx.bucket, newest) |
| + 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("the take after the L0 went: %v, want clean_marker_above_l0", err) |
| } |
| - if w := fx.keys("again", false); len(w) != 0 { |
| - t.Fatalf("a point with nothing to change wrote %v", w) |
| + if err := h.Release(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// A switch an expired holder already sent (its PUT in flight, conditional |
| +// on the head ETag it read) cannot land after a point, even a point at the |
| +// generation head.json already names: the point's own conditional |
| +// rewrite changed the ETag first (Task 14 R1). The lock the point lowers |
| +// here is that holder's expired held lock (carlos_min_txid), and the next |
| +// take, over it, starts from the pointed generation. |
| +func TestPointFencesADelayedSwitch(t *testing.T) { |
| + haBox(t) |
| + fx := newGenFixture(t) |
| + g1, t1 := fx.seed(t, time.Minute, 3) |
| + const ttl = time.Second |
| + h := fx.acquire(t, ttl) |
| + tk, err := h.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L2"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.setPhase("a") |
| + arrived, release := heldSwitch(fx) |
| + t.Cleanup(release) |
| + done := make(chan error, 1) |
| + go func() { done <- tk.Switch(ctx) }() |
| + <-arrived |
| + lease.AbandonHeldForTest(h) // the holder dies with its switch in flight |
| + held := fx.lockView(t) |
| + if held.Lock.Release != nil || held.Lock.GenName == "" { |
| + t.Fatalf("fixture: %+v, want a held generations lock", held.Lock) |
| + } |
| + // The store's clock (whole seconds) past the expiry and its margin. |
| + time.Sleep(time.Until(held.Lock.ExpiresAt.Add(lease.RenewMargin + 1500*time.Millisecond))) |
| + |
| + fx.setPhase("point") |
| + res, err := fx.point(t, g1, t1, true) |
| + if err != nil || !res.HeadWritten || !res.LockWritten { |
| + t.Fatalf("point %+v: %v", res, err) |
| + } |
| + if got := fx.lockView(t).Lock; got.MinTXID != t1 || got.GenName != held.Lock.GenName || got.Owner != held.Lock.Owner || |
| + got.Generation != held.Lock.Generation || !got.ExpiresAt.Equal(held.Lock.ExpiresAt) || got.Release != nil { |
| + t.Fatalf("held lock after the point %+v, want %+v with carlos_min_txid %d", got, held.Lock, t1) |
| + } |
| + release() |
| + if err := <-done; !errors.Is(err, lease.ErrHeadMoved) { |
| + t.Fatalf("the delayed switch: %v, want ErrHeadMoved", err) |
| + } |
| + if head, _, _ := fx.head(t); head.Generation != g1 { |
| + t.Fatalf("head names %s after the delayed switch, want the pointed %s", head.Generation, g1) |
| + } |
| + fx.setPhase("") |
| + next := fx.acquire(t, time.Minute) |
| + tk2, err := next.StartGeneration(ctx, fx.st, fx.vs, lease.TakeOptions{Self: selfA, Lifetime: "L3"}) |
| + if err != nil || tk2.Predecessor != g1 || tk2.StartTXID != t1 || tk2.Bound != t1 { |
| + t.Fatalf("the take after the point %+v: %v, want from %s at %d", tk2, err, g1, t1) |
| + } |
| + if err := next.Release(ctx); err != nil { |
| + t.Fatal(err) |
| } |
| } |
| // 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. |
| +// generation's newest L0 (above or below), a generation head.json neither |
| +// names nor keeps in history (absent or abandoned), one that fails |
| +// verify, and a head.json that moved while the point verified. |
| func TestPointRefusalsWriteNothing(t *testing.T) { |
| haBox(t) |
| fx := newGenFixture(t) |
| @@ -295,7 +408,34 @@ func TestPointRefusalsWriteNothing(t *testing.T) { |
| } |
| }) |
| t.Run("absent", func(t *testing.T) { |
| - refused(t, lease.PointNoGeneration, replicagen.Name(9), t1, nil) |
| + refused(t, lease.PointNotRetained, replicagen.Name(9), t1, nil) |
| + }) |
| + t.Run("abandoned", func(t *testing.T) { |
| + // A complete prefix no head.json ever named (or no longer keeps): |
| + // an earlier holder's retirement may still be deleting it. |
| + for _, k := range fx.current(t, replicagen.Prefix(fx.loc, g1)) { |
| + body, _ := fx.m.Current(fx.bucket, k) |
| + fx.m.Put(fx.bucket, strings.Replace(k, g1, replicagen.Name(9), 1), body) |
| + } |
| + refused(t, lease.PointNotRetained, replicagen.Name(9), t1, nil) |
| + }) |
| + t.Run("head-changed", func(t *testing.T) { |
| + head := mustCurrent(t, fx, "head.json") |
| + lock := mustCurrent(t, fx, "lock.json") |
| + fx.setPhase(t.Name()) |
| + _, err := lease.PointGeneration(ctx, lease.PointRequest{Bucket: fx.bucket, Loc: fx.loc, Region: fx.region, |
| + Generation: g1, TXID: t1, Write: true, Verify: func(ctx context.Context, gen string) (uint64, error) { |
| + fx.m.Put(fx.bucket, fx.loc+"/head.json", append(slices.Clone(head), ' ')) // a late switch lands |
| + return fx.pointVerify(t)(ctx, gen) |
| + }}) |
| + var pr *lease.PointRefusal |
| + if !errors.As(err, &pr) || pr.Reason != lease.PointHeadChanged { |
| + t.Fatalf("point: %v, want head_changed", err) |
| + } |
| + if w := fx.keys(t.Name(), false); len(w) != 0 || !bytes.Equal(mustCurrent(t, fx, "lock.json"), lock) { |
| + t.Fatalf("a refused point wrote %v", w) |
| + } |
| + fx.m.Put(fx.bucket, fx.loc+"/head.json", head) |
| }) |
| t.Run("verify", func(t *testing.T) { |
| refused(t, lease.PointVerifyFailed, g1, t1, func(context.Context, string) (uint64, error) { |
diff --git a/internal/lease/gentake.go b/internal/lease/gentake.go| index 43004f4c7..c0d213613 100644 |
| --- a/internal/lease/gentake.go |
| +++ b/internal/lease/gentake.go |
| @@ -117,6 +117,7 @@ type Take struct { |
| prev Head |
| prevFound bool |
| etag string |
| + headRead bool // prev and prevFound are set (start) |
| mu sync.Mutex |
| state takeState |
| @@ -256,10 +257,12 @@ func (t *Take) start(ctx context.Context, vs VersionedStore, bucket string, opt |
| if err := CopyStart(ctx, vs, bucket, t.loc, plan, t.Generation); err != nil { |
| return err |
| } |
| - t.prev, t.prevFound, t.etag = head, found, "" |
| + t.mu.Lock() |
| + t.prev, t.prevFound, t.etag, t.headRead = head, found, "", true |
| if found { |
| t.etag = etag |
| } |
| + t.mu.Unlock() |
| t.StartTXID, t.Empty = plan.T, plan.Empty |
| if !plan.Empty { |
| // An empty start copied nothing: it records no predecessor, so the |
| @@ -312,6 +315,22 @@ func (t *Take) switched() bool { |
| return t.state == takeSwitched |
| } |
| +// HeadGeneration is the generation the take copied from as head.json |
| +// named it when the take read it: head.json's generation, or |
| +// replicagen.Root when there was no head.json; "" when the take read no |
| +// head.json (a first wake, or a take that failed before its plan). |
| +func (t *Take) HeadGeneration() string { |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + switch { |
| + case !t.headRead: |
| + return "" |
| + case t.prevFound: |
| + return t.prev.Generation |
| + } |
| + return replicagen.Root |
| +} |
| + |
| // Reader is the take's read-only replica client, bound to g-N: the local |
| // restore reads it (RestoreTake). |
| func (t *Take) Reader() litestream.ReplicaClient { return t.reader } |
diff --git a/internal/ops/hagenerations.go b/internal/ops/hagenerations.go| index 1c76c05ea..146df8f19 100644 |
| --- a/internal/ops/hagenerations.go |
| +++ b/internal/ops/hagenerations.go |
| @@ -35,10 +35,10 @@ 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. |
| +For a region HA host whose wake was refused (ha_generation_refused): list |
| +and verify only read data. point is a dry run unless --yes: it points the |
| +host at a complete generation and permanently 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, |
| @@ -148,7 +148,7 @@ func parseHAGenArgs(w io.Writer, sub string, args []string) (haGenArgs, error) { |
| 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) |
| + fmt.Fprintf(w, "ha-generations %s: --accept-loss-after %q is not a transaction ID\n", a.sub, *txid) |
| return a, errUsage |
| } |
| a.txid, a.txidSet = n, true |
| @@ -190,11 +190,11 @@ func (r haGenRun) run(ctx context.Context, sub string, args []string) int { |
| // 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.") |
| + fmt.Fprintln(r.Err, "ha-generations: not run: refusing to run as root. Run it as the carlos user, like carlos-hibernate-verify.service.") |
| 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.") |
| + fmt.Fprintln(r.Err, "ha-generations: CARLOS_HIBERNATE_BUCKET is not set, so this box has no data bucket configured and cannot read any host here.") |
| return 1 |
| } |
| loc := activator.HibernatePrefix(r.Cfg.Prefix, a.host) |
| @@ -221,8 +221,8 @@ func (r haGenRun) list(ctx context.Context, host, loc string) int { |
| 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)) |
| + fmt.Fprintf(w, "head.json: %s, start_txid %d, created by %s (iid %s, lifetime %s, lock generation %d) at %s\n", |
| + h.Generation, h.StartTXID, h.CreatedBy.Box, orNone(h.CreatedBy.IID), orNone(h.CreatedBy.Lifetime), 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)) |
| } |
| @@ -235,11 +235,7 @@ func (r haGenRun) list(ctx context.Context, host, loc string) int { |
| 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) |
| + fmt.Fprintf(w, " %s: newest L0 transaction %d%s\n", gi.Name, gi.NewestL0, currency(g, gi.Name)) |
| } |
| v := g.Lock |
| switch { |
| @@ -254,7 +250,7 @@ func (r haGenRun) list(ctx context.Context, host, loc string) int { |
| 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", |
| + fmt.Fprintf(w, "lock.json: released by %s at lock generation %d (%s marker): %s, txid %d, the transaction the next wake must reach (bound %d)\n", |
| m.Box, v.Lock.Generation, format, clean, m.TXID, v.TakeBound()) |
| default: |
| state := "" |
| @@ -264,7 +260,7 @@ func (r haGenRun) list(ctx context.Context, host, loc string) int { |
| state = " (live)" |
| } |
| } |
| - fmt.Fprintf(w, "lock.json: held by %s at lock generation %d, expires %s%s, bound %d\n", |
| + fmt.Fprintf(w, "lock.json: held by %s at lock generation %d, expires %s%s, the transaction the next wake must reach (bound %d)\n", |
| v.Lock.Owner, v.Lock.Generation, stamp(v.Lock.ExpiresAt), state, v.TakeBound()) |
| } |
| if len(v.Unknown) > 0 { |
| @@ -273,6 +269,29 @@ func (r haGenRun) list(ctx context.Context, host, loc string) int { |
| return 0 |
| } |
| +// orNone is s, or "none" when it is empty. |
| +func orNone(s string) string { |
| + if s == "" { |
| + return "none" |
| + } |
| + return s |
| +} |
| + |
| +// currency marks a listed generation: the one head.json names, one in its |
| +// history, or a g-* prefix that was never current (abandoned: a point |
| +// refuses it). The root layout is marked only when history keeps it. |
| +func currency(g lease.HostGenerations, name string) string { |
| + switch { |
| + case g.HeadFound && name == g.Head.Generation: |
| + return " (head.json names it)" |
| + case g.HeadFound && slices.ContainsFunc(g.Head.History, func(e lease.HeadHistory) bool { return e.Generation == name }): |
| + return " (in history)" |
| + case name == replicagen.Root: |
| + return "" |
| + } |
| + return " (never current)" |
| +} |
| + |
| // 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) { |
| @@ -309,35 +328,19 @@ func (r haGenRun) point(ctx context.Context, a haGenArgs, loc string) int { |
| 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" |
| + switch { |
| + case !a.yes: |
| + fmt.Fprintln(w, "Dry run: nothing written. Run it again with --yes to write these two documents.") |
| + fmt.Fprintf(w, "head.json, If-Match %s:\n%s\n", res.HeadETag, res.HeadBody) |
| + fmt.Fprintf(w, "lock.json, If-Match %s:\n%s\n", res.LockETag, res.LockBody) |
| + default: |
| + if res.HeadWritten { |
| + fmt.Fprintf(w, "Wrote head.json:\n%s\n", res.HeadBody) |
| } |
| - 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 |
| + if res.LockWritten { |
| + fmt.Fprintf(w, "Wrote lock.json:\n%s\n", res.LockBody) |
| } |
| - 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)) |
| @@ -346,18 +349,31 @@ func (r haGenRun) point(ctx context.Context, a haGenArgs, loc string) int { |
| return 0 |
| } |
| -// lossSentence names what a point keeps and what it gives up. |
| +// lossSentence names what a point keeps and what it gives up. A point at |
| +// head.json's own generation gives up what that generation holds past |
| +// its newest L0 (a marker's higher TXID, files above the L0); a point at a |
| +// history entry gives up everything written since that entry stopped |
| +// being current, whatever its TXIDs (they are not comparable across |
| +// generations). |
| 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" |
| + old := res.OldHead |
| + if res.Generation == old.Generation { |
| + return fmt.Sprintf("Pointing %s at %s, the generation head.json names, keeps its data up to transaction %d and permanently gives up every transaction after it (%s started at transaction %d and reached %d; %s %d).", |
| + host, res.Generation, res.NewestL0, old.Generation, old.StartTXID, res.OldReached, recorded, res.OldBound) |
| + } |
| + var ended time.Time |
| + for _, e := range old.History { |
| + if e.Generation == res.Generation { |
| + ended = e.EndedAt |
| + break |
| + } |
| } |
| - 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) |
| + return fmt.Sprintf("Pointing %s at %s keeps its data up to transaction %d and permanently gives up everything written since %s stopped being current at %s (the old head, %s, started at transaction %d and reached %d; %s %d).", |
| + host, res.Generation, res.NewestL0, res.Generation, stamp(ended), old.Generation, old.StartTXID, res.OldReached, recorded, res.OldBound) |
| } |
| // rerun is the recovery every lost write names. |
| @@ -404,6 +420,12 @@ func (r haGenRun) refusal(pr *lease.PointRefusal, a haGenArgs, loc string) strin |
| 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." |
| + case lease.PointHeadChanged: |
| + return "head.json changed while the point was verifying. Nothing was written; run it again." |
| + case lease.PointNoHead: |
| + return fmt.Sprintf("%s has no head.json, so there is no generation a point can return it to.", a.host) |
| + case lease.PointNotRetained: |
| + return fmt.Sprintf("%s is neither the generation head.json names nor one in its history, so a point cannot use it: an earlier holder may still be deleting it.", a.gen) |
| default: |
| return pr.Error() |
| } |
diff --git a/internal/ops/hagenerations_test.go b/internal/ops/hagenerations_test.go| index 112228659..91df68138 100644 |
| --- a/internal/ops/hagenerations_test.go |
| +++ b/internal/ops/hagenerations_test.go |
| @@ -40,8 +40,9 @@ const ( |
| 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). |
| +// in its history, a clean generations marker recording a TXID above g-7's |
| +// newest L0 (every take refuses: clean_marker_above_l0), and an abandoned |
| +// g-9. |
| type hgFixture struct { |
| m *leasetest.VersionedBucket |
| g5, g7 string |
| @@ -100,6 +101,9 @@ func newHGFixture(t *testing.T) *hgFixture { |
| t.Fatal(err) |
| } |
| fx.m.Put(rsBucket, hgLoc+"/lock.json", body) |
| + // An abandoned prefix head.json never named (a lost switch's), whose |
| + // only L0 file is damaged. |
| + fx.m.Put(rsBucket, replicagen.Prefix(hgLoc, replicagen.Name(9))+"0000/0000000000000001-0000000000000003.ltx", []byte("not an ltx file")) |
| return fx |
| } |
| @@ -186,13 +190,14 @@ 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 |
| +head.json: %[1]s, start_txid %[3]d, created by box-b (iid i-b, lifetime L2, 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) |
| + %[2]s: newest L0 transaction %[3]d (in history) |
| + %[1]s: newest L0 transaction %[4]d (head.json names it) |
| + %[6]s: newest L0 transaction 3 (never current) |
| +lock.json: released by box-b at lock generation 7 (generations marker): clean, txid %[5]d, the transaction the next wake must reach (bound %[5]d) |
| +`, fx.g7, fx.g5, fx.t5, fx.t7, fx.t7+50, replicagen.Name(9)) |
| if code != 0 || out != want { |
| t.Fatalf("list exit %d:\n%s\nwant:\n%s", code, out, want) |
| } |
| @@ -228,14 +233,14 @@ func TestHAGenerationsVerify(t *testing.T) { |
| 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}, |
| + CreatedBy: lease.HeadCreator{LockGeneration: 7, 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 |
| + m.TXID, m.MinTXID = fx.t5, fx.t5 |
| if lock, err = hafresh.MarkerBody(7, m); err != nil { |
| t.Fatal(err) |
| } |
| @@ -254,13 +259,13 @@ func TestHAGenerationsPointDryRun(t *testing.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). |
| + want := fmt.Sprintf(`Pointing shop.example.com at %[1]s keeps its data up to transaction %[2]d and permanently gives up everything written since %[1]s stopped being current at 2026-11-18T10:00:00Z (the old head, %[7]s, started at transaction %[2]d and reached %[3]d; the marker recorded %[4]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) |
| +head.json, If-Match %[5]s: |
| +%[6]s |
| +lock.json, If-Match %[8]s: |
| +%[9]s |
| +`, fx.g5, fx.t5, fx.t7, fx.t7+50, etagOf(headBefore), head, fx.g7, etagOf(lockBefore), lock) |
| if code != 0 || out != want { |
| t.Fatalf("dry run exit %d:\n%s\nwant:\n%s", code, out, want) |
| } |
| @@ -276,12 +281,12 @@ 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). |
| + want := fmt.Sprintf(`Pointing shop.example.com at %[1]s keeps its data up to transaction %[2]d and permanently gives up everything written since %[1]s stopped being current at 2026-11-18T10:00:00Z (the old head, %[7]s, started at transaction %[2]d and reached %[3]d; the marker recorded %[4]d). |
| Wrote head.json: |
| -%s |
| +%[5]s |
| Wrote lock.json: |
| -%s |
| -`, fx.g5, fx.t5, fx.t7, fx.t7+50, head, lock) |
| +%[6]s |
| +`, fx.g5, fx.t5, fx.t7, fx.t7+50, head, lock, fx.g7) |
| if code != 0 || out != want { |
| t.Fatalf("point exit %d:\n%s\nwant:\n%s", code, out, want) |
| } |
| @@ -295,14 +300,16 @@ Wrote lock.json: |
| t.Fatalf("lock.json %s, want %s", got, lock) |
| } |
| - // Again: head.json names g-5 and the bound is g-5's newest L0. |
| + // Again, at the generation head.json now names: both documents are |
| + // written again (the head rewrite is the fence), and the sentence says |
| + // what a point at head.json's own generation gives up. |
| 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 want := fmt.Sprintf("Pointing shop.example.com at %[1]s, the generation head.json names, keeps its data up to transaction %[2]d and permanently gives up every transaction after it (%[1]s started at transaction 0 and reached %[2]d; the marker recorded %[2]d).\n", fx.g5, fx.t5); code != 0 || !strings.HasPrefix(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) |
| + if _, w := fx.counts(); strings.Join(w, ",") != "PUT "+hgLoc+"/head.json,PUT "+hgLoc+"/lock.json" { |
| + t.Fatalf("second point writes %v, want head.json then lock.json", w) |
| } |
| } |
| @@ -341,13 +348,22 @@ func TestHAGenerationsPointRefusals(t *testing.T) { |
| 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), |
| + refused(t, fx, fmt.Sprintf("ha-generations point: refused: %s is neither the generation head.json names nor one in its history, so a point cannot use it: an earlier holder may still be deleting it.\n", g9), |
| "--gen", g9, "--accept-loss-after", "3", "--yes") |
| }) |
| + t.Run("retired", func(t *testing.T) { |
| + fx := newHGFixture(t) |
| + g3 := replicagen.Name(3) |
| + fx.head.History = append(fx.head.History, lease.HeadHistory{Generation: g3, CreatedAt: time.Date(2026, 11, 16, 9, 0, 0, 0, time.UTC), EndedAt: time.Date(2026, 11, 17, 9, 0, 0, 0, time.UTC)}) |
| + fx.put(t, "head.json", fx.head) |
| + refused(t, fx, fmt.Sprintf("ha-generations point: refused: %s does not exist under s3://data/hib/shop.example.com.\n", g3), |
| + "--gen", g3, "--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.head.History = append(fx.head.History, lease.HeadHistory{Generation: g9, CreatedAt: time.Date(2026, 11, 16, 9, 0, 0, 0, time.UTC), EndedAt: time.Date(2026, 11, 17, 9, 0, 0, 0, time.UTC)}) |
| + fx.put(t, "head.json", fx.head) |
| 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) { |
| @@ -410,7 +426,7 @@ 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 { |
| + if want := "ha-generations: not run: refusing to run as root. Run it as the carlos user, like carlos-hibernate-verify.service.\n"; code != 1 || out != want { |
| t.Fatalf("exit %d: %q, want %q", code, out, want) |
| } |
| if n, _ := fx.counts(); n != 0 { |
diff --git a/internal/ops/ops.go b/internal/ops/ops.go| index 2e68cdf94..43df8fb61 100644 |
| --- a/internal/ops/ops.go |
| +++ b/internal/ops/ops.go |
| @@ -92,12 +92,12 @@ func usage() { |
| 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 |
| + recover 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. |
| + host at one. point permanently 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. |