carlos / platform Public

console: keep proven evidence of a retired record (#658)

A normal retirement now stores the body it captured (obs.Raw at
RecordETag; nil when the delete migrated a legacy record in the same
call) and is marked restorable only when the tombstone over exactly that
body is proven: N1's own CAS landed, or an observed tombstone at the key
has the row's incarnation and record_seq one past the body's, seen
before N2 (pred branch) or before N3 (retired branch). The mark is
durable before N2/N3; a failed mark is pending so the tombstone stays
for recovery. ConvertRetirementKind clears restorable and record_body in
the same UPDATE that makes the row a cleanup.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5e78782ec897a6f7a834882f21698d4f5545d9ca parent 25eab93
3 files changed, +547 −5
  • internal/console/lifetimes_retire.go +60 −3
  • internal/console/lifetimes_store.go +4 −2
  • internal/console/restore_retire_test.go +483 −0
diff --git a/internal/console/lifetimes_retire.go b/internal/console/lifetimes_retire.go
index 8d9dcf653..b0746cd16 100644
--- a/internal/console/lifetimes_retire.go
+++ b/internal/console/lifetimes_retire.go
@@ -1,6 +1,7 @@
package console
import (
+ "bytes"
"context"
"errors"
"fmt"
@@ -139,6 +140,10 @@ func (s *Server) retireRecordWithLifetimeLocked(ctx context.Context, acct, app,
return s.retireStaleLocked(ctx, acct, app, host, obs, liveOwned)
}
rec, etag, slotETag := obs.Rec, obs.ETag, obs.SlotETag
+ // The candidate for restore evidence (#658): the exact bytes at
+ // RecordETag. A record migrated in this call keeps none (its migrated
+ // bytes are not to hand, and it has no allocation at its incarnation).
+ body := obs.Raw
if rec.Incarnation == 0 && slot == nil { // (e): legacy, bound to this read
mrec, _, metag, state, err := s.migrateHostLifetimeLocked(ctx, acct, app, host, obs.ETag)
switch {
@@ -154,7 +159,7 @@ func (s *Server) retireRecordWithLifetimeLocked(ctx context.Context, acct, app,
if slot, slotETag, err = provision.ReadHostIncarnation(ctx, s.cfg.Releases, host); err != nil {
return fmt.Errorf("console: lifetimes: retire %s: read the migrated slot: %w", key, err)
}
- rec, etag = mrec, metag
+ rec, etag, body = mrec, metag, nil
liveOwned = slotOwnedBy(slot, acct, app) && slot.State == provision.SlotLive
}
// (f)
@@ -169,7 +174,7 @@ func (s *Server) retireRecordWithLifetimeLocked(ctx context.Context, acct, app,
return err
}
r := Retirement{OpID: opID, Kind: retireNormal, Account: acct, App: app, Host: host, Incarnation: rec.Incarnation,
- RecordETag: etag, SlotETag: slotETag, SlotIntent: slot.Intent, State: lifetimePending}
+ RecordETag: etag, SlotETag: slotETag, SlotIntent: slot.Intent, State: lifetimePending, RecordBody: body}
if err := s.store.BeginRetirement(r); err != nil {
return fmt.Errorf("console: lifetimes: begin the retirement of %s: %w", host, err)
}
@@ -227,6 +232,13 @@ func (s *Server) retireStaleLocked(ctx context.Context, acct, app, host string,
// captured bytes → N1; another ETag at N → fence, refused.
//
// A failed write or re-read is pending, never a terminal branch.
+//
+// A normal row with a captured body is marked restorable (#658, spec §5)
+// once its tombstone is proven, and the mark is durable before N2 or N3:
+// N1's own write landed, or a tombstone observed at the key (the pred
+// branch before N2, the retired branch before N3) is the one written over
+// exactly that body (provenTombstone). A failed mark is pending, so the
+// tombstone stays for the next pass to prove.
func (s *Server) retirementStepsLocked(ctx context.Context, r Retirement) error {
// The canary-retire guard's evidence, first: N1 turns the record into
// its tombstone, which every reader takes as gone, and recovery enters
@@ -250,6 +262,17 @@ func (s *Server) retirementStepsLocked(ctx context.Context, r Retirement) error
return errLifetimePending
}
ctx = provision.WithLifetimes(ctx, s.judge)
+ marked := false
+ mark := func() error {
+ if marked || r.Kind != retireNormal || r.RecordBody == nil {
+ return nil
+ }
+ if err := s.store.MarkRetirementRestorable(r.OpID); err != nil {
+ return pending("record the restore evidence", err)
+ }
+ marked = true
+ return nil
+ }
for round := 0; round < retireRounds; round++ {
obs, err := s.classifyLocked(ctx, r.Account, r.App, r.Host)
if err != nil {
@@ -265,6 +288,11 @@ func (s *Server) retirementStepsLocked(ctx context.Context, r Retirement) error
return s.settleRetirement(ctx, r, lifetimeVoid, nil)
case retired:
if obs.Present {
+ if provenTombstone(r, obs) {
+ if err := mark(); err != nil {
+ return err
+ }
+ }
if err := s.deleteUnderRetiredSlot(ctx, r, true); err != nil {
return pending("remove the body under the retired slot", err)
}
@@ -298,8 +326,13 @@ func (s *Server) retirementStepsLocked(ctx context.Context, r Retirement) error
if err := s.store.ConvertRetirementKind(r.OpID, retireCleanup, obs.ETag); err != nil {
return pending("convert to a cleanup", err)
}
- r.Kind, r.RecordETag = retireCleanup, obs.ETag
+ r.Kind, r.RecordETag, r.RecordBody = retireCleanup, obs.ETag, nil
case rec.Retired && rec.Incarnation == r.Incarnation:
+ if provenTombstone(r, obs) {
+ if err := mark(); err != nil {
+ return err
+ }
+ }
if done, err := s.retireSlotStep(ctx, r, logf); done { // N2, then N3 from the retired branch
return err
}
@@ -324,6 +357,12 @@ func (s *Server) retirementStepsLocked(ctx context.Context, r Retirement) error
if err != nil && !errors.Is(err, release.ErrCASConflict) {
return pending("write the tombstone", err)
}
+ if err == nil && bytes.Equal(obs.Raw, r.RecordBody) {
+ // N1's own CAS on the captured bytes landed: proven.
+ if err := mark(); err != nil {
+ return err
+ }
+ }
// Landed or lost: on from what is there now.
default:
// The same lifetime under another ETag: changed in its lifetime.
@@ -343,6 +382,24 @@ func (s *Server) retirementStepsLocked(ctx context.Context, r Retirement) error
return errLifetimePending
}
+// provenTombstone reports whether obs is the tombstone N1 writes over r's
+// captured body (#658, spec §5): a normal row with a body, a retired record
+// at the key with the row's incarnation, and a record_seq exactly one past
+// the body's (TombstoneBody keeps record_seq and WriteRecord advances it by
+// one; a body with no counter reads as 0). Anything unreadable is no proof.
+func provenTombstone(r Retirement, obs provision.Observation) bool {
+ if r.Kind != retireNormal || r.RecordBody == nil || !obs.Present || obs.Rec == nil ||
+ !obs.Rec.Retired || obs.Rec.Incarnation != r.Incarnation {
+ return false
+ }
+ _, base, err := provision.RecordSequence(r.RecordBody)
+ if err != nil || base == ^uint64(0) {
+ return false
+ }
+ _, seq, err := provision.RecordSequence(obs.Raw)
+ return err == nil && seq == base+1
+}
+
// retireSlotStep is N2, O1 and C1's slot write. done reports that the caller
// returns err; otherwise the slot is retired and the dispatcher goes on.
func (s *Server) retireSlotStep(ctx context.Context, r Retirement, logf func(string, ...any)) (bool, error) {
diff --git a/internal/console/lifetimes_store.go b/internal/console/lifetimes_store.go
index 6581f3061..6481c52ae 100644
--- a/internal/console/lifetimes_store.go
+++ b/internal/console/lifetimes_store.go
@@ -277,12 +277,14 @@ func (s *Store) BeginCancellingRetirement(r Retirement, voidAllocation string) e
// into a cleanup one, carrying the corrupt body's ETag (self-serve moves plan
// 1, Task 4): the body that was to be tombstoned turned out corrupt, so the
// slot retires first and the body is removed on that ETag. Only normal ->
-// cleanup is allowed, and only while the row is pending.
+// cleanup is allowed, and only while the row is pending. The same UPDATE
+// drops the restore evidence (restorable and record_body, #658): a cleanup
+// row never keeps any.
func (s *Store) ConvertRetirementKind(opID, kind, recordETag string) error {
if kind != retireCleanup {
return fmt.Errorf("console: a retirement converts only to %s, not %q", retireCleanup, kind)
}
- res, err := s.db.Exec(`UPDATE record_retirements SET kind = ?, record_etag = ? WHERE op_id = ? AND state = ? AND kind = ?`,
+ res, err := s.db.Exec(`UPDATE record_retirements SET kind = ?, record_etag = ?, restorable = 0, record_body = NULL WHERE op_id = ? AND state = ? AND kind = ?`,
kind, recordETag, opID, lifetimePending, retireNormal)
return oneRow(res, err, "pending normal record_retirements", opID)
}
diff --git a/internal/console/restore_retire_test.go b/internal/console/restore_retire_test.go
new file mode 100644
index 000000000..c18202cbe
--- /dev/null
+++ b/internal/console/restore_retire_test.go
@@ -0,0 +1,483 @@
+package console
+
+// Proven retirement evidence (instance restore #658, plan Task 4; spec §5):
+// a normal retirement keeps the body it captured, and is marked restorable
+// only when the tombstone over exactly that body is proven, before N2 or N3
+// can run. Every other outcome leaves the mark unset, or leaves a row a
+// restore refuses (not normal, or not committed). Driven through the real
+// doors, dispatcher, recovery and SQLite over the ltStore bucket.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "sync/atomic"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// evidenceOf is host's newest retirement row with its restore columns.
+func evidenceOf(t *testing.T, st *Store, host string) *RetirementEvidence {
+ t.Helper()
+ e, err := st.NewestRetirement(host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if e == nil {
+ t.Fatalf("no retirement of %s", host)
+ }
+ return e
+}
+
+// restoreGrade is what a restore requires of the newest retirement: normal,
+// committed and restorable together (controller's ruling; Task 5).
+func restoreGrade(e *RetirementEvidence) bool {
+ return e.Kind == retireNormal && e.State == lifetimeCommitted && e.Restorable
+}
+
+// requireNotRestorable fails unless host's newest row is settled to state,
+// carries no restorable flag, and so fails the restore grade.
+func requireNotRestorable(t *testing.T, st *Store, host, kind, state string) *RetirementEvidence {
+ t.Helper()
+ e := evidenceOf(t, st, host)
+ if e.Kind != kind || e.State != state || e.Restorable || restoreGrade(e) {
+ t.Fatalf("retirement = %s %s restorable=%v, want %s %s not restorable", e.Kind, e.State, e.Restorable, kind, state)
+ }
+ return e
+}
+
+// lostAnswer is a bucket whose next Put on key lands and then reports a
+// failure, as a write whose response was lost does.
+type lostAnswer struct {
+ *ltStore
+ key string
+ armed atomic.Bool
+}
+
+func (s *lostAnswer) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if key == s.key && s.armed.CompareAndSwap(true, false) {
+ if _, err := s.ltStore.Put(ctx, key, body, ifMatch); err != nil {
+ return "", err
+ }
+ return "", errBucketDown
+ }
+ return s.ltStore.Put(ctx, key, body, ifMatch)
+}
+
+// loseN1Answer makes the next tombstone write of ltOne land unanswered.
+func (l ltOn) loseN1Answer(t *testing.T) *lostAnswer {
+ t.Helper()
+ b := &lostAnswer{ltStore: l.bucket, key: recKey(ltApp, ltOne)}
+ b.armed.Store(true)
+ l.fx.srv.cfg.Releases = b
+ t.Cleanup(func() { l.fx.srv.cfg.Releases = l.bucket })
+ return b
+}
+
+// markedBefore checks, at the first call of op on key, that host's newest
+// retirement is already marked restorable; the returned func reports
+// whether that call was seen.
+func markedBefore(t *testing.T, st *Store, op, key string) (func(string, string) error, func() bool) {
+ t.Helper()
+ var seen atomic.Bool
+ return onNth(op, key, 1, func() {
+ seen.Store(true)
+ if e, err := st.NewestRetirement(ltOne); err != nil || e == nil || !e.Restorable {
+ t.Errorf("at the first %s of %s the retirement is %+v (%v), want it already restorable", op, key, e, err)
+ }
+ }), func() bool {
+ return seen.Load()
+ }
+}
+
+// requireTombstone fails unless the body under ltOne is a tombstone at n.
+func requireTombstone(t *testing.T, st release.Store, n uint64) {
+ t.Helper()
+ raw, _ := rawOf(t, st, ltApp, ltOne)
+ if raw == nil {
+ t.Fatal("no tombstone under the key")
+ }
+ if rec := decodeRec(t, raw); !rec.Retired || rec.Incarnation != n {
+ t.Fatalf("record = %s, want the tombstone at %d", raw, n)
+ }
+}
+
+func TestDeleteLeavesRestorableEvidence(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ before, _ := rawOf(t, l.fx.rel, ltApp, ltOne)
+ hook, seen := markedBefore(t, l.fx.st, "put", provision.HostIncarnationKey(ltOne)) // N2
+ l.bucket.setHook(hook)
+ if code, body := l.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent {
+ t.Fatalf("delete = %d %s", code, body)
+ }
+ if !seen() {
+ t.Fatal("N2 never ran")
+ }
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ e := evidenceOf(t, l.fx.st, ltOne)
+ if !restoreGrade(e) {
+ t.Fatalf("retirement = %s %s restorable=%v, want normal committed restorable", e.Kind, e.State, e.Restorable)
+ }
+ if !bytes.Equal(e.RecordBody, before) {
+ t.Fatalf("record body = %s, want the record before the delete %s", e.RecordBody, before)
+ }
+}
+
+func TestLostN1ResponseProvenByRecordSeq(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ before, _ := rawOf(t, l.fx.rel, ltApp, ltOne)
+ b := l.loseN1Answer(t)
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); !errors.Is(err, errLifetimePending) {
+ t.Fatalf("retire = %v, want pending", err)
+ }
+ if b.armed.Load() {
+ t.Fatal("the tombstone write never ran")
+ }
+ l.fx.srv.cfg.Releases = l.bucket
+ requireTombstone(t, l.fx.rel, 1)
+ if e := evidenceOf(t, l.fx.st, ltOne); e.State != lifetimePending || e.Restorable {
+ t.Fatalf("after the lost answer = %s restorable=%v, want pending, not yet restorable", e.State, e.Restorable)
+ }
+ r := lastRetirement(t, l.fx.st, ltOne)
+ hook, seen := markedBefore(t, l.fx.st, "put", provision.HostIncarnationKey(ltOne)) // N2
+ l.bucket.setHook(hook)
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ if !seen() {
+ t.Fatal("recovery never ran N2")
+ }
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ e := evidenceOf(t, l.fx.st, ltOne)
+ if !restoreGrade(e) || !bytes.Equal(e.RecordBody, before) {
+ t.Fatalf("retirement = %s %s restorable=%v body=%s, want normal committed restorable with the captured body", e.Kind, e.State, e.Restorable, e.RecordBody)
+ }
+}
+
+func TestN1MarkHoldsWhenTheTombstoneIsLost(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ // N1 lands, and an older delayed deletion takes the tombstone before
+ // the next observation: N1's own answer was the proof.
+ var once atomic.Bool
+ l.bucket.setAfter(func(op, key string, err error) {
+ if op == "put" && key == recKey(ltApp, ltOne) && err == nil && once.CompareAndSwap(false, true) {
+ if err := l.fx.rel.Delete(context.Background(), recKey(ltApp, ltOne)); err != nil {
+ t.Error(err)
+ }
+ }
+ })
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); err != nil {
+ t.Fatalf("retire = %v", err)
+ }
+ if !once.Load() {
+ t.Fatal("N1 never landed")
+ }
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ if e := evidenceOf(t, l.fx.st, ltOne); !restoreGrade(e) {
+ t.Fatalf("retirement = %s %s restorable=%v, want restorable from N1's own write", e.Kind, e.State, e.Restorable)
+ }
+}
+
+func TestEvidenceWriteFailureStaysPending(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ drop := sqlFailRetirement(t, l.fx.st, "lt_fail_mark", "NEW.restorable = 1")
+ slotPuts := len(l.bucket.opsOf(provision.HostIncarnationKey(ltOne)))
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); !errors.Is(err, errLifetimePending) {
+ t.Fatalf("retire = %v, want pending", err)
+ }
+ drop()
+ r := lastRetirement(t, l.fx.st, ltOne)
+ if r.State != lifetimePending {
+ t.Fatalf("retirement = %+v, want pending", r)
+ }
+ requireTombstone(t, l.fx.rel, 1)
+ for _, op := range l.bucket.opsOf(provision.HostIncarnationKey(ltOne))[slotPuts:] {
+ if op == "put" {
+ t.Fatal("N2 ran after the mark failed")
+ }
+ }
+ if slot, _ := slotOf(t, l.fx.rel, ltOne); slot == nil || slot.State != provision.SlotLive {
+ t.Fatalf("slot = %+v, want it still live", slot)
+ }
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ if e := evidenceOf(t, l.fx.st, ltOne); !restoreGrade(e) {
+ t.Fatalf("retirement = %s %s restorable=%v, want restorable after recovery", e.Kind, e.State, e.Restorable)
+ }
+}
+
+func TestAbsentRecordNotRestorable(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ r := l.pendingRetire(t, "begin")
+ if err := l.fx.rel.Delete(context.Background(), recKey(ltApp, ltOne)); err != nil {
+ t.Fatal(err)
+ }
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeCommitted)
+}
+
+func TestCleanupConversionNotRestorable(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ l.bucket.setHook(onNth("put", recKey(ltApp, ltOne), 1, func() {
+ _, etag := rawOf(t, l.fx.rel, ltApp, ltOne)
+ if _, err := l.fx.rel.Put(context.Background(), recKey(ltApp, ltOne), []byte(`{"schema":1,"host":`), etag); err != nil {
+ t.Error(err)
+ }
+ }))
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); err != nil {
+ t.Fatalf("retire = %v", err)
+ }
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ if e := requireNotRestorable(t, l.fx.st, ltOne, retireCleanup, lifetimeCommitted); e.RecordBody != nil {
+ t.Fatalf("record body = %s, want none on a cleanup", e.RecordBody)
+ }
+}
+
+func TestConversionAfterMarkClearsEvidence(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ r := l.pendingRetire(t, "n1") // N1 landed, then N2 failed
+ if e := evidenceOf(t, l.fx.st, ltOne); !e.Restorable || e.RecordBody == nil {
+ t.Fatalf("after N1 = restorable %v body %s, want marked with a body", e.Restorable, e.RecordBody)
+ }
+ _, etag := rawOf(t, l.fx.rel, ltApp, ltOne)
+ if _, err := l.fx.rel.Put(context.Background(), recKey(ltApp, ltOne), []byte(`{"schema":1,"host":`), etag); err != nil {
+ t.Fatal(err)
+ }
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ if e := requireNotRestorable(t, l.fx.st, ltOne, retireCleanup, lifetimeCommitted); e.RecordBody != nil {
+ t.Fatalf("record body = %s, want none after the conversion", e.RecordBody)
+ }
+}
+
+func TestForeignTombstoneNotRestorable(t *testing.T) {
+ ctx := context.Background()
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ r := l.pendingRetire(t, "begin")
+ // Another writer moves the record on, then tombstones the moved body:
+ // a tombstone at N whose record_seq is the candidate's plus two.
+ bump(t, l.fx.rel, ltApp, ltOne)
+ raw, etag := rawOf(t, l.fx.rel, ltApp, ltOne)
+ tomb, err := provision.TombstoneBody(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := provision.WriteRecord(provision.WithRecordSequence(ctx), l.fx.rel, recKey(ltApp, ltOne), raw, tomb, etag); err != nil {
+ t.Fatal(err)
+ }
+ requireTombstone(t, l.fx.rel, 1)
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeCommitted)
+}
+
+func TestMigratedDeleteNotRestorable(t *testing.T) {
+ l := newLtOn(t)
+ legacyBody(t, l.fx.rel, ltApp, ltOne, "stable")
+ before := len(l.bucket.opsOf(recKey(ltApp, ltOne)))
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); err != nil {
+ t.Fatalf("retire = %v", err)
+ }
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ puts := 0
+ for _, op := range l.bucket.opsOf(recKey(ltApp, ltOne))[before:] {
+ if op == "put" {
+ puts++
+ }
+ }
+ if puts < 2 { // the migration's writes, then N1
+ t.Fatalf("record writes = %v, want the migration and then N1", l.bucket.opsOf(recKey(ltApp, ltOne))[before:])
+ }
+ if e := requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeCommitted); e.RecordBody != nil {
+ t.Fatalf("record body = %s, want none after a same-call migration", e.RecordBody)
+ }
+}
+
+func TestOldPendingRowNotRestorable(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ r := l.pendingRetire(t, "begin")
+ // A row written before the columns existed: no body.
+ if _, err := l.fx.st.db.Exec(`UPDATE record_retirements SET record_body = NULL WHERE op_id = ?`, r.OpID); err != nil {
+ t.Fatal(err)
+ }
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeCommitted)
+}
+
+// ---- the other outcomes of Task 1's inventory (notes §1.1) -----------------
+
+func TestRetiredSlotBranchProvesTheTombstone(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ l.loseN1Answer(t)
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); !errors.Is(err, errLifetimePending) {
+ t.Fatalf("retire = %v, want pending", err)
+ }
+ l.fx.srv.cfg.Releases = l.bucket
+ r := lastRetirement(t, l.fx.st, ltOne)
+ // N2 lands too (a late slot write), so recovery first sees the retired
+ // slot with the unproven tombstone under it.
+ writeSlot(t, l.fx.rel, ltOne, provision.HostIncarnation{Incarnation: 1, State: provision.SlotRetired, Account: "bab", App: ltApp, Intent: "retire " + r.OpID})
+ requireTombstone(t, l.fx.rel, 1)
+ hook, seen := markedBefore(t, l.fx.st, "delete-if-match", recKey(ltApp, ltOne)) // N3
+ l.bucket.setHook(hook)
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ if !seen() {
+ t.Fatal("recovery never ran N3")
+ }
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ if e := evidenceOf(t, l.fx.st, ltOne); !restoreGrade(e) {
+ t.Fatalf("retirement = %s %s restorable=%v, want restorable", e.Kind, e.State, e.Restorable)
+ }
+}
+
+func TestOtherIncarnationTombstoneNotRestorable(t *testing.T) {
+ ctx := context.Background()
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ r := l.pendingRetire(t, "begin")
+ // A tombstone with the candidate's record_seq plus one, but of another
+ // incarnation, under the slot retired at N.
+ raw, etag := rawOf(t, l.fx.rel, ltApp, ltOne)
+ rec := decodeRec(t, raw)
+ rec.Incarnation = 5
+ other, _ := json.Marshal(rec)
+ tomb, err := provision.TombstoneBody(other)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := provision.WriteRecord(provision.WithRecordSequence(ctx), l.fx.rel, recKey(ltApp, ltOne), raw, tomb, etag); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := rawOf(t, l.fx.rel, ltApp, ltOne); !decodeRec(t, got).Retired || decodeRec(t, got).Incarnation != 5 || decodeRec(t, got).RecordSeq != decodeRec(t, raw).RecordSeq+1 {
+ t.Fatalf("record = %s, want a tombstone at 5 one past the candidate", got)
+ }
+ writeSlot(t, l.fx.rel, ltOne, provision.HostIncarnation{Incarnation: 1, State: provision.SlotRetired, Account: "bab", App: ltApp, Intent: "retire " + r.OpID})
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeCommitted)
+}
+
+func TestRetiredSlotMarkFailureStaysPending(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ l.loseN1Answer(t)
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); !errors.Is(err, errLifetimePending) {
+ t.Fatalf("retire = %v, want pending", err)
+ }
+ l.fx.srv.cfg.Releases = l.bucket
+ r := lastRetirement(t, l.fx.st, ltOne)
+ writeSlot(t, l.fx.rel, ltOne, provision.HostIncarnation{Incarnation: 1, State: provision.SlotRetired, Account: "bab", App: ltApp, Intent: "retire " + r.OpID})
+ drop := sqlFailRetirement(t, l.fx.st, "lt_fail_mark", "NEW.restorable = 1")
+ l.recoveredTo(t, r.OpID, lifetimePending)
+ drop()
+ requireTombstone(t, l.fx.rel, 1) // N3 did not run
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ if e := evidenceOf(t, l.fx.st, ltOne); !restoreGrade(e) {
+ t.Fatalf("retirement = %s %s restorable=%v, want restorable", e.Kind, e.State, e.Restorable)
+ }
+}
+
+func TestSlotAlreadyRetiredNotRestorable(t *testing.T) {
+ // The slot is retired while a live body is still under the key: no
+ // tombstone to prove.
+ for _, bumped := range []bool{false, true} {
+ name := map[bool]string{false: "the captured body", true: "a later body one past it"}[bumped]
+ t.Run(name, func(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ r := l.pendingRetire(t, "begin")
+ if bumped {
+ bump(t, l.fx.rel, ltApp, ltOne)
+ }
+ writeSlot(t, l.fx.rel, ltOne, provision.HostIncarnation{Incarnation: 1, State: provision.SlotRetired, Account: "bab", App: ltApp, Intent: "retire " + r.OpID})
+ l.recoveredTo(t, r.OpID, lifetimeCommitted)
+ requireRetired(t, l.fx.rel, ltApp, ltOne, 1)
+ requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeCommitted)
+ })
+ }
+}
+
+func TestAnotherIncarnationNotRestorable(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ r := l.pendingRetire(t, "begin")
+ raw, etag := rawOf(t, l.fx.rel, ltApp, ltOne)
+ rec := decodeRec(t, raw)
+ rec.Incarnation = 5
+ body, _ := json.Marshal(rec)
+ if _, _, err := provision.WriteRecord(context.Background(), l.fx.rel, recKey(ltApp, ltOne), raw, body, etag); err != nil {
+ t.Fatal(err)
+ }
+ l.recoveredTo(t, r.OpID, lifetimeVoid)
+ requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeVoid)
+}
+
+func TestChangedBodyRefusedNotRestorable(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ l.bucket.setHook(onNth("put", recKey(ltApp, ltOne), 1, func() { bump(t, l.fx.rel, ltApp, ltOne) }))
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); !errors.Is(err, errRetireRefused) {
+ t.Fatalf("retire = %v, want errRetireRefused", err)
+ }
+ requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeRefused)
+}
+
+func TestSuccessorSlotNotRestorable(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ r := l.pendingRetire(t, "begin")
+ writeSlot(t, l.fx.rel, ltOne, provision.HostIncarnation{Incarnation: 2, State: provision.SlotLive, Account: "bab", App: "web", Intent: "create web"})
+ l.recoveredTo(t, r.OpID, lifetimeVoid)
+ requireNotRestorable(t, l.fx.st, ltOne, retireNormal, lifetimeVoid)
+}
+
+func TestSupersededAfterN1FailsTheRestoreGrade(t *testing.T) {
+ l := newLtOn(t)
+ l.mustCreate(t, ltOne)
+ // N1 lands and is marked; a successor takes the slot before N2.
+ l.bucket.setHook(onNth("put", provision.HostIncarnationKey(ltOne), 1, func() {
+ writeSlot(t, l.fx.rel, ltOne, provision.HostIncarnation{Incarnation: 2, State: provision.SlotLive, Account: "bab", App: "web", Intent: "create web"})
+ }))
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); err != nil {
+ t.Fatalf("retire = %v, want nil (void)", err)
+ }
+ e := evidenceOf(t, l.fx.st, ltOne)
+ if e.State != lifetimeVoid || restoreGrade(e) {
+ t.Fatalf("retirement = %s %s restorable=%v, want void and failing the restore grade", e.Kind, e.State, e.Restorable)
+ }
+}
+
+func TestOrphanAndCleanupNotRestorable(t *testing.T) {
+ t.Run("orphan", func(t *testing.T) {
+ l := newLtOn(t)
+ writeSlot(t, l.fx.rel, ltOne, provision.HostIncarnation{Incarnation: 1, State: provision.SlotLive, Account: "bab", App: ltApp, Intent: "create lost"})
+ if err := retireOn(t, l.fx.srv, ltOne, retireAny); err != nil {
+ t.Fatalf("retire = %v", err)
+ }
+ requireNotRestorable(t, l.fx.st, ltOne, retireOrphan, lifetimeCommitted)
+ })
+ t.Run("cleanup of a stale body", func(t *testing.T) {
+ l := newLtOn(t)
+ writeSlot(t, l.fx.rel, ltOne, provision.HostIncarnation{Incarnation: 1, State: provision.SlotLive, Account: "bab", App: ltApp, Intent: "create late"})
+ etag := legacyBody(t, l.fx.rel, ltApp, ltOne, "stable")
+ if err := retireOn(t, l.fx.srv, ltOne, retireExpectETag(etag)); err != nil {
+ t.Fatalf("retire = %v", err)
+ }
+ requireNotRestorable(t, l.fx.st, ltOne, retireCleanup, lifetimeCommitted)
+ })
+}