Skip to content

fix(routing): correct capacity-rate window accounting - #527

Merged
Gajesh2007 merged 1 commit into
masterfrom
fix/capacity-rate-accounting-followup
Jul 9, 2026
Merged

Gajesh2007 merged 1 commit into
masterfrom
fix/capacity-rate-accounting-followup

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to #523. This corrects two capacity-rate accounting defects before the v0.7.5 coordinator stack is merged:

  • retain every served dispatch for the five-minute denominator, including accepts before the first capacity reject;
  • merge timestamp histories chronologically when a provider's stable identity is rebound, so bounded cleanup cannot discard fresh state;
  • keep the new accept path bounded with binary-search window pruning, amortized prefix reslicing, new-key-only map sweeps, and clamp snapshot work only for pairs with a live clamp.

The same chronological merge helper is applied to inference-error and capacity-cooldown strike histories because they had the identical migration and tail-sweep invariant.

Before

flowchart LR
  subgraph Behavior["Behavior before"]
    A[Recent successful dispatches] --> B[Accept history discarded]
    C[First capacity 503 burst] --> D[Reject-only rate]
    D --> E[False high routing penalty]
    F[Identity rebind with destination history] --> G[Older source appended last]
    G --> H[Large-map sweep can delete fresh state]
  end

  subgraph Code["Code before"]
    I[RecordCapacityAcceptOutcome] --> J{Reject already present}
    J -- No --> K[Return without rate outcome]
    J -- Yes --> L[Append accept]
    M[migrateFaultStateLocked] --> N[Append destination and source]
    N --> O[Sweep trusts final timestamp]
  end
Loading

After

flowchart LR
  subgraph Behavior["Behavior after"]
    A[Every served dispatch] --> B[Retained for five-minute window]
    C[Capacity 503 burst] --> D[Rejects divided by all recent outcomes]
    D --> E[Penalty only above sample and rate thresholds]
    F[Identity rebind] --> G[Histories merged oldest to newest]
    G --> H[Large-map sweep preserves fresh state]
  end

  subgraph Code["Code after"]
    I[RecordCapacityAcceptOutcome] --> J[Append and reslice accept history]
    K[recordCapacityRateRejectLocked] --> L[Prune accepts and append reject]
    J --> M[Binary-search window counts]
    L --> M
    N[migrateFaultStateLocked] --> O[mergeChronologicalTimestamps]
    O --> P[Newest timestamp remains at tail]
  end
Loading

Regression coverage

  • 100 accepts followed by eight rejects reports 8/108, not 8/8.
  • Accept-first, reject-first, and interleaved outcomes produce the same rate.
  • Exact five-minute boundary behavior and accept-only history pruning.
  • Commit, clean completion, and parked completion count each served dispatch once.
  • SE-key to serial rebind preserves chronological histories for all four timestamp maps.
  • A map larger than 1,024 entries retains fresh migrated rate state during cleanup.
  • Equal timestamps remain distinct outcomes.
  • Window pruning advances the expired prefix instead of compacting the live history under the registry lock.

The two principal regressions were verified failing against 3220bd9e before the implementation.

Verification

  • go test ./... -race -count=1 (28 packages)
  • go vet ./...
  • go build -o /tmp/d-inference-coordinator-capacity-rate-fast-follow ./coordinator/cmd/coordinator
  • gofmt -l on every changed Go file
  • git diff --check

The race suite emitted only the recurring macOS LC_DYSYMTAB linker warnings and exited successfully.

Rollout

Merge this before rebasing and completing #524. Per the v0.7.5 release policy, merging this PR does not authorize a partial coordinator deployment; it becomes part of the single complete coordinator release candidate.


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

@vercel

vercel Bot commented Jul 9, 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 9, 2026 7:28pm
d-inference-console-ui-dev Ready Ready Preview Jul 9, 2026 7:28pm
d-inference-landing Building Building Preview Jul 9, 2026 7:28pm

Request Review

@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

This PR contains only comment/documentation rewording of internal capacity-rate tracking logic; no security-relevant code paths, trust boundary enforcement, or cryptographic operations are modified.

Trust Boundaries Touched

  • TB-001 (consumer.go) — comment only
  • TB-002 (provider.go, registry.go) — comment only

Threat Assessment

Threat Assessment
T-002 (unbounded request body OOM) ℹ️ Neutral — consumer.go touched but only a comment on noteInferenceSuccess; no change to body-reading logic at lines 526/2359.
T-005 (consumer billing repudiation) ℹ️ Neutral — RecordCapacityAcceptOutcome call site is unchanged; only the explanatory comment describing double-count prevention is reworded.
T-006 (WebSocket registry flooding) ℹ️ Neutral — registry.go touched but only the rateOutcomeCounted field comment; registration/admission logic untouched.
T-007 / T-012 / T-027 (weight hash enforcement) ℹ️ Neutral — no changes to hash admission or RecordCapacityAccept logic paths.
T-031 (unauthenticated earnings endpoint) ℹ️ Neutral — consumer.go touched at line ~406; the unauthenticated /v1/provider/earnings path (line ~2265) is unaffected.
T-034 / T-036 (attestation chain / trust elevation) ℹ️ Neutral — provider.go touched only at handleComplete comment; attestation, trust-level assignment, and the APNs challenge path are unchanged.
T-040 (host header injection in URL generation) ℹ️ Neutral — unrelated section of consumer.go.

