Skip to content

fix(routing): gray-box budget clamp + capacity-503 rate penalty (postmortem layers 3-4) - #523

Merged
Gajesh2007 merged 5 commits into
masterfrom
fix/budget-clamp-gray-box
Jul 8, 2026
Merged

Gajesh2007 merged 5 commits into
masterfrom
fix/budget-clamp-gray-box

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

PR body — fix/budget-clamp-gray-box @ da7957ca

Suggested title: fix(routing): gray-box budget clamp + capacity-503 rate penalty
Base: master (branched from 76447bc0) · 1 commit · worktree .worktrees/budget-clamp
Deploy batch: A (before the shed lift, before the v0.7.5 provider release)

Problem

Postmortem layers 3 and 4 (docs/reports/2026-07-06-gemma4-serving-failure-postmortem.md): during the Jul 6 open-pool window, mixed boxes co-resident with gpt-oss served ~60% of their gemma dispatches while failing the other ~40% with capacity-shaped 503s — 11,581 provider 503s in 6 hours ("gray boxes").

  • Layer 3 — breakers blind by design: every existing capacity breaker (pair cooldown in capacity_cooldown.go, node capacity streak in health_ejection.go) requires zero interleaved accepts; each accept reset the streak, so a box failing 40% of dispatches was never tripped.
  • Layer 4 — heartbeat trust: the provider's live KV gate rejects while its last heartbeat still advertises a ~1.4%-used token budget (active_token_budget_used ~72k of ~5.2M at admit time). The heartbeat budget is stale-optimistic; coordinator admission believed it and kept dispatching.

What changed (per commit)

One commit, da7957ca, two complementary mechanisms — both keyed by the stable fault identity (faultKeyLocked: serial → SE-key → account → session), migrated on identity rebind, never cleared on Disconnect:

  1. Budget clamp (coordinator/registry/budget_clamp.go, new): on the first capacity-shaped 503 for a (provider, model) pair (same classified RecordCapacityReject entry point that feeds the cooldown), admission stops believing the pair's heartbeat budget — the slot is treated FULL (freeMemoryAdmits budget branch rejects; liveRemainingBudget in servability.go reports zero live headroom; the structural ceiling stays raw so the transient clamp can never feed the fleet-level structural 429). Release requires provider-side proof, whichever lands later: (a) a heartbeat delivered strictly after the clamp whose raw budget shows ≥ 1024 tokens of headroom, and (b) an accept for the pair after the clamp. Fail-open: 5-minute TTL, so a zero-traffic pair can never strand; a re-reject re-arms. Scoped to budget-reporting slots only (activeTokenBudgetMax > 0) — legacy providers keep the existing threshold-5 pair cooldown and are never one-shot clamped.
  2. Capacity-503 rate penalty (coordinator/registry/capacity_rate.go, new): a 5-minute sliding window of capacity-503s AND accepts per (identity, model) with no accept-triggered reset (that reset was the blindness). Above a 0.25 reject rate with ≥8 windowed outcomes, buildCandidateWithReason adds rate × EIGENINFERENCE_CAPACITY_RATE_PENALTY_MS (default 15,000 ms) to the candidate's cost — proportional deration, never ejection; fail-open selection untouched; the penalty decays as outcomes age out. One served request counts exactly one accept outcome: the completion-time accept is deduped against the commit-time accept via the new RecordCapacityAcceptOutcome(provider, model, !pr.ContentCommittedSafe()) (api/consumer.go).

Observability: RoutingDecision gains CapacityRateMs and CapacityRejectRate (in-memory only — telemetry rows keep RAW budgets, no DB schema change, wire protocol unchanged). Both trackers are migrated in migrateFaultStateLocked (health_ejection.go) and bounded by the sibling >1024 opportunistic sweeps.

Before / After

