carlos / platform Public

host: bound departure nudges and run them on the backstop

Coalesce inventory requests on the agent-lifetime backstop loop.
Use three global round timestamps to cap retries for each evidence
window without retaining departure IDs. Keep unindexed full passes
working and cover deadlines, failed walks, coalescing and shared budgets.
Implemented-by: Astra (codex)
claude pushed by paul@keymail.dev a5ecbe76aa5f94e50250ecb091edf1620f0fd488 parent 445e881
5 files changed, +411 −47
  • internal/host/agent.go +2 −2
  • internal/host/changeindex.go +84 −20
  • internal/host/hadepartures.go +1 −3
  • internal/host/hadepartures_inventory_test.go +317 −5
  • internal/host/hadepartures_scan.go +7 −17

Intent

Human

<task-notification> <task-id>bah09311w</task-id> <tool-use-id>toolu_01JtaAJoq6EyRwbjw6di3fqe</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/87a21814-5655-4016-9e7e-41935ee8e96e/tasks/bah09311w.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; echo "Task 2: dispatched (Astra, base 68082f7b)" &gt;&gt; $W/progress.md; for i in $(seq 1 340); do [ -f $W/t2.done ] &amp;&amp; break; sleep 10; done; cat $W/t2.done 2&gt;/dev/null; tail -2 $W/t2.log" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 12.5 g CO₂e (1,435,010 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/agent.go b/internal/host/agent.go
index 3190cf693..fe7325fc0 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1003,11 +1003,11 @@ func runAgent(args []string, buildClaims ClaimFactory) {
startRelocationPass(agentCtx, claimCtx, claims, reg, svc)
// The change index (S3 change-index design §4): armed before the
// loops that read through it, with its backstop running from here.
- // Unset CARLOS_CHANGE_INDEX, or a fleet box: nothing.
+ // Without an index the backstop loop handles early full-pass requests.
v := armChangeIndex(agentCtx, os.Getenv, openDeployStore)
go func() {
runHAIngressStartup(agentCtx, openDeployStore, boxJudge, reg)
- if v != nil && agentCtx.Err() == nil {
+ if agentCtx.Err() == nil {
recordViewBackstopLoop(agentCtx, v)
}
}()
diff --git a/internal/host/changeindex.go b/internal/host/changeindex.go
index e32db5743..954994fd3 100644
--- a/internal/host/changeindex.go
+++ b/internal/host/changeindex.go
@@ -150,43 +150,107 @@ func viewStore(ctx context.Context, live release.Store) (s release.Store, epoch
// unrestricted full pass, so every leg is re-run over everything at least
// that often. The full pass runs on the fast converge loop's goroutine
// (backstopFullDue); on a box where that loop is not armed only the
-// rebuild runs.
+// rebuild runs. With no view, only early requests run; the existing live-store
+// reconcile loops retain their normal cadence.
func recordViewBackstopLoop(ctx context.Context, v *provision.RecordView) {
- for {
+ var timer *time.Timer
+ var tick <-chan time.Time
+ if v != nil {
recordViewBackstop(ctx, v, &backstopFullDue)
+ timer = time.NewTimer(backstopEvery())
+ defer timer.Stop()
+ tick = timer.C
+ }
+ for {
select {
case <-ctx.Done():
return
- case <-time.After(backstopEvery()):
+ case <-departureInventoryNudges.wake:
+ if ctx.Err() == nil && departureInventoryNudges.begin() {
+ recordViewBackstop(ctx, v, &backstopFullDue)
+ }
+ case <-tick:
+ recordViewBackstop(ctx, v, &backstopFullDue)
+ timer.Reset(backstopEvery())
}
}
}
// recordViewBackstop is one backstop round: the rebuild, then the request
-// for a full pass, whether or not the rebuild succeeded (a failed one
-// leaves the view unable to vouch, so that pass walks).
+// for a full pass, whether or not the rebuild succeeded. Without an index,
+// the full pass walks the live store and publishes the departure inventory.
func recordViewBackstop(ctx context.Context, v *provision.RecordView, due *atomic.Bool) {
- err := v.Rebuild(ctx)
- publishHAIngressSnapshot(v.Snapshot(), err)
- if err != nil {
- log.Printf("agent: record view backstop: %v", err)
+ if v != nil {
+ err := v.Rebuild(ctx)
+ publishHAIngressSnapshot(v.Snapshot(), err)
+ if err != nil {
+ log.Printf("agent: record view backstop: %v", err)
+ }
}
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)
+// Three start times cover every departure observed before those rounds began.
+// Keeping only those times bounds memory even when another path abandons or
+// acknowledges a departure. A new controller does not reset the process budget.
+type inventoryNudger struct {
+ mu sync.Mutex
+ wake chan struct{}
+ now func() time.Time
+ starts [3]time.Time
+ pending time.Time
+}
+
+func newInventoryNudger(now func() time.Time) *inventoryNudger {
+ return &inventoryNudger{wake: make(chan struct{}, 1), now: now}
+}
+
+var departureInventoryNudges = newInventoryNudger(time.Now)
+
+func (n *inventoryNudger) eligible(observed, now time.Time) bool {
+ return now.After(observed) && !n.starts[0].After(observed) && (n.starts[2].IsZero() || now.Sub(n.starts[2]) >= time.Minute)
+}
+
+func (n *inventoryNudger) request(observed time.Time) {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ if !n.eligible(observed, n.now()) {
return
}
- backstopFullDue.Store(true)
+ if observed.After(n.pending) {
+ n.pending = observed
+ }
+ select {
+ case n.wake <- struct{}{}:
+ default:
+ }
+}
+
+func (n *inventoryNudger) begin() bool {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ now := n.now()
+ observed := n.pending
+ n.pending = time.Time{}
+ if observed.IsZero() || !n.eligible(observed, now) {
+ return false
+ }
+ n.starts[0], n.starts[1], n.starts[2] = n.starts[1], n.starts[2], now
+ return true
+}
+
+// requestDepartureInventory only signals the agent-lifetime backstop loop.
+// Early rounds are globally spaced by at least 60 s, with at most three after
+// any given departure evidence. One round serves all evidence predating its
+// start, even departures not scanned yet. Exhausted evidence waits for the
+// regular backstop; early rounds do not postpone that backstop.
+// Each indexed round costs one index GET and a full record walk: paginated
+// LISTs of accounts, apps, instances and sidecars, account and app metadata
+// GETs, and GETs for changed record bodies. Unchanged ETags reuse bodies.
+// The requested full converge pass has its usual additional reads. Without
+// an index, only that live-store full pass is requested.
+func requestDepartureInventory(_ context.Context, observed time.Time) {
+ departureInventoryNudges.request(observed)
}
// backstopEvery is release.ChangeIndexBackstop jittered by +-10%.
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go
index 2218c986d..7f564847f 100644
--- a/internal/host/hadepartures.go
+++ b/internal/host/hadepartures.go
@@ -76,7 +76,7 @@ type DepartureConfig struct {
Self hadeparture.Box
DeploymentBucket string
Inventory func() provision.InventorySnapshot
- RequestInventory func(context.Context)
+ RequestInventory func(context.Context, time.Time)
Policy func() LocalPolicy
Invalidate func(string, string)
Now func() time.Time
@@ -100,8 +100,6 @@ 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
index 3cc8b50e0..48d46add0 100644
--- a/internal/host/hadepartures_inventory_test.go
+++ b/internal/host/hadepartures_inventory_test.go
@@ -4,7 +4,10 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"os"
+ "strings"
+ "sync/atomic"
"testing"
"time"
@@ -18,14 +21,19 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-func departureInventoryRig(t *testing.T) (*Controller, departureArm, release.Store, *provision.RecordView, string) {
+func departureInventoryRig(t *testing.T, withoutIndex ...bool) (*Controller, departureArm, release.Store, *provision.RecordView, string) {
t.Helper()
+ oldNudges := departureInventoryNudges
+ departureInventoryNudges = newInventoryNudger(time.Now)
+ t.Cleanup(func() { departureInventoryNudges = oldNudges })
locks := locktest.NewLockFixture(t)
a, _, _ := departureArmFixtureBucket(t, locks.Bucket)
s, err := a.OpenStore(t.Context())
if err != nil {
t.Fatal(err)
}
+ s = &departureInventoryStore{DirStore: s.(*release.DirStore), entered: make(chan struct{}, 1), release: make(chan struct{})}
+ a.OpenStore = func(context.Context) (release.Store, error) { return s, nil }
signer := boxidtest.NewSigner(t)
a.Verifier = boxid.Verifier{Account: a.Self.Account, Certs: signer.Certs()}
iid := "i-2123456789abcdef0"
@@ -63,6 +71,14 @@ func departureInventoryRig(t *testing.T) (*Controller, departureArm, release.Sto
boxHAIngress.routes.Store(oldRoutes)
})
v := armView(t, s)
+ if len(withoutIndex) > 0 && withoutIndex[0] {
+ disarmView(t)
+ v = nil
+ }
+ startInventoryBackstop(t, v)
+ if v != nil {
+ waitInventoryRound(t)
+ }
departureInventoryReconcile(t, a, s)
if inv := a.Inventory.Snapshot(); !inv.Complete || len(inv.Records) != 1 {
t.Fatalf("initial inventory: %+v", inv)
@@ -112,9 +128,7 @@ func TestDepartureInventoryNudgeRetiresGroup(t *testing.T) {
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")
- }
+ waitInventoryRound(t)
departureInventoryReconcile(t, a, s)
if !c.cfg.Inventory().FreshAfter(d.ObservedAt) {
t.Fatal("nudge did not produce a full walk started after evidence")
@@ -143,11 +157,13 @@ func TestDepartureInventoryNudgeRateLimit(t *testing.T) {
now := start
c.cfg.Now = func() time.Time { return now }
epoch := v.Snapshot().Epoch
+ walks := uint64(0)
for _, check := range []struct {
seconds int
walks uint64
- }{{0, 1}, {30, 1}, {59, 1}, {60, 2}} {
+ }{{0, 1}, {30, 1}, {59, 1}, {60, 2}, {120, 3}, {180, 3}, {1200, 3}} {
now = start.Add(time.Duration(check.seconds) * time.Second)
+ setInventoryNudgeTime(now)
// 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)
@@ -155,6 +171,10 @@ func TestDepartureInventoryNudgeRateLimit(t *testing.T) {
if _, err := c.ScanPass(t.Context()); err != nil {
t.Fatal(err)
}
+ if check.walks > walks {
+ waitInventoryRound(t)
+ walks = check.walks
+ }
if got := v.Snapshot().Epoch - epoch; got != check.walks {
t.Fatalf("at %ds: full rebuilds = %d, want %d", check.seconds, got, check.walks)
}
@@ -173,15 +193,18 @@ func TestDepartureInventoryCompletionNudge(t *testing.T) {
start := time.Now()
now := start
c.cfg.Now = func() time.Time { return now }
+ setInventoryNudgeTime(now)
if _, err := c.ScanPass(t.Context()); err != nil {
t.Fatal(err)
}
+ waitInventoryRound(t)
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)
+ setInventoryNudgeTime(now)
// Resume completion while the new inventory has not yet been published.
scan, err := a.Registry.DepartureScan(t.Context(), id)
if err != nil {
@@ -196,6 +219,7 @@ func TestDepartureInventoryCompletionNudge(t *testing.T) {
}
want := epoch
if seconds == 60 {
+ waitInventoryRound(t)
want++
}
if got := v.Snapshot().Epoch; got != want {
@@ -210,3 +234,291 @@ func TestDepartureInventoryCompletionNudge(t *testing.T) {
}
}
}
+
+// Keep the real directory store and its optional interfaces; delay only the
+// record listing to model a walk that outlives a departure step.
+type departureInventoryStore struct {
+ *release.DirStore
+ block atomic.Bool
+ fail atomic.Bool
+ entered chan struct{}
+ release chan struct{}
+}
+
+func (s *departureInventoryStore) wait(ctx context.Context, prefix string) error {
+ if !strings.HasPrefix(prefix, "apps/") {
+ return nil
+ }
+ if s.fail.Load() {
+ return errors.New("inventory listing unavailable")
+ }
+ if s.block.Load() {
+ select {
+ case s.entered <- struct{}{}:
+ default:
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-s.release:
+ }
+ }
+ return nil
+}
+
+func (s *departureInventoryStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) {
+ if err := s.wait(ctx, prefix); err != nil {
+ return nil, err
+ }
+ return s.DirStore.ListETags(ctx, prefix)
+}
+
+func (s *departureInventoryStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if err := s.wait(ctx, prefix); err != nil {
+ return nil, err
+ }
+ return s.DirStore.List(ctx, prefix)
+}
+
+func TestDepartureInventoryNudgeStepDeadline(t *testing.T) {
+ c, _, s, v, _ := departureInventoryRig(t)
+ before := v.Snapshot()
+ stalled := s.(*departureInventoryStore)
+ stalled.block.Store(true)
+ ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
+ defer cancel()
+ _, scanErr := c.ScanPass(ctx)
+ select {
+ case <-stalled.entered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("early backstop did not start")
+ }
+ <-ctx.Done()
+ if sn := v.Snapshot(); !sn.Complete || sn.Epoch != before.Epoch {
+ t.Fatalf("step nudge changed complete view: complete=%v epoch=%d, want %d", sn.Complete, sn.Epoch, before.Epoch)
+ }
+ if scanErr != nil {
+ t.Fatal(scanErr)
+ }
+ // A second scan can take scanMu while the worker's real store walk is blocked.
+ if _, err := c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ close(stalled.release)
+ waitInventoryRound(t)
+ if sn := v.Snapshot(); !sn.Complete || sn.Epoch != before.Epoch+1 {
+ t.Fatalf("agent-lifetime walk did not finish complete: %+v", sn)
+ }
+}
+
+func startInventoryBackstop(t *testing.T, v *provision.RecordView) {
+ t.Helper()
+ ctx, cancel := context.WithCancel(t.Context())
+ done := make(chan struct{})
+ go func() { defer close(done); recordViewBackstopLoop(ctx, v) }()
+ t.Cleanup(func() { cancel(); <-done })
+}
+
+func waitInventoryRound(t *testing.T) {
+ t.Helper()
+ deadline := time.Now().Add(3 * time.Second)
+ for !backstopFullDue.Swap(false) {
+ if time.Now().After(deadline) {
+ t.Fatal("early backstop did not request the full pass")
+ }
+ time.Sleep(time.Millisecond)
+ }
+}
+
+func setInventoryNudgeTime(now time.Time) {
+ n := departureInventoryNudges
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ n.now = func() time.Time { return now.Add(time.Millisecond) }
+}
+
+func TestDepartureInventoryNudgeGlobalBudget(t *testing.T) {
+ for _, failed := range []bool{false, true} {
+ t.Run(fmt.Sprintf("failed_walk=%v", failed), func(t *testing.T) { departureInventoryGlobalBudget(t, failed) })
+ }
+}
+
+func departureInventoryGlobalBudget(t *testing.T, failed bool) {
+ c, a, s, v, id := departureInventoryRig(t)
+ d, err := a.Registry.Departure(t.Context(), id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.(*departureInventoryStore).fail.Store(failed)
+ ids := []string{id}
+ c.evidence[id] = true
+ for i := 1; i < 12; i++ {
+ other := d
+ other.Box.InstanceID = fmt.Sprintf("i-%017x", i)
+ other.Box.Ref = groupReferenceOf(other.Box.Account, other.Box.InstanceID)
+ other.ID = departureID(c.cfg.DeploymentBucket, other.Box)
+ other.EdgesKey = "control/edges/" + other.Box.Ref + ".json"
+ raw, err := json.Marshal(edgesfile.PlacementView{V: 1, Box: other.Box.Ref, BoxID: other.Box.Ref, Region: a.Self.Scope.CloudRegion, DataBucket: a.Self.Scope.DataBucket, SecretsKeyFP: a.Self.Scope.SecretsKeyFP})
+ if err != nil {
+ t.Fatal(err)
+ }
+ other.EdgesETag, err = s.Put(t.Context(), other.EdgesKey, raw, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = a.Registry.EnrollDeparture(t.Context(), other, ""); err != nil {
+ t.Fatal(err)
+ }
+ c.evidence[other.ID] = true
+ ids = append(ids, other.ID)
+ }
+ start := time.Now()
+ now := start
+ c.cfg.Now = func() time.Time { return now }
+ epoch := v.Snapshot().Epoch
+ for round := 0; round < 6; round++ {
+ now = start.Add(time.Duration(round) * time.Minute)
+ setInventoryNudgeTime(now)
+ for _, id := range ids {
+ if _, err := a.Registry.RetryDeparture(t.Context(), id, now, now, "reserve", false); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := range ids {
+ if _, err := c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ // Finish the shared round before the other eleven departures even ask.
+ if i == 0 && round < 3 {
+ waitInventoryRound(t)
+ if failed && v.Snapshot().Complete {
+ t.Fatal("failed listing did not invalidate the view")
+ }
+ }
+ }
+ if got, want := v.Snapshot().Epoch-epoch, uint64(min(round+1, 3)); got != want {
+ t.Fatalf("round %d: twelve stuck departures caused %d rebuilds, want %d", round, got, want)
+ }
+ if len(departureInventoryNudges.wake) != 0 {
+ t.Fatal("excess nudge queued")
+ }
+ }
+ for _, id := range ids {
+ row, err := a.Registry.Departure(t.Context(), id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := s.Get(t.Context(), row.EdgesKey); err != nil {
+ t.Fatal("stale inventory deleted edges", err)
+ }
+ }
+ // Later evidence gets a fresh budget; old evidence still cannot request work.
+ now = now.Add(time.Minute)
+ if err := a.Registry.ReobserveDeparture(t.Context(), id, now); err != nil {
+ t.Fatal(err)
+ }
+ now = now.Add(time.Second)
+ setInventoryNudgeTime(now)
+ if _, err := a.Registry.RetryDeparture(t.Context(), id, now, now, "reserve", false); err != nil {
+ t.Fatal(err)
+ }
+ // Move the other rows out of this scan's page.
+ for _, other := range ids[1:] {
+ if _, err := a.Registry.RetryDeparture(t.Context(), other, now, now.Add(time.Hour), "reserve", false); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ waitInventoryRound(t)
+ if got := v.Snapshot().Epoch - epoch; got != 4 {
+ t.Fatalf("new evidence rebuilds=%d, want 4", got)
+ }
+}
+
+func TestDepartureInventoryNudgeWithoutIndex(t *testing.T) {
+ c, a, s, v, id := departureInventoryRig(t, true)
+ if v != nil || armedChangeWatch.Load() != nil || armedRecordView.Load() != nil {
+ t.Fatal("index still armed")
+ }
+ now := time.Now()
+ c.cfg.Now = func() time.Time { return now }
+ setInventoryNudgeTime(now)
+ if _, err := c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ waitInventoryRound(t)
+ // fastConvergeLoop supplies fullDue independently of the change-index gate.
+ // Exercise its real tick and reconcile with the directory store and registry.
+ d, _, _, _ := ciFastDeps(t)
+ d.watch = nil
+ d.store = s
+ d.reg = a.Registry
+ d.fullDue = &backstopFullDue
+ d.fullPass = func(context.Context) { departureInventoryReconcile(t, a, s) }
+ backstopFullDue.Store(true)
+ fastTick(t.Context(), d, now)
+ if backstopFullDue.Load() {
+ t.Fatal("unindexed fast tick did not consume fullDue")
+ }
+ row, err := a.Registry.Departure(t.Context(), id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !c.cfg.Inventory().FreshAfter(row.ObservedAt) {
+ t.Fatal("live-store pass did not refresh departure inventory")
+ }
+ for range 2 {
+ now = now.Add(30 * time.Second)
+ if err := c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ row, err = a.Registry.Departure(t.Context(), id)
+ if err != nil || row.Phase != "complete" {
+ t.Fatalf("unindexed retirement: %+v %v", row, err)
+ }
+ if _, _, err := s.Get(t.Context(), row.EdgesKey); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("unindexed edges retained: %v", err)
+ }
+}
+
+func TestDepartureInventoryNudgeCoalesces(t *testing.T) {
+ c, a, s, v, id := departureInventoryRig(t)
+ d, err := a.Registry.Departure(t.Context(), id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ before := v.Snapshot().Epoch
+ stalled := s.(*departureInventoryStore)
+ stalled.block.Store(true)
+ now := time.Now()
+ setInventoryNudgeTime(now)
+ c.cfg.RequestInventory(t.Context(), d.ObservedAt)
+ select {
+ case <-stalled.entered:
+ case <-time.After(3 * time.Second):
+ t.Fatal("early round did not start")
+ }
+ // Many requests arrive while the first walk is still running. Their only
+ // effect is one queued round, and none waits for the walk's mutex.
+ setInventoryNudgeTime(now.Add(time.Minute))
+ for range 1000 {
+ c.cfg.RequestInventory(t.Context(), d.ObservedAt)
+ }
+ if got := len(departureInventoryNudges.wake); got != 1 {
+ t.Fatalf("queued rounds=%d, want 1", got)
+ }
+ close(stalled.release)
+ deadline := time.Now().Add(3 * time.Second)
+ for v.Snapshot().Epoch != before+2 {
+ if time.Now().After(deadline) {
+ t.Fatalf("coalesced rounds: epoch=%d, want %d", v.Snapshot().Epoch, before+2)
+ }
+ time.Sleep(time.Millisecond)
+ }
+ if !v.Snapshot().Complete {
+ t.Fatal("coalesced walk incomplete")
+ }
+}
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index 1c0c63353..7eeb11ec6 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -136,7 +136,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
d.Phase = "scanning"
}
if !inv.FreshAfter(d.ObservedAt) {
- c.requestInventory(ctx, d.ID)
+ c.requestInventory(ctx, d.ObservedAt)
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 {
@@ -435,7 +435,7 @@ 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)
+ c.requestInventory(ctx, d.ObservedAt)
}
s.Cursor = 0
s.Rescan = false
@@ -531,7 +531,6 @@ 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()
@@ -539,21 +538,12 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) {
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
+// 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) {
+ if c.cfg.RequestInventory != nil {
+ c.cfg.RequestInventory(ctx, observed)
}
- 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)