New Attack Surface

None introduced. The diff is three comment blocks describing internal denominator-accounting semantics; no control flow, data handling, or security-relevant logic changed.

SEC-* Findings Resolved

None. No open findings are addressed by this PR.


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

@blacksmith-sh

blacksmith-sh Bot commented Jul 9, 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
Gajesh2007 marked this pull request as ready for review July 9, 2026 19:46

@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 — ✅ No issues found

Performance — 2 finding(s) (2 blocking)

  • 🟡 [MEDIUM] coordinator/registry/capacity_rate.go:89-110 — Map growth without bounded cleanup on hot path
    • Suggestion: Move sweepCapacityRateMapLocked call outside the !existed condition to ensure cleanup runs on every reject, not just new keys
  • 🟡 [MEDIUM] coordinator/registry/capacity_rate.go:125-130 — Map growth without bounded cleanup on hot path
    • Suggestion: Move sweepCapacityRateMapLocked call outside the !existed condition to ensure cleanup runs on every accept, not just new keys

Type_diligence — ✅ No issues found

Additive_complexity — ✅ No issues found

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

🤖 Automated review by Centaur · DAR-186

Comment on lines 89 to 110
if r.capacityRateCfg.PenaltyMs <= 0 {
return
}
sweepCapacityRateMapLocked(r.capacityRateRejects, now)
_, existed := r.capacityRateRejects[key]
r.capacityRateRejects[key] = appendWindowedOutcome(r.capacityRateRejects[key], now)
if !existed {
sweepCapacityRateMapLocked(r.capacityRateRejects, now)
}

// A pair may have gone quiet long enough for its accept-only history to
// expire before this first/new reject. Prune it now so repeated routing reads
// do not keep scanning stale timestamps and the first rate uses only the same
// five-minute window as the reject side.
if accepts, ok := r.capacityRateAccepts[key]; ok {
accepts = pruneWindowedOutcomes(accepts, now)
if len(accepts) == 0 {
delete(r.capacityRateAccepts, key)
} else {
r.capacityRateAccepts[key] = accepts
}
}
}

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.

🟡 [MEDIUM] ⚡ Map growth without bounded cleanup on hot path

💡 Suggestion: Move sweepCapacityRateMapLocked call outside the !existed condition to ensure cleanup runs on every reject, not just new keys

📊 Score: 3×4 = 12 · Category: unbounded_allocations

Comment on lines 125 to 130
r.capacityRateAccepts[key] = appendWindowedOutcome(r.capacityRateAccepts[key], now)
if !existed {
sweepCapacityRateMapLocked(r.capacityRateAccepts, now)
}
return true
}

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.

🟡 [MEDIUM] ⚡ Map growth without bounded cleanup on hot path

💡 Suggestion: Move sweepCapacityRateMapLocked call outside the !existed condition to ensure cleanup runs on every accept, not just new keys

📊 Score: 3×4 = 12 · Category: unbounded_allocations

@Gajesh2007
Gajesh2007 merged commit 9b1d3b0 into master Jul 9, 2026
22 of 25 checks passed
@Gajesh2007
Gajesh2007 deleted the fix/capacity-rate-accounting-followup branch July 9, 2026 19:51

@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: e2b96982cc

ℹ️ 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".

// skip a redundant read-lock probe. Completion calls that already counted
// their rate outcome retain the old healthy fast path: use the read lock to
// avoid write acquisition when there is no cooldown/clamp state to clear.
shouldRecordRate := countRateOutcome && r.capacityRateCfg.PenaltyMs > 0

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 Avoid serializing first-token accepts on r.mu

With the default rate tracker enabled, every successful request reaches RecordCapacityAccept(..., true) from the first-content paths before the first chunk is written. This makes shouldRecordRate true even for pairs with no reject history, so the old healthy fast path is skipped and the function takes the registry-wide write lock below; concurrent first tokens, ReserveProviderEx, and heartbeat updates all serialize on r.mu. On healthy high-QPS traffic this can inflate TTFT and reduce routing throughput just to append dormant accept history, so consider a sharded/per-pair recording path or another way to avoid the global write lock for reject-free pairs.

Useful? React with 👍 / 👎.

Comment on lines 125 to 129
r.capacityRateAccepts[key] = appendWindowedOutcome(r.capacityRateAccepts[key], now)
if !existed {
sweepCapacityRateMapLocked(r.capacityRateAccepts, now)
}
return true

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 Refresh long-stream accepts at completion

When a stream emits first content and then runs longer than capacityRateWindow, this unconditional append/true return causes the API to mark RateOutcomeCounted at commit time. If capacity rejects arrive near the end of that long stream, the commit timestamp has already aged out and noteInferenceSuccess/parked completion will not re-offer the served request, so the active stream disappears from the denominator and the pair can be derated as reject-only despite serving. Keep a completion-time refresh path when the commit-time accept is outside the window.

Useful? React with 👍 / 👎.

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — e2b96982 Deployed Jul 9, 2026 by vercel[bot]
Preview – d-inference — e2b96982 Deployed Jul 9, 2026 by vercel[bot]
Preview – d-inference-landing — e2b96982 Deployed Jul 9, 2026 by vercel[bot]
benchmarks — e2b96982 Deployed Jul 9, 2026 by Gajesh2007 via E2E Benchmarks #1636
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