flowchart TB
  subgraph Before["Before — gray box invisible (layers 3+4)"]
    A1[dispatch to mixed box] --> B1{provider live KV gate}
    B1 -- "40%: capacity 503" --> C1[RecordCapacityReject<br/>streak +1]
    B1 -- "60%: serves" --> D1[RecordCapacityAccept<br/>streak RESET to 0]
    D1 --> E1[breaker never trips]
    C1 --> E1
    E1 --> F1[admission re-reads heartbeat budget:<br/>~1.4% used → believes it]
    F1 --> A1
  end
  subgraph After["After — clamp + rate penalty"]
    A2[dispatch to mixed box] --> B2{provider live KV gate}
    B2 -- "first capacity 503" --> C2[RecordCapacityReject →<br/>recordBudgetClampLocked +<br/>recordCapacityRateRejectLocked]
    C2 --> D2["slot treated FULL:<br/>freeMemoryAdmits=false,<br/>liveRemainingBudget=0"]
    D2 --> E2{"release proof?<br/>(a) fresher heartbeat ≥1024 headroom<br/>AND (b) accept after clamp"}
    E2 -- no --> F2[stays clamped, ≤5 min TTL fail-open]
    E2 -- yes --> G2[released; re-reject re-arms]
    B2 -- serves --> H2[accept counted ONCE in rate window,<br/>NO streak reset]
    H2 --> I2["rate >0.25 @ ≥8 outcomes →<br/>cost += rate × 15000ms<br/>(derated, never ejected)"]
  end
Loading

Code flow delta: RecordCapacityReject → (new) recordBudgetClampLocked + recordCapacityRateRejectLocked; RecordCapacityAccept → wrapper over (new) RecordCapacityAcceptOutcome → noteBudgetClampAcceptLocked + deduped recordCapacityRateAcceptLocked; snapshotProviderLockedEx / quickCapacityCheck → (new) snap.budgetClamped via budgetClampActiveLocked; freeMemoryAdmits + liveRemainingBudget consume it; buildCandidateWithReason → (new) capacityRatePenaltyLocked cost term.

New envs

Env Default Semantics Runbook flip
EIGENINFERENCE_BUDGET_CLAMP true Kill switch for the budget clamp; false/0 restores stale-heartbeat admission Active from Deploy A; leave default. Kill switch only if clamp misbehaves
EIGENINFERENCE_BUDGET_CLAMP_TTL_SECONDS 300 Fail-open bound: a clamp never outlives clampedAt + TTL Leave default
EIGENINFERENCE_CAPACITY_RATE_PENALTY_MS 15000 Penalty scale: cost += rate × this once rate >0.25 with ≥8 outcomes; 0/negative disables the tracker entirely Active from Deploy A; leave default

(Window 5 min, threshold 0.25, min-sample 8, release headroom 1024 tokens are code constants, not envs.)

Test evidence

coordinator/registry/budget_clamp_test.go (533 lines) + capacity_rate_test.go (268 lines):

  • TestGrayBoxSelectionShareDropsWithFix — the prod gray-box scenario (40% 503s with interleaved accepts): selection share drops with the fix; monopoly preserved with both kill switches off (pins the old behavior).
  • Clamp lifecycle: TestBudgetClampBlocksAdmissionOnFirstCapacityReject, TestBudgetClampReleaseRequiresFreshHeartbeatAndAccept (both orders), TestBudgetClampNoMeaningfulHeadroomDoesNotRelease, TestBudgetClampTTLFailOpen, TestBudgetClampReArmResetsReleaseProof, TestBudgetClampLegacyBudgetlessProviderNotClamped, TestBudgetClampKillSwitch.
  • Rate window: TestCapacityRateAcceptsDoNotResetRejects (the core semantic), TestCapacityRateOutcomeDedupe (one outcome per served request), TestCapacityRateBelowMinSampleNoPenalty, TestCapacityRateAtThresholdNoPenalty, TestCapacityRateDecays, TestCapacityRateNeverClosesRouting (sole-candidate fail-open), TestCapacityRateKillSwitch.
  • Identity: TestBudgetClampSurvivesReconnect, TestCapacityRateSurvivesReconnect, TestBudgetClampAndRateStateMigrateOnFirstBind; TestBudgetClampAndRateConcurrentAccess (-race hammer).

