carlos / platform Public

host: refresh departure inventory before the backstop

Request a full record-view rebuild when departure scans or completion
lack a post-evidence inventory. Share a 60-second per-departure limit
between both paths and retain the existing freshness and rescan gates.

Cover production wiring, quiet-index retirement, rate limiting, and stale
completion with a real registry and RecordView over a directory store.
Implemented-by: Astra (codex)
claude pushed by paul@keymail.dev 68082f7bc27b04c1012038150fee6a1b0e0313da parent c7b1df8
5 files changed, +253 −1
  • internal/host/changeindex.go +15 −0
  • internal/host/hadepartures.go +3 −0
  • internal/host/hadepartures_inventory_test.go +212 −0
  • internal/host/hadepartures_scan.go +22 −0
  • internal/host/hadepartures_wiring.go +1 −1

Intent

Human

<task-notification> <task-id>bezi66h24</task-id> <tool-use-id>toolu_018wCJaKZgxu7nf8Zoi6pidM</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/bezi66h24.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/.superpowers/sdd/2026-11-06-region-ha-g2r-fixes; for i in $(seq 1 340); do [ -f $W/t1.done ] &amp;&amp; break; sleep 10; done; cat $W/t1.done 2&gt;/dev/null || echo "still running $(wc -c &lt; $W/t1.log)"; tail -3 $W/t1.log" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a94e7288b2cc3a11c</task-id> <tool-use-id>toolu_013wQBVuRLqZSPCCcg6QREj1</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/a94e7288b2cc3a11c.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 W2a serve-only wildcard" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Task 1 review (W2a, commit c7b1df8f): Approved.** No Critical findings. I re-ran only the four new tests (`-count=1`), and they pass in 0.285s. **Spec compliance: ✅** - ✅ **Serving stays ungated; DNS-01 ordering stays gated.** In `passWithClock`, `loadCached` still runs before any gate. The new `dns == nil` stand-down (wildcard.go:524-527) sits after the cache load and before `issuerGate()` and `obtain`. - ✅ **Ungated boxes still get nil.** wildcard.go:900-904 checks `e.issuer == nil` and keeps the old line and the nil return. This is safe because `RunWithActivator` calls `armCertIssuance` (edge.go:4657) before `newWildcardFromEnv` (edge.go:4719), so a box with no store has already had its gate cleared. - ✅ **A provider-less manager never reaches `obtain`.** `obtain` has one caller (wildcard.go:542), and `w.dns` is used only inside `obtain` (:658, :758). `run()` loops only through `pass` → `passWithClock`, so this covers pass, run, the backoff retries and the hourly cap. `refresh()` only wakes `run()`. Renewal is the same code path. `dnsProviderFromEnv` returns a plain `nil` interface on every failure branch (dns.go:66-82), so there is no non-nil interface wrapping a nil pointer. - ✅ **devbox still refuses.** devbox.go:191 checks `w == nil || w.dns == nil`. The devbox has no gate, so it already got nil; the new check is a backstop. - ✅ **Logs are rate-limited.** `logNoDNSStandDown` prints at most one line per hour across all parents and passes, using the pass clock under `mu`. When the lease is held it prints the "holds the issuer lease but cannot renew" warning instead. - ✅ **The key test fails on the base commit.** The report shows the mutation run against 98c43eea failing with `acme: not available here` and the CA being contacted twice. The test wiring is real: dir store, mirror, `wrapGetCertificate`, and a verified TLS client. **What changes on boxes that now get a manager** (gated, with a store, without DNS, such as group members): - **Refresh cost and S3 reads.** `loadCached` goes through `publishingCache.Get`, which is local-only (certsync.go:262), so a pass makes no S3 reads. Wakes come from the mirror and home map only when something changed (homemap.go:310), and the stand-down delay is capped at 1h. The cost is one local-disk read per missing parent per hour. - **Mirror backfill.** `attachWildcardToMirror` now gives `ownsCertName` a non-nil parent set, so the issuer's backfill may republish wildcard PEMs. It only publishes when its copy is newer than the bucket's (certsync.go:1311-1315), so this is the intended repair path, not a risk. **Findings** - **Minor: proactive cert warm stops covering some names when the lease holder has no DNS** (edge.go:4744-4746, certwarm.go:712). - **Why:** the warm's parent set used to be nil on these boxes. It is now `wm.currentParents`, and the warm skips any name one label under a configured or delegated parent. - **Scenario:** a group member without DNS wins the issuer lease. That can still happen until the W2b eligibility fix lands; any box with a deployment bucket can win today. A delegated parent's wildcard then nears expiry. Before this commit, the warm would have ordered per-host certs for those names. Now it orders nothing, and no box can renew the wildcard. - **Impact:** no outage. Once the wildcard expires, `certFor` returns nil and on-demand HTTP-01 through `issuerHostPolicy` still covers registered names. Names under the apps domain were already excluded from the warm. - **Suggestion:** pass `parents = nil` to the warm when `wm.dns == nil`, or note it in W2b. - **Minor: newly armed boxes now complete handshakes for unregistered names.** These boxes will serve a mirrored wildcard to any one-label SNI under a parent, registered or not, before any registry check. Before this commit, a non-issuer's handshake for an unregistered name failed. This is the documented posture every DNS-armed box already has (edge.go:1618, wrapGetCertificate), and the brief intends it. I am noting it for the census because it widens that posture to group boxes. - **Minor: the TLS test rebuilds the production wiring instead of calling it** (wildcard_serveonly_test.go:88-94). It copies edge.go:4719-4727 and calls `w.pass()` synchronously rather than through `RunWithActivator`. If edge.go's wiring changed, for example a new nil-manager short-circuit, this test would not notice. It is acceptable because the brief allows this shape. - **Minor: the TLS test never checks that a manager was built** (wildcard_serveonly_test.go:89). It does not assert `w != nil`; a nil manager only shows up later as a handshake error. An explicit check would make that failure clearer. This is cosmetic. **⚠️ Cannot verify from the diff** - That nothing outside `internal/edge`, such as host-side status or metrics, treats "manager non-nil" as "this box can order wildcards". I grepped only `internal/edge`, where `wm` feeds the warm and the mirror and nothing else. - Whether the operations docs say a box without DNS has "wildcards off". The edge's startup log will now also print `edge: wildcard certs on (...)` after the serve-only line, which could confuse someone reading the journal. **Task quality: Approved.** Before the Minor items are dealt with, decide the warm question in W2b or in this task. Files reviewed: - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/internal/edge/wildcard.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/internal/edge/devbox.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/internal/edge/wildcard_serveonly_test.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/internal/edge/edge.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/internal/edge/certwarm.go - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/g2r-fixes/internal/edge/certsync.go</result> <usage><subagent_tokens>76055</subagent_tokens><tool_uses>16</tool_uses><duration_ms>120163</duration_ms></usage> </task-notification>

