Repository navigation
Allow self-route keys to use owned local models - #471
Conversation
|
@justin-schroeder is attempting to deploy a commit to the EigenLabs Team on Vercel. A member of the Team first needs to authorize it. |
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/components/api-keys/useApiKeys.ts:45-80— Synchronous HTTP call in fetchSelfRouteModels blocks UI thread- Suggestion: Move the fetch call to a web worker or use streaming/chunked responses for large provider lists to avoid blocking the main thread during JSON parsing
Type_diligence — ✅ No issues found
Additive_complexity — ✅ No issues found
1 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| adoptConsoleKey: (created: CreatedKey) => void; | ||
| } | ||
|
|
||
| type ProviderModelsResponse = { | ||
| providers?: Array<{ | ||
| online?: boolean; | ||
| status?: string; | ||
| runtime_verified?: boolean; | ||
| last_challenge_verified?: string; | ||
| models?: Array<{ id?: string }>; | ||
| }>; | ||
| }; | ||
|
|
||
| async function fetchSelfRouteModels(token: string): Promise<string[]> { | ||
| const res = await fetch("/api/me/providers", { | ||
| headers: { Authorization: `Bearer ${token}` }, | ||
| cache: "no-store", | ||
| }); | ||
| if (!res.ok) return []; | ||
| const data = (await res.json()) as ProviderModelsResponse; | ||
| const ids = new Set<string>(); | ||
| for (const provider of data.providers ?? []) { | ||
| if ( | ||
| !provider.online || | ||
| provider.status === "untrusted" || | ||
| !provider.runtime_verified || | ||
| !provider.last_challenge_verified | ||
| ) { | ||
| continue; | ||
| } | ||
| for (const model of provider.models ?? []) { | ||
| if (model.id) ids.add(model.id); | ||
| } | ||
| } | ||
| return [...ids].sort(); | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Synchronous HTTP call in fetchSelfRouteModels blocks UI thread
💡 Suggestion: Move the fetch call to a web worker or use streaming/chunked responses for large provider lists to avoid blocking the main thread during JSON parsing
📊 Score: 3×4 = 12 · Category: blocking_io
There was a problem hiding this comment.
Thanks, agreed that the browser should not parse the full provider dashboard payload just to populate this picker. I moved model extraction behind a small /api/me/provider-models proxy, so the client now receives only { models }, and added route coverage in api-routes.test.ts.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: COMMENT
Security — ✅ No issues found
Performance — ✅ No issues found
Type_diligence — ✅ No issues found
Additive_complexity — ✅ No issues found
✅ All four passes clean. No issues found.
🤖 Automated review by Centaur · DAR-186
|
@codex review this |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 092b9e7388
ℹ️ 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".
| const visibleModels = selfRouteOnly ? selfRouteModels : models; | ||
| const hasModels = visibleModels.length > 0; |
There was a problem hiding this comment.
Clear hidden model selections when switching route modes
When a user selects one or more public models and then toggles “My Machine only”, this switches the displayed list to selfRouteModels, but the existing allowed array is left intact and handleSubmit still sends those hidden public IDs as allowed_models. Since the coordinator checks the key allow-list before self-route routing, the created/edited self-route key can reject the local machine models the UI now appears to allow unless the user first manually deselects the old models. Clear/filter allowed when the mode changes, or derive submissions only from models visible in the current mode.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch — fixed in 96cf148. KeyForm now derives the submitted allow-list only from models visible in the current route mode (visibleAllowed), so a hidden public selection can no longer reach a self-route key's allowed_models (or vice versa). Selections stay in state so toggling back restores them, and the "N models selected" count reflects only visible selections. Covered by a new test in self-route.test.tsx that selects a public model, switches modes, and asserts the submission contains only the machine model.
|
|
||
| // Reject requests for models not in the catalog. | ||
| if !s.registry.IsModelInCatalog(model) { | ||
| if !policy.enabled && !s.registry.IsModelInCatalog(model) { |
There was a problem hiding this comment.
Permit off-catalog self-route VLMs past vision checks
For self-route image/video requests to an owned off-catalog VLM, bypassing only this catalog check lets the request reach routing, but the scheduler still rejects every candidate via the vision gate: ReserveProviderEx requires providerServesVisionModelLocked, and that helper only returns true when modelAllowedByCatalogLocked passes. The same bypass exists in the generic handler, so an owned local model advertised as vision-capable can be listed/accepted for self-route but can never be selected for media requests unless the owner/off-catalog allowance is threaded into the vision-capability check too.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right — the routable gate admitted the off-catalog VLM but the vision gate then starved it. Fixed in e01b885: providerServesVisionModelLocked takes an allowOffCatalog flag (mirroring providerServesRoutableModelLocked's allowDedicated), and both dispatch-path call sites (scanCandidatesLocked and the ReserveProviderEx admit re-check) pass the same owner-context bool used for the routable gate. Public-path call sites (quickCapacityCheck, cold-spill, HasVisionProviderForModel) pass false, so nothing changes for the public fleet. New test TestSelfRouteVisionRoutesToOwnedOffCatalogVLM covers owner-media-routes, public-media-rejected, and text-only-build-still-rejected.
| !provider.online || | ||
| provider.status === "untrusted" || | ||
| !provider.runtime_verified || | ||
| !provider.last_challenge_verified |
There was a problem hiding this comment.
Exclude stale challenges from provider-model picker
This treats any non-empty last_challenge_verified as eligible, but the coordinator’s self-route paths require that timestamp to be fresh (challengeFreshnessMaxAge, also returned by /v1/me/providers as challenge_max_age_seconds). If a connected machine has a stale challenge but has not otherwise been marked offline/untrusted, this proxy will still offer its models in the self-route key picker; a user can then save an allow-list for a model that the actual /v1/models and inference routing paths omit/reject. Parse the timestamp against the returned max age, or source this list from the same registry eligibility as OwnedModels.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 96cf148. The proxy now parses last_challenge_verified against the response's challenge_max_age_seconds (falling back to the same 360s default the providers dashboard uses), so a stale-challenge machine's models are no longer offered in the picker. Unparseable timestamps are excluded too (Number.isFinite guard, since NaN > maxAge is false). Added a test with stale, garbled, and fresh providers.
| if allowDedicated { | ||
| serves = r.providerAdvertisesModelLocked(p, model) |
There was a problem hiding this comment.
Use provider-reported sizes for off-catalog routes
When this owner path admits a model solely because the provider advertises it, the later scheduler still fills routingSnapshot.modelSizeGB and minRAMGb only from the public catalog. For an owned off-catalog model those values are zero, so the hardware-fit and free-memory gates fail open and can select a machine that merely has an oversized local model on disk but cannot actually load it, turning a deterministic model_too_large/unavailable case into a provider-side load failure. Carry the advertised ModelInfo.SizeBytes (or another loadability signal) into the off-catalog self-route path before bypassing the catalog gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e01b885. Both routing snapshots now fill modelSizeGB via modelSizeGBForFitLocked, which prefers the catalog's authoritative SizeGB and — for a model with no catalog entry — falls back to the provider-advertised ModelInfo.SizeBytes (same unpadded decimal-GB basis, so freeMemoryAdmits/reportedFreeForLoadAdmits padding still applies correctly). An oversized local model is now rejected deterministically as model_too_large instead of dispatching into a load failure. A nil catalog (dev/test) and an operator-unsized catalog entry keep the gate disabled as before. Covered by TestSelfRouteOffCatalogFitGateUsesAdvertisedSize (200GB model on a 64GB machine rejected with ModelTooLargeRejections=1; right-sized model routes).
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: COMMENT
Security — ✅ No issues found
Performance — ✅ No issues found
Type_diligence — ✅ No issues found
Additive_complexity — ✅ No issues found
✅ All four passes clean. No issues found.
🤖 Automated review by Centaur · DAR-186
The owner context that admits an off-catalog model past the routable gate now carries through the vision gate, so an owned local VLM is selectable for image/video requests instead of being listed but never routed. The hardware-fit and free-memory gates fall back to the provider-advertised SizeBytes when a model has no catalog entry, so an oversized local model is rejected deterministically as model_too_large instead of dispatching into a provider-side load failure.
The provider-models proxy now checks last_challenge_verified against the coordinator's challenge_max_age_seconds instead of accepting any non-empty timestamp, matching the eligibility the self-route paths enforce. KeyForm submits only the allow-list entries visible in the current route mode, so toggling "My Machine only" cannot leak hidden public model ids into a self-route key (or vice versa); selections are kept in state so toggling back restores them.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:31-40— Upstream response not validated before processing- Suggestion: Add response validation to ensure data structure matches expected schema before processing providers array
Performance — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:44-58— Unbounded Set allocation in loop without size pre-allocation- Suggestion: Pre-allocate the Set with an estimated size based on providers.length or add a reasonable upper bound check to prevent memory exhaustion from malicious provider data
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
|
Addressed all four review findings in e01b885 + 96cf148 (details in the inline replies):
Test plan re-run: |
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:33-40— Upstream response not validated before processing- Suggestion: Validate response content-type and structure before JSON parsing to prevent errors from malformed responses
Performance — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:44-57— Unbounded loop over providers and models without pre-allocation- Suggestion: Pre-allocate the Set with an estimated capacity based on provider count, or use a slice with known upper bound to avoid repeated Set resizing
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
| const res = await fetch(`${coordinatorUrl()}/v1/me/providers`, { | ||
| headers: { Authorization: authHeader }, | ||
| cache: "no-store", | ||
| }); | ||
| if (!res.ok) { | ||
| const text = await res.text(); | ||
| return NextResponse.json({ error: text || `Upstream ${res.status}` }, { status: res.status }); | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] 🔒 Upstream response not validated before processing
💡 Suggestion: Validate response content-type and structure before JSON parsing to prevent errors from malformed responses
📊 Score: 3×4 = 12 · Category: missing-input-validation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 661a04f33f
ℹ️ 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".
| // back restores them) but must never be submitted: the coordinator checks | ||
| // the allow-list before self-route routing, so a hidden public id on a | ||
| // "My Machine only" key would block the machine models the picker shows. | ||
| const visibleAllowed = allowed.filter((m) => visibleModels.includes(m)); |
There was a problem hiding this comment.
Preserve unseen allow-list entries when editing
When editing a key whose existing allowed_models includes a model that is not in the current picker feed (for example an owned local model is offline/stale while another self-route model is visible, or a public model is temporarily absent), this filters it out of visibleAllowed; because edit mode later sends modelsOrClear([], true), simply saving an unrelated change clears the allow-list and broadens the key to all models. The route-mode filter should avoid submitting hidden selections from the other mode without dropping same-mode existing IDs that are just absent from the current live list.
Useful? React with 👍 / 👎.
| if ( | ||
| !provider.online || | ||
| provider.status === "untrusted" || | ||
| !provider.runtime_verified || | ||
| !provider.last_challenge_verified || | ||
| !challengeFresh(provider.last_challenge_verified, maxAgeSeconds) |
There was a problem hiding this comment.
Mirror self-route eligibility in the model picker
This picker still accepts providers based only on online/status/runtime/fresh challenge, but actual self-route listing and routing also require registry.OwnedModels/providerSupportsPrivateTextLocked gates such as runtime manifest check, private-text capabilities, encrypted chunks, SIP, and code-attestation policy. In contexts like a Swift provider with runtime_verified=true but RuntimeManifestChecked=false, the UI can offer and save a model that /v1/models for the self-route key and inference routing will omit/reject; source this list from the same coordinator eligibility instead of reconstructing a partial subset from /v1/me/providers.
Useful? React with 👍 / 👎.
| if k := apiKeyFromContext(r.Context()); k != nil && k.SelfRouteOnly { | ||
| writeJSON(w, http.StatusOK, types.ModelListResponse{ | ||
| Object: "list", | ||
| Data: s.selfRouteModelEntries(consumerKeyFromContext(r.Context())), | ||
| }) | ||
| return |
There was a problem hiding this comment.
Return self-route models from retrieve endpoint too
This special-case makes GET /v1/models advertise owned off-catalog models to a self-route-only key, but GET /v1/models/{id} below still calls listModelEntries(true) and only searches the public catalog/build list. A client that lists local/foo and then performs the standard retrieve/validation call for /v1/models/local/foo with the same key gets a 404 even though inference can route it; apply the self-route model view to the retrieve path as well.
Useful? React with 👍 / 👎.
| if allowDedicated { | ||
| serves = r.providerAdvertisesModelLocked(p, model) |
There was a problem hiding this comment.
Preserve catalog hash checks for owned routes
When allowDedicated is true for self-route/prefer-owned routing, this replaces the catalog-allowed check with a raw advertisement check for every model, not just IDs absent from the catalog. If an owned provider advertises a public catalog model with a stale or mismatched WeightHash after a failed/partial download, the owner route now bypasses the catalog hash gate that public routing still enforces and can serve unverified weights; keep the catalog check for catalog entries and only fall back to raw advertisements for truly off-catalog IDs.
Useful? React with 👍 / 👎.
| serves := r.providerAdvertisesModelLocked(p, model) && | ||
| p.RuntimeVerified && | ||
| r.providerSupportsPrivateTextLocked(p) && | ||
| !p.LastChallengeVerified.IsZero() && |
There was a problem hiding this comment.
Reject render-broken owned models before queueing
For an owned off-catalog model whose advertised ModelInfo has template_render_ok=false, this counts the machine as serving the model based only on the raw advertisement. The scheduler later applies providerEligibleForTraitsLocked and rejects render-broken builds for every request shape, so self-route preflight passes and the request can sit in the queue until it returns machine_busy instead of failing immediately as unavailable; include the all-shape template-render gate in this summary path.
Useful? React with 👍 / 👎.
| RoutableProviders: m.Providers, | ||
| CanAccept: m.Providers > 0, |
There was a problem hiding this comment.
Compute self-route capacity before advertising can_accept
For a self-route-only key this marks every owned advertised model as routable and can_accept solely from the provider count, but OwnedModels does not check slot state, concurrency/token-budget headroom, free memory, or queue pressure. When the user's Mac has the model but is already at its quality cap, has a crashed/reloading slot, or cannot accept another request, /v1/models still reports can_accept: true even though inference will 429 or time out; use an owner-scoped capacity snapshot or avoid claiming immediate acceptability here.
Useful? React with 👍 / 👎.
… parity, preserve saved allow-lists
- providerServesRoutableModelLocked / providerServesVisionModelLocked: the
owner self-route context now lifts catalog MEMBERSHIP only — a build the
catalog tracks must still pass the weight-hash tamper tripwire
(modelServableForOwnerLocked). Off-catalog local models unaffected.
- GET /v1/models/{id} honors self-route-only keys so list and retrieve agree
(OpenAI clients that validate via retrieve-model can use listed local models).
- OwnedModels: count attested providers + attestation summary (was always 0),
deterministic metadata backfill instead of map-order first-writer-wins.
- KeyForm: only drop allow-list ids that belong to the OTHER route mode's
list — saved entries in neither list (offline machine, delisted model) are
no longer silently stripped by an unrelated edit.
- Tests: owner weight-hash gate (registry + vision helper), retrieve-model
parity + paid-key off-catalog 404 (API), preserved allow-list (vitest).
|
Maintainer review (dual-pass: Codex + independent Claude reviewer, full diff + local Pushed
Two informational notes, no action needed in this PR:
Note: the 4 failing console vitest files (provider-dashboard MDA severity) fail identically on clean master — pre-existing, unrelated to this PR. Vercel check failures are the usual external-fork deploy authorization, not code. |
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: COMMENT
Security — ✅ No issues found
Performance — ✅ No issues found
Type_diligence — ✅ No issues found
Additive_complexity — ✅ No issues found
✅ All four passes clean. No issues found.
🤖 Automated review by Centaur · DAR-186
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 31eac797f6
ℹ️ 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".
| for _, m := range models { | ||
| if m.ID == "" { | ||
| continue | ||
| } | ||
| a, ok := agg[m.ID] |
There was a problem hiding this comment.
Filter owned model listings through owner servability
When an owned provider still advertises a catalog-tracked model whose WeightHash no longer matches the catalog (for example after a stale or failed download), this loop adds it to OwnedModels solely by ID. The routing path now correctly rejects that same ModelInfo via modelServableForOwnerLocked, so a self_route_only key's GET /v1/models and retrieve endpoint can advertise a model that every inference request then fails to dispatch. Apply the same owner servability filter here while still allowing true off-catalog IDs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in dc8aecd. OwnedModels now filters each advertised build through modelServableForOwnerLocked — the exact predicate the routing path uses — so a stale-hash catalog build is never listed only to fail every dispatch. OwnedProviderSummary mirrors it (via providerServesOwnedRoutableModelLocked) so the pre-flight error paths report model_not_loaded instead of admitting an undispatchable request. Covered by list/route-agreement assertions added to TestSelfRouteCatalogModelKeepsWeightHashGate.
| if k := apiKeyFromContext(r.Context()); k != nil && k.SelfRouteOnly { | ||
| writeJSON(w, http.StatusOK, types.ModelListResponse{ | ||
| Object: "list", | ||
| Data: s.selfRouteModelEntries(consumerKeyFromContext(r.Context())), | ||
| }) |
There was a problem hiding this comment.
Preserve catalog aliases for self-route lists
For a self_route_only key whose owned machine serves a catalog build behind an active public alias, this branch replaces the normal listModelEntries response with raw owned provider IDs only. The normal /v1/models path hides those concrete quant builds and advertises the alias, and inference can still resolve that alias for the owned provider, so clients using /v1/models to choose or validate model IDs won't discover the documented alias name for their self-route key. Merge owned off-catalog entries with the alias-aware catalog view instead of replacing it wholesale.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in dc8aecd. selfRouteModelEntries now presents owned catalog builds behind an active alias under the alias id (desired/previous members aggregated, display name carried), hiding the concrete quant builds exactly like the public list; ?include_builds=1 re-exposes them and retrieve-by-exact-id works for both the alias and the hidden build (parity with the public GET /v1/models/{id}). New test TestSelfRouteOnlyKeyListsAliasForOwnedCatalogBuild.
|
|
||
| // Reject requests for models not in the catalog. | ||
| if !s.registry.IsModelInCatalog(model) { | ||
| if !policy.enabled && !s.registry.IsModelInCatalog(model) { |
There was a problem hiding this comment.
Let prefer-owner reach owned off-catalog models
When a client sends X-Darkbloom-Route: prefer for an owned local model that is not in the public catalog, policy.prefer is true but policy.enabled is false, so this check returns model_not_found before the prefer-owner scheduler can select the caller's machine. The routing code already treats owned prefer candidates like self-route for off-catalog advertisements, so this blocks a valid owned-local prefer request instead of serving it free or falling back only when appropriate; include the prefer-owner path in the owner/off-catalog admission instead of using the public catalog gate here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Intentionally keeping the 404 here. Prefer-mode's contract is 'owned-first, PAID fallback' — for a model only the owner's box serves, the fallback leg can never succeed, and letting the request past this gate doesn't produce that anyway: prefer takes an upfront paid reservation (a pricing lookup on an id the table doesn't know) and then hits the pre-dispatch shed (shedIfModelRejected → modelShed), which evaluates PUBLIC capacity — so the observable result would be a confusing capacity 429 (or a 402 for a zero-balance owner) instead of today's clean model_not_found. Supporting prefer+off-catalog properly means exempting owned-only models from the shed and skipping the reservation when no public provider can serve — at which point it IS exclusive self-route. X-Darkbloom-Route: self (or a self-route-only key) is the right tool for off-catalog models; the owner-context relaxation prefer shares in the scheduler still matters for CATALOG models on mixed/dedicated-exempt owned boxes. Happy to revisit as a follow-up if there's real demand.
…oute model lists - OwnedModels filters through modelServableForOwnerLocked so a stale-hash catalog build an owned box still advertises is never listed only to fail every dispatch; OwnedProviderSummary mirrors it so the self-route error paths report model_not_loaded instead of admitting an undispatchable request. - selfRouteModelEntries presents owned catalog builds behind an active public alias under the alias id (the documented name inference resolves), hiding the concrete quant builds like the public list; retrieve-by-exact-id keeps working for both names (includeHidden), and ?include_builds=1 re-exposes them in the list (public-path parity). - Prefer-mode + off-catalog intentionally still 404s: the paid fallback leg can never succeed for a model only the owner's box serves, and prefer takes an upfront paid reservation + public-capacity shed — exclusive self-route is the correct tool there (see PR discussion).
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 3 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:32-59— Synchronous fetch call in request handler blocks event loop- Suggestion: This is a request handler that makes a blocking HTTP call to the coordinator. Consider using streaming or async patterns if this becomes a bottleneck, though for a user-specific endpoint the impact may be acceptable.
- 🔵 [INFO]
console-ui/src/components/api-keys/KeyForm.tsx:51-54— O(n²) filtering operation on every render- Suggestion: The visibleAllowed calculation filters allowed models against otherModeModels on every render. Consider memoizing this with useMemo if the arrays are large or the component re-renders frequently.
- 🔵 [INFO]
coordinator/registry/registry.go:3894-3979— Potential large slice allocation without pre-sizing- Suggestion: The models slice is allocated with capacity len(agg) but agg can grow during iteration. Consider pre-calculating the final size or using a more predictable allocation pattern if the provider count is large.
Type_diligence — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:23-26— challengeFresh function performs unsafe date parsing without validation- Suggestion: Add type assertion and validation: const parsed = new Date(lastVerified); if (isNaN(parsed.getTime())) return false; const ageSec = (Date.now() - parsed.getTime()) / 1000;
Additive_complexity — ✅ No issues found
4 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| // never silently strips it from the saved key. | ||
| const visibleAllowed = allowed.filter( | ||
| (m) => visibleModels.includes(m) || !otherModeModels.includes(m) | ||
| ); |
There was a problem hiding this comment.
🔵 [INFO] ⚡ O(n²) filtering operation on every render
💡 Suggestion: The visibleAllowed calculation filters allowed models against otherModeModels on every render. Consider memoizing this with useMemo if the arrays are large or the component re-renders frequently.
📊 Score: 2×3 = 6 · Category: inefficient_algorithm
| return models | ||
| } | ||
|
|
||
| // OwnedModels returns deduplicated live models advertised by providers owned by | ||
| // accountID. Unlike ListModels, it intentionally does not apply the public | ||
| // catalog filter; self-route keys may target off-catalog local models. | ||
| func (r *Registry) OwnedModels(accountID string) []AggregateModel { | ||
| if accountID == "" { | ||
| return nil | ||
| } | ||
| now := time.Now() | ||
| agg := make(map[string]*AggregateModel) | ||
|
|
||
| r.mu.RLock() | ||
| defer r.mu.RUnlock() | ||
| for _, p := range r.providers { | ||
| p.mu.Lock() | ||
| eligible := p.AccountID == accountID && | ||
| p.Status != StatusOffline && | ||
| p.Status != StatusUntrusted && | ||
| p.RuntimeVerified && | ||
| r.providerSupportsPrivateTextLocked(p) && | ||
| !p.LastChallengeVerified.IsZero() && | ||
| now.Sub(p.LastChallengeVerified) <= challengeFreshnessMaxAge | ||
| if !eligible { | ||
| p.mu.Unlock() | ||
| continue | ||
| } | ||
| trust := p.TrustLevel | ||
| attested := p.Attested | ||
| attestResult := p.AttestationResult | ||
| models := make([]protocol.ModelInfo, len(p.Models)) | ||
| copy(models, p.Models) | ||
| p.mu.Unlock() | ||
|
|
||
| for _, m := range models { | ||
| if m.ID == "" { | ||
| continue | ||
| } | ||
| // List/route agreement: only builds the routing path would admit for | ||
| // this owner appear in the list — an off-catalog local model, or a | ||
| // catalog build passing the weight-hash gate. A stale-hash catalog | ||
| // build must not be advertised here only to fail every dispatch. | ||
| if !r.modelServableForOwnerLocked(m) { | ||
| continue | ||
| } | ||
| a, ok := agg[m.ID] | ||
| if !ok { | ||
| a = &AggregateModel{ | ||
| ID: m.ID, | ||
| TrustLevel: TrustNone, | ||
| } | ||
| agg[m.ID] = a | ||
| } | ||
| // Metadata backfill rather than first-writer-wins: two owned boxes | ||
| // can advertise the same id with one omitting metadata, and map | ||
| // iteration order must not decide which copy the owner sees. | ||
| if a.ModelType == "" { | ||
| a.ModelType = m.ModelType | ||
| } | ||
| if a.Quantization == "" { | ||
| a.Quantization = m.Quantization | ||
| } | ||
| a.Providers++ | ||
| if trustRank(trust) > trustRank(a.TrustLevel) { | ||
| a.TrustLevel = trust | ||
| } | ||
| if attested && attestResult != nil { | ||
| a.AttestedProviders++ | ||
| if a.Attestation == nil { | ||
| a.Attestation = &AttestationSummary{} | ||
| } | ||
| a.Attestation.SecureEnclave = a.Attestation.SecureEnclave || attestResult.SecureEnclaveAvailable | ||
| a.Attestation.SIPEnabled = a.Attestation.SIPEnabled || attestResult.SIPEnabled | ||
| a.Attestation.SecureBoot = a.Attestation.SecureBoot || attestResult.SecureBootEnabled | ||
| } | ||
| } | ||
| } | ||
|
|
||
| models := make([]AggregateModel, 0, len(agg)) | ||
| for _, a := range agg { | ||
| models = append(models, *a) | ||
| } | ||
| sort.Slice(models, func(i, j int) bool { return models[i].ID < models[j].ID }) | ||
| return models | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] ⚡ Potential large slice allocation without pre-sizing
💡 Suggestion: The models slice is allocated with capacity len(agg) but agg can grow during iteration. Consider pre-calculating the final size or using a more predictable allocation pattern if the provider count is large.
📊 Score: 2×3 = 6 · Category: unbounded_allocation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dc8aecd60b
ℹ️ 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".
| continue; | ||
| } | ||
| for (const model of provider.models ?? []) { | ||
| if (model.id) ids.add(model.id); |
There was a problem hiding this comment.
Return alias IDs from the self-route picker
When an owned catalog build is behind an active alias, the self-route /v1/models path now hides the concrete build and advertises the alias, but this picker still saves the raw provider-reported model.id. If the user creates a self-route key from that picker, allowed_models contains the hidden build while clients that validate/list models see and request the alias; keyModelAllowed checks the requested name before alias resolution, so those alias requests are rejected with model_not_allowed. Source these options from the alias-aware self-route model view or translate covered builds to their alias IDs before returning them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6012f2d by moving the source of truth coordinator-side: new Privy-authed GET /v1/me/self-route-models returns the SAME alias-aware view /v1/models serves to self-route keys (aliases for catalog builds, raw ids for off-catalog), and this proxy is now a thin passthrough. The picker can no longer save a hidden build id that the pre-resolution allow-list check rejects — and the three-way eligibility-filter drift (proxy re-deriving freshness rules) is gone with it. Go coverage in TestSelfRouteModelViewRespectsKeyAllowListAndPickerEndpoint; proxy tests rewritten as passthrough tests.
| const selectedModels = hasModels | ||
| ? allowed | ||
| ? visibleAllowed | ||
| : modelText.split(",").map((s) => s.trim()).filter(Boolean); |
There was a problem hiding this comment.
Keep empty self-route lists from submitting hidden models
Fresh evidence after the earlier fix: this fallback still bypasses visibleAllowed whenever the current mode has no visible models. If an existing public-scoped key has allowed_models=["gpt-oss-20b"], the user toggles “My Machine only” while selfRouteModels is empty because no eligible machine is online or the picker fetch failed, saving submits the stale modelText public ID as the self-route key’s allow-list. That hidden public ID then blocks future local machine model requests until the user manually clears the text field.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6012f2d. The free-text fallback now applies the same other-mode exclusion as the picker: ids provably belonging to the other route mode's list are dropped from the submitted text, so toggling "My Machine only" with no machine models available clears the stale public allow-list instead of submitting it (manual entry of local ids still works). Covered by a new vitest asserting allowed_models is cleared in exactly that scenario.
| if k := apiKeyFromContext(r.Context()); k != nil && k.SelfRouteOnly { | ||
| writeJSON(w, http.StatusOK, types.ModelListResponse{ | ||
| Object: "list", | ||
| Data: s.selfRouteModelEntries(consumerKeyFromContext(r.Context()), r.URL.Query().Get("include_builds") == "1"), |
There was a problem hiding this comment.
Filter self-route model lists by the key allow-list
When a self-route-only key also has allowed_models set, this branch returns every owned live model for the account instead of only the models that key is permitted to use. That is a new privacy/permission gap for off-catalog local inventory: a restricted key handed out for one local model can enumerate other private model IDs (and retrieve their metadata through the matching self-route retrieve path) even though inference would reject them via keyModelAllowed. Filter the self-route list/retrieve view through k.AllowedModels when it is non-empty.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6012f2d. Both the self-route list and retrieve now filter through the key's allowed_models when set (filterEntriesByKeyAllowList) — a restricted key sees exactly the inventory it may use, mirroring keyModelAllowed. Empty allow-list keeps the full owned view. Covered in TestSelfRouteModelViewRespectsKeyAllowListAndPickerEndpoint (alias-allowed, unrelated-allowed, and unrestricted cases).
…rivacy - New GET /v1/me/self-route-models (Privy-authed): the alias-aware owned live-model view shared with /v1/models for self-route keys. The console picker proxy is now a thin passthrough to it, so the ids saved into a key's allow-list are exactly the ids clients will list and request (aliases for catalog builds, raw ids for off-catalog) — deriving the list client-side from raw provider advertisements produced allow-lists holding hidden build ids that keyModelAllowed (checked pre-alias-resolution) then rejected. Also collapses the eligibility-filter drift (proxy re-derived freshness rules). - Self-route /v1/models list + retrieve now respect the key's allow-list: owned live models are private inventory; a restricted key handed out for one local model can no longer enumerate the account's other model ids. - KeyForm free-text fallback applies the same other-mode exclusion as the picker: toggling 'My Machine only' with no machine models available no longer submits the key's stale public allow-list from the text field.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/components/api-keys/useApiKeys.ts:102-106— Parallel API calls block UI thread with Promise.all on hot path- Suggestion: Move fetchOwnedModels to background or make it optional/cached to avoid blocking the main reload flow
Type_diligence — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:29-30— Array.filter with type predicate lacks runtime validation- Suggestion: Add explicit type checking: data.models.filter((m): m is string => typeof m === 'string' && m !== null && m.length > 0)
Additive_complexity — ✅ No issues found
2 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| setSelfRouteModels([]); | ||
| setError("Sign in to view your API keys."); | ||
| return; | ||
| } | ||
| await fetchKeys(token); | ||
| await Promise.all([fetchKeys(token), fetchOwnedModels(token)]); |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Parallel API calls block UI thread with Promise.all on hot path
💡 Suggestion: Move fetchOwnedModels to background or make it optional/cached to avoid blocking the main reload flow
📊 Score: 3×4 = 12 · Category: blocking_io
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6012f2db33
ℹ️ 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".
| const visibleAllowed = allowed.filter( | ||
| (m) => visibleModels.includes(m) || !otherModeModels.includes(m) | ||
| ); |
There was a problem hiding this comment.
Drop unknown selections when route mode changes
When editing a self-route key whose saved local model is currently offline or otherwise absent from selfRouteModels, then switching “My Machine only” off, this filter keeps that hidden local ID because it is in neither the visible public list nor otherModeModels. Public mode renders the picker when public models exist, so the user cannot uncheck the hidden local ID, and saving sends an off-catalog allowed_models value that makes the paid key reject normal public models until it is cleared through another path. Preserve unknown IDs for unrelated edits, but drop or reclassify them when the route mode actually changes.
Useful? React with 👍 / 👎.
| for _, m := range models { | ||
| if _, hidden := covered[m.ID]; hidden && !includeHidden { | ||
| continue | ||
| } | ||
| data = append(data, ownedModelEntry(m)) |
There was a problem hiding this comment.
Hide raw local IDs that collide with aliases
If an owner has an off-catalog local model whose ID equals an active public alias but the machine does not serve that alias's desired/previous build, this raw loop advertises that ID in the self-route /v1/models view. Inference never treats that name as the raw local model, though: resolveRequestedModel checks aliases first and ResolveModelConstrained returns unavailable when no owned provider serves the alias members. The listed model is therefore impossible to call under the advertised name; skip raw owned entries that collide with active aliases unless they are actually represented by the alias entry.
Useful? React with 👍 / 👎.
| serves := r.providerServesOwnedRoutableModelLocked(p, model) && | ||
| p.RuntimeVerified && | ||
| r.providerSupportsPrivateTextLocked(p) && | ||
| !p.LastChallengeVerified.IsZero() && |
There was a problem hiding this comment.
Fail media self-routes before queueing
For a self-route image/video request to an owned off-catalog text-only model, this summary counts the machine as serving the model solely from the owner routability check. That suppresses selfRouteUnavailable, while visionToolsFailFast skips self-route requests; the scheduler later rejects the only owned provider in the vision gate and the request can queue or return machine_busy instead of immediately telling the user the model is not vision-capable. Thread the media requirement into this owner preflight, or add an owner-scoped vision fail-fast before dispatch.
Useful? React with 👍 / 👎.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/components/api-keys/KeyForm.tsx:45-56— O(n) array filtering on every render for visibleAllowed computation- Suggestion: Memoize the visibleAllowed computation with useMemo to avoid recalculating on every render when dependencies haven't changed
Type_diligence — ✅ No issues found
Additive_complexity — ✅ No issues found
1 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| // back restores them) but must never be submitted: the coordinator checks | ||
| // the allow-list before self-route routing, so a hidden public id on a | ||
| // "My Machine only" key would block the machine models the picker shows. | ||
| // Only ids that provably belong to the OTHER mode's list are dropped — | ||
| // an allow-list entry in neither list (a temporarily offline machine's | ||
| // model, a since-delisted public model) is preserved, so an unrelated edit | ||
| // never silently strips it from the saved key. | ||
| const visibleAllowed = allowed.filter( | ||
| (m) => visibleModels.includes(m) || !otherModeModels.includes(m) | ||
| ); | ||
| const nameTrim = name.trim(); | ||
| const canSubmit = !!nameTrim && !submitting; |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ O(n) array filtering on every render for visibleAllowed computation
💡 Suggestion: Memoize the visibleAllowed computation with useMemo to avoid recalculating on every render when dependencies haven't changed
📊 Score: 3×4 = 12 · Category: inefficient_data_structures
…k vision call site to 3-arg signature (public context)
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/components/api-keys/KeyForm.tsx:52-55— O(n) array filtering on every render for visibleAllowed calculation- Suggestion: Memoize the visibleAllowed calculation with useMemo to avoid recomputing on every render when dependencies haven't changed
Type_diligence — ✅ No issues found
Additive_complexity — ✅ No issues found
1 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| const visibleAllowed = allowed.filter( | ||
| (m) => visibleModels.includes(m) || !otherModeModels.includes(m) | ||
| ); | ||
| const nameTrim = name.trim(); |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ O(n) array filtering on every render for visibleAllowed calculation
💡 Suggestion: Memoize the visibleAllowed calculation with useMemo to avoid recomputing on every render when dependencies haven't changed
📊 Score: 3×4 = 12 · Category: Inefficient data structures
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d8fe9c93e1
ℹ️ 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 := apiKeyFromContext(r.Context()); k != nil && k.SelfRouteOnly { | ||
| entries := s.selfRouteModelEntries(consumerKeyFromContext(r.Context()), r.URL.Query().Get("include_builds") == "1") |
There was a problem hiding this comment.
Honor header self-route in model listing
This only switches /v1/models to the owned-model view for keys with SelfRouteOnly, but resolveSelfRoutePolicy also supports per-request X-Darkbloom-Route: self on ordinary keys. With that supported header, a zero-balance caller can successfully infer against an owned off-catalog model, but the same key/header still lists only the public catalog and GET /v1/models/{id} 404s, so OpenAI clients that list or retrieve before sending the inference request cannot use the header-based self-route path. Apply the same self-route policy check here (and in retrieve) or make the header path intentionally non-discoverable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c2cc48a. Both /v1/models and GET /v1/models/{id} now key off the request's RESOLVED self-route policy (resolveSelfRoutePolicy) instead of only the per-key flag — so X-Darkbloom-Route: self on an ordinary key discovers exactly the owned-model view its header-based inference accepts (list and retrieve agree), while the same key without the header keeps the public catalog view (matching its public routing). Key allow-list filtering still applies. New test TestHeaderSelfRouteSeesOwnedModelView (header list + retrieve = owned view; headerless list must not leak the off-catalog id).
| serves := r.providerServesOwnedRoutableModelLocked(p, model) && | ||
| p.RuntimeVerified && | ||
| r.providerSupportsPrivateTextLocked(p) && | ||
| !p.LastChallengeVerified.IsZero() && |
There was a problem hiding this comment.
Reject unsupported tool self-routes before queuing
For a self-route tool call where the owned machine advertises the model but is below the tools capability floor, this summary still reports servesModel > 0 because it checks only owner routability/runtime/private-text/challenge freshness. visionToolsFailFast is skipped for self-route requests, while the scheduler later applies providerEligibleForTraitsLocked with HasTools, so the request can be admitted and then sit in the queue until machine_busy instead of immediately returning that the machine cannot serve tool calls. Thread the request traits into this owner preflight so it matches the dispatch gates.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c2cc48a. OwnedProviderSummary now takes the request's RequestTraits + media shape and mirrors the dispatch gates (providerEligibleForTraitsLocked — tools floor + template render — and the vision gate in owner context), and selfRouteUnavailable threads the real request shape through. A tool call to a below-floor owned box (or media to a text-only build) now fails fast with a precise 503 model_capability_unsupported (distinguished from model_not_loaded via a base-shape recheck) instead of queueing 120s into machine_busy. The queue-cleanup call site keeps the base-shape question, unchanged. Tests: TestOwnedProviderSummaryAppliesTraitAndVisionGates (below/at tools floor, text-only vs VLM build).
…e owner preflight - /v1/models list + retrieve now follow the request's RESOLVED self-route policy (per-key flag OR X-Darkbloom-Route: self), matching inference: a header-based self-route client discovers the same owned-model ids the inference path accepts. Headerless ordinary keys keep the public view. - OwnedProviderSummary takes the request's traits + media shape and mirrors the dispatch gates (tools capability floor / template render, vision-capable build): a tool call to a below-floor owned box or media to a text-only build now fails fast with the real cause (503 model_capability_unsupported) instead of queueing 120s into machine_busy. Queue-cleanup call site keeps the base-shape question (unchanged behavior).
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 4 finding(s) (2 blocking)
- 🟡 [MEDIUM]
coordinator/api/models_endpoints.go:271-284— selfRouteModelEntries creates multiple unbounded slices without pre-allocation- Suggestion: Pre-allocate slices with estimated capacity: data := make([]types.ModelEntry, 0, len(models)+len(aliases)) and members := make([]registry.AggregateModel, 0, 2)
- 🔵 [INFO]
coordinator/api/models_endpoints.go:418-425— filterEntriesByKeyAllowList creates filtered slice without pre-allocation- Suggestion: Pre-allocate with capacity: filtered := make([]types.ModelEntry, 0, len(entries))
- 🟡 [MEDIUM]
coordinator/registry/registry.go:3895-3970— OwnedModels creates multiple unbounded allocations in hot path- Suggestion: Pre-allocate map and slice: agg := make(map[string]*AggregateModel, estimatedModels) and models := make([]AggregateModel, 0, len(agg))
- 🔵 [INFO]
console-ui/src/components/api-keys/useApiKeys.ts:88-106— reload function calls fetchKeys and fetchOwnedModels sequentially instead of concurrently- Suggestion: The Promise.all on line 106 already handles concurrent execution correctly - no change needed
Type_diligence — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:29-30— Array.isArray check without type assertion for data.models- Suggestion: Add type assertion: const models = Array.isArray(data.models) ? (data.models as unknown[]).filter((m): m is string => typeof m === 'string' && m.length > 0) : [];
Additive_complexity — ✅ No issues found
5 finding(s) total, 3 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| now := time.Now() | ||
| agg := make(map[string]*AggregateModel) | ||
|
|
||
| r.mu.RLock() | ||
| defer r.mu.RUnlock() | ||
| for _, p := range r.providers { | ||
| p.mu.Lock() | ||
| eligible := p.AccountID == accountID && | ||
| p.Status != StatusOffline && | ||
| p.Status != StatusUntrusted && | ||
| p.RuntimeVerified && | ||
| r.providerSupportsPrivateTextLocked(p) && | ||
| !p.LastChallengeVerified.IsZero() && | ||
| now.Sub(p.LastChallengeVerified) <= challengeFreshnessMaxAge | ||
| if !eligible { | ||
| p.mu.Unlock() | ||
| continue | ||
| } | ||
| trust := p.TrustLevel | ||
| attested := p.Attested | ||
| attestResult := p.AttestationResult | ||
| models := make([]protocol.ModelInfo, len(p.Models)) | ||
| copy(models, p.Models) | ||
| p.mu.Unlock() | ||
|
|
||
| for _, m := range models { | ||
| if m.ID == "" { | ||
| continue | ||
| } | ||
| // List/route agreement: only builds the routing path would admit for | ||
| // this owner appear in the list — an off-catalog local model, or a | ||
| // catalog build passing the weight-hash gate. A stale-hash catalog | ||
| // build must not be advertised here only to fail every dispatch. | ||
| if !r.modelServableForOwnerLocked(m) { | ||
| continue | ||
| } | ||
| a, ok := agg[m.ID] | ||
| if !ok { | ||
| a = &AggregateModel{ | ||
| ID: m.ID, | ||
| TrustLevel: TrustNone, | ||
| } | ||
| agg[m.ID] = a | ||
| } | ||
| // Metadata backfill rather than first-writer-wins: two owned boxes | ||
| // can advertise the same id with one omitting metadata, and map | ||
| // iteration order must not decide which copy the owner sees. | ||
| if a.ModelType == "" { | ||
| a.ModelType = m.ModelType | ||
| } | ||
| if a.Quantization == "" { | ||
| a.Quantization = m.Quantization | ||
| } | ||
| a.Providers++ | ||
| if trustRank(trust) > trustRank(a.TrustLevel) { | ||
| a.TrustLevel = trust | ||
| } | ||
| if attested && attestResult != nil { | ||
| a.AttestedProviders++ | ||
| if a.Attestation == nil { | ||
| a.Attestation = &AttestationSummary{} | ||
| } | ||
| a.Attestation.SecureEnclave = a.Attestation.SecureEnclave || attestResult.SecureEnclaveAvailable | ||
| a.Attestation.SIPEnabled = a.Attestation.SIPEnabled || attestResult.SIPEnabled | ||
| a.Attestation.SecureBoot = a.Attestation.SecureBoot || attestResult.SecureBootEnabled | ||
| } | ||
| } | ||
| } | ||
|
|
||
| models := make([]AggregateModel, 0, len(agg)) | ||
| for _, a := range agg { | ||
| models = append(models, *a) | ||
| } | ||
| sort.Slice(models, func(i, j int) bool { return models[i].ID < models[j].ID }) | ||
| return models | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ OwnedModels creates multiple unbounded allocations in hot path
💡 Suggestion: Pre-allocate map and slice: agg := make(map[string]*AggregateModel, estimatedModels) and models := make([]AggregateModel, 0, len(agg))
📊 Score: 3×4 = 12 · Category: unbounded_allocations
| const models = Array.isArray(data.models) | ||
| ? data.models.filter((m): m is string => typeof m === "string" && m.length > 0) |
There was a problem hiding this comment.
🟡 [MEDIUM] 🏷️ Array.isArray check without type assertion for data.models
💡 Suggestion: Add type assertion: const models = Array.isArray(data.models) ? (data.models as unknown[]).filter((m): m is string => typeof m === 'string' && m.length > 0) : [];
📊 Score: 3×4 = 12 · Category: missing_type_assertion
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c2cc48a2cc
ℹ️ 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 !r.modelServableForOwnerLocked(m) { | ||
| continue | ||
| } |
There was a problem hiding this comment.
Exclude render-broken models from owned listings
When an owned provider advertises a model with template_render_ok=false, this listing path still aggregates it because the only per-model filter is modelServableForOwnerLocked. The actual self-route preflight/dispatch path also applies providerEligibleForTraitsLocked(..., RequestTraits{}), which fences render-broken builds for every request shape, so /v1/models and the self-route key picker can advertise a local model that every inference request then rejects as unavailable/not loaded. Apply the same template-render gate before adding the model to OwnedModels.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0b60b8f. OwnedModels now skips builds with an explicit template_render_ok=false — the same tri-state semantics as providerTemplateRenderBrokenLocked (nil = pre-0.6.5 no-opinion stays listed, matching dispatch). List, picker, and preflight now agree with the dispatch gates for weight hash, tools floor, vision, AND template render. Covered by TestOwnedModelsExcludesRenderBrokenBuilds (false excluded + preflight agreement, true and nil listed).
…or the template gate)
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 5 finding(s) (3 blocking)
- 🟡 [MEDIUM]
console-ui/src/components/api-keys/KeyForm.tsx:51-55— O(n) filter operation inside render function on every state change- Suggestion: Memoize visibleAllowed calculation with useMemo to avoid recomputing on every render when dependencies haven't changed
- 🟡 [MEDIUM]
console-ui/src/components/api-keys/KeyForm.tsx:62-65— O(n) filter operation inside render function on every modelQuery change- Suggestion: Memoize filteredModels calculation with useMemo to avoid recomputing on every render when modelQuery or visibleModels haven't changed
- 🟡 [MEDIUM]
console-ui/src/components/api-keys/KeyForm.tsx:72-79— Multiple O(n) operations in form submission handler- Suggestion: Pre-compute otherModeModels as a Set for O(1) lookups instead of O(n) includes() calls in the filter chain
- 🔵 [INFO]
coordinator/api/models_endpoints.go:271-334— Multiple map allocations without size hints in selfRouteModelEntries- Suggestion: Pre-allocate byID map with len(models) and covered map with estimated size based on aliases length to reduce allocations
- 🔵 [INFO]
coordinator/registry/registry.go:3888-3977— Map allocation without size hint in OwnedModels hot path- Suggestion: Pre-allocate agg map with estimated capacity based on provider count to reduce map growth overhead
Type_diligence — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/app/api/me/provider-models/route.ts:29-30— Array.filter with type predicate lacks runtime validation of string content- Suggestion: Add validation: .filter((m): m is string => typeof m === 'string' && m.trim().length > 0) to ensure non-empty strings
Additive_complexity — ✅ No issues found
6 finding(s) total, 4 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| // never silently strips it from the saved key. | ||
| const visibleAllowed = allowed.filter( | ||
| (m) => visibleModels.includes(m) || !otherModeModels.includes(m) | ||
| ); | ||
| const nameTrim = name.trim(); |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ O(n) filter operation inside render function on every state change
💡 Suggestion: Memoize visibleAllowed calculation with useMemo to avoid recomputing on every render when dependencies haven't changed
📊 Score: 3×4 = 12 · Category: inefficient_data_structures
| const filteredModels = modelQuery.trim() | ||
| ? models.filter((m) => m.toLowerCase().includes(modelQuery.trim().toLowerCase())) | ||
| : models; | ||
| ? visibleModels.filter((m) => m.toLowerCase().includes(modelQuery.trim().toLowerCase())) | ||
| : visibleModels; | ||
|
|
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ O(n) filter operation inside render function on every modelQuery change
💡 Suggestion: Memoize filteredModels calculation with useMemo to avoid recomputing on every render when modelQuery or visibleModels haven't changed
📊 Score: 3×4 = 12 · Category: inefficient_data_structures
| // PUBLIC ids — submitting those would block every local model request. | ||
| const selectedModels = hasModels | ||
| ? allowed | ||
| : modelText.split(",").map((s) => s.trim()).filter(Boolean); | ||
| ? visibleAllowed | ||
| : modelText | ||
| .split(",") | ||
| .map((s) => s.trim()) | ||
| .filter(Boolean) | ||
| .filter((m) => !otherModeModels.includes(m)); |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Multiple O(n) operations in form submission handler
💡 Suggestion: Pre-compute otherModeModels as a Set for O(1) lookups instead of O(n) includes() calls in the filter chain
📊 Score: 3×4 = 12 · Category: inefficient_data_structures
| func (s *Server) selfRouteModelEntries(accountID string, includeHidden bool) []types.ModelEntry { | ||
| models := s.registry.OwnedModels(accountID) | ||
| byID := make(map[string]registry.AggregateModel, len(models)) | ||
| for _, m := range models { | ||
| byID[m.ID] = m | ||
| } | ||
|
|
||
| aliases, err := s.store.ListModelAliases() | ||
| if err != nil { | ||
| // Degrade to the raw build listing rather than hiding the owner's | ||
| // models outright. | ||
| s.logger.Error("model registry: failed to list aliases for self-route models", "error", err) | ||
| aliases = nil | ||
| } | ||
|
|
||
| covered := make(map[string]struct{}) | ||
| data := make([]types.ModelEntry, 0, len(models)) | ||
| for _, a := range aliases { | ||
| if !a.Active || a.DesiredBuild == "" { | ||
| continue | ||
| } | ||
| // Owned members: the alias's live builds this account's machines | ||
| // actually serve. Retired builds stay raw — the alias would not | ||
| // resolve to them for inference. | ||
| members := make([]registry.AggregateModel, 0, 2) | ||
| for _, b := range []string{a.DesiredBuild, a.PreviousBuild} { | ||
| if m, ok := byID[b]; b != "" && ok { | ||
| members = append(members, m) | ||
| } | ||
| } | ||
| if len(members) == 0 { | ||
| continue | ||
| } | ||
| // Primary member (desired-first order above) carries the metadata; | ||
| // provider counts aggregate across members, mirroring the public | ||
| // alias entry's capacity roll-up. | ||
| agg := members[0] | ||
| for _, m := range members[1:] { | ||
| agg.Providers += m.Providers | ||
| agg.AttestedProviders += m.AttestedProviders | ||
| } | ||
| agg.ID = a.AliasID | ||
| // An alias spans quants; omit the per-build quant like the public list. | ||
| agg.Quantization = "" | ||
| entry := ownedModelEntry(agg) | ||
| if a.DisplayName != "" { | ||
| entry.Name = a.DisplayName | ||
| entry.Metadata.DisplayName = a.DisplayName | ||
| } | ||
| data = append(data, entry) | ||
| for _, m := range members { | ||
| covered[m.ID] = struct{}{} | ||
| } | ||
| } | ||
|
|
||
| for _, m := range models { | ||
| if _, hidden := covered[m.ID]; hidden && !includeHidden { | ||
| continue | ||
| } | ||
| data = append(data, ownedModelEntry(m)) | ||
| } | ||
| return data | ||
| } | ||
|
|
There was a problem hiding this comment.
🔵 [INFO] ⚡ Multiple map allocations without size hints in selfRouteModelEntries
💡 Suggestion: Pre-allocate byID map with len(models) and covered map with estimated size based on aliases length to reduce allocations
📊 Score: 2×3 = 6 · Category: unbounded_allocations
| // OwnedModels returns deduplicated live models advertised by providers owned by | ||
| // accountID. Unlike ListModels, it intentionally does not apply the public | ||
| // catalog filter; self-route keys may target off-catalog local models. | ||
| func (r *Registry) OwnedModels(accountID string) []AggregateModel { | ||
| if accountID == "" { | ||
| return nil | ||
| } | ||
| now := time.Now() | ||
| agg := make(map[string]*AggregateModel) | ||
|
|
||
| r.mu.RLock() | ||
| defer r.mu.RUnlock() | ||
| for _, p := range r.providers { | ||
| p.mu.Lock() | ||
| eligible := p.AccountID == accountID && | ||
| p.Status != StatusOffline && | ||
| p.Status != StatusUntrusted && | ||
| p.RuntimeVerified && | ||
| r.providerSupportsPrivateTextLocked(p) && | ||
| !p.LastChallengeVerified.IsZero() && | ||
| now.Sub(p.LastChallengeVerified) <= challengeFreshnessMaxAge | ||
| if !eligible { | ||
| p.mu.Unlock() | ||
| continue | ||
| } | ||
| trust := p.TrustLevel | ||
| attested := p.Attested | ||
| attestResult := p.AttestationResult | ||
| models := make([]protocol.ModelInfo, len(p.Models)) | ||
| copy(models, p.Models) | ||
| p.mu.Unlock() | ||
|
|
||
| for _, m := range models { | ||
| if m.ID == "" { | ||
| continue | ||
| } | ||
| // List/route agreement: only builds the routing path would admit for | ||
| // this owner appear in the list — an off-catalog local model, or a | ||
| // catalog build passing the weight-hash gate. A stale-hash catalog | ||
| // build must not be advertised here only to fail every dispatch. | ||
| if !r.modelServableForOwnerLocked(m) { | ||
| continue | ||
| } | ||
| // Same principle for the template-render gate: an explicit | ||
| // template_render_ok=false fences EVERY request shape at dispatch | ||
| // (see providerTemplateRenderBrokenLocked / the trait gate), so a | ||
| // render-broken build must not be listed either. nil (pre-0.6.5, no | ||
| // opinion) stays listed, matching dispatch. | ||
| if m.TemplateRenderOK != nil && !*m.TemplateRenderOK { | ||
| continue | ||
| } | ||
| a, ok := agg[m.ID] | ||
| if !ok { | ||
| a = &AggregateModel{ | ||
| ID: m.ID, | ||
| TrustLevel: TrustNone, | ||
| } | ||
| agg[m.ID] = a | ||
| } | ||
| // Metadata backfill rather than first-writer-wins: two owned boxes | ||
| // can advertise the same id with one omitting metadata, and map | ||
| // iteration order must not decide which copy the owner sees. | ||
| if a.ModelType == "" { | ||
| a.ModelType = m.ModelType | ||
| } | ||
| if a.Quantization == "" { | ||
| a.Quantization = m.Quantization | ||
| } | ||
| a.Providers++ | ||
| if trustRank(trust) > trustRank(a.TrustLevel) { | ||
| a.TrustLevel = trust | ||
| } | ||
| if attested && attestResult != nil { | ||
| a.AttestedProviders++ | ||
| if a.Attestation == nil { | ||
| a.Attestation = &AttestationSummary{} | ||
| } | ||
| a.Attestation.SecureEnclave = a.Attestation.SecureEnclave || attestResult.SecureEnclaveAvailable | ||
| a.Attestation.SIPEnabled = a.Attestation.SIPEnabled || attestResult.SIPEnabled | ||
| a.Attestation.SecureBoot = a.Attestation.SecureBoot || attestResult.SecureBootEnabled | ||
| } | ||
| } | ||
| } | ||
|
|
||
| models := make([]AggregateModel, 0, len(agg)) | ||
| for _, a := range agg { | ||
| models = append(models, *a) | ||
| } | ||
| sort.Slice(models, func(i, j int) bool { return models[i].ID < models[j].ID }) | ||
| return models |
There was a problem hiding this comment.
🔵 [INFO] ⚡ Map allocation without size hint in OwnedModels hot path
💡 Suggestion: Pre-allocate agg map with estimated capacity based on provider count to reduce map growth overhead
📊 Score: 2×3 = 6 · Category: unbounded_allocations
| const models = Array.isArray(data.models) | ||
| ? data.models.filter((m): m is string => typeof m === "string" && m.length > 0) |
There was a problem hiding this comment.
🟡 [MEDIUM] 🏷️ Array.filter with type predicate lacks runtime validation of string content
💡 Suggestion: Add validation: .filter((m): m is string => typeof m === 'string' && m.trim().length > 0) to ensure non-empty strings
📊 Score: 3×3 = 9 · Category: unsafe_type_cast
…nd 3 consumer.go is no longer frozen (v0.6.31-era WIP has long since landed), so the deferred items from this PR's original scope now close: - cancelDispatch itself now drops the attempt's chunk-decryption key (plain forget, consumer-goroutine); the cancelDispatchAndForget wrapper is deleted and all 37 dispatch.go sites call cancelDispatch directly — consumer.go's own cancel paths get the forget for free (Codex P2 + earlier Centaur suggestion, both now unblocked). - Every direct RemovePending abort site (13: pre-commit timeout, client-gone, ErrorCh exits, reservation-failure paths in both the chat and generic pipelines) forgets via the RemovePending return value — covers the generic /v1/completions //v1/messages aborts Codex flagged. - All three reservation_extra_refund swallows now log ERROR + emit billing.refund_failures, and skip the success counters + the ReservedMicroUSD reset on failure so a later settlement can retry. - releaseInitialReservation returns after a failed refund instead of falling through to billing.reservation_refunds/releases — a failure counted as a success would undercount exactly what the alert surfaces (Codex P2). - Tombstone key now derived via reflect.ValueOf(priv).Pointer() — drops the unsafe import (review nit); identical non-pinning semantics. Rebased onto master b78c97f (post #512/#510/#502/#471); full api suite + registry/protocol green, race-clean on the touched suites.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mlx-swift-lm moves to main 4bec0c2435: the stop-string rows (#460), the width-3 compiled feed-forward (#463) and the refused prefix restore release (#471, the same change dev pins through 995f3a5ec4); the rest is CI. The LaunchAgent keeps every forwarded key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Before / After
flowchart TB subgraph Before A1[request model X on self-route-only key] --> B1{X in public catalog?} B1 -- no --> C1[404 model_not_found] B1 -- yes --> D1[route to owned box only] L1[GET /v1/models] --> M1[public catalog list] end subgraph After A2[request model X on self-route-only key] --> B2{exclusive self-route?} B2 -- yes --> D2[route to owned box advertising X<br/>off-catalog OK; catalog builds still hash-checked;<br/>vision + hardware-fit gates use advertised metadata] B2 -- no --> E2{X in catalog?} -- no --> C2[404 model_not_found] E2 -- yes --> F2[public routing unchanged] L2[GET /v1/models + /v1/models/id<br/>self-route-only key] --> M2[owner's live machine models<br/>OwnedModels: fresh challenge, runtime-verified] endflowchart TB subgraph Before code a1[handleChatCompletions] --> b1[IsModelInCatalog gate] b1 --> c1[providerServesRoutableModelLocked<br/>always catalog+hash check] c1 --> d1[providerServesVisionModelLocked<br/>catalog-only] d1 --> e1[fit gates: catalogSizeGBLocked<br/>0 for off-catalog = fail open] end subgraph After code a2[handleChatCompletions] --> b2[catalog gate skipped when policy.enabled] b2 --> c2[providerServesRoutableModelLocked<br/>owner ctx: providerServesOwnedRoutableModelLocked<br/>= advertised AND catalog-allowed-or-untracked] c2 --> d2[providerServesVisionModelLocked allowOffCatalog<br/>same owner rule; public sites pass false] d2 --> e2[fit gates: modelSizeGBForFitLocked<br/>catalog size, else advertised SizeBytes] f2[handleListModels/handleGetModel<br/>self-route branch -> selfRouteModelEntries] --> g2[registry.OwnedModels] h2[console: /api/me/provider-models proxy<br/>KeyForm visibleAllowed by route mode] endTest plan
go test ./registry ./api+ vitest green.