Suite status: full registry (-race) + api suites green, golangci-lint clean (Warden session); re-verified 2026-07-07 by ship-prep: go test ./registry/... ./api/... ok in the worktree.

Review status

Built and tested by the Warden session (JOURNAL.md row, 2026-07-06): registry -race + api suites green, golangci-lint clean. Committed locally, not yet pushed — orchestrator review on the PR itself.

Rollout notes

  • Deploy batch A (with coord-a). Must precede any gemma shed lift.
  • Nothing dormant: clamp + rate penalty are active immediately at deploy (defaults on). They only affect pairs that emit capacity-503s, so today's healthy fleet is byte-identical.
  • Post-deploy verify with the postmortem gray-box SQL (appendix): capacity-503 share from previously-gray boxes must drop; watch clamp arm/release counts and CapacityRejectRate on routing decisions.
  • Rollback: env kill switches (EIGENINFERENCE_BUDGET_CLAMP=false, EIGENINFERENCE_CAPACITY_RATE_PENALTY_MS=0) — no code revert needed.
  • Merge-order note: conflicts with coord-a in registry/scheduler.go (both touch snapshotProviderLockedEx/freeMemoryAdmits); whichever merges second takes a small rebase. No conflict with coord-b.

View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

Fixes the Jul 6 gray-box gap: mixed boxes co-resident with gpt-oss served
~60% of gemma dispatches while capacity-503ing the rest (11,581 503s/6h).
Their heartbeat budgets looked ~1.4% used at admit time (stale-optimistic
vs the provider's live KV gate), and every existing breaker requires ZERO
interleaved accepts, so each accept reset it — the router stayed blind.

Two complementary mechanisms, both keyed by stable fault identity
(survive reconnect, migrate on rebind, never cleared on Disconnect):

1. Budget clamp (registry/budget_clamp.go): on the first capacity-shaped
   503 (same classified RecordCapacityReject entry point), admission stops
   believing the pair's heartbeat budget and treats the slot as FULL
   (freeMemoryAdmits budget branch + providerBudgetFits live headroom).
   Release needs provider-side proof — an accept AND a strictly-fresher
   heartbeat with >=1024 tokens of raw headroom, whichever lands later —
   with a 5-min TTL fail-open so a zero-traffic pair can never strand.
   Scoped to budget-reporting slots; legacy providers keep the threshold-5
   pair cooldown. Kill switch: EIGENINFERENCE_BUDGET_CLAMP (default on),
   TTL via EIGENINFERENCE_BUDGET_CLAMP_TTL_SECONDS.

2. Capacity-503 rate penalty (registry/capacity_rate.go): 5-min sliding
   window of capacity-503s AND accepts per (identity, model) — one outcome
   per dispatch (completion-time accept deduped via ContentCommittedSafe).
   NO accept-triggered reset (that reset was the blindness). Above a 0.25
   rate with >=8 outcomes, buildCandidateWithReason adds rate x
   EIGENINFERENCE_CAPACITY_RATE_PENALTY_MS (default 15000, 0 disables) to
   the candidate cost: proportional deration, never ejection — fail-open
   selection is untouched and the penalty decays as outcomes age out.
   Exposed on RoutingDecision (CapacityRateMs, CapacityRejectRate);
   telemetry rows keep RAW budgets, no DB schema change, wire unchanged.

Regression tests: prod gray-box scenario (40% 503s with interleaved
accepts -> selection share drops with fix, monopoly preserved with kill
switches), clamp lifecycle (immediate block, stale-heartbeat no-release,
accept+fresh-heartbeat release both orders, headroom floor, TTL fail-open,
re-arm), rate window (min-sample, threshold, decay, no-reset-on-accept,
dedupe, reconnect, sole-candidate fail-open), stable-key migration, and a
-race concurrency hammer. Full registry (-race) + api suites green;
golangci-lint clean.

Co-authored-by: Cursor <cursoragent@cursor.com>
@vercel

vercel Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jul 8, 2026 10:08pm
d-inference-console-ui-dev Ready Ready Preview Jul 8, 2026 10:08pm
d-inference-landing Ready Ready Preview Jul 8, 2026 10:08pm

Request Review

@github-actions

github-actions Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces a multi-tier capacity rejection classifier (cold-miss / request-shape / genuine capacity) and a sliding-window capacity-503 rate tracker; the changes are purely routing/scheduling logic and do not touch any trust boundary enforcement, cryptographic primitive, or attestation path.


Trust boundaries touched

Boundary Relevance
TB-001 (consumer → coordinator) consumer.go changes affect how inference errors are classified and how billing/error state is recorded
TB-002 (coordinator → provider WebSocket) registry.go changes affect provider capacity state, scoring, and routing eligibility

No changes touch TB-003 through TB-009.


Threat assessments

T-002 (unbounded request body → coordinator OOM) — ℹ️ Neutral
The new isRequestShapeBatchBudgetReject helper in consumer.go calls s.registry.GetProvider and s.store.GetModelRegistryRecord on the error path, but the body-size problem (no MaxBytesReader on inference endpoints) is not changed. No regression, no fix.

T-005 (consumer denies billing charges / repudiation) — ℹ️ Neutral
noteInferenceSuccess and noteDispatchProviderError signatures change, but the ledger write paths are unaffected. The rate-outcome accounting is internal scheduling state only.

T-006 (unauthenticated WebSocket floods provider registry) — ℹ️ Neutral
New budgetClamps, capacityRateRejects, and capacityRateAccepts maps are added to Registry (registry.go lines ~1353–1370). These are keyed by stable identity and are not cleared on Disconnect. No pre-auth rate limit or connection cap is introduced, so the open finding (SEC-034) is unaffected.

T-007 / T-012 / T-027 (weight hash enforcement fail-open) — ℹ️ Neutral
No changes to weight hash admission or routing gate logic.

T-034 (APNs code-identity gate / CodeAttested) — ℹ️ Neutral
providerSupportsPrivateTextLocked and the CodeAttested gate are not modified. The new capacity-rate maps added to Registry sit alongside—not inside—the routing gate.

T-036 (trust level elevated without full MDM/MDA chain) — ℹ️ Neutral
No attestation or trust-state machine code is touched.

T-031 (provider earnings unauthenticated) — ℹ️ Neutral
consumer.go is modified but not the /v1/provider/earnings handler. SEC-030 remains open.

T-040 (host-header injection influences installer URLs) — ℹ️ Neutral
consumer.go changes do not touch URL generation.


New attack surface not covered by an existing threat

isRequestShapeBatchBudgetReject trusts provider-supplied errReason as a routing signal (consumer.go, new function ~line 380–405).

The function receives errReason which originates from InferenceErrorMessage.ErrorReason — a string set by the provider. The logic specifically states "a provider that says request_exceeds_node_budget / capacity_busy is TRUSTED over the stale heartbeat-budget heuristic". A malicious provider (ADV-001) that persistently replies with errReason = "request_exceeds_context" or "request_exceeds_node_budget" for every request would be classified as rejectionDeterministicUnservable by classifyRejection, routing the rejection only to RecordCapacityRejectRequestShape instead of the full gray-box tracker (RecordCapacityReject). This means:

  • The pair's capacityRateRejects sliding window does not accumulate.
  • The budgetClamps entry is not set.
  • The black-hole cooldown (RecordCapacityRejectLifecycle) is hit for cold-miss claims, but a provider can avoid even that by always claiming request_exceeds_context.

Net effect: a provider that rejects every request with the right structured reason can suppress its own capacity-rate penalty and budget-clamp indefinitely. This is a new provider-controlled signal that weakens the gray-box capacity tracking without an independent cross-check. This does not map cleanly to an existing threat (it is not about attestation, encryption, or billing—it is about routing correctness under adversarial provider behaviour), but ADV-001 is the relevant adversary and the affected asset is availability / fair scheduling.

Recommendation: errReason from the provider should be treated as advisory, not determinative. The classification should require corroboration (e.g., the heartbeat budget already agrees the context window is the binding constraint) before exempting the pair from the rate tracker, rather than trusting the provider's self-report alone.


Open SEC findings resolved by this PR

None. No existing open findings (SEC-007, SEC-011, SEC-012, SEC-016, SEC-017, SEC-021, SEC-034, etc.) are addressed by this change.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@Gajesh2007
Gajesh2007 marked this pull request as ready for review July 8, 2026 06:28

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — 1 finding(s)

  • 🔵 [INFO] coordinator/registry/budget_clamp.go:67-72 — Environment variable EIGENINFERENCE_BUDGET_CLAMP_TTL_SECONDS not validated for negative values
    • Suggestion: Add validation to ensure TTL is positive before converting to time.Duration

Performance — 1 finding(s) (1 blocking)

  • 🟡 [MEDIUM] coordinator/api/consumer.go:343 — Redundant ContentCommittedSafe() call in hot path
    • Suggestion: Cache the result of pr.ContentCommittedSafe() since it's called twice in the same function and the state won't change between calls

Type_diligence — 1 finding(s) (1 blocking)

  • 🟡 [MEDIUM] coordinator/api/consumer.go:343 — pr.ContentCommittedSafe() called without type assertion check
    • Suggestion: Add type assertion check: if committed, ok := pr.ContentCommittedSafe(); ok && !committed { ... } or ensure ContentCommittedSafe() method handles nil receiver safely

Additive_complexity — ✅ No issues found

3 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/registry/budget_clamp.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da7957caca

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/registry/scheduler.go Resolved
…dow; pre-reject-commit streams enter the capacity-rate denominator

Two Codex review findings on #523:

- Reconnect shed: a clamped stable identity that reconnected had
  BackendCapacity == nil until its first heartbeat, so the routing snapshot
  skipped the clamp evaluation (activeTokenBudgetMax == 0 branch) and
  admission fell back to the legacy memory path — shedding the clamp at the
  exact moment the stable fault key exists to prevent it. budgetClampEntry
  now records (sticky across re-arms) whether the pair was budget-reporting
  at clamp time; a budgetless snapshot holds the clamp for such pairs until
  the post-clamp heartbeat release proof or the TTL. Never-budget-reporting
  legacy pairs keep their documented exemption. The clamp check moved to the
  top of freeMemoryAdmits so a budgetless-but-clamped snapshot rejects.

- Rate denominator honesty: the commit-time RecordCapacityAccept records a
  rate outcome only while a reject is in-window, but the completion-time
  accept suppressed itself on ContentCommittedSafe — so a stream that
  committed BEFORE the pair's first windowed reject and served THROUGH the
  rejects never entered the denominator, letting a few later 503s overstate
  a healthy pair's reject rate. RecordCapacityAccept(Outcome) now returns
  whether the outcome was actually recorded; commit sites stamp the request
  (MarkRateOutcomeCounted) and noteInferenceSuccess re-offers only when the
  commit-time offer recorded nothing. One request counts exactly once.

Regression tests: TestBudgetClampHoldsAcrossReconnectBeforeFirstHeartbeat
(fails without the budgetless hold), TestCapacityRatePreRejectCommitCountsAtCompletion
(pins offer/record semantics and the double-count guard).

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — 1 finding(s)

  • 🔵 [INFO] coordinator/registry/budget_clamp.go:67-72 — Environment variable TTL parsing lacks bounds validation
    • Suggestion: Add validation to ensure TTL is within reasonable bounds (e.g., 1 second to 24 hours) to prevent extremely large or zero values that could cause operational issues

Performance — 3 finding(s) (2 blocking)

  • 🟡 [MEDIUM] coordinator/registry/budget_clamp.go:140-160 — Opportunistic sweep creates O(n) allocation on every capacity reject when map exceeds 1024 entries
    • Suggestion: Consider using a separate cleanup goroutine or batching cleanup operations to avoid blocking the hot path
  • 🟡 [MEDIUM] coordinator/registry/capacity_rate.go:137-147 — Map sweep iterates entire map on every record operation when size exceeds 1024
    • Suggestion: Use background cleanup or limit sweep frequency to avoid O(n) work on request hot path
  • 🔵 [INFO] coordinator/registry/capacity_rate.go:123-133 — appendWindowedOutcome creates new slice on every call, potentially copying large arrays
    • Suggestion: Pre-allocate slice capacity based on expected window size or use circular buffer for better memory efficiency

Type_diligence — ✅ No issues found

Additive_complexity — ✅ No issues found

4 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/registry/budget_clamp.go Resolved
Comment thread coordinator/registry/budget_clamp.go Resolved
Comment thread coordinator/registry/capacity_rate.go Resolved
Comment thread coordinator/registry/capacity_rate.go Resolved
@blacksmith-sh

blacksmith-sh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Found 2 test failures on Blacksmith runners:

Failures

Test View Logs
github.com/eigeninference/d-inference/e2e/TestIntegration_ConcurrentRequests View Logs
github.com/eigeninference/d-inference/e2e/TestProfile_SingleProviderNonStreaming View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

@Gajesh2007

Copy link
Copy Markdown
Member Author

Review round addressed @ethenotethan — ready for re-review.

  • Fixed (98fc1ae): both Codex findings — the budget clamp now holds through a reconnect's pre-heartbeat window (budgetless snapshots no longer shed onto the legacy memory path; legacy never-budget-reporting pairs keep their exemption), and pre-reject-committed streams now enter the capacity-rate denominator exactly once (RecordCapacityAccept returns whether the outcome recorded; completion re-offers only when it didn't). Regression tests for both, verified failing pre-fix.
  • Declined with evidence (per-thread replies): TTL bounds (zero/negative already clamped to default), the ContentCommittedSafe double-call/type-assertion findings (single guarded bool read; no assertion exists), and the >1024 sweep / appendWindowedOutcome allocation findings (sibling-map pattern parity; filter-in-place reuses the backing array).
  • CI: the E2E TestIntegration_ConcurrentRequests failure is the known provider-side MLX broadcast_shapes batching crash — it reproduces on master @ 76447bc (run 28758695595), unrelated to this branch.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 98fc1aef67

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/registry/budget_clamp.go Resolved
Comment thread coordinator/api/consumer.go Resolved
…ed completions enter the rate window correctly