Attributed to this commit: 9.09 g CO₂e (1,025,460 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2r-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/changeindex.go b/internal/host/changeindex.go
index 5c8ab0d82..e32db5743 100644
--- a/internal/host/changeindex.go
+++ b/internal/host/changeindex.go
@@ -174,6 +174,21 @@ func recordViewBackstop(ctx context.Context, v *provision.RecordView, due *atomi
due.Store(true)
}
+// requestDepartureInventory uses the backstop path immediately after departure
+// evidence. Per departure, each nudge costs one index GET plus a full record
+// walk: paginated LISTs of accounts, apps, each account's apps and each app's
+// instances and sidecars; one account manifest GET per account, three metadata
+// GETs per app, and GETs for new or changed record bodies (unchanged ETags reuse
+// bodies). The requested full converge pass has its usual additional reads.
+// The controller limits nudges to one per departure per 60 s.
+func requestDepartureInventory(ctx context.Context) {
+ if v := armedRecordView.Load(); v != nil {
+ recordViewBackstop(ctx, v, &backstopFullDue)
+ return
+ }
+ backstopFullDue.Store(true)
+}
+
// backstopEvery is release.ChangeIndexBackstop jittered by +-10%.
func backstopEvery() time.Duration {
b := release.ChangeIndexBackstop
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go
index 730b7f20d..2218c986d 100644
--- a/internal/host/hadepartures.go
+++ b/internal/host/hadepartures.go
@@ -76,6 +76,7 @@ type DepartureConfig struct {
Self hadeparture.Box
DeploymentBucket string
Inventory func() provision.InventorySnapshot
+ RequestInventory func(context.Context)
Policy func() LocalPolicy
Invalidate func(string, string)
Now func() time.Time
@@ -99,6 +100,8 @@ type Controller struct {
evidence map[string]bool
suspects map[string]bool
notices map[string]time.Time
+
+ inventoryRequests map[string]time.Time // guarded by scanMu
}
func NewController(cfg DepartureConfig) (*Controller, error) {
diff --git a/internal/host/hadepartures_inventory_test.go b/internal/host/hadepartures_inventory_test.go
new file mode 100644
index 000000000..3cc8b50e0
--- /dev/null
+++ b/internal/host/hadepartures_inventory_test.go
@@ -0,0 +1,212 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "testing"
+ "time"
+
+ "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/lease/locktest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func departureInventoryRig(t *testing.T) (*Controller, departureArm, release.Store, *provision.RecordView, string) {
+ t.Helper()
+ locks := locktest.NewLockFixture(t)
+ a, _, _ := departureArmFixtureBucket(t, locks.Bucket)
+ s, err := a.OpenStore(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ signer := boxidtest.NewSigner(t)
+ a.Verifier = boxid.Verifier{Account: a.Self.Account, Certs: signer.Certs()}
+ iid := "i-2123456789abcdef0"
+ ref := groupReferenceOf(a.Self.Account, iid)
+ _, raw := signer.Record(t, ref, a.Self.Account, a.Self.Scope.CloudRegion, iid)
+ if _, err = s.Put(t.Context(), boxid.Key(ref), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ key := "control/edges/" + ref + ".json"
+ raw, err = json.Marshal(edgesfile.PlacementView{V: 1, Box: ref, BoxID: ref, Region: a.Self.Scope.CloudRegion, Placement: a.Self.Scope.Placement, DataBucket: a.Self.Scope.DataBucket, SecretsKeyFP: a.Self.Scope.SecretsKeyFP})
+ if err != nil {
+ t.Fatal(err)
+ }
+ tag, err := s.Put(t.Context(), key, raw, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = release.BumpChangeIndex(t.Context(), s, key); err != nil {
+ t.Fatal(err)
+ }
+ rec := provision.Record{Schema: 1, Host: "other.example.com", Slug: "other", Account: release.OpsAccount, App: "other", Channel: "stable", Pool: "other", HA: true, CreatedAt: time.Now()}
+ if err = provision.CreateRecord(t.Context(), s, rec); err != nil {
+ t.Fatal(err)
+ }
+ oldInventory := boxDepartureInventory
+ boxDepartureInventory = a.Inventory
+ oldDue := backstopFullDue.Swap(false)
+ oldEpoch := boxHAIngress.epoch
+ oldRoutes := boxHAIngress.routes.Load()
+ boxHAIngress.epoch = 0
+ t.Cleanup(func() {
+ boxDepartureInventory = oldInventory
+ backstopFullDue.Store(oldDue)
+ boxHAIngress.epoch = oldEpoch
+ boxHAIngress.routes.Store(oldRoutes)
+ })
+ v := armView(t, s)
+ departureInventoryReconcile(t, a, s)
+ if inv := a.Inventory.Snapshot(); !inv.Complete || len(inv.Records) != 1 {
+ t.Fatalf("initial inventory: %+v", inv)
+ }
+ c, life, err := armHADepartures(t.Context(), a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = life.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ o, err := c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: ref, Scope: a.Self.Scope}, EdgesKey: key, EdgesETag: tag})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = c.Enqueue(t.Context(), o); err != nil {
+ t.Fatal(err)
+ }
+ return c, a, s, v, departureID(c.cfg.DeploymentBucket, o.Box)
+}
+
+func departureInventoryReconcile(t *testing.T, a departureArm, s release.Store) {
+ t.Helper()
+ cfg := provision.ReconcileConfig{DataDir: t.TempDir(), Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }}
+ if err := reconcileSerializedAuth(t.Context(), s, a.Registry, cfg, nil, newAssetAuthority(nil)); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDepartureInventoryNudgeRetiresGroup(t *testing.T) {
+ c, a, s, v, id := departureInventoryRig(t)
+ before := v.Snapshot()
+ now := time.Now()
+ c.cfg.Now = func() time.Time { return now }
+ // A quiet index and another reconcile must not manufacture source freshness.
+ departureInventoryReconcile(t, a, s)
+ if !v.Snapshot().SourceReadStartedAt.Equal(before.SourceReadStartedAt) {
+ t.Fatal("quiet refresh changed source read time")
+ }
+ if err := c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ d, err := a.Registry.Departure(t.Context(), id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err = s.Get(t.Context(), d.EdgesKey); err != nil {
+ t.Fatal("deleted before a fresh inventory and lock rescan", err)
+ }
+ if !backstopFullDue.Swap(false) {
+ t.Fatal("stale departure inventory did not request the backstop full pass")
+ }
+ departureInventoryReconcile(t, a, s)
+ if !c.cfg.Inventory().FreshAfter(d.ObservedAt) {
+ t.Fatal("nudge did not produce a full walk started after evidence")
+ }
+ for range 2 {
+ now = now.Add(30 * time.Second)
+ if err = c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ d, err = a.Registry.Departure(t.Context(), id)
+ if err != nil || d.Phase != "complete" {
+ t.Fatalf("departure still pending after two steps: %+v %v", d, err)
+ }
+ if _, _, err = s.Get(t.Context(), d.EdgesKey); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("dead group edges file retained: %v", err)
+ }
+ if got := v.Snapshot().Epoch - before.Epoch; got != 1 {
+ t.Fatalf("retirement required %d rebuilds, want one", got)
+ }
+}
+
+func TestDepartureInventoryNudgeRateLimit(t *testing.T) {
+ c, a, s, v, id := departureInventoryRig(t)
+ start := time.Now()
+ now := start
+ c.cfg.Now = func() time.Time { return now }
+ epoch := v.Snapshot().Epoch
+ for _, check := range []struct {
+ seconds int
+ walks uint64
+ }{{0, 1}, {30, 1}, {59, 1}, {60, 2}} {
+ now = start.Add(time.Duration(check.seconds) * time.Second)
+ // Keep the departure runnable while withholding the full reconcile pass.
+ if _, err := a.Registry.RetryDeparture(t.Context(), id, now, now, "reserve", false); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if got := v.Snapshot().Epoch - epoch; got != check.walks {
+ t.Fatalf("at %ds: full rebuilds = %d, want %d", check.seconds, got, check.walks)
+ }
+ d, err := a.Registry.Departure(t.Context(), id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err = s.Get(t.Context(), d.EdgesKey); err != nil {
+ t.Fatal("deleted without a published post-evidence inventory", err)
+ }
+ }
+}
+
+func TestDepartureInventoryCompletionNudge(t *testing.T) {
+ c, a, s, v, id := departureInventoryRig(t)
+ start := time.Now()
+ now := start
+ c.cfg.Now = func() time.Time { return now }
+ if _, err := c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.Registry.SaveDepartureScan(t.Context(), id, "scanning", registry.HADepartureScan{}); err != nil {
+ t.Fatal(err)
+ }
+ epoch := v.Snapshot().Epoch
+ for _, seconds := range []int{30, 60} {
+ now = start.Add(time.Duration(seconds) * time.Second)
+ // Resume completion while the new inventory has not yet been published.
+ scan, err := a.Registry.DepartureScan(t.Context(), id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ scan.Generation = departureInventoryDigest(c.cfg.Inventory())
+ if err = a.Registry.SaveDepartureScan(t.Context(), id, "authority_complete", scan); err != nil {
+ t.Fatal(err)
+ }
+ if err = c.Complete(t.Context(), id); err != nil {
+ t.Fatal(err)
+ }
+ want := epoch
+ if seconds == 60 {
+ want++
+ }
+ if got := v.Snapshot().Epoch; got != want {
+ t.Fatalf("completion at %ds: epoch %d, want %d", seconds, got, want)
+ }
+ d, err := a.Registry.Departure(t.Context(), id)
+ if err != nil || d.Phase != "scanning" {
+ t.Fatalf("stale completion did not return to scanning: %+v %v", d, err)
+ }
+ if _, _, err = s.Get(t.Context(), d.EdgesKey); err != nil {
+ t.Fatal("stale completion deleted edges", err)
+ }
+ }
+}
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index f280c95e1..1c0c63353 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -136,6 +136,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
d.Phase = "scanning"
}
if !inv.FreshAfter(d.ObservedAt) {
+ c.requestInventory(ctx, d.ID)
return false, c.retryScan(ctx, d, nil, "inventory", c.now().Sub(d.ObservedAt) > release.ChangeIndexBackstop+release.ChangeIndexBackstop/10)
}
if c.cfg.NewReader == nil || c.cfg.Prefix == nil {
@@ -433,6 +434,9 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) {
}
inv := c.cfg.Inventory()
if !inv.FreshAfter(d.ObservedAt) || departureInventoryDigest(inv) != s.Generation {
+ if !inv.FreshAfter(d.ObservedAt) {
+ c.requestInventory(ctx, id)
+ }
s.Cursor = 0
s.Rescan = false
s.Generation = ""
@@ -527,12 +531,30 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) {
if err = save("complete"); err != nil {
return err
}
+ delete(c.inventoryRequests, id)
c.telemetry.mu.Lock()
c.telemetry.sample.Completions++
c.telemetry.mu.Unlock()
c.logf("Recovered duties for %d instances from box %s.", len(s.Hosts), d.Box.Ref)
return c.ackDeparture(ctx, d)
}
+
+// requestInventory runs under scanMu. A failed or unpublished rebuild may be
+// requested again after 60 s; it never substitutes for FreshAfter's full walk.
+func (c *Controller) requestInventory(ctx context.Context, id string) {
+ if c.cfg.RequestInventory == nil {
+ return
+ }
+ now := c.now()
+ if last, ok := c.inventoryRequests[id]; ok && now.Sub(last) < 60*time.Second {
+ return
+ }
+ if c.inventoryRequests == nil {
+ c.inventoryRequests = map[string]time.Time{}
+ }
+ c.inventoryRequests[id] = now
+ c.cfg.RequestInventory(ctx)
+}
func defaultDepartureReader(ctx context.Context, region string) (DepartureLockReader, error) {
return lease.NewLockReader(ctx, region)
}
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go
index 33c804083..dbac38bb9 100644
--- a/internal/host/hadepartures_wiring.go
+++ b/internal/host/hadepartures_wiring.go
@@ -110,7 +110,7 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
return api, nil
}
}
- c, err := NewController(DepartureConfig{Admitted: a.Admitted, BeginWork: a.BeginWork, Registry: a.Registry, OpenStore: a.OpenStore, NewReader: defaultDepartureReader, Prefix: func(host string) string { return activator.HibernatePrefix(a.Backend.Cfg.Prefix, host) }, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, Policy: func() LocalPolicy {
+ c, err := NewController(DepartureConfig{Admitted: a.Admitted, BeginWork: a.BeginWork, Registry: a.Registry, OpenStore: a.OpenStore, NewReader: defaultDepartureReader, Prefix: func(host string) string { return activator.HibernatePrefix(a.Backend.Cfg.Prefix, host) }, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, RequestInventory: requestDepartureInventory, Policy: func() LocalPolicy {
return LocalPolicy{Scope: a.Self.Scope, Pools: provisionTickConfig(a.Getenv).Pools, Inbound: provisionTickConfig(a.Getenv).Inbound}
}, Invalidate: a.Service.InvalidateDutyHolder, PageIdentity: func(ctx context.Context, h registry.HAPendingTermination, code string) error {
return PageOperator(ctx, alerting.LevelWarning, "ha_departure_pending", fmt.Sprintf("code=%s account=%s region=%s iid=%s", code, h.Account, h.Region, h.IID))