carlos / platform Public

host: finalize HA departures despite lease waits and inventory churn

Keep lease-expiry waits off the failure backoff ladder and track each
record revision visited during adoption and the independent rescan.
Unrelated record writes must not restart the deployment-wide walk and
leave terminated members' edges files in place indefinitely.

Rebind late edges publications only for the same verified, immutable
group identity and exact scope, then delete on the persisted ETag.
Preserve fixed-box retention and real-blocker paging. Cover due-time
production wiring, inventory churn, late publications, and 64 seeded
safety and liveness simulations.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f81cfd5cf9985b77d3f59818875062eff7f954a2 parent a9a3e4e
6 files changed, +848 −57
  • internal/host/group_departure_test.go +5 −0
  • internal/host/hadepartures_fix_test.go +4 −0
  • internal/host/hadepartures_g3_test.go +689 −0
  • internal/host/hadepartures_scan.go +140 −56
  • internal/host/hadepartures_scan_test.go +1 −1
  • internal/registry/ha_scan.go +9 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>b4b46jsuo</task-id> <tool-use-id>toolu_01EKrDG6KZ9ZQmsowAaoirzj</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/b4b46jsuo.output</output-file> <status>completed</status> <summary>Background command "sleep 15; .superpowers/sdd/2026-11-07-region-ha-g3-fixes/wait.sh t4" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 37.2 g CO₂e (4,315,448 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g3-fixes, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/host/group_departure_test.go b/internal/host/group_departure_test.go
index ccf75d13a..0f5112aa2 100644
--- a/internal/host/group_departure_test.go
+++ b/internal/host/group_departure_test.go
@@ -171,6 +171,11 @@ func TestGroupDepartureStepAndComplete(t *testing.T) {
t.Fatal(err)
}
scan.Generation = departureInventoryDigest(x.inv)
+ scan.Rescan = true
+ scan.Visited = map[string]registry.HADepartureVisit{}
+ for _, h := range x.inv.Records {
+ scan.Visited[h.Host] = registry.HADepartureVisit{RecordDigest: scanDigest(h)}
+ }
if err := x.r.SaveDepartureScan(t.Context(), x.d.ID, "scanning", scan); err != nil {
t.Fatal(err)
}
diff --git a/internal/host/hadepartures_fix_test.go b/internal/host/hadepartures_fix_test.go
index dd7d92ada..c4dcea69b 100644
--- a/internal/host/hadepartures_fix_test.go
+++ b/internal/host/hadepartures_fix_test.go
@@ -65,6 +65,10 @@ func TestDepartureReplacementRevision(t *testing.T) {
t.Fatal(err)
}
s.Generation = departureInventoryDigest(x.inv)
+ // This completion-only fixture supplies a finished rescan.
+ for _, h := range x.inv.Records {
+ s.Visited[h.Host] = registry.HADepartureVisit{RecordDigest: scanDigest(h)}
+ }
s.DeleteUncertain = true
if err = x.r.SaveDepartureScan(t.Context(), x.d.ID, "authority_complete", s); err != nil {
t.Fatal(err)
diff --git a/internal/host/hadepartures_g3_test.go b/internal/host/hadepartures_g3_test.go
new file mode 100644
index 000000000..a319caab7
--- /dev/null
+++ b/internal/host/hadepartures_g3_test.go
@@ -0,0 +1,689 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math/rand"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/boxid/boxidtest"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type g3Departure struct {
+ a departureArm
+ c *Controller
+ fx *locktest.LockFixture
+ store release.Store
+ queue *departureSQSTransport
+ now, start, expiry time.Time
+ dead, peer hadeparture.Box
+ id, edgesKey, edgesTag string
+ records []provision.Record
+ pages int
+}
+
+func newG3Departure(t *testing.T, n int) *g3Departure {
+ t.Helper()
+ t.Cleanup(lease.ProcessStateForTest())
+ previous := metricsDepartures.Load()
+ t.Cleanup(func() { metricsDepartures.Store(previous) })
+ x := &g3Departure{fx: locktest.NewLockFixture(t), start: time.Now().Add(-time.Hour).UTC()}
+ x.now, x.expiry = x.start, x.start.Add(15*time.Minute)
+ x.a, _, _ = departureArmFixtureBucket(t, x.fx.Bucket)
+ a := &x.a
+ a.Backend.Registry = a.Registry
+ a.Backend.DataDir = filepath.Join(t.TempDir(), "data")
+ a.Backend.RunDirOverride = filepath.Join(t.TempDir(), "run")
+ a.Backend.Control = instancectl.NewClient("/unused/control.sock")
+ var err error
+ x.store, err = a.OpenStore(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ x.dead = hadeparture.Box{Account: a.Self.Account, InstanceID: "i-1123456789abcdef0", Scope: a.Self.Scope}
+ x.dead.Ref = groupReferenceOf(x.dead.Account, x.dead.InstanceID)
+ x.peer = hadeparture.Box{Account: a.Self.Account, InstanceID: "i-2123456789abcdef0", Scope: a.Self.Scope}
+ x.peer.Ref = groupReferenceOf(x.peer.Account, x.peer.InstanceID)
+ signer := boxidtest.NewSigner(t)
+ a.Verifier = boxid.Verifier{Account: a.Self.Account, Certs: signer.Certs()}
+ for _, b := range []hadeparture.Box{a.Self, x.dead, x.peer} {
+ _, raw := signer.Record(t, b.Ref, b.Account, b.Scope.CloudRegion, b.InstanceID)
+ if _, err = x.store.Put(t.Context(), boxid.Key(b.Ref), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < n; i++ {
+ rec := provision.Record{Schema: 1, Account: "bab", App: "shop", Host: fmt.Sprintf("g3-%03d.example.com", i), Channel: "stable", HA: true, CreatedAt: x.start.Add(-time.Hour)}
+ if i > 0 {
+ rec.Region = "elsewhere"
+ }
+ x.records = append(x.records, rec)
+ if err = provision.CreateRecord(t.Context(), x.store, rec); err != nil {
+ t.Fatal(err)
+ }
+ }
+ a.Backend.Cfg.Record = func(ctx context.Context, rt registry.Route) (activator.RecordFacts, error) {
+ rec, _, e := provision.FindRecordByHost(ctx, x.store, rt.Host)
+ if e != nil {
+ return activator.RecordFacts{}, e
+ }
+ return activator.RecordFactsOf(*rec)
+ }
+ rec := x.records[0]
+ rt := registry.Route{Host: rec.Host, Kind: "instance", Account: rec.Account, App: rec.App, Channel: rec.Channel, Status: "ready", HA: true, Provisioned: true, Hibernate: true, DBPath: provision.NestedDBPath(a.Backend.DataDir, rec.Host), Socket: filepath.Join(a.Backend.RunDirOverride, "instances", provision.InstanceID(rec.Host), "app.sock")}
+ if err = a.Registry.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ files, err := lease.NewFilesStore(t.Context(), x.fx.Bucket, a.Self.Scope.CloudRegion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.Backend.FilesStore = files
+ a.Service = activator.New(a.Backend.Cfg, a.Backend, a.Registry)
+ a.Service.DutyStore = a.Registry
+ lease.SetSelf(hafresh.Self{Ref: a.Self.Ref, IID: a.Self.InstanceID, Account: a.Self.Account, Region: a.Self.Scope.CloudRegion})
+ if err = lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ pub, err := hostfiles.Open(t.Context(), files, "instances/"+rec.Host+"/files/0/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ due := time.Now().Add(48 * time.Hour).Unix()
+ if err = hostfiles.StageWake(t.Context(), pub, hostfiles.WakeState{V: 1, Host: rec.Host, NextDue: due, Timers: []hostfiles.WakeTimer{{Name: "reminder", Kind: "once", Spec: fmt.Sprintf("at %d", due), Path: "/remind", NextAt: due, DueAt: due, Registration: "original"}}}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = pub.Commit(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ x.putLock(t, x.dead, 5, x.expiry)
+ x.edgesKey = "control/edges/" + x.dead.Ref + ".json"
+ x.writeEdges(t)
+ x.queue = &departureSQSTransport{queue: "g3-receiver", body: string(terminationHint(x.dead.InstanceID))}
+ a.MakeQueue = func(ctx context.Context) (hadeparture.Queue, error) { return x.queue.open(ctx, departureCloud(a.Self)) }
+ c, life, err := armHADepartures(t.Context(), *a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ x.c = c
+ select {
+ case <-life.Started():
+ case <-time.After(3 * time.Second):
+ t.Fatal("queue startup")
+ }
+ if err = life.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ c.cfg.Now = func() time.Time { return x.now }
+ c.cfg.Logf = func(string, ...any) {}
+ c.cfg.Page = func(context.Context, registry.HADeparture, []provision.DepartureHost) error { x.pages++; return nil }
+ for _, b := range []hadeparture.Box{a.Self, x.dead, x.peer} {
+ tag := "known"
+ if b.Ref == x.dead.Ref {
+ tag = x.edgesTag
+ }
+ obs, e := c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: b, EdgesKey: "control/edges/" + b.Ref + ".json", EdgesETag: tag})
+ if e != nil {
+ t.Fatal(e)
+ }
+ if b.Ref == x.dead.Ref {
+ x.dead = obs.Box
+ if e = c.Enqueue(t.Context(), obs); e != nil {
+ t.Fatal(e)
+ }
+ x.id = departureID(c.cfg.DeploymentBucket, obs.Box)
+ }
+ }
+ x.reconcile(t)
+ return x
+}
+func (x *g3Departure) putLock(t *testing.T, b hadeparture.Box, gen int64, expiry time.Time) {
+ t.Helper()
+ raw, err := json.Marshal(hafresh.Lock{Generation: gen, Owner: hafresh.OwnerFor(hafresh.Self{Ref: b.Ref, IID: b.InstanceID}, 1, true), ExpiresAt: expiry})
+ if err != nil {
+ t.Fatal(err)
+ }
+ x.fx.PutLock("instances/"+x.records[0].Host, raw)
+}
+func (x *g3Departure) writeEdges(t *testing.T) {
+ t.Helper()
+ raw, _ := json.Marshal(edgesFile{V: 1, Box: x.dead.Ref, BoxID: x.dead.Ref, Region: x.dead.Scope.CloudRegion, Placement: x.dead.Scope.Placement, DataBucket: x.dead.Scope.DataBucket, SecretsKeyFP: x.dead.Scope.SecretsKeyFP, EIP: fmt.Sprint(x.now.UnixNano())})
+ var err error
+ x.edgesTag, err = x.store.Put(t.Context(), x.edgesKey, raw, x.edgesTag)
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+func (x *g3Departure) reconcile(t *testing.T) {
+ t.Helper()
+ at := x.now.Add(time.Second)
+ cfg := provision.ReconcileConfig{DataDir: x.a.Backend.DataDir, Departures: x.a.Inventory.Begin(at.String(), at, at, true), Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }}
+ if err := provision.Reconcile(t.Context(), x.store, x.a.Registry, cfg); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.ReconcileSidecars(t.Context(), x.store, x.a.Registry, cfg); err != nil {
+ t.Fatal(err)
+ }
+ if inv := x.a.Inventory.Snapshot(); !inv.Complete || len(inv.Records) != len(x.records) {
+ t.Fatalf("inventory: %+v", inv)
+ }
+}
+func (x *g3Departure) row(t *testing.T) registry.HADeparture {
+ t.Helper()
+ d, e := x.a.Registry.Departure(t.Context(), x.id)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return d
+}
+
+func TestDepartureG3Production(t *testing.T) {
+ for _, mode := range []string{"peer", "adopt", "unbound", "churn_each_pass", "churn_two_minutes", "churn_released", "late_edges"} {
+ t.Run(mode, func(t *testing.T) {
+ n := 100
+ if mode == "churn_two_minutes" || mode == "churn_released" {
+ n = 260
+ }
+ x := newG3Departure(t, n)
+ if mode == "churn_released" {
+ entry, _ := provision.LifetimeEntryOf(x.records[0])
+ raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID})
+ x.fx.PutLock("instances/"+x.records[0].Host, raw)
+ x.expiry = x.start.Add(-time.Second)
+ }
+ end := x.expiry.Add(time.Duration(2*((n+31)/32))*30*time.Second + time.Minute)
+ nextChurn := x.start.Add(2 * time.Minute)
+ takeover := false
+ passes := 0
+ for !x.now.After(end) {
+ d := x.row(t)
+ if d.Phase == "complete" {
+ break
+ }
+ if (mode == "peer" || mode == "unbound") && !takeover && !x.now.Before(x.expiry.Add(5*time.Second)) {
+ peer := x.peer
+ if mode == "unbound" {
+ peer.InstanceID = "i-3123456789abcdef0"
+ peer.Ref = groupReferenceOf(peer.Account, peer.InstanceID)
+ }
+ x.putLock(t, peer, 6, x.expiry.Add(time.Hour))
+ takeover = true
+ }
+ if !x.now.Before(d.NextAttempt) && x.now.Sub(x.start)%(30*time.Second) == 0 {
+ if mode == "churn_each_pass" && passes > 0 || (mode == "churn_two_minutes" || mode == "churn_released") && !x.now.Before(nextChurn) {
+ rec := &x.records[1]
+ rec.Channel = fmt.Sprintf("churn-%d", passes)
+ key := provision.RecordKey(rec.Account, rec.App, rec.Host)
+ _, tag, e := x.store.Get(t.Context(), key)
+ if e != nil {
+ t.Fatal(e)
+ }
+ raw, _ := json.Marshal(rec)
+ if _, e = x.store.Put(t.Context(), key, raw, tag); e != nil {
+ t.Fatal(e)
+ }
+ x.reconcile(t)
+ nextChurn = x.now.Add(2 * time.Minute)
+ }
+ if mode == "late_edges" && passes == 1 {
+ x.writeEdges(t)
+ }
+ if e := x.c.step(t.Context()); e != nil {
+ // A changed ETag is refused by the conditional delete, then rebound
+ // from a fresh read on the next completion attempt.
+ if mode != "late_edges" || !errors.Is(e, release.ErrCASConflict) {
+ t.Fatal(e)
+ }
+ }
+ passes++
+ d = x.row(t)
+ if mode != "late_edges" && (mode != "unbound" || !takeover) {
+ if d.LastError == "blocked" || d.RetryCount != 0 || x.pages != 0 {
+ t.Fatalf("wait/churn treated as failure: %+v pages=%d", d, x.pages)
+ }
+ }
+ if !x.now.After(x.expiry) {
+ entry, _ := provision.LifetimeEntryOf(x.records[0])
+ _, adopted, e := x.a.Registry.HAAdoption(t.Context(), x.records[0].Host, entry.ID, x.id)
+ if e != nil || adopted || d.Phase == "complete" {
+ t.Fatalf("early adoption/deletion: %+v %v", d, e)
+ }
+ if _, _, e = x.store.Get(t.Context(), x.edgesKey); e != nil {
+ t.Fatal("early edges deletion", e)
+ }
+ _, _, acks := x.queue.counts()
+ if acks != 0 {
+ t.Fatal("early ack")
+ }
+ }
+ }
+ x.now = x.now.Add(time.Second)
+ }
+ d := x.row(t)
+ _, _, acks := x.queue.counts()
+ if mode == "unbound" {
+ if d.Phase == "complete" || d.LastError != "blocked" || d.RetryCount == 0 || x.pages == 0 || acks != 0 {
+ t.Fatalf("unbound successor discharged: %+v pages=%d acks=%d", d, x.pages, acks)
+ }
+ if _, _, e := x.store.Get(t.Context(), x.edgesKey); e != nil {
+ t.Fatal(e)
+ }
+ return
+ }
+ if mode == "late_edges" {
+ scan, e := x.a.Registry.DepartureScan(t.Context(), x.id)
+ if e != nil || scan.EdgesETag != x.edgesTag || scan.EdgesETag == d.EdgesETag {
+ t.Fatalf("new ETag not durably bound: %+v %v", scan, e)
+ }
+ }
+ if d.Phase != "complete" || acks != 1 {
+ t.Fatalf("not finalized within %s: %+v acks=%d", end.Sub(x.expiry), d, acks)
+ }
+ if _, _, e := x.store.Get(t.Context(), x.edgesKey); !errors.Is(e, os.ErrNotExist) {
+ t.Fatalf("edges retained: %v", e)
+ }
+ timer, e := x.a.Registry.GetTimer(x.records[0].Host, "reminder")
+ if mode == "peer" {
+ if timer != nil {
+ t.Fatal("peer takeover imported locally")
+ }
+ } else if e != nil || timer == nil || timer.Registration != "original" {
+ t.Fatalf("wake not imported: %+v %v", timer, e)
+ }
+ t.Logf("%d records, %d due passes; complete %s after expiry", n, passes, x.now.Sub(x.expiry))
+ })
+ }
+}
+
+func TestDepartureG3Simulation(t *testing.T) {
+ seeds := 64
+ if testing.Short() {
+ seeds = 12
+ }
+ for seed := int64(0); seed < int64(seeds); seed++ {
+ t.Run(fmt.Sprint(seed), func(t *testing.T) {
+ rng := rand.New(rand.NewSource(seed))
+ n := 1 + rng.Intn(300)
+ x := newScanRig(t, n)
+ rng.Shuffle(n, func(i, j int) { x.inv.Records[i], x.inv.Records[j] = x.inv.Records[j], x.inv.Records[i] })
+ start := x.now
+ lastExpiry := start
+ type duty struct {
+ kind int
+ expiry time.Time
+ recovered bool
+ }
+ duties := map[string]*duty{}
+ blocker := false
+ for _, h := range x.inv.Records {
+ kind := rng.Intn(4)
+ if seed%3 == 0 && kind == 3 {
+ kind = 4
+ }
+ if kind == 0 {
+ delete(x.locks.views, h.Host)
+ continue
+ }
+ d := &duty{kind: kind}
+ duties[h.Host] = d
+ if kind >= 2 {
+ // Every dead lock is observed before any takeover. Positions vary.
+ d.expiry = start.Add(time.Duration(600+rng.Intn(900)) * time.Second)
+ v := x.locks.views[h.Host]
+ v.Lock.Release = nil
+ v.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: x.d.Box.Ref, IID: x.d.Box.InstanceID}, 1, true)
+ v.Lock.ExpiresAt = d.expiry
+ x.locks.views[h.Host] = v
+ if d.expiry.After(lastExpiry) {
+ lastExpiry = d.expiry
+ }
+ }
+ if kind == 4 {
+ blocker = true
+ }
+ }
+ x.c.cfg.ValidateSuccessor = func(_ context.Context, ref, iid string) (bool, error) {
+ return ref == "peer" || ref == x.c.cfg.Self.Ref, nil
+ }
+ adopt := x.c.cfg.Adopt
+ x.c.cfg.Adopt = func(ctx context.Context, h provision.DepartureHost, d registry.HADeparture, v hafresh.View) (activator.AdoptResult, error) {
+ if v.Lock.Release == nil && !x.now.After(v.Lock.ExpiresAt) {
+ t.Fatalf("seed %d: early adoption of %s", seed, h.Host)
+ }
+ result, e := adopt(ctx, h, d, v)
+ if e == nil {
+ duties[h.Host].recovered = true
+ }
+ return result, e
+ }
+ pages := 0
+ x.c.cfg.Page = func(context.Context, registry.HADeparture, []provision.DepartureHost) error { pages++; return nil }
+ // At most one mutation per 30s interval and at most 320 live records.
+ // Each full page therefore clears at least 31 outstanding revisions.
+ // Allow a residual dirty walk, a clean adoption walk, and a rescan,
+ // plus one extra walk for expiries distributed across a page boundary.
+ bound := lastExpiry.Add(time.Duration(4*((320+30)/31))*30*time.Second + time.Minute)
+ serial := n
+ for !x.now.After(bound) {
+ for host, d := range duties {
+ if (d.kind == 3 || d.kind == 4) && !d.recovered && x.now.After(d.expiry.Add(5*time.Second)) {
+ v := x.locks.views[host]
+ ref := "peer"
+ if d.kind == 4 {
+ ref = "unbound"
+ }
+ v.ETag = "takeover"
+ v.Lock.Generation = 2
+ v.Lock.Owner = hafresh.OwnerFor(hafresh.Self{Ref: ref, IID: "i-peer"}, 1, true)
+ v.Lock.ExpiresAt = bound.Add(time.Hour)
+ x.locks.views[host] = v
+ d.recovered = d.kind == 3
+ }
+ }
+ if x.now.After(start) && rng.Intn(4) != 0 {
+ candidates := []int{}
+ for i, h := range x.inv.Records {
+ if duties[h.Host] == nil {
+ candidates = append(candidates, i)
+ }
+ }
+ action := rng.Intn(3)
+ if action == 0 && len(x.inv.Records) < 320 {
+ serial++
+ x.inv.Records = append(x.inv.Records, provision.DepartureHost{Host: fmt.Sprintf("churn-%d.example.com", serial), Lifetime: "new", Kind: "instance", HA: true, Revision: fmt.Sprint(serial)})
+ } else if len(candidates) > 0 {
+ i := candidates[rng.Intn(len(candidates))]
+ if action == 1 {
+ x.inv.Records = append(x.inv.Records[:i], x.inv.Records[i+1:]...)
+ } else {
+ x.inv.Records[i].Revision = x.now.String()
+ }
+ }
+ }
+ row, e := x.r.Departure(t.Context(), x.d.ID)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if !x.now.Before(row.NextAttempt) {
+ if _, e = x.c.ScanPass(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ }
+ row, e = x.r.Departure(t.Context(), x.d.ID)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if row.Phase == "complete" {
+ for host, d := range duties {
+ if !d.recovered {
+ t.Fatalf("seed %d deleted before %s recovered: %+v", seed, host, d)
+ }
+ }
+ if blocker {
+ t.Fatal("unbound successor completed")
+ }
+ return
+ }
+ if !blocker && (row.LastError == "blocked" || pages != 0) {
+ t.Fatalf("seed %d wait/churn paged: %+v", seed, row)
+ }
+ x.now = x.now.Add(30 * time.Second)
+ }
+ if !blocker {
+ t.Fatalf("seed %d: failed liveness bound %s", seed, bound.Sub(lastExpiry))
+ }
+ if pages == 0 {
+ t.Fatal("real blocker never paged")
+ }
+ if _, _, e := x.store.Get(t.Context(), x.d.EdgesKey); e != nil {
+ t.Fatal("blocked edges deleted", e)
+ }
+ })
+ }
+}
+
+func TestDepartureG3InventoryWrites(t *testing.T) {
+ x := newG3Departure(t, 100)
+ digest := departureInventoryDigest(x.a.Inventory.Snapshot())
+ check := func(name string, changed bool) {
+ t.Helper()
+ x.reconcile(t)
+ next := departureInventoryDigest(x.a.Inventory.Snapshot())
+ if (next != digest) != changed {
+ t.Fatalf("%s: digest changed=%v, want %v", name, next != digest, changed)
+ }
+ t.Logf("%s: digest changed=%v", name, next != digest)
+ digest = next
+ }
+ m := release.Manifest{App: "shop", Version: "v1abc", Kind: "binary", Artifacts: map[string]release.Artifact{"linux-amd64": {}}}
+ if e := release.Ship(t.Context(), x.store, "bab", m, map[string][]byte{"linux-amd64": []byte("test binary")}); e != nil {
+ t.Fatal(e)
+ }
+ check("ship", false)
+ seed, _, e := release.GenerateKey()
+ if e != nil {
+ t.Fatal(e)
+ }
+ key, e := release.ParseSigningKey(seed, "test")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = release.Promote(t.Context(), x.store, key, "bab", "shop", "stable", "v1abc"); e != nil {
+ t.Fatal(e)
+ }
+ check("promote", false)
+ pub, e := hostfiles.Open(t.Context(), x.a.Backend.FilesStore, "instances/"+x.records[0].Host+"/files/0/")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = hostfiles.StageWake(t.Context(), pub, hostfiles.WakeState{V: 1, Host: x.records[0].Host}); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = pub.Commit(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ check("wake-state publication", false)
+ rec := x.records[1]
+ recordKey := provision.RecordKey(rec.Account, rec.App, rec.Host)
+ raw, tag, e := x.store.Get(t.Context(), recordKey)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = x.store.Put(t.Context(), recordKey, append(raw, '\n'), tag); e != nil {
+ t.Fatal(e)
+ }
+ check("raw record whitespace", true)
+ _, tag, e = x.store.Get(t.Context(), recordKey)
+ if e != nil {
+ t.Fatal(e)
+ }
+ rec.Channel = "canary/test"
+ if e = provision.UpdateRecord(t.Context(), x.store, rec, tag); e != nil {
+ t.Fatal(e)
+ }
+ check("instance channel update", true)
+ // Reproduce the old digest/cursor rule independently of lease failures:
+ // nine pages cannot finish if a raw-record write resets it every four.
+ oldGeneration := digest
+ cursor, resets := 0, 0
+ for pass := 0; pass < 80; pass++ {
+ current := fmt.Sprint(pass / 4)
+ if current != oldGeneration {
+ cursor = 0
+ resets++
+ oldGeneration = current
+ }
+ cursor += 32
+ if cursor >= 260 {
+ t.Fatal("legacy cursor unexpectedly completed")
+ }
+ }
+ t.Logf("legacy 260-record walk, write every 2m: %d resets in 40m, cursor=%d", resets, cursor)
+}
+
+func TestDepartureG3CatchUp(t *testing.T) {
+ for _, mode := range []string{"changed", "added", "removed", "inflight"} {
+ t.Run(mode, func(t *testing.T) {
+ x := newScanRig(t, 65)
+ x.locks.views = map[string]hafresh.View{}
+ x.pass(t)
+ h := x.inv.Records[0]
+ marker := hafresh.Marker{V: 1, Box: x.d.Box.Ref, IID: x.d.Box.InstanceID, Lifetime: h.Lifetime}
+ change := func() {
+ if mode == "removed" {
+ x.inv.Records = x.inv.Records[1:]
+ return
+ }
+ if mode == "added" {
+ h.Host = "added.example.com"
+ x.inv.Records = append([]provision.DepartureHost{h}, x.inv.Records...)
+ } else {
+ x.inv.Records[0].Revision = "changed"
+ }
+ x.locks.views[h.Host] = hafresh.View{ETag: "dead", Lock: hafresh.Lock{Generation: 1, Owner: hafresh.MarkerOwner(marker), Release: &marker, ExpiresAt: time.Unix(0, 0)}}
+ }
+ if mode == "inflight" {
+ inventory := x.c.cfg.Inventory
+ reads := 0
+ x.c.cfg.Inventory = func() provision.InventorySnapshot {
+ reads++
+ if reads == 2 {
+ change()
+ }
+ return inventory()
+ }
+ } else {
+ change()
+ }
+ for i := 0; i < 8; i++ {
+ x.pass(t)
+ row, e := x.r.Departure(t.Context(), x.d.ID)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if row.LastError == "blocked" {
+ t.Fatal("inventory change blocked")
+ }
+ if row.Phase == "complete" {
+ want := 1
+ if mode == "removed" {
+ want = 0
+ }
+ if x.imports != want {
+ t.Fatalf("catch-up imports=%d want=%d", x.imports, want)
+ }
+ return
+ }
+ }
+ t.Fatal("catch-up never completed")
+ })
+ }
+}
+
+func TestDepartureG3EdgesRebindRefusals(t *testing.T) {
+ for _, mode := range []string{"wrong_scope", "wrong_ref", "null_placement", "malformed", "unbound"} {
+ t.Run(mode, func(t *testing.T) {
+ x := newG3Departure(t, 1)
+ if e := x.c.step(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ view := edgesfile.PlacementView{V: 1, Box: x.dead.Ref, BoxID: x.dead.Ref, Region: x.dead.Scope.CloudRegion, Placement: x.dead.Scope.Placement, DataBucket: x.dead.Scope.DataBucket, SecretsKeyFP: x.dead.Scope.SecretsKeyFP}
+ if mode == "wrong_scope" {
+ view.DataBucket = "another"
+ }
+ if mode == "wrong_ref" {
+ view.BoxID = x.peer.Ref
+ }
+ raw, _ := json.Marshal(view)
+ if mode == "malformed" {
+ raw = []byte("{")
+ }
+ if mode == "null_placement" {
+ var obj map[string]any
+ _ = json.Unmarshal(raw, &obj)
+ obj["placement"] = nil
+ raw, _ = json.Marshal(obj)
+ }
+ tag, e := x.store.Put(t.Context(), x.edgesKey, raw, x.edgesTag)
+ if e != nil {
+ t.Fatal(e)
+ }
+ x.now = x.expiry.Add(30 * time.Second)
+ if e = x.c.step(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ x.now = x.now.Add(30 * time.Second)
+ if e = x.c.step(t.Context()); !errors.Is(e, release.ErrCASConflict) {
+ t.Fatalf("stale ETag accepted: %v", e)
+ }
+ if mode == "unbound" {
+ x.c.cfg.Identities = nil
+ }
+ if e = x.c.Complete(t.Context(), x.id); !errors.Is(e, errDepartureIdentity) {
+ t.Fatalf("unsafe rebind: %v", e)
+ }
+ if _, current, e := x.store.Get(t.Context(), x.edgesKey); e != nil || current != tag {
+ t.Fatal("replacement deleted", current, e)
+ }
+ if d := x.row(t); d.Phase == "complete" || d.LastError != "replacement_binding" {
+ t.Fatalf("unsafe completion: %+v", d)
+ }
+ _, _, acks := x.queue.counts()
+ if acks != 0 {
+ t.Fatal("unsafe acknowledgement")
+ }
+ })
+ }
+}
+
+func TestDepartureG3LateEdges(t *testing.T) {
+ x := newG3Departure(t, 1)
+ d := x.row(t)
+ scan, e := x.a.Registry.DepartureScan(t.Context(), x.id)
+ if e != nil || d.EdgesETag == "" || scan.EdgesETag != "" {
+ t.Fatalf("enrollment binding: departure=%q scan=%q %v", d.EdgesETag, scan.EdgesETag, e)
+ }
+ entry, _ := provision.LifetimeEntryOf(x.records[0])
+ raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID})
+ x.fx.PutLock("instances/"+x.records[0].Host, raw)
+ if e = x.c.step(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ x.now = x.now.Add(30 * time.Second)
+ x.writeEdges(t)
+ if e = x.c.step(t.Context()); !errors.Is(e, release.ErrCASConflict) {
+ t.Fatalf("stale ETag was not refused: %v", e)
+ }
+ x.now = x.now.Add(30 * time.Second)
+ if e = x.c.step(t.Context()); e != nil {
+ t.Fatal("late publication stuck", e)
+ }
+ if d = x.row(t); d.Phase != "complete" {
+ t.Fatalf("late publication never finalized: %+v", d)
+ }
+ scan, e = x.a.Registry.DepartureScan(t.Context(), x.id)
+ if e != nil || scan.EdgesETag != x.edgesTag {
+ t.Fatalf("replacement ETag not persisted: %+v %v", scan, e)
+ }
+ _, _, acks := x.queue.counts()
+ if acks != 1 {
+ t.Fatal("missing ack", acks)
+ }
+}
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index 7eeb11ec6..3e9b1a96d 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -14,6 +14,7 @@ import (
"github.com/aws/smithy-go"
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/provision"
@@ -125,11 +126,14 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
// A process restart requires a new qualifying inventory and a new full scan.
generation := departureInventoryDigest(inv)
s.InventoryGeneration = inv.Generation
- if d.Phase == "pending" || s.Generation != generation {
+ if d.Phase == "pending" || s.Visited == nil {
s.Generation = generation
s.Cursor = 0
s.Rescan = false
s.Unresolved = 0
+ s.Waiting = 0
+ s.NotBefore = time.Time{}
+ s.Visited = map[string]registry.HADepartureVisit{}
if s.Hosts == nil {
s.Hosts = map[string]registry.HADepartureHostScan{}
}
@@ -148,10 +152,25 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
}
blockers := []provision.DepartureHost{}
count := 0
- for s.Cursor < len(inv.Records) && count < 32 && ctx.Err() == nil {
- h := inv.Records[s.Cursor]
- s.Cursor++
+ for _, h := range inv.Records {
+ digest := scanDigest(h)
+ if visit, ok := s.Visited[h.Host]; ok && visit.RecordDigest == digest {
+ continue
+ }
+ if count == 32 || ctx.Err() != nil {
+ break
+ }
count++
+ visit := registry.HADepartureVisit{RecordDigest: digest}
+ s.Visited[h.Host] = visit
+ block := func() {
+ visit.Unresolved = true
+ s.Visited[h.Host] = visit
+ }
+ wait := func(until time.Time) {
+ visit.NotBefore = until
+ s.Visited[h.Host] = visit
+ }
old, seen := s.Hosts[h.Host]
if seen && old.Lifetime != h.Lifetime {
delete(s.Hosts, h.Host)
@@ -159,12 +178,12 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
old = registry.HADepartureHostScan{}
}
if h.Lifetime == "" || !provision.ValidHostShape(h.Host) || departureCoverageGap(h, d.Box.Scope) {
- s.Unresolved++
+ block()
blockers = append(blockers, h)
continue
}
if !s.Rescan && seen && old.RecordDigest == scanDigest(h) && !old.NotBefore.IsZero() && !c.now().After(old.NotBefore) {
- s.Unresolved++
+ wait(old.NotBefore)
continue
}
call, done := context.WithTimeout(ctx, 5*time.Second)
@@ -172,12 +191,12 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
v, e := reader.ReadLock(call, d.Box.Scope.DataBucket, c.cfg.Prefix(h.Host))
done()
if e != nil {
- s.Unresolved++
+ block()
continue
}
if v.Absent {
if seen {
- s.Unresolved++
+ block()
}
continue
}
@@ -186,7 +205,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
}
ref, iid, valid := departureLockIdentity(v, h.Lifetime)
if !valid {
- s.Unresolved++
+ block()
blockers = append(blockers, h)
continue
}
@@ -198,34 +217,34 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
if seen && ref == c.cfg.Self.Ref && iid == c.cfg.Self.InstanceID {
receipt, present, e := c.cfg.Registry.HAAdoption(ctx, h.Host, h.Lifetime, d.ID)
if e != nil {
- s.Unresolved++
+ block()
continue
}
if present && receipt.Phase != "adopted" {
// Our marker cannot discharge our unfinished local commit.
// Resume the one importer using its original departure view.
if s.Rescan || c.cfg.Adopt == nil {
- s.Unresolved++
+ block()
continue
}
result, e := c.adoptMeasured(ctx, h, d, old.Observed)
if e != nil || result == activator.Deferred {
- s.Unresolved++
+ block()
continue
}
}
}
if seen && v.Lock.Generation <= old.Observed.Lock.Generation {
- s.Unresolved++
+ block()
continue
}
if c.cfg.ValidateSuccessor == nil {
- s.Unresolved++
+ block()
continue
}
ok, e := c.cfg.ValidateSuccessor(ctx, ref, iid)
if e != nil || !ok {
- s.Unresolved++
+ block()
continue
}
if seen {
@@ -246,33 +265,34 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
old.Result = "pending"
old.NotBefore = time.Time{}
s.Hosts[h.Host] = old
- if s.Rescan {
- s.Unresolved++
- continue
- }
if !CanAdopt(h, c.cfg.Policy()) || !h.HA {
- s.Unresolved++
+ block()
blockers = append(blockers, h)
continue
}
if v.Lock.Release == nil && !readStarted.After(v.Lock.ExpiresAt) {
old.NotBefore = v.Lock.ExpiresAt
s.Hosts[h.Host] = old
- s.Unresolved++
+ wait(old.NotBefore)
+ continue
+ }
+ if s.Rescan {
+ block()
continue
}
// Save the source authority before the importer may transfer it.
+ block()
if e = c.cfg.Registry.SaveDepartureScan(ctx, d.ID, "scanning", s); e != nil {
return true, errors.Join(e, c.retryScan(ctx, d, nil, "journal", true))
}
s.Version++
if c.cfg.Adopt == nil {
- s.Unresolved++
+ block()
continue
}
result, e := c.adoptMeasured(ctx, h, d, v)
if e != nil || result == activator.Deferred {
- s.Unresolved++
+ block()
if errors.Is(e, registry.ErrHAWake) {
blockers = append(blockers, h)
}
@@ -280,27 +300,36 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
}
old.Result = fmt.Sprint(result)
s.Hosts[h.Host] = old
+ visit.Unresolved = false
+ s.Visited[h.Host] = visit
}
if ctx.Err() != nil {
return true, errors.Join(ctx.Err(), c.retryScan(ctx, d, nil, "scan_timeout", true))
}
- // A changed or incomplete published inventory invalidates the entire pass.
- if departureInventoryDigest(c.cfg.Inventory()) != generation {
- s.Generation = ""
- s.Cursor = 0
- s.Rescan = false
- s.Unresolved++
- }
+ // a departure finalizes within a bounded time after every dead-owned lease has expired, unless a
+ // real blocker exists, and never deletes the edges file before every dead-owned host is adopted or superseded
+ // Keep visits across inventory publications. A changed or added record must
+ // be read at its current revision; unrelated writes cannot restart the walk.
+ inv = c.cfg.Inventory()
+ finished := departureScanCoverage(&s, inv)
+ s.Generation = departureInventoryDigest(inv)
blocked := s.Unresolved > 0
phase := "scanning"
- if s.Cursor == len(inv.Records) && s.Generation == generation {
- if s.Rescan && CanCompleteDeparture(RescanResult{Inventory: inv, EvidenceAt: d.ObservedAt, Finished: true, Unresolved: s.Unresolved}) {
+ next := c.now().Add(30 * time.Second)
+ if finished && inv.FreshAfter(d.ObservedAt) {
+ if s.Rescan && CanCompleteDeparture(RescanResult{Inventory: inv, EvidenceAt: d.ObservedAt, Finished: true, Unresolved: s.Unresolved + s.Waiting}) {
phase = "authority_complete"
} else {
+ if !blocked && s.Waiting > 0 && s.NotBefore.Add(time.Second).After(next) {
+ next = s.NotBefore.Add(time.Second)
+ }
// A clean adoption pass is followed by an independent full lock walk.
- s.Rescan = s.Unresolved == 0
+ s.Rescan = s.Unresolved == 0 && s.Waiting == 0
s.Cursor = 0
s.Unresolved = 0
+ s.Waiting = 0
+ s.NotBefore = time.Time{}
+ s.Visited = map[string]registry.HADepartureVisit{}
}
}
if err = c.cfg.Registry.SaveDepartureScan(ctx, d.ID, phase, s); err != nil {
@@ -309,7 +338,34 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
if phase == "authority_complete" {
return true, c.complete(ctx, d.ID)
}
- return true, c.retryScan(ctx, d, blockers, "scan", len(blockers) > 0 || blocked)
+ return true, c.retryScanAt(ctx, d, blockers, "scan", blocked, next)
+}
+
+// departureScanCoverage drops removed and changed revisions, retaining all other
+// visits. Counts describe only the current inventory, including catch-up reads.
+func departureScanCoverage(s *registry.HADepartureScan, inv provision.InventorySnapshot) bool {
+ current := make(map[string]registry.HADepartureVisit, len(inv.Records))
+ s.Cursor, s.Unresolved, s.Waiting = 0, 0, 0
+ s.NotBefore = time.Time{}
+ for _, h := range inv.Records {
+ v, ok := s.Visited[h.Host]
+ if !ok || v.RecordDigest != scanDigest(h) {
+ continue
+ }
+ current[h.Host] = v
+ s.Cursor++
+ if v.Unresolved {
+ s.Unresolved++
+ }
+ if !v.NotBefore.IsZero() {
+ s.Waiting++
+ if s.NotBefore.IsZero() || v.NotBefore.Before(s.NotBefore) {
+ s.NotBefore = v.NotBefore
+ }
+ }
+ }
+ s.Visited = current
+ return s.Cursor == len(inv.Records)
}
// Operator text for two departure faults (copy approved by delegation, one
@@ -323,12 +379,16 @@ const (
)
func (c *Controller) retryScan(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost, code string, page bool) error {
+ return c.retryScanAt(ctx, d, hosts, code, page, c.now().Add(30*time.Second))
+}
+
+func (c *Controller) retryScanAt(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost, code string, page bool, next time.Time) error {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
if code == "scan" && page {
code = "blocked"
}
- claimed, err := c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), code, page)
+ claimed, err := c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), next, code, page)
if err != nil {
return err
}
@@ -433,21 +493,21 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) {
return errDeparturePending
}
inv := c.cfg.Inventory()
- if !inv.FreshAfter(d.ObservedAt) || departureInventoryDigest(inv) != s.Generation {
+ if !inv.FreshAfter(d.ObservedAt) || !departureScanCoverage(&s, inv) {
if !inv.FreshAfter(d.ObservedAt) {
c.requestInventory(ctx, d.ObservedAt)
}
- s.Cursor = 0
- s.Rescan = false
- s.Generation = ""
return save("scanning")
}
s.InventoryGeneration = inv.Generation
- tag := d.EdgesETag
+ tag := s.EdgesETag
+ if tag == "" {
+ tag = d.EdgesETag
+ }
fixed := d.Box.Ref != groupReferenceOf(d.Box.Account, d.Box.InstanceID)
if fixed || s.DeleteUncertain || tag == "" {
call, cancel := context.WithTimeout(ctx, 5*time.Second)
- _, newTag, e := store.Get(call, d.EdgesKey)
+ raw, newTag, e := store.Get(call, d.EdgesKey)
cancel()
code = "edges_read"
if pe := permission(e); pe != nil {
@@ -463,21 +523,27 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) {
} else if fixed || tag == "" || newTag != tag {
code = "replacement_binding"
if !fixed {
- return errDepartureIdentity
- }
- code = "ha_departure_edges_retained"
- if c.cfg.Identities == nil {
- return errDepartureIdentity
- }
- // P18: a reused fixed ref cannot attribute any edges ETag to an iid.
- // Only absence or a verified newer incarnation discharges this phase.
- o, known, e := c.cfg.Identities.Resolve(ctx, d.Box.Ref, "")
- if e != nil || !known || !o.Known || o.PlacementNull || o.Box.Ref != d.Box.Ref || o.Box.InstanceID == "" || o.Box.InstanceID == d.Box.InstanceID || o.Box.Account != d.Box.Account || o.Box.Scope != d.Box.Scope {
- return errors.Join(e, errDepartureIdentity)
- }
- s.PermissionAlerted = false
- if err = save("edges_deleted_or_absent"); err != nil {
- return err
+ // A group ref names one account/iid forever. Rebind a late
+ // publication only with that verified identity and exact scope.
+ if e := c.bindDepartureEdges(ctx, d, raw, newTag); e != nil {
+ return e
+ }
+ tag, s.EdgesETag = newTag, newTag
+ } else {
+ code = "ha_departure_edges_retained"
+ if c.cfg.Identities == nil {
+ return errDepartureIdentity
+ }
+ // P18: a reused fixed ref cannot attribute any edges ETag to an iid.
+ // Only absence or a verified newer incarnation discharges this phase.
+ o, known, e := c.cfg.Identities.Resolve(ctx, d.Box.Ref, "")
+ if e != nil || !known || !o.Known || o.PlacementNull || o.Box.Ref != d.Box.Ref || o.Box.InstanceID == "" || o.Box.InstanceID == d.Box.InstanceID || o.Box.Account != d.Box.Account || o.Box.Scope != d.Box.Scope {
+ return errors.Join(e, errDepartureIdentity)
+ }
+ s.PermissionAlerted = false
+ if err = save("edges_deleted_or_absent"); err != nil {
+ return err
+ }
}
}
}
@@ -538,6 +604,24 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) {
return c.ackDeparture(ctx, d)
}
+func (c *Controller) bindDepartureEdges(ctx context.Context, d registry.HADeparture, raw []byte, tag string) error {
+ if tag == "" || c.cfg.Identities == nil || d.Box.Ref != groupReferenceOf(d.Box.Account, d.Box.InstanceID) {
+ return errDepartureIdentity
+ }
+ o, known, err := c.cfg.Identities.Resolve(ctx, d.Box.Ref, d.Box.InstanceID)
+ if err != nil || !known || !o.Known || o.PlacementNull || o.Box != d.Box {
+ return errors.Join(err, errDepartureIdentity)
+ }
+ var view edgesfile.PlacementView
+ var placement struct {
+ Placement json.RawMessage `json:"placement"`
+ }
+ if json.Unmarshal(raw, &view) != nil || json.Unmarshal(raw, &placement) != nil || strings.TrimSpace(string(placement.Placement)) == "null" || view.V != 1 || view.Box != d.Box.Ref || view.BoxID != d.Box.Ref || view.Region != d.Box.Scope.CloudRegion || view.Placement != d.Box.Scope.Placement || view.DataBucket != d.Box.Scope.DataBucket || view.SecretsKeyFP != d.Box.Scope.SecretsKeyFP {
+ return errDepartureIdentity
+ }
+ return nil
+}
+
// requestInventory runs under scanMu; the hook only queues a backstop round.
// FreshAfter still requires the resulting full walk before scanning proceeds.
func (c *Controller) requestInventory(ctx context.Context, observed time.Time) {
diff --git a/internal/host/hadepartures_scan_test.go b/internal/host/hadepartures_scan_test.go
index 322948b6e..388ff3b17 100644
--- a/internal/host/hadepartures_scan_test.go
+++ b/internal/host/hadepartures_scan_test.go
@@ -167,7 +167,7 @@ func TestDepartureWaitsExpiry(t *testing.T) {
if x.imports != 0 || x.locks.reads != 1 {
t.Fatal(x.imports, x.locks.reads)
}
- x.now = v.Lock.ExpiresAt.Add(time.Nanosecond)
+ x.now = v.Lock.ExpiresAt.Add(time.Second)
x.pass(t)
if x.imports != 1 {
t.Fatal(x.imports)
diff --git a/internal/registry/ha_scan.go b/internal/registry/ha_scan.go
index ffaa44d56..8f2523914 100644
--- a/internal/registry/ha_scan.go
+++ b/internal/registry/ha_scan.go
@@ -16,6 +16,12 @@ type HADepartureHostScan struct {
Result string
NotBefore time.Time
}
+type HADepartureVisit struct {
+ RecordDigest string
+ Unresolved bool
+ NotBefore time.Time
+}
+
type HADepartureScan struct {
Version uint64
Generation string
@@ -23,6 +29,9 @@ type HADepartureScan struct {
Cursor int
Rescan bool
Unresolved int
+ Waiting int
+ NotBefore time.Time
+ Visited map[string]HADepartureVisit
Hosts map[string]HADepartureHostScan
DeleteUncertain bool
EdgesETag string