Codex review round 2 on the gray-box fix (three P2s):

- budget clamp: a clamp armed while the pair reported NO token budget
  (cold 'model not loaded' miss, first dispatch before the first
  capacity heartbeat) never gates — even after a later heartbeat starts
  reporting a budget. The budgeted release branch would otherwise find
  acceptedSince=false and hold until TTL with no way to produce the
  accept proof (the clamp itself blocks dispatch). Clamps armed while
  budget-reporting still hold through budgetless reconnect windows.

- capacity-503 rate: cold 'not loaded' / 'no model loaded' lifecycle
  misses no longer derate the pair. New RecordCapacityRejectLifecycle
  feeds the black-hole cooldown and the clamp but not the rate window
  (which has no accept-reset, so normal warm-up reloads would
  accumulate as capacity dishonesty). noteInferenceError classifies via
  isColdModelMissRejection; genuine token-budget 503s still derate.

- capacity-503 rate: the after-commit client-gone completion path
  (handleComplete with a parked settlement, consumerGone=true) now
  re-offers the served dispatch into the rate denominator keyed on
  RateOutcomeCountedSafe, exactly like noteInferenceSuccess — a stream
  that committed before the pair's first windowed reject and whose
  consumer disconnected no longer vanishes from the denominator.

Regression tests (each verified to fail without its fix):
TestBudgetClampArmedBudgetlessDoesNotGateAfterBudgetAppears,
TestCapacityRateLifecycleRejectFeedsCooldownNotRate,
TestCapacityRateExcludesColdModelMiss,
TestCapacityRateParkedCompletionCountsAtHandleComplete.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a85c0fcef2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/registry/budget_clamp.go Resolved
Comment thread coordinator/api/consumer.go Resolved
…ch-budget rejects arm no gray-box state

