host: retry transient HA ingress reads within bounded startup attempts
Transient record reads left scopes pending until another startup attempt, while the shared reconcile lock could hold tenant admission closed. Retry failed scopes once in the same refresh, and budget startup at 5 seconds plus 50 milliseconds per observed record scope, capped at 20 seconds. Prove the lock coupling and two-refresh baseline before the fix, then cover retry bounds, cancellation, generations, and real startup deadlines.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
internal/host/haingress.go+30 −3internal/host/haingress_g3_test.go+275 −0internal/provision/recordview.go+21 −3internal/provision/recordview_g3_test.go+125 −0
Intent
<task-notification> <task-id>bd5rsdr04</task-id> <tool-use-id>toolu_01LhPR8NzWBPs9eLtr5SGgfV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/f72ef775-81b3-4d2e-a18d-c8edb14aa192/tasks/bd5rsdr04.output</output-file> <status>completed</status> <summary>Background command "sleep 15; .superpowers/sdd/2026-11-07-region-ha-g3-fixes/wait.sh t1f1" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 5.05 g CO₂e (620,216 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/haingress.go b/internal/host/haingress.go| index 37a0c4833..889d1d915 100644 |
| --- a/internal/host/haingress.go |
| +++ b/internal/host/haingress.go |
| @@ -5,6 +5,7 @@ import ( |
| "errors" |
| "log" |
| "os" |
| + "strings" |
| "sync" |
| "sync/atomic" |
| "time" |
| @@ -136,10 +137,36 @@ func wireHAIngressScan(ctx context.Context, s release.Store, cfg *provision.Reco |
| } |
| } |
| -// haIngressStartupAttempt bounds each startup attempt, its alias pass |
| -// included. |
| +// haIngressStartupAttempt is the base budget, including the alias pass. |
| const haIngressStartupAttempt = 5 * time.Second |
| +func haIngressStartupContext(ctx context.Context) (context.Context, context.CancelFunc) { |
| + start := time.Now() |
| + scopes := 0 |
| + if v := armedRecordView.Load(); v != nil { |
| + watch := v.Watch() |
| + observed, usable := watch.Observed() |
| + if !usable { |
| + // A cold watch has no count yet. Charge this bounded index read |
| + // to the attempt, before taking reconcileMu. |
| + poll, cancel := context.WithTimeout(ctx, haIngressStartupAttempt) |
| + _, _ = watch.Poll(poll) |
| + cancel() |
| + observed, _ = watch.Observed() |
| + } |
| + for scope := range observed { |
| + _, _, app := provision.ScopeApp(scope) |
| + account, acct := strings.CutPrefix(scope, "accounts/") |
| + if app || (acct && account != "" && !strings.Contains(account, "/")) { |
| + scopes++ |
| + } |
| + } |
| + } |
| + // At 300 scopes the budget reaches its 20-second cap. |
| + budget := haIngressStartupAttempt + time.Duration(min(scopes, 300))*50*time.Millisecond |
| + return context.WithDeadline(ctx, start.Add(budget)) |
| +} |
| + |
| // runHAIngressStartup finishes after success or three retries. The existing |
| // instances and record-view loops own every later refresh. |
| func runHAIngressStartup(ctx context.Context, open func(context.Context) (release.Store, error), judge *provision.LifetimeJudge, reg *registry.Registry) { |
| @@ -156,7 +183,7 @@ func runHAIngressStartup(ctx context.Context, open func(context.Context) (releas |
| if ctx.Err() != nil { |
| return |
| } |
| - attempt, cancel := context.WithTimeout(ctx, haIngressStartupAttempt) |
| + attempt, cancel := haIngressStartupContext(ctx) |
| attempt = provision.WithLifetimes(attempt, judge) |
| err := refreshHAIngressAtStart(attempt, open, judge) |
| if err == nil { |
diff --git a/internal/host/haingress_g3_test.go b/internal/host/haingress_g3_test.go| new file mode 100644 |
| index 000000000..4b9b8f99e |
| --- /dev/null |
| +++ b/internal/host/haingress_g3_test.go |
| @@ -0,0 +1,275 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxroles" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/groupadmission" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type g3StartupStore struct { |
| + *ciCountingStore |
| + mu sync.Mutex |
| + fail map[string]int |
| + reads map[string]int |
| + entered chan struct{} |
| + resume chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func (s *g3StartupStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + s.mu.Lock() |
| + _, injected := s.fail[prefix] |
| + failed := injected && s.reads[prefix] == 1 |
| + s.mu.Unlock() |
| + if failed { |
| + return nil, fmt.Errorf("transient scope read (List fallback)") |
| + } |
| + return s.ciCountingStore.List(ctx, prefix) |
| +} |
| + |
| +func (s *g3StartupStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) { |
| + s.mu.Lock() |
| + s.reads[prefix]++ |
| + fail := s.fail[prefix] > 0 |
| + if fail { |
| + s.fail[prefix]-- |
| + } |
| + s.mu.Unlock() |
| + if fail { |
| + if s.entered != nil { |
| + s.once.Do(func() { close(s.entered) }) |
| + select { |
| + case <-s.resume: |
| + case <-ctx.Done(): |
| + return nil, ctx.Err() |
| + } |
| + } |
| + return nil, fmt.Errorf("transient scope read") |
| + } |
| + return s.ciCountingStore.ListETags(ctx, prefix) |
| +} |
| + |
| +func g3StartupFixture(t *testing.T) (*g3StartupStore, *provision.RecordView) { |
| + t.Helper() |
| + t.Setenv("CARLOS_HOST_CLAIM", "") |
| + t.Setenv("CARLOS_REGION_HA", "true") |
| + t.Setenv("CARLOS_REGION", "") |
| + s := &g3StartupStore{ciCountingStore: newCICountingStore(t), fail: map[string]int{}, reads: map[string]int{}} |
| + a := domains.Sqid(2) |
| + if _, err := s.Put(t.Context(), "accounts/"+a+"/account.json", []byte(fmt.Sprintf(`{"id":2,"sqid":%q,"name":"fixture"}`, a)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 79; i++ { |
| + app := fmt.Sprintf("app%02d", i) |
| + rec := provision.Record{Schema: 1, Host: app + ".example.com", Slug: app, Account: a, App: app, Channel: "stable", Region: "elsewhere", CreatedAt: time.Now()} |
| + if err := provision.CreateRecord(t.Context(), s, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + oldWatch, oldView := armedChangeWatch.Load(), armedRecordView.Load() |
| + v := armChangeIndex(t.Context(), admissionEnv, func(context.Context) (release.Store, error) { return s, nil }) |
| + t.Cleanup(func() { armedChangeWatch.Store(oldWatch); armedRecordView.Store(oldView) }) |
| + if v == nil { |
| + t.Fatal("view not armed") |
| + } |
| + if err := v.Refresh(t.Context()); err != nil || !v.Snapshot().Complete { |
| + t.Fatalf("initial view: %v", err) |
| + } |
| + for i := 0; i < 79; i++ { |
| + app := fmt.Sprintf("app%02d", i) |
| + if err := provision.PutManifest(t.Context(), s, a, app, provision.Manifest{Schema: 1, App: app, Domain: "example.com"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if i < 8 { |
| + s.fail[provision.RecordsPrefix(a, app)] = 1 |
| + } |
| + } |
| + s.reset() |
| + s.reads = map[string]int{} |
| + aliasClaimCache.Reset() |
| + oldAuthority := boxAssetAuthority |
| + boxAssetAuthority = newAssetAuthority(nil) |
| + t.Cleanup(func() { |
| + aliasClaimCache.Reset() |
| + boxAssetAuthority = oldAuthority |
| + }) |
| + oldRoutes, oldAliases, oldRegional, oldEpoch := boxHAIngress.routes.Load(), boxHAIngress.aliases.Load(), boxHAIngress.regional.Load(), boxHAIngress.epoch |
| + boxHAIngress.routes.Store(nil) |
| + boxHAIngress.aliases.Store(nil) |
| + boxHAIngress.regional.Store(nil) |
| + boxHAIngress.epoch = 0 |
| + t.Cleanup(func() { |
| + boxHAIngress.routes.Store(oldRoutes) |
| + boxHAIngress.aliases.Store(oldAliases) |
| + boxHAIngress.regional.Store(oldRegional) |
| + boxHAIngress.epoch = oldEpoch |
| + }) |
| + return s, v |
| +} |
| + |
| +func TestG3StartupTransientScopeRefreshes(t *testing.T) { |
| + s, v := g3StartupFixture(t) |
| + reg := edgesTestRegistry(t) |
| + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) |
| + defer cancel() |
| + runHAIngressStartup(ctx, func(context.Context) (release.Store, error) { return s, nil }, newBoxJudge(claimsOffEnv), reg) |
| + if ctx.Err() != nil || !v.Snapshot().Complete { |
| + t.Fatalf("startup incomplete: %v", ctx.Err()) |
| + } |
| + got := s.count("GetIfChanged", release.ChangeIndexKey) |
| + t.Logf("80 scopes, 8 transient failures: startup required %d refreshes", got) |
| + if got != 1 { |
| + t.Fatalf("refreshes = %d, want 1", got) |
| + } |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + for prefix, reads := range s.reads { |
| + if !strings.HasSuffix(prefix, "/instances/") { |
| + continue |
| + } |
| + want := 1 |
| + if _, failed := s.fail[prefix]; failed { |
| + want = 2 |
| + } |
| + if reads != want { |
| + t.Errorf("%s read %d times, want %d", prefix, reads, want) |
| + } |
| + } |
| +} |
| + |
| +func TestG3StartupAttemptBudget(t *testing.T) { |
| + for _, mode := range []string{"no-view", "warm", "cold", "cap", "parent"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, v := g3StartupFixture(t) |
| + s.fail = map[string]int{} |
| + want := 9 * time.Second // 79 apps and one account. |
| + if mode == "no-view" { |
| + armedRecordView.Store(nil) |
| + want = 5 * time.Second |
| + } |
| + if mode == "cap" { |
| + entries, _ := v.Watch().Observed() |
| + for i := 0; i < 400; i++ { |
| + entries[fmt.Sprintf("apps/bac/old%03d", i)] = 1 |
| + } |
| + body, err := json.Marshal(release.ChangeIndex{Schema: 1, Entries: entries}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, etag, err := s.Get(t.Context(), release.ChangeIndexKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.Put(t.Context(), release.ChangeIndexKey, body, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + want = 20 * time.Second |
| + } |
| + if mode == "cold" || mode == "cap" { |
| + v = armChangeIndex(t.Context(), admissionEnv, func(context.Context) (release.Store, error) { return s, nil }) |
| + } |
| + reg := edgesTestRegistry(t) |
| + parent := t.Context() |
| + var parentDeadline time.Time |
| + if mode == "parent" { |
| + var cancel context.CancelFunc |
| + parentDeadline = time.Now().Add(time.Second) |
| + parent, cancel = context.WithDeadline(parent, parentDeadline) |
| + defer cancel() |
| + } |
| + var deadlines []time.Time |
| + start := time.Now() |
| + runHAIngressStartup(parent, func(ctx context.Context) (release.Store, error) { |
| + deadline, ok := ctx.Deadline() |
| + if !ok { |
| + t.Error("startup has no deadline") |
| + } |
| + deadlines = append(deadlines, deadline) |
| + return s, nil |
| + }, newBoxJudge(claimsOffEnv), reg) |
| + if len(deadlines) == 0 { |
| + t.Fatal("startup did not reach alias pass") |
| + } |
| + for _, deadline := range deadlines { |
| + if mode == "parent" { |
| + if !deadline.Equal(parentDeadline) { |
| + t.Errorf("startup exceeded parent deadline: %v", deadline) |
| + } |
| + } else if got := deadline.Sub(start); got < want || got > want+100*time.Millisecond { |
| + t.Errorf("startup budget = %s, want %s", got, want) |
| + } |
| + } |
| + if mode != "no-view" && !v.Snapshot().Complete { |
| + t.Fatal("startup view incomplete") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestG3StartupHoldsAdmissionReconcile(t *testing.T) { |
| + s, _ := g3StartupFixture(t) |
| + s.entered, s.resume = make(chan struct{}), make(chan struct{}) |
| + a := newFixedAdmission(admissionEnv, admissionHealth()) |
| + oldAdmission := armedFixedAdmission.Swap(a) |
| + oldInventory := boxDepartureInventory |
| + boxDepartureInventory = &provision.DepartureInventory{} |
| + t.Cleanup(func() { armedFixedAdmission.Store(oldAdmission); boxDepartureInventory = oldInventory }) |
| + if err := a.applyRole(boxroles.Serve, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.observe(groupadmission.Facts{EnvLoaded: true, RolePublished: true, TerminationStarted: true}) |
| + reg := edgesTestRegistry(t) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + runHAIngressStartup(ctx, func(context.Context) (release.Store, error) { return s, nil }, newBoxJudge(claimsOffEnv), reg) |
| + }() |
| + defer func() { cancel(); <-done }() |
| + select { |
| + case <-s.entered: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("startup did not enter scope read") |
| + } |
| + cfg := ciReconcileConfig(t) |
| + reconciled := make(chan error, 1) |
| + reconcileDone := make(chan struct{}) |
| + go func() { |
| + defer close(reconcileDone) |
| + reconciled <- reconcileSerialized(ctx, s, reg, cfg) |
| + }() |
| + defer func() { cancel(); <-reconcileDone }() |
| + select { |
| + case err := <-reconciled: |
| + t.Fatalf("reconcile bypassed startup lock: %v", err) |
| + case <-time.After(100 * time.Millisecond): |
| + } |
| + a.tick(ctx) |
| + if a.TenantAdmitted() { |
| + t.Fatal("admission opened while startup held reconcile") |
| + } |
| + close(s.resume) |
| + select { |
| + case err := <-reconciled: |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("reconcile stayed blocked") |
| + } |
| + a.tick(ctx) |
| + if !a.TenantAdmitted() { |
| + t.Fatal("complete reconcile did not open admission") |
| + } |
| + t.Log("startup's record read blocked the real reconcile entry point and tenant admission; admission opened after reconcile") |
| +} |
diff --git a/internal/provision/recordview.go b/internal/provision/recordview.go| index 3f092b466..2d660fbf6 100644 |
| --- a/internal/provision/recordview.go |
| +++ b/internal/provision/recordview.go |
| @@ -116,9 +116,10 @@ func viewScope(scope string) bool { |
| // unusable (no index support, a denied or malformed index) runs Rebuild |
| // instead, which is the walk every pass ran before the index (§3.4). |
| // |
| -// A scope that fails to re-read keeps its applied generation, is retried on |
| -// the next Refresh even when the index answers 304, and is published with the |
| -// failure cached, so the snapshot is not Complete and a strict reader over it |
| +// A scope that fails to re-read is retried once while ctx is live. If it still |
| +// fails, it keeps its applied generation, is retried on the next Refresh even |
| +// when the index answers 304, and is published with the failure cached, so |
| +// the snapshot is not Complete and a strict reader over it |
| // fails as it would on the bucket. A refresh whose ctx ends mid-read still |
| // publishes, with the reads that died cached as failures, and returns the |
| // ctx error. A refresh that walks and fails publishes the walk's failure |
| @@ -164,6 +165,23 @@ func (v *RecordView) Refresh(ctx context.Context) error { |
| results[scope] = r |
| mu.Unlock() |
| }) |
| + var retry []string |
| + for _, scope := range due { |
| + if !results[scope].ok { |
| + retry = append(retry, scope) |
| + } |
| + } |
| + if ctx.Err() == nil { |
| + forEach(retry, func(scope string) { |
| + if ctx.Err() != nil { |
| + return |
| + } |
| + r := v.readScope(ctx, prev, scope) |
| + mu.Lock() |
| + results[scope] = r |
| + mu.Unlock() |
| + }) |
| + } |
| next := prev.clone() |
| for _, scope := range due { |
| r := results[scope] |
diff --git a/internal/provision/recordview_g3_test.go b/internal/provision/recordview_g3_test.go| new file mode 100644 |
| index 000000000..da90c69c2 |
| --- /dev/null |
| +++ b/internal/provision/recordview_g3_test.go |
| @@ -0,0 +1,125 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "slices" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type g3RetryStore struct { |
| + *viewCountingStore |
| + key string |
| + failures, reads int |
| + lastFailed bool |
| + cancel context.CancelFunc |
| + beforeRetry func() |
| +} |
| + |
| +func (s *g3RetryStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == s.key && s.lastFailed { |
| + return nil, "", errors.New("transient record read (Get fallback)") |
| + } |
| + return s.viewCountingStore.Get(ctx, key) |
| +} |
| + |
| +func (s *g3RetryStore) GetIfChanged(ctx context.Context, key, etag string) ([]byte, string, bool, error) { |
| + if key == s.key { |
| + s.reads++ |
| + s.lastFailed = s.failures > 0 |
| + if s.reads == 2 && s.beforeRetry != nil { |
| + s.beforeRetry() |
| + } |
| + if s.failures > 0 { |
| + s.failures-- |
| + if s.cancel != nil { |
| + s.cancel() |
| + } |
| + return nil, "", false, errors.New("transient record read") |
| + } |
| + } |
| + return s.viewCountingStore.GetIfChanged(ctx, key, etag) |
| +} |
| + |
| +func TestG3ViewRetryBoundAndCancellation(t *testing.T) { |
| + for _, mode := range []string{"once", "persistent", "cancelled"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newViewFixture(t, true, true) |
| + s := &g3RetryStore{viewCountingStore: f.live} |
| + v := NewRecordView(s, release.NewChangeWatch(s)) |
| + previous := mustRebuild(t, v) |
| + a := f.acct[0] |
| + scope := "apps/" + a + "/shop" |
| + generation := v.applied[scope] |
| + f.record(t, f.live, a, "shop", "three") |
| + s.key = RecordKey(a, "shop", "three.shop.example.com") |
| + s.failures = 1 |
| + rctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + if mode == "persistent" { |
| + s.failures = 100 |
| + } |
| + if mode == "cancelled" { |
| + s.cancel = cancel |
| + } |
| + err := v.Refresh(rctx) |
| + sn := v.Snapshot() |
| + if mode == "cancelled" { |
| + if !errors.Is(err, context.Canceled) || s.reads != 1 { |
| + t.Fatalf("cancelled refresh: %v, reads %d", err, s.reads) |
| + } |
| + } else if err != nil || s.reads != 2 { |
| + t.Fatalf("refresh: %v, reads %d", err, s.reads) |
| + } |
| + if mode == "once" { |
| + if !sn.Complete || v.pending[scope] || v.applied[scope] <= generation { |
| + t.Fatal("successful retry not applied") |
| + } |
| + if !slices.Contains(viewHosts(t, sn.Store(s)), "three.shop.example.com") { |
| + t.Fatal("retry omitted new record") |
| + } |
| + } else { |
| + if sn.Complete || !v.pending[scope] || v.applied[scope] != generation { |
| + t.Fatal("failed scope was applied or lost") |
| + } |
| + if _, _, err := ListAllRecordsStrict(t.Context(), sn.Store(s)); err == nil { |
| + t.Fatal("strict consumer accepted failed scope") |
| + } |
| + s.failures, s.cancel = 0, nil |
| + if !mustRefresh(t, v).Complete { |
| + t.Fatal("pending scope did not recover on unchanged index") |
| + } |
| + } |
| + if !previous.Complete || slices.Contains(viewHosts(t, previous.Store(s)), "three.shop.example.com") { |
| + t.Fatal("retry mutated prior snapshot") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestG3ViewRetryKeepsObservedGeneration(t *testing.T) { |
| + f := newViewFixture(t, true, true) |
| + s := &g3RetryStore{viewCountingStore: f.live} |
| + v := NewRecordView(s, release.NewChangeWatch(s)) |
| + mustRebuild(t, v) |
| + a := f.acct[0] |
| + f.record(t, f.live, a, "shop", "three") |
| + s.key, s.failures = RecordKey(a, "shop", "three.shop.example.com"), 1 |
| + s.beforeRetry = func() { |
| + f.record(t, f.live, a, "shop", "four") |
| + if _, err := v.Watch().Poll(t.Context()); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + sn := mustRefresh(t, v) |
| + observed, _ := v.Watch().Observed() |
| + scope := "apps/" + a + "/shop" |
| + if !sn.Complete || v.applied[scope] >= observed[scope] { |
| + t.Fatal("retry skipped a generation observed during the read") |
| + } |
| + if !slices.Contains(viewHosts(t, mustRefresh(t, v).Store(s)), "four.shop.example.com") { |
| + t.Fatal("next refresh lost concurrent write") |
| + } |
| +} |