carlos / platform Public

console: restore columns on allocations and retirements (#658)

Allocations gain restore_origin and restore_of; retirements gain
record_body and restorable. Adds HostLineage, NewestRetirement and
MarkRetirementRestorable. RetirementEvidence embeds Retirement, so
RecordBody is the embedded field.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 39266bed8799ea0f9581fa502c973fa28f019c01 parent b361f4e
3 files changed, +226 −12
  • internal/console/lifetimes_store.go +65 −12
  • internal/console/lifetimes_store_test.go +154 −0
  • internal/console/store.go +7 −0
diff --git a/internal/console/lifetimes_store.go b/internal/console/lifetimes_store.go
index dcf3c690f..4af775188 100644
--- a/internal/console/lifetimes_store.go
+++ b/internal/console/lifetimes_store.go
@@ -58,6 +58,10 @@ type Allocation struct {
// removes it at step 5; recovery removes it, observed afresh, before
// it commits the allocation.
PrevOwnerKey string
+ // RestoreOrigin marks an allocation made by an instance restore;
+ // RestoreOf is the op id of the retirement it restores, "" otherwise.
+ RestoreOrigin bool
+ RestoreOf string
}
// Retirement is one pending retirement of a record or a slot. Cancels names
@@ -67,6 +71,16 @@ type Retirement struct {
Incarnation uint64
RecordETag, SlotETag string
SlotIntent, Cancels, State string
+ // RecordBody is the record's body as retired, kept for a restore; nil
+ // for none.
+ RecordBody []byte
+}
+
+// RetirementEvidence is a retirement row with its restorable flag. The
+// record body is the embedded Retirement's RecordBody.
+type RetirementEvidence struct {
+ Retirement
+ Restorable bool
}
// Migration is one pending migration of a record into the lifetime shape.
@@ -101,9 +115,9 @@ func (s *Store) BeginAllocation(a Allocation) error {
return err
}
_, err = s.db.Exec(`INSERT INTO host_allocations
- (op_id, account, app, host, incarnation, state, body, predecessor_etag, stale_etag, app_lifetime, prev_owner_key, created_at)
-VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- a.OpID, a.Account, a.App, a.Host, inc, lifetimePending, a.Body, a.PredecessorETag, a.StaleETag, a.AppLifetime, a.PrevOwnerKey, time.Now().Unix())
+ (op_id, account, app, host, incarnation, state, body, predecessor_etag, stale_etag, app_lifetime, prev_owner_key, restore_origin, restore_of, created_at)
+VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ a.OpID, a.Account, a.App, a.Host, inc, lifetimePending, a.Body, a.PredecessorETag, a.StaleETag, a.AppLifetime, a.PrevOwnerKey, a.RestoreOrigin, a.RestoreOf, time.Now().Unix())
return err
}
@@ -149,10 +163,14 @@ func (s *Store) SetAllocationState(opID, state string) error {
return s.setState("host_allocations", opID, state)
}
-const allocationCols = `op_id, account, app, host, incarnation, state, body, predecessor_etag, stale_etag, app_lifetime, prev_owner_key`
+const allocationCols = `op_id, account, app, host, incarnation, state, body, predecessor_etag, stale_etag, app_lifetime, prev_owner_key, restore_origin, restore_of`
func (s *Store) allocations(where string, args ...any) ([]Allocation, error) {
- rows, err := s.db.Query(`SELECT `+allocationCols+` FROM host_allocations WHERE `+where+` ORDER BY rowid`, args...)
+ return s.allocationsOrdered(`rowid`, where, args...)
+}
+
+func (s *Store) allocationsOrdered(order, where string, args ...any) ([]Allocation, error) {
+ rows, err := s.db.Query(`SELECT `+allocationCols+` FROM host_allocations WHERE `+where+` ORDER BY `+order, args...)
if err != nil {
return nil, err
}
@@ -161,7 +179,7 @@ func (s *Store) allocations(where string, args ...any) ([]Allocation, error) {
for rows.Next() {
var a Allocation
var inc int64
- if err := rows.Scan(&a.OpID, &a.Account, &a.App, &a.Host, &inc, &a.State, &a.Body, &a.PredecessorETag, &a.StaleETag, &a.AppLifetime, &a.PrevOwnerKey); err != nil {
+ if err := rows.Scan(&a.OpID, &a.Account, &a.App, &a.Host, &inc, &a.State, &a.Body, &a.PredecessorETag, &a.StaleETag, &a.AppLifetime, &a.PrevOwnerKey, &a.RestoreOrigin, &a.RestoreOf); err != nil {
return nil, err
}
if a.Incarnation, err = storedIncarnation(inc); err != nil {
@@ -200,8 +218,8 @@ func retirementKindKnown(k string) bool {
}
const retirementInsert = `INSERT INTO record_retirements
- (op_id, kind, account, app, host, incarnation, record_etag, slot_etag, slot_intent, cancels, state, created_at)
-VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
+ (op_id, kind, account, app, host, incarnation, record_etag, slot_etag, slot_intent, cancels, state, record_body, created_at)
+VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
// BeginRetirement records a retirement intent. It never sets Cancels: only
// BeginCancellingRetirement does, together with voiding what it cancels.
@@ -217,7 +235,7 @@ func (s *Store) BeginRetirement(r Retirement) error {
return err
}
_, err = s.db.Exec(retirementInsert, r.OpID, r.Kind, r.Account, r.App, r.Host, inc,
- r.RecordETag, r.SlotETag, r.SlotIntent, "", lifetimePending, time.Now().Unix())
+ r.RecordETag, r.SlotETag, r.SlotIntent, "", lifetimePending, r.RecordBody, time.Now().Unix())
return err
}
@@ -242,7 +260,7 @@ func (s *Store) BeginCancellingRetirement(r Retirement, voidAllocation string) e
}
defer tx.Rollback()
if _, err := tx.Exec(retirementInsert, r.OpID, r.Kind, r.Account, r.App, r.Host, inc,
- r.RecordETag, r.SlotETag, r.SlotIntent, voidAllocation, lifetimePending, time.Now().Unix()); err != nil {
+ r.RecordETag, r.SlotETag, r.SlotIntent, voidAllocation, lifetimePending, r.RecordBody, time.Now().Unix()); err != nil {
return err
}
res, err := tx.Exec(`UPDATE host_allocations SET state = ? WHERE op_id = ? AND state = ?`,
@@ -267,12 +285,47 @@ func (s *Store) ConvertRetirementKind(opID, kind, recordETag string) error {
return oneRow(res, err, "pending normal record_retirements", opID)
}
+// MarkRetirementRestorable flags a normal retirement as restorable. It
+// judges the kind only, not the state: a restore later requires normal,
+// committed and restorable together. Idempotent; any other kind or a
+// missing row is an error.
+func (s *Store) MarkRetirementRestorable(opID string) error {
+ res, err := s.db.Exec(`UPDATE record_retirements SET restorable = 1 WHERE op_id = ? AND kind = ?`, opID, retireNormal)
+ return oneRow(res, err, "normal record_retirements", opID)
+}
+
+// NewestRetirement is the latest retirement row of host: highest
+// incarnation, then newest created_at, then last inserted. nil for none.
+func (s *Store) NewestRetirement(host string) (*RetirementEvidence, error) {
+ var e RetirementEvidence
+ var inc int64
+ err := s.db.QueryRow(`SELECT op_id, kind, account, app, host, incarnation, record_etag, slot_etag, slot_intent, cancels, state, record_body, restorable
+FROM record_retirements WHERE host = ? ORDER BY incarnation DESC, created_at DESC, rowid DESC LIMIT 1`, host).
+ Scan(&e.OpID, &e.Kind, &e.Account, &e.App, &e.Host, &inc, &e.RecordETag, &e.SlotETag, &e.SlotIntent, &e.Cancels, &e.State, &e.RecordBody, &e.Restorable)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ if e.Incarnation, err = storedIncarnation(inc); err != nil {
+ return nil, err
+ }
+ return &e, nil
+}
+
+// HostLineage lists every non-void allocation of host, lowest incarnation
+// first.
+func (s *Store) HostLineage(host string) ([]Allocation, error) {
+ return s.allocationsOrdered(`incarnation, rowid`, `host = ? AND state <> ?`, host, lifetimeVoid)
+}
+
func (s *Store) SetRetirementState(opID, state string) error {
return s.setState("record_retirements", opID, state)
}
func (s *Store) pendingRetirements(order string) ([]Retirement, error) {
- rows, err := s.db.Query(`SELECT op_id, kind, account, app, host, incarnation, record_etag, slot_etag, slot_intent, cancels, state
+ rows, err := s.db.Query(`SELECT op_id, kind, account, app, host, incarnation, record_etag, slot_etag, slot_intent, cancels, state, record_body
FROM record_retirements WHERE state = ? ORDER BY `+order, lifetimePending)
if err != nil {
return nil, err
@@ -282,7 +335,7 @@ FROM record_retirements WHERE state = ? ORDER BY `+order, lifetimePending)
for rows.Next() {
var r Retirement
var inc int64
- if err := rows.Scan(&r.OpID, &r.Kind, &r.Account, &r.App, &r.Host, &inc, &r.RecordETag, &r.SlotETag, &r.SlotIntent, &r.Cancels, &r.State); err != nil {
+ if err := rows.Scan(&r.OpID, &r.Kind, &r.Account, &r.App, &r.Host, &inc, &r.RecordETag, &r.SlotETag, &r.SlotIntent, &r.Cancels, &r.State, &r.RecordBody); err != nil {
return nil, err
}
if r.Incarnation, err = storedIncarnation(inc); err != nil {
diff --git a/internal/console/lifetimes_store_test.go b/internal/console/lifetimes_store_test.go
index eba358bec..2c63a328e 100644
--- a/internal/console/lifetimes_store_test.go
+++ b/internal/console/lifetimes_store_test.go
@@ -658,3 +658,157 @@ func elsewhere() { _ = ("INSERT INTO " + "apps") + suffix }
t.Fatalf("SQL declarations = %q, want %q", got, want)
}
}
+
+func TestAllocationRestoreColumns(t *testing.T) {
+ s := openTestStore(t)
+ plain := testAllocation("a2", "h.example", 2)
+ restored := testAllocation("a3", "h.example", 3)
+ restored.RestoreOrigin, restored.RestoreOf = true, "r-1"
+ void := testAllocation("a4", "h.example", 4)
+ first := testAllocation("a1", "h.example", 1)
+ other := testAllocation("x1", "other.example", 1)
+ // Insert out of incarnation order.
+ for _, a := range []Allocation{restored, void, plain, first, other} {
+ if err := s.BeginAllocation(a); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.SetAllocationState("a4", lifetimeVoid); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.HostLineage("h.example")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var ops []string
+ for _, a := range got {
+ ops = append(ops, a.OpID)
+ }
+ if !reflect.DeepEqual(ops, []string{"a1", "a2", "a3"}) {
+ t.Fatalf("lineage = %v, want a1 a2 a3 (void excluded, by incarnation)", ops)
+ }
+ if got[0].RestoreOrigin || got[0].RestoreOf != "" || got[1].RestoreOrigin {
+ t.Fatalf("plain rows read as restore: %+v %+v", got[0], got[1])
+ }
+ if !got[2].RestoreOrigin || got[2].RestoreOf != "r-1" || got[2].Incarnation != 3 || string(got[2].Body) != `{"app":"shop"}` {
+ t.Fatalf("restore row did not round-trip: %+v", got[2])
+ }
+ pend, err := s.PendingAllocations()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, a := range pend {
+ if a.OpID == "a3" && (!a.RestoreOrigin || a.RestoreOf != "r-1") {
+ t.Fatalf("pending scan lost restore columns: %+v", a)
+ }
+ }
+}
+
+func TestRetirementEvidence(t *testing.T) {
+ s := openTestStore(t)
+ if r, err := s.NewestRetirement("h.example"); err != nil || r != nil {
+ t.Fatalf("empty host: %v, %v", r, err)
+ }
+ ret := func(op, kind string, inc uint64, body []byte) Retirement {
+ return Retirement{OpID: op, Kind: kind, Account: "bab", App: "shop", Host: "h.example", Incarnation: inc,
+ RecordETag: `"r"`, SlotETag: `"s"`, SlotIntent: "i", RecordBody: body}
+ }
+ if err := s.BeginRetirement(ret("n1", retireNormal, 1, []byte(`{"b":1}`))); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.BeginRetirement(ret("n2", retireNormal, 2, nil)); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.NewestRetirement("h.example")
+ if err != nil || got == nil || got.OpID != "n2" || got.RecordBody != nil || got.Restorable {
+ t.Fatalf("newest = %+v, %v", got, err)
+ }
+ if err := s.BeginRetirement(ret("o0", retireOrphan, 0, nil)); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.BeginRetirement(ret("c0", retireCleanup, 0, nil)); err != nil {
+ t.Fatal(err)
+ }
+ for _, op := range []string{"o0", "c0", "missing"} {
+ if err := s.MarkRetirementRestorable(op); err == nil {
+ t.Fatalf("MarkRetirementRestorable(%s) = nil, want error", op)
+ }
+ }
+ // Body round-trips through the older row via a direct read.
+ var body []byte
+ if err := s.db.QueryRow(`SELECT record_body FROM record_retirements WHERE op_id = 'n1'`).Scan(&body); err != nil || string(body) != `{"b":1}` {
+ t.Fatalf("body = %q, %v", body, err)
+ }
+ // Marking is state-blind and idempotent.
+ for i := 0; i < 2; i++ {
+ if err := s.MarkRetirementRestorable("n2"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The flag stayed off the cleanup/orphan rows.
+ var n int
+ if err := s.db.QueryRow(`SELECT count(*) FROM record_retirements WHERE restorable = 1 AND kind <> 'normal'`).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("non-normal restorable rows: %d, %v", n, err)
+ }
+
+ // Same incarnation and created_at, opposite restorable: the later insert wins.
+ for _, restorableFirst := range []bool{true, false} {
+ host := "tie-" + strconv.FormatBool(restorableFirst)
+ a, b := ret("t-a-"+host, retireNormal, 5, nil), ret("t-b-"+host, retireNormal, 5, nil)
+ a.Host, b.Host = host, host
+ if err := s.BeginRetirement(a); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.BeginRetirement(b); err != nil {
+ t.Fatal(err)
+ }
+ first, second := a.OpID, b.OpID
+ if err := s.MarkRetirementRestorable(map[bool]string{true: first, false: second}[restorableFirst]); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.db.Exec(`UPDATE record_retirements SET created_at = 1000 WHERE host = ?`, host); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.NewestRetirement(host)
+ if err != nil || got == nil {
+ t.Fatal(got, err)
+ }
+ if got.OpID != second || got.Restorable == restorableFirst {
+ t.Fatalf("restorableFirst=%v: newest = %s restorable=%v, want the later insert %s", restorableFirst, got.OpID, got.Restorable, second)
+ }
+ }
+}
+
+func TestRestoreColumnsMigrateOldRows(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ raw, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, stmt := range []string{
+ `CREATE TABLE host_allocations (op_id TEXT PRIMARY KEY, account TEXT, app TEXT, host TEXT, incarnation INTEGER, state TEXT, body BLOB, predecessor_etag TEXT, stale_etag TEXT, app_lifetime TEXT, prev_owner_key TEXT NOT NULL DEFAULT '', created_at INTEGER)`,
+ `CREATE TABLE record_retirements (op_id TEXT PRIMARY KEY, kind TEXT, account TEXT, app TEXT, host TEXT, incarnation INTEGER, record_etag TEXT, slot_etag TEXT, slot_intent TEXT, cancels TEXT, state TEXT, created_at INTEGER)`,
+ `INSERT INTO host_allocations VALUES ('a1','bab','shop','h.example',1,'committed',x'7b7d','p','s','l','',1)`,
+ `INSERT INTO record_retirements VALUES ('r1','normal','bab','shop','h.example',1,'e','s','i','','committed',1)`,
+ } {
+ if _, err := raw.Exec(stmt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ raw.Close()
+ for pass := 1; pass <= 2; pass++ {
+ s, err := Open(path)
+ if err != nil {
+ t.Fatalf("pass %d: %v", pass, err)
+ }
+ lin, err := s.HostLineage("h.example")
+ if err != nil || len(lin) != 1 || lin[0].RestoreOrigin || lin[0].RestoreOf != "" {
+ t.Fatalf("pass %d: lineage %+v, %v", pass, lin, err)
+ }
+ r, err := s.NewestRetirement("h.example")
+ if err != nil || r == nil || r.OpID != "r1" || r.RecordBody != nil || r.Restorable {
+ t.Fatalf("pass %d: retirement %+v, %v", pass, r, err)
+ }
+ s.Close()
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index ad99449b1..ea73b1e89 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -522,6 +522,13 @@ func (s *Store) migrate() error {
// the create removes and recovery removes if the create could not.
// "" for none.
`ALTER TABLE host_allocations ADD COLUMN prev_owner_key TEXT NOT NULL DEFAULT '';`,
+ // Instance restore (#658): an allocation made by a restore, and the
+ // retirement op it restores; a retirement's record body (for the
+ // restore to put back) and whether it may be restored.
+ `ALTER TABLE host_allocations ADD COLUMN restore_origin INTEGER NOT NULL DEFAULT 0;`,
+ `ALTER TABLE host_allocations ADD COLUMN restore_of TEXT NOT NULL DEFAULT '';`,
+ `ALTER TABLE record_retirements ADD COLUMN record_body BLOB;`,
+ `ALTER TABLE record_retirements ADD COLUMN restorable INTEGER NOT NULL DEFAULT 0;`,
// Plans 4c: the account's throttle, JSON, "" for none.
`ALTER TABLE account_plans ADD COLUMN throttle TEXT NOT NULL DEFAULT '';`,
// Plans 4d: when the account's limits last fell from a paid