Codex review round 3 on the gray-box fix (three P2 lifecycle gaps):

- clamp entry lifecycle: budgetClamps entries are now DELETED when they
  can no longer gate — released (accept proof + strictly-fresher
  heartbeat with >=1024 raw headroom), TTL-expired, or armed budgetless.
  Dropped from the accept path (RecordCapacityAcceptOutcome) and from a
  new heartbeat release sweep (releaseBudgetClampsOnHeartbeat, called by
  Heartbeat after the snapshot is stamped). Fixes two gaps: a released
  entry kept pulling every later accept for the pair onto the r.mu
  write lock forever (the healthy fast path keys on map presence), and
  it revived as a block on the identity's next reconnect-before-first-
  heartbeat (the budgetless hold branch read map presence as an active
  clamp on a pair that had already proven recovery). The sweep evaluates
  the heartbeat's OWN stamped time and report rather than re-reading
  r.providers, so a disconnect racing in after the heartbeat cannot
  void the release proof. Unreleased clamps still hold through
  budgetless reconnect windows, unchanged.

- deterministic batch-budget rejects: a 'batch token budget' reject that
  classifyRejection proves request-deterministic (provider reported
  budget not below the model context => the prompt exceeded the
  fleet-wide context) indicts the request, not the provider. It now
  routes through new RecordCapacityRejectRequestShape: cooldown strikes
  only — no one-shot clamp, no no-reset rate outcome — so a single
  oversized prompt cannot gate or derate a healthy pair. A budget-
  misreporting box still trips the cooldown (zero-interleaved-accepts
  discriminator), and node-pressured batch-budget rejects (budget <
  context) still feed the full gray-box state, mirroring the DAR-347
  dispatch classification.

