carlos / platform Public

ha: persist termination inbox and pending departure retries

Bound inbox bodies and active rows, normalize atomically into durable departures, and retain unique box identity bindings. Preserve retry and hourly page state across enrollment replay and registry restart, with remote registry parity.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c71effe625c38c2b72cb48102a63b0b767ecbc1e parent 62cfcd1
4 files changed, +447 −1
  • internal/registry/ha_duties.go +4 −1
  • internal/registry/ha_journal.go +314 −0
  • internal/registry/ha_journal_test.go +125 −0
  • internal/registry/remote_dispatch.go +4 −0

Intent

Human

<task-notification> <task-id>bwc56h1ol</task-id> <tool-use-id>toolu_01CbgAjZ7JaZX4XT3ekT5ApG</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22c9817b-87ae-432b-b6d2-3ebbc209af38/tasks/bwc56h1ol.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra B3" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/registry/ha_duties.go b/internal/registry/ha_duties.go
index 6372c0063..b20aff9ff 100644
--- a/internal/registry/ha_duties.go
+++ b/internal/registry/ha_duties.go
@@ -62,7 +62,10 @@ END;
if err != nil {
return err
}
- return r.migrateHAAdoptions()
+ if err := r.migrateHAAdoptions(); err != nil {
+ return err
+ }
+ return r.migrateHAJournal()
}
func (r *Registry) HADuty(host, lifetime string) (DutyState, bool, error) {
diff --git a/internal/registry/ha_journal.go b/internal/registry/ha_journal.go
new file mode 100644
index 000000000..e5fc25c69
--- /dev/null
+++ b/internal/registry/ha_journal.go
@@ -0,0 +1,314 @@
+package registry
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hadeparture"
+)
+
+var ErrHAJournal = errors.New("ha_journal_invalid")
+
+type HATerminationInbox struct {
+ Key, MessageID string
+ Body []byte
+ ReceivedAt, NextAttempt time.Time
+ LastError string
+}
+type HADeparture struct {
+ hadeparture.Departure
+ ProofKey, ProofDigest, Phase, InventoryGeneration, LastError string
+ NextAttempt, LastPage time.Time
+}
+type HABoxIdentity struct {
+ Ref, IID, Account, Region, Digest string
+ Raw []byte
+ Observation hadeparture.BoxObservation
+}
+type HAIdentityWalk struct {
+ Cursor string
+ Keys []string
+ Offset int
+ Failed bool
+ StartedAt time.Time
+}
+
+type haJournalRequest struct {
+ Op, Key, ID, Code string
+ Body []byte
+ At, Next time.Time
+ Limit int
+ Page bool
+ Departure HADeparture
+ Identity HABoxIdentity
+ Walk HAIdentityWalk
+}
+type haJournalResponse struct {
+ Inbox []HATerminationInbox
+ Departures []HADeparture
+ Identity HABoxIdentity
+ Walk HAIdentityWalk
+ Found bool
+}
+
+func (r *Registry) migrateHAJournal() error {
+ _, err := r.sql.Exec(`
+ CREATE TABLE IF NOT EXISTS ha_termination_inbox(key TEXT PRIMARY KEY,message_id TEXT NOT NULL,body BLOB NOT NULL CHECK(length(body)<=65536),received INTEGER NOT NULL,next_attempt INTEGER NOT NULL,last_error TEXT NOT NULL DEFAULT '');
+ CREATE TABLE IF NOT EXISTS ha_departures(id TEXT PRIMARY KEY,body BLOB NOT NULL,phase TEXT NOT NULL DEFAULT 'pending',next_attempt INTEGER NOT NULL,last_page INTEGER NOT NULL DEFAULT 0,last_error TEXT NOT NULL DEFAULT '');
+ CREATE TABLE IF NOT EXISTS ha_box_identities(ref TEXT PRIMARY KEY,iid TEXT NOT NULL UNIQUE,body BLOB NOT NULL);
+ CREATE TABLE IF NOT EXISTS ha_identity_walk(id INTEGER PRIMARY KEY CHECK(id=1),body BLOB NOT NULL);
+ `)
+ return err
+}
+func journalTime(t time.Time) int64 {
+ if t.IsZero() {
+ return 0
+ }
+ return t.UnixNano()
+}
+func journalDate(n int64) time.Time {
+ if n == 0 {
+ return time.Time{}
+ }
+ return time.Unix(0, n).UTC()
+}
+func (r *Registry) RecordTermination(ctx context.Context, id string, body []byte, at time.Time) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "record", ID: id, Body: body, At: at})
+ return err
+}
+func (r *Registry) TerminationInbox(ctx context.Context, at time.Time, limit int) ([]HATerminationInbox, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "inbox", At: at, Limit: limit})
+ return out.Inbox, err
+}
+func (r *Registry) RetryTermination(ctx context.Context, key string, next time.Time, code string) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "retry_inbox", Key: key, Next: next, Code: code})
+ return err
+}
+func (r *Registry) RejectTermination(ctx context.Context, key string) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "reject", Key: key})
+ return err
+}
+func (r *Registry) EnrollDeparture(ctx context.Context, d HADeparture, inbox string) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "enroll", Departure: d, Key: inbox})
+ return err
+}
+func (r *Registry) PendingDepartures(ctx context.Context, at time.Time, limit int) ([]HADeparture, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "pending", At: at, Limit: limit})
+ return out.Departures, err
+}
+func (r *Registry) RetryDeparture(ctx context.Context, id string, at, next time.Time, code string, page bool) (bool, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "retry_departure", ID: id, At: at, Next: next, Code: code, Page: page})
+ return out.Found, err
+}
+func (r *Registry) SaveHAIdentity(ctx context.Context, b HABoxIdentity) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "identity_save", Identity: b})
+ return err
+}
+func (r *Registry) HAIdentity(ctx context.Context, ref, iid string) (HABoxIdentity, bool, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "identity", ID: ref, Key: iid})
+ return out.Identity, out.Found, err
+}
+func (r *Registry) LoadHAIdentityWalk(ctx context.Context) (HAIdentityWalk, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "walk"})
+ return out.Walk, err
+}
+func (r *Registry) SaveHAIdentityWalk(ctx context.Context, w HAIdentityWalk) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "walk_save", Walk: w})
+ return err
+}
+func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJournalResponse, err error) {
+ if r.remote != nil {
+ resp, e := r.remote.call(ctx, remoteRequest{Method: "HAJournal", HAJournal: q}, nil)
+ return resp.HAJournal, e
+ }
+ switch q.Op {
+ case "record":
+ if q.ID == "" || len(q.ID) > 1024 || len(q.Body) > hadeparture.MaxBodyBytes || q.At.IsZero() {
+ return out, ErrHAJournal
+ }
+ key := fmt.Sprintf("%x", sha256.Sum256(append(append([]byte(q.ID), 0), q.Body...)))
+ tx, e := r.beginClaimTransaction(ctx, true)
+ if e != nil {
+ return out, e
+ }
+ defer tx.Rollback()
+ var exists int
+ if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM ha_termination_inbox WHERE key=?`, key).Scan(&exists); e != nil {
+ return out, e
+ }
+ if exists != 0 {
+ return out, nil
+ }
+ var count int
+ if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM ha_termination_inbox`).Scan(&count); e != nil {
+ return out, e
+ }
+ if count >= hadeparture.MaxInboxRows {
+ return out, ErrHAJournal
+ }
+ _, e = tx.ExecContext(ctx, `INSERT INTO ha_termination_inbox(key,message_id,body,received,next_attempt) VALUES(?,?,?,?,?)`, key, q.ID, q.Body, journalTime(q.At), journalTime(q.At))
+ if e != nil {
+ return out, e
+ }
+ err = tx.Commit()
+ case "inbox":
+ if q.Limit < 1 || q.Limit > 32 {
+ return out, ErrHAJournal
+ }
+ rows, e := r.sql.QueryContext(ctx, `SELECT key,message_id,body,received,next_attempt,last_error FROM ha_termination_inbox WHERE next_attempt<=? ORDER BY next_attempt,received,key LIMIT ?`, journalTime(q.At), q.Limit)
+ if e != nil {
+ return out, e
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var row HATerminationInbox
+ var at, next int64
+ if e = rows.Scan(&row.Key, &row.MessageID, &row.Body, &at, &next, &row.LastError); e != nil {
+ return out, e
+ }
+ row.ReceivedAt = journalDate(at)
+ row.NextAttempt = journalDate(next)
+ out.Inbox = append(out.Inbox, row)
+ }
+ err = rows.Err()
+ case "reject":
+ _, err = r.sql.ExecContext(ctx, `DELETE FROM ha_termination_inbox WHERE key=?`, q.Key)
+ case "retry_inbox":
+ _, err = r.sql.ExecContext(ctx, `UPDATE ha_termination_inbox SET next_attempt=?,last_error=? WHERE key=?`, journalTime(q.Next), q.Code, q.Key)
+ case "enroll":
+ d := q.Departure
+ if d.ID == "" || d.ObservedAt.IsZero() || d.ProofKey == "" || d.ProofDigest == "" || d.Box.Ref == "" || d.Box.InstanceID == "" {
+ return out, ErrHAJournal
+ }
+ d.Phase = "pending"
+ d.LastPage = time.Time{}
+ d.LastError = ""
+ d.NextAttempt = d.ObservedAt
+ body, e := json.Marshal(d)
+ if e != nil {
+ return out, e
+ }
+ tx, e := r.beginClaimTransaction(ctx, true)
+ if e != nil {
+ return out, e
+ }
+ defer tx.Rollback()
+ // Replays preserve retry, phase and evidence provenance.
+ if _, e = tx.ExecContext(ctx, `INSERT OR IGNORE INTO ha_departures(id,body,next_attempt) VALUES(?,?,?)`, d.ID, body, journalTime(d.NextAttempt)); e != nil {
+ return out, e
+ }
+ if q.Key != "" {
+ if _, e = tx.ExecContext(ctx, `DELETE FROM ha_termination_inbox WHERE key=?`, q.Key); e != nil {
+ return out, e
+ }
+ }
+ err = tx.Commit()
+ case "pending":
+ if q.Limit < 1 || q.Limit > 32 {
+ return out, ErrHAJournal
+ }
+ rows, e := r.sql.QueryContext(ctx, `SELECT body,phase,next_attempt,last_page,last_error FROM ha_departures WHERE phase<>'complete' AND next_attempt<=? ORDER BY next_attempt,id LIMIT ?`, journalTime(q.At), q.Limit)
+ if e != nil {
+ return out, e
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var body []byte
+ var d HADeparture
+ var phase, code string
+ var next, page int64
+ if e = rows.Scan(&body, &phase, &next, &page, &code); e != nil {
+ return out, e
+ }
+ if e = json.Unmarshal(body, &d); e != nil {
+ return out, e
+ }
+ d.Phase = phase
+ d.LastError = code
+ d.NextAttempt = journalDate(next)
+ d.LastPage = journalDate(page)
+ out.Departures = append(out.Departures, d)
+ }
+ err = rows.Err()
+ case "retry_departure":
+ tx, e := r.beginClaimTransaction(ctx, true)
+ if e != nil {
+ return out, e
+ }
+ defer tx.Rollback()
+ if q.Page {
+ res, e := tx.ExecContext(ctx, `UPDATE ha_departures SET last_page=? WHERE id=? AND phase<>'complete' AND (last_page=0 OR last_page<=?)`, journalTime(q.At), q.ID, journalTime(q.At.Add(-time.Hour)))
+ if e != nil {
+ return out, e
+ }
+ n, e := res.RowsAffected()
+ if e != nil {
+ return out, e
+ }
+ out.Found = n == 1
+ }
+ if _, e = tx.ExecContext(ctx, `UPDATE ha_departures SET next_attempt=?,last_error=? WHERE id=? AND phase<>'complete'`, journalTime(q.Next), q.Code, q.ID); e != nil {
+ return out, e
+ }
+ err = tx.Commit()
+ case "identity_save":
+ b := q.Identity
+ if b.Ref == "" || b.IID == "" || b.Account == "" || b.Region == "" || len(b.Raw) > 64*1024 || len(b.Raw) == 0 || b.Digest != fmt.Sprintf("%x", sha256.Sum256(b.Raw)) {
+ return out, ErrHAJournal
+ }
+ body, e := json.Marshal(b)
+ if e != nil {
+ return out, e
+ }
+ res, e := r.sql.ExecContext(ctx, `INSERT INTO ha_box_identities(ref,iid,body) VALUES(?,?,?) ON CONFLICT(ref) DO UPDATE SET body=excluded.body WHERE iid=excluded.iid AND json_extract(body,'$.Digest')=json_extract(excluded.body,'$.Digest')`, b.Ref, b.IID, body)
+ if e != nil {
+ return out, e
+ }
+ n, e := res.RowsAffected()
+ if e != nil {
+ return out, e
+ }
+ if n != 1 {
+ return out, ErrHAJournal
+ }
+ case "identity":
+ var body []byte
+ err = r.sql.QueryRowContext(ctx, `SELECT body FROM ha_box_identities WHERE (?<>'' AND ref=?) OR (?<>'' AND iid=?)`, q.ID, q.ID, q.Key, q.Key).Scan(&body)
+ if errors.Is(err, sql.ErrNoRows) {
+ return out, nil
+ }
+ if err == nil {
+ err = json.Unmarshal(body, &out.Identity)
+ out.Found = err == nil
+ }
+ if out.Found && ((q.ID != "" && q.ID != out.Identity.Ref) || (q.Key != "" && q.Key != out.Identity.IID)) {
+ return haJournalResponse{}, ErrHAJournal
+ }
+ case "walk_save":
+ if len(q.Walk.Keys) > 1000 || q.Walk.Offset < 0 || q.Walk.Offset > len(q.Walk.Keys) {
+ return out, ErrHAJournal
+ }
+ body, e := json.Marshal(q.Walk)
+ if e != nil {
+ return out, e
+ }
+ _, err = r.sql.ExecContext(ctx, `INSERT INTO ha_identity_walk(id,body) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET body=excluded.body`, body)
+ case "walk":
+ var body []byte
+ err = r.sql.QueryRowContext(ctx, `SELECT body FROM ha_identity_walk WHERE id=1`).Scan(&body)
+ if errors.Is(err, sql.ErrNoRows) {
+ return out, nil
+ }
+ if err == nil {
+ err = json.Unmarshal(body, &out.Walk)
+ }
+ default:
+ return out, ErrHAJournal
+ }
+ return out, err
+}
diff --git a/internal/registry/ha_journal_test.go b/internal/registry/ha_journal_test.go
new file mode 100644
index 000000000..acc780c3e
--- /dev/null
+++ b/internal/registry/ha_journal_test.go
@@ -0,0 +1,125 @@
+package registry
+
+import (
+ "context"
+ "crypto/sha256"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hadeparture"
+)
+
+func TestTerminationJournalDurability(t *testing.T) {
+ for _, remote := range []bool{false, true} {
+ t.Run(fmt.Sprint(remote), func(t *testing.T) {
+ var r *Registry
+ var path string
+ if remote {
+ r, path = remoteTestRegistry(t)
+ } else {
+ r, path = adoptRegistry(t)
+ }
+ ctx := context.Background()
+ now := time.Now().UTC()
+ body := []byte(`{"hint":"pending"}`)
+ if err := r.RecordTermination(ctx, "message", body, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.RecordTermination(ctx, "message", body, now); err != nil {
+ t.Fatal(err)
+ }
+ rows, err := r.TerminationInbox(ctx, now, 32)
+ if err != nil || len(rows) != 1 {
+ t.Fatalf("inbox %v %v", rows, err)
+ }
+ d := HADeparture{Departure: hadeparture.Departure{ID: "departure", Box: hadeparture.Box{Ref: "box", InstanceID: "i-12345678"}, ObservedAt: now}, ProofKey: "proof", ProofDigest: "digest"}
+ if err = r.EnrollDeparture(ctx, d, rows[0].Key); err != nil {
+ t.Fatal(err)
+ }
+ // Duplicate enrollment must not reset durable retry/page state.
+ if ok, err := r.RetryDeparture(ctx, d.ID, now, now.Add(time.Hour), "blocked_host", true); err != nil || !ok {
+ t.Fatalf("page %v %v", ok, err)
+ }
+ if err = r.EnrollDeparture(ctx, d, ""); err != nil {
+ t.Fatal(err)
+ }
+ r.Close()
+ r, err = Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ rows, err = r.TerminationInbox(ctx, now.Add(time.Hour), 32)
+ if err != nil || len(rows) != 0 {
+ t.Fatalf("normalized %v %v", rows, err)
+ }
+ pending, err := r.PendingDepartures(ctx, now.Add(time.Hour), 32)
+ if err != nil || len(pending) != 1 || pending[0].LastError != "blocked_host" || !pending[0].LastPage.Equal(now) {
+ t.Fatalf("pending %+v %v", pending, err)
+ }
+ if ok, err := r.RetryDeparture(ctx, d.ID, now.Add(time.Minute), now, "blocked_host", true); err != nil || ok {
+ t.Fatalf("page throttling %v %v", ok, err)
+ }
+ })
+ }
+}
+func TestTerminationJournalBounds(t *testing.T) {
+ r, _ := adoptRegistry(t)
+ ctx := context.Background()
+ now := time.Now()
+ if err := r.RecordTermination(ctx, "large", make([]byte, hadeparture.MaxBodyBytes+1), now); err == nil {
+ t.Fatal("oversize accepted")
+ }
+ for n := 0; n < hadeparture.MaxInboxRows; n++ {
+ if err := r.RecordTermination(ctx, fmt.Sprint(n), []byte("x"), now); err != nil {
+ t.Fatal(n, err)
+ }
+ }
+ if err := r.RecordTermination(ctx, "overflow", []byte("x"), now); err == nil {
+ t.Fatal("cap not enforced")
+ }
+ if err := r.RecordTermination(ctx, "0", []byte("x"), now); err != nil {
+ t.Fatal("duplicate at cap", err)
+ }
+ rows, err := r.TerminationInbox(ctx, now, 32)
+ if err != nil || len(rows) != 32 {
+ t.Fatalf("bounded page %d %v", len(rows), err)
+ }
+ if err := r.RetryTermination(ctx, rows[0].Key, now.Add(time.Hour), "identity"); err != nil {
+ t.Fatal(err)
+ }
+ next, _ := r.TerminationInbox(ctx, now, 32)
+ if next[0].Key == rows[0].Key {
+ t.Fatal("retry starves next message")
+ }
+}
+func TestDepartureIdentityPersistence(t *testing.T) {
+ r, path := adoptRegistry(t)
+ ctx := context.Background()
+ raw := []byte("verified exact bytes")
+ digest := fmt.Sprintf("%x", sha256.Sum256(raw))
+ b := HABoxIdentity{Ref: "box", IID: "i-12345678", Account: "123456789012", Region: "eu-west-1", Digest: digest, Raw: raw}
+ if err := r.SaveHAIdentity(ctx, b); err != nil {
+ t.Fatal(err)
+ }
+ b.Ref = "poison"
+ if err := r.SaveHAIdentity(ctx, b); err == nil {
+ t.Fatal("iid alias accepted")
+ }
+ b.Ref = "box"
+ b.IID = "i-87654321"
+ if err := r.SaveHAIdentity(ctx, b); err == nil {
+ t.Fatal("ref rebound")
+ }
+ r.Close()
+ r, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ got, ok, err := r.HAIdentity(ctx, "box", "")
+ if err != nil || !ok || string(got.Raw) != string(raw) || got.Digest != digest {
+ t.Fatalf("reopen %+v %v %v", got, ok, err)
+ }
+}
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 33ba45a86..03fbe02d0 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -6,6 +6,7 @@ import (
)
type remoteRequest struct {
+ HAJournal haJournalRequest
Lifetime, Receipt string
Revision uint64
Duty DutyState
@@ -118,6 +119,7 @@ type remoteRequest struct {
}
type remoteResponse struct {
+ HAJournal haJournalResponse
Duty DutyState
Import ImportResult
Adoption HAAdoption
@@ -150,6 +152,8 @@ type remoteResponse struct {
func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback func(remoteResponse) error) (out remoteResponse, err error) {
switch q.Method {
+ case "HAJournal":
+ out.HAJournal, err = r.haJournal(ctx, q.HAJournal)
case "AdvanceHADuty":
err = r.AdvanceHADuty(ctx, q.Host)
case "HADuty":