Skip to content

perf(registry): cut avoidable per-candidate cost in the provider scan - #1340

Merged
Gajesh2007 merged 1 commit into
masterfrom
perf/registry-scan-cost
Oct 4, 2026
Merged

Gajesh2007 merged 1 commit into
masterfrom
perf/registry-scan-cost

Conversation

@jonathan308

@jonathan308 jonathan308 commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The coordinator reorganization (#1324) made the per-request provider scan slower: BenchmarkReserveProviderEx_350x2 went from about 227 µs to 392 µs. This PR removes three avoidable costs on that path and recovers roughly a quarter of the regression. Routing outcomes are unchanged.

It is a partial fix. The rest of the gap comes from the detached-policy design itself and is described under "Notes for reviewers".

Linked issue

None. Follow-up to #1324.

What changed

  1. Autopilot eligibility no longer reads the clock for every candidate. Before refactor(coordinator): reorganize domain ownership and storage backends #1324 the expiry comparison was the last condition of the lease check, so a provider without a grant never reached time.Now(). After it, the clock was evaluated up front as an argument, up to three times per candidate. Lease.Active is now split into grantMatches plus the expiry comparison, and the per-request checks (RoutingBlocked, LegacyChangesBlocked, OrdinaryAllowed) take the clock as a function and call it only when a matching grant exists.
  2. Selection ranks the projected pool in place. Rank, Choose and affinityWinner copied each 80-byte candidate on every pass. They now index the pool, and Project takes the forecast and cost breakdown by pointer.
  3. Arena chunks fill one allocation size class. Candidate grew from 1,416 to 1,448 bytes, which pushed a 20-candidate chunk from the 28,672-byte size class into the 32,768-byte one and wasted 12% of every chunk. ChunkSize is now 22, the most candidates that fit 32 KiB. A test fails when the struct size changes enough to need retuning.

Before

flowchart LR
  R["Reserve provider"] --> S["Scan every candidate"]
  S --> A["Autopilot fence<br/>reads clock up to 3x per candidate"]
  S --> K["Arena chunk of 20<br/>rounded up to 32 KiB, 12% unused"]
  S --> P["Project pool, rank in several passes<br/>copying each candidate per pass"]
  A --> T["392 µs per reservation<br/>475 KB, 20 allocations"]
  K --> T
  P --> T
  classDef step fill:#1e40af,color:#fff,stroke:#93c5fd;
  classDef cost fill:#991b1b,color:#fff,stroke:#fca5a5;
  class R,S step;
  class A,K,P,T cost;
Loading

Blue is the unchanged scan; red is avoidable per-candidate cost.

After

flowchart LR
  R["Reserve provider"] --> S["Scan every candidate"]
  S --> A["Autopilot fence<br/>clock read only for a matching grant"]
  S --> K["Arena chunk of 22<br/>fills the 32 KiB class"]
  S --> P["Project pool, rank in place<br/>no per-pass copies"]
  A --> T["351 µs per reservation<br/>435 KB, 19 allocations"]
  K --> T
  P --> T
  classDef step fill:#1e40af,color:#fff,stroke:#93c5fd;
  classDef fixed fill:#166534,color:#fff,stroke:#86efac;
  class R,S step;
  class A,K,P,T fixed;
Loading

Green is the same decision at lower cost. Winner, runner-up, near-tie size and selection path are identical for every pool.

Benchmarks

Apple M3 Ultra, Go 1.25.0, GOMAXPROCS=12. Medians of 6 runs, master and this branch interleaved. "Before #1324" is 48d2be45.

Benchmark Before #1324 master d3de4b4a This PR vs master
BenchmarkReserveProviderEx_350x2 227 µs 392 µs 351 µs −10.5%
BenchmarkFleetReserveProviderEx 114 µs 187 µs 171 µs −8.8%
BenchmarkRequestPathSerial 158 µs 242 µs 225 µs −6.9%
BenchmarkFleetQuickCapacityCheck 80 µs 118 µs 109 µs −7.3%
BenchmarkSelectRoutingCandidate/providers=350 2.0 µs 19.5 µs 10.5 µs −46%
BenchmarkSelectRoutingCandidate/providers=32 0.12 µs 2.3 µs 1.6 µs −31%
BenchmarkRequestPathParallel 76 µs 80 µs 82 µs +1.8% (noise)

BenchmarkReserveProviderEx_350x2 allocates 435 KB in 19 allocations per reservation, down from 475 KB in 20.

Test plan

  • go test -race -p 1 -count=1 ./coordinator/tests/registry/... — all 8 packages pass.
  • go test -p 1 -count=1 ./coordinator/... — 91 packages pass, including the layout guard TestCoordinatorTestsAreIsolated. PostgreSQL-backed tests skipped (no DATABASE_URL).
  • gofmt -l coordinator empty; go vet ./coordinator/... clean; git diff --check clean.
  • python3 scripts/docs-impact-check.py --base origin/master — coverage OK.
  • New regression tests, each confirmed to fail with its fix undone:
    • TestAutopilotRoutingChecksSkipClockWithoutMatchingGrant fails if any routing check reads the clock without a matching grant (five provider states, both model kinds).
    • TestAutopilotRoutingChecksHonorGrantExpiry pins that a matching grant still stops managing the provider at exactly its expiry instant.
    • TestCandidateArenaChunkFillsLargestSmallSizeClass fails at ChunkSize = 20.
    • TestRankKeepsFiniteBestWhenLaterRankIsNaN fails if the best-rank scan uses min, which adopts NaN.
  • golangci-lint was not available locally; this relies on CI's Coordinator Lint.
  • make docs-check was run on a partial checkout (no landing/, submodules not initialized). Its only reported problems were paths under those; this relies on CI's Docs Lint.

Refactor pass

A dedicated refactor subagent reviewed the first working version, as AGENTS.md requires. It made these behaviour-preserving changes, and the validation above was rerun on the combined result:

  • Moved the lazy expiry comparison onto Lease (activeNow, beside Active) and renamed managedAt to managedNow, because At elsewhere in the codebase means "takes an instant".
  • Corrected the ChunkSize comment and tightened three test and doc comments.
  • Added one test row for a grant whose selection has since changed.

It left Rank, Choose, affinityWinner and the call-site edits unchanged and found no behavioural risk.

Components touched

  • coordinator (Go)
  • provider (Rust, legacy)
  • provider-swift (Swift CLI)
  • console-ui (Next.js)
  • enclave (Swift)
  • infra / CI / release
  • docs

Protocol / interface changes

  • No protocol/interface changes
  • Yes — described above and matching side updated

Two internal Go signatures changed: autopilotstate.State.OrdinaryAllowed takes now func() time.Time, and selection.Project takes *forecast.Estimate and *cachepolicy.ServiceBreakdown.

Documentation impact

  • Canonical documentation updated: a "Scan cost per candidate" section in docs/architecture/routing.md, one sentence in docs/architecture/model-autopilot.md, a row in docs/developer/navigation.md, and a CHANGELOG.md entry.
  • No documentation needed

Notes for reviewers

  • What remains. Wall time per reservation is still about 1.5× the pre-refactor(coordinator): reorganize domain ownership and storage backends #1324 figure. Profiling attributes it to the detached-policy boundaries: each candidate is projected into by-value evidence structs (forecast.Evidence is 408 bytes, performance.CalibrationEvidence 248) that are built and copied per candidate, where the old code read snapshot fields directly. The largest pieces are the first-content estimate (3 µs → 18 µs per reservation), candidate build (7 → 19 µs) and the first-content snapshot fill (9 → 20 µs). Closing that means the registry no longer re-projecting per-candidate state by value, for example pointer-based inputs to forecast.Evaluate, deadline.BoundSlots and the Qualified catalogs, plus their test call sites. I left that for a separate decision because it changes the component contracts refactor(coordinator): reorganize domain ownership and storage backends #1324 introduced.
  • Small pools. selection.Select still zeroes a 512-entry stack array on every call (about 0.7 µs), which dominates the single-provider micro-benchmark. It is under 1% of a fleet-sized reservation, so this PR leaves it.
  • Absolute scale. The whole regression is about 0.15 ms per reservation at 350 providers.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Autopilot eligibility read the clock for every candidate of every request. It now reads it only for a provider holding a matching control grant.

Selection ranks the projected pool in place instead of copying each candidate on every pass, and Project takes the forecast and cost breakdown by pointer.

Candidate arena chunks hold 22 candidates (was 20), which fills the allocator's 32 KiB size class.

Routing outcomes are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Oct 4, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated
d-inference Ready Ready Preview Oct 4, 2026 7:34pm UTC
d-inference-console-ui-dev Ready Ready Preview Oct 4, 2026 7:34pm UTC
d-inference-landing Ready Ready Preview Oct 4, 2026 7:34pm UTC
eigen-homepages-darkbloom Ready Ready Preview Oct 4, 2026 7:34pm UTC

Request Review

@github-actions

github-actions Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head f0c9be91f09c against base d3de4b4a001d.

Review not completed for this head. Previous findings are superseded, not confirmed resolved.
Ten-PR pilot complete; maintainer evaluation required

Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging.

Coverage: 0/0 source units; cross-file integration pending. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned.

Cost this run: $0.0000 reported, $0.0000 reserved with unknown cost; 0 paid request(s), 0 reused batch(es), 0 provider cache-hit tokens.

Saved findings and earlier report · Historical findings are not confirmed resolved.

@jonathan308
jonathan308 requested a review from Gajesh2007 October 4, 2026 20:26
@Gajesh2007

Copy link
Copy Markdown
Member

@codex review this

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-04T20:32:59.991213Z f0c9be9 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: f0c9be91f0

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

This branch was successfully deployed

4 active deployments
benchmarks — f0c9be91 Deployed Oct 4, 2026 by jonathan308 via E2E Benchmarks #2193
Preview – d-inference-console-ui-dev — f0c9be91 Deployed Oct 4, 2026 by vercel[bot]
Preview – d-inference — f0c9be91 Deployed Oct 4, 2026 by vercel[bot]
Preview – d-inference-landing — f0c9be91 Deployed Oct 4, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — f0c9be91 Deployed Oct 4, 2026 by vercel[bot]
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