Regression tests (each verified to fail without its fix):
TestBudgetClampReleasedEntryDoesNotReviveOnReconnect (both release
orders), TestBudgetClampInactiveEntriesAreDeleted,
TestBudgetClampHeartbeatReleaseSurvivesDisconnectRace,
TestCapacityRejectDeterministicBatchBudgetArmsNoGrayBoxState.
@Gajesh2007

Gajesh2007 commented Jul 8, 2026 •

Copy link
Copy Markdown
Member Author

Two on-the-record notes from the round-3 independent review (PASS, non-blocking — logged here to avoid another push cycle):

  1. Follow-up: api/consumer.go:381 passes reason="" into the deterministic-reject classifier while the dispatch path threads msg.ErrorReason. No live divergence today; once providers ship request_exceeds_node_budget (DAR-347), thread errMsg.ErrorReason through so both paths classify identically.
  2. Accepted bounded blind spot: on a ≥DAR-347 provider, a node-pressured 'batch token budget' reject under a stale-optimistic heartbeat (reported budget ≥ model context) arms no clamp/rate for up to one heartbeat interval; the next heartbeat re-syncs and subsequent rejects feed everything. Mirrors classifyRejection's documented LIMITATION; the incident's dominant reject strings are unaffected, and misreporting boxes still accrue cooldown strikes throughout.

UPDATE (c777054): Item 1 is now addressed — errMsg.ErrorReason is threaded through noteInferenceError into the gray-box classifier (classifyRejection(errReason, …)), matching the dispatch path; item 2's blind spot narrows accordingly for ≥DAR-347 providers (a structured node-budget reason now overrides the stale snapshot). See the resolved round-4 review thread on api/consumer.go.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 79a592d3e0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/registry/budget_clamp.go Resolved
Comment thread coordinator/api/consumer.go Resolved

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: COMMENT

Security — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Performance — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Type_diligence — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Additive_complexity — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

… touch the clamp, structured reasons reach gray-box classification

Codex review round 4 on the gray-box fix (three P2s):

- expired sticky-OR: recordBudgetClampLocked no longer inherits
  budgetReported from a TTL-expired entry. An expired cycle already
  failed open; donating its sticky bit let a later benign budgetless
  reject (cold 404, pre-heartbeat window) re-arm as stale-budget
  dishonesty and gate the pair for another TTL. The sticky-OR still
  protects live clamps' budgetless reconnect windows.

- lifecycle misses vs stale snapshots: RecordCapacityRejectLifecycle no
  longer arms the budget clamp at all (armClamp=false). The lifecycle
  classification takes precedence over snapshot budget presence: a
  provider that idle-unloads a model after its last heartbeat still
  shows the slot budget in the stale snapshot, so the previous
  budgetless-keyed exemption armed a REAL gating clamp from a routine
  re-warm 404 (1h idle-unload + lazy reload) — and with dispatch
  blocked, no accept could prove release until TTL. The forever-404
  black hole stays covered by the zero-accept cooldown, which lifecycle
  misses still feed (documented rationale in the function comment).

- structured reasons: noteInferenceError (and the dispatch retry
  helpers) now thread InferenceErrorMessage.ErrorReason into the
  gray-box request-shape classifier, which passes it to
  classifyRejection exactly like the dispatch failover path. A provider
  declaring request_exceeds_node_budget/capacity_busy is trusted over
  the stale heartbeat-budget heuristic (a stale >= context snapshot can
  no longer misroute a genuine node-capacity failure away from the
  clamp and rate trackers), and an explicit request_exceeds_context is
  request-deterministic regardless of string. Closes the follow-up
  logged in PR #523 comment 4919442466 (item 1).

Regression tests (each verified to fail without its fix):
TestBudgetClampExpiredEntryDoesNotDonateBudgetState,
TestBudgetClampLifecycleMissWithStaleBudgetSnapshotDoesNotClamp,
TestGrayBoxClassificationTrustsStructuredReason.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c777054472

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if k.ProviderID == oldKey {
nk := k
nk.ProviderID = newKey
r.capacityRateRejects[nk] = append(r.capacityRateRejects[nk], outcomes...)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep migrated rate windows ordered before sweeping

When an identity rebinds from oldKey to newKey and both keys already have capacity-rate history, appending the old outcomes after the existing new-key slice can make the merged slice non-chronological. The new rate-map sweep treats outcomes[len(outcomes)-1] as the newest timestamp, so in a high-churn registry (len(map) > 1024) an older appended tail can cause the next record to delete the whole rate window even though earlier entries are still fresh; that lets a gray-box shed its derating on rebind. Merge in timestamp order or prune by scanning for the max timestamp before sweeping.

Useful? React with 👍 / 👎.

Comment on lines +403 to +406
if !hasStrikes && !hasCooldown && !hasTrips && !hasClamp && !hasRateRejects && !hasNodeStreak && !capacityTripped {
// Nothing recorded: with no reject in the rate window the accept
// would not be stored anyway (see recordCapacityRateAcceptLocked).
return false

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Count pre-reject accepts in the rate denominator

This fast path drops every accept while the pair has no reject already recorded, but those accepts still fall inside the same 5-minute rate window if a reject burst starts shortly afterward. Separate from the overlapping-stream fixes, a provider that just completed many healthy short requests can then record capacityRateMinSample rejects and be measured as 100% rejecting instead of rejects / (recent accepts + rejects), causing a transient burst to derate an otherwise healthy high-volume pair. Keep a bounded recent-accept window/count even before the first reject, or seed the denominator from recent accepts when the reject window opens.

Useful? React with 👍 / 👎.

@Gajesh2007
Gajesh2007 merged commit 3220bd9 into master Jul 8, 2026
35 of 38 checks passed

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: COMMENT

Security — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Performance — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Type_diligence — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Additive_complexity — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: COMMENT

Security — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Performance — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Type_diligence — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Additive_complexity — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — c7770544 Deployed Jul 8, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — c7770544 Deployed Jul 8, 2026 by vercel[bot]
Preview – d-inference-landing — c7770544 Deployed Jul 8, 2026 by vercel[bot]
benchmarks — c7770544 Deployed Jul 8, 2026 by Gajesh2007 via E2E Benchmarks #1627
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants