Skip to content

Bound the /validate calls one autoload cascade can send - #10508

Merged
danielhanchen merged 2 commits into
mainfrom
bound-autoload-validate-attempts
Sep 9, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
bound-autoload-validate-attempts

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The problem

MAX_AUTO_LOAD_ATTEMPTS = 3 is the only cap on the autoload cascade, and it bounds /load only.

When the validate preflight refuses a candidate (requires_trust_remote_code, requires_security_review, requires_transformers_upgrade), loadAutoLoadCandidate adds it to skippedAutoLoadCandidates and returns before loadAttempts += 1. That is deliberate, since a refusal should not spend the budget a loadable model needs. The side effect is that a refused candidate costs nothing at all, so both cascade loops keep pulling the next one.

sources is the union of every cached GGUF repo, every cached model repo and every local row, with no slice. So a cache whose entries are all refused sends one POST /validate per repo and never reaches a cap. The larger the model cache, the worse it gets.

The fix

Give validate its own budget, separate from the load budget:

  • MAX_AUTO_VALIDATE_ATTEMPTS = 8 beside MAX_AUTO_LOAD_ATTEMPTS
  • validateAttempts declared inside autoLoadSmallestModel, so it resets per cascade rather than leaking across sessions
  • incremented inside canAutoLoad immediately before the POST, after the existing throwIfAborted(), so it counts requests that reject and cancellation still short circuits first
  • checked at both loop sites plus the existing early return guard

A refusal still does not consume a load attempt. 8 is roughly 2.5x the load cap because every successful load spends a validate first, so a cap near 3 would refuse a loadable model sitting behind a couple of blocked repos.

The default download preflight further down is a single call outside any loop and is left ungated, so a device whose cached repos are all refused still falls back to the default model exactly as it does today.

Tests

New studio/frontend/tests/auto-load-validate-budget.test.ts, 5 cases. autoLoadSmallestModel is not exported and pulls in the stores, so the test lifts the two real loop conditions out of the shipped source and replays a cascade over 40 refused repos, following the same idiom as tests/auto-load-target-key.test.ts. A missing MAX_AUTO_VALIDATE_ATTEMPTS is treated as an infinite budget, so the unfixed tree fails on behaviour rather than on the lift.

Without the fix, 4 of the 5 fail:

x a cache full of refused models cannot POST /validate once per repo
  AssertionError: the cascade issued one /validate per cached repo (40 of 40),
  so nothing bounds it but the size of the inventory

Checks

  • npm run test: 7060 passed, 0 failed
  • npm run typecheck: clean
  • eslint on chat-adapter.ts reports the same 14 pre-existing errors before and after; the new test file is clean
  • biome check on chat-adapter.ts reports the same 2 diagnostics before and after

A candidate the validate preflight refuses is marked skipped and returns
before loadAttempts is incremented, so it costs nothing. MAX_AUTO_LOAD_ATTEMPTS
only ever bounded /load, and the candidate list is the unsliced union of every
cached GGUF repo, cached model repo and local row. A cache where the entries are
refused for trust_remote_code or security review therefore sends one POST
/validate per repo, bounded only by how much the user has downloaded.

Count the validate calls in their own budget. A refusal still does not spend a
load attempt, since that would stop the cascade reaching a model it can load.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 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-09-09T09:56:38.620849Z 0db48ce 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.

Two corrections to the budget.

Counting every validate truncated the sweep: a preflight that passes reaches
loadAttempts on the next statement, and MAX_AUTO_LOAD_ATTEMPTS already bounds
that, so charging it here as well stopped a device finding a model it could load
behind a run of blocked repos. Only the preflights that dead-end are counted now.

A rejected validate dead-ends too, and was missed. The sweep keeps going after a
transport failure on purpose, and recordCandidateFailure only stops it for a user
cancellation, so a dead backend still POSTed once per cached repo. Count it in a
catch on the call.

Budget is now 12 dead ends plus the 3 load attempts, so at most 15 preflights per
cascade whatever the inventory size, and a loadable model behind up to 11 dead
ends still auto-loads.

Tests read the cap and counter names out of the source, so a rename cannot
silently disarm them.
@danielhanchen

Copy link
Copy Markdown
Member Author

Update: two corrections to the budget

Simulation over 623 generated cascade scenarios turned up two defects in the first version of this, both now fixed.

Counting every validate truncated the sweep. A preflight that passes reaches loadAttempts += 1 on the very next statement, and MAX_AUTO_LOAD_ATTEMPTS already bounds that, so charging it against the validate budget as well meant a device could stop before reaching a model it could actually load. Only the preflights that dead end are counted now.

A rejected validate dead ends too, and was missed. The sweep deliberately keeps going after a transport failure, and recordCandidateFailure only stops it for a user cancellation, so a dead backend still POSTed once per cached repo. That is the same runaway this PR exists to stop, just reached by a different path. It is counted in a catch on the call now.

The counter is validateFailures rather than validateRefusals because it no longer counts only refusals.

Bound

At most 12 + 3 = 15 preflights per cascade whatever the inventory size, and the two budgets compose rather than share a pool: 12 dead ends and 3 load attempts, in any interleaving. A loadable model behind up to 11 dead ends still auto loads.

Simulation

623 scenarios, 623 passed. Inventory sizes to 5000, refusal densities, refusal position, multi quant repos to 30 quants each, 21 abort offsets, 20 cancel depths, interleaved refusals and rejections.

  • 65 of the 623 exceed the 15 call bound under the pre PR conditions, topping out at 5000
  • 43 load pre PR but not post PR, and every one of those had at least 12 dead ends ahead of the loadable model, so truncation never happens spuriously
  • control: mutating the inner loop guard out of the source makes the harness report failures, so it is reading the real conditions rather than a copy

The harness and the test file both lift the loop conditions out of the shipped source. The tests additionally read the cap and counter names out of the source, so a rename cannot silently disarm them. Five mutations were tried against the suite and all five were caught.

Compatibility

No new API and no new compatibility floor. The added constructs are Promise.prototype.catch, += and comparisons. AbortSignal.throwIfAborted is pre existing in this file (23 occurrences) and both lines near it in the diff are context. The repo sets no browserslist, so Vite's default target applies (chrome111, edge111, firefox114, safari16.4, ios16.4), all well past the throwIfAborted floor of Chrome 100 / Edge 100 / Firefox 97 / Safari 15.4. WebView2, WKWebView and WebKitGTK in the Tauri shells are past it too.

Nothing here reads or writes persisted state: both counters are function local lets that live and die with one cascade, so an older install cannot skew it.

Checks

  • npm run test: 7067 passed, 0 failed
  • npm run typecheck: clean
  • eslint on chat-adapter.ts: the same 14 pre existing errors before and after, identical set. Clean on the new test file
  • biome check on chat-adapter.ts: the same 2 errors and 20 warnings before and after, identical rule by rule

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the cascade in studio/frontend/src/features/chat/api/chat-adapter.ts only bounds loadAttempts, so a refused or rejected preflight costs nothing and the sweep walks the whole cache; the split budget with the default-download preflight left ungated looks right. Will get this reviewed.

@danielhanchen

Copy link
Copy Markdown
Member Author

Executed in all three browser engines

Static audit is not execution, so I ran the shipped code in real engines. A generator splices the source verbatim out of chat-adapter.ts (both caps, the let validateFailures declaration, the whole canAutoLoad body, the source-loop stop guard and the per-source while condition), bundles it with the repo's own rolldown at the repo's es2020 target with minification on, and Playwright drives the result. Nothing is retyped, and the harness asserts the caps it read rather than assuming them.

engine version covers result
chromium 153.0.8010.12 Chrome, Edge 57/57 pass, 0 page errors
firefox 155.0 Firefox 57/57 pass, 0 page errors
webkit 26.6 Safari 57/57 pass, 0 page errors

Caps read out of the shipped source in every engine: {"MAX_AUTO_LOAD_ATTEMPTS":3,"MAX_AUTO_VALIDATE_FAILURES":12}.

Promise ordering is identical across engines

This was the real risk. The budget depends on a .catch attached to the awaited call running before the post-await throwIfAborted, and engines can differ on microtask ordering. They do not here:

resolve: pre-post-throwIfAborted-passed, settle:resolve, aborted, await-returned, threw:AbortError, counter=0
reject : pre-post-throwIfAborted-passed, settle:reject,  aborted, catch-ran,      threw:Error,      counter=1

Byte identical in chromium, firefox and webkit. The two lines that matter: an abort that lands while the request is in flight counts nothing, and a rejection counts one, in every engine.

What is execution and what is inference

Executed: chromium, firefox, webkit on Linux, on the minified bundle.

Inferred, not executed: the Tauri shells. WebView2 on Windows, WKWebView on macOS and WebKitGTK on Linux are Chromium and WebKit derivatives, and the engines above are the same two families, but I have no Windows or macOS host here and am not claiming otherwise. This is lower risk than it sounds because the PR introduces no new browser API: the additions are Promise.prototype.catch, += and comparisons. AbortSignal.throwIfAborted is pre-existing in this file with 23 occurrences, and both diff lines near it are context lines.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 0db48ced16

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

@danielhanchen
danielhanchen merged commit f5be3fa into main Sep 9, 2026
3 of 41 checks passed
@danielhanchen
danielhanchen deleted the bound-autoload-validate-attempts branch September 9, 2026 10:01
danielhanchen added a commit that referenced this pull request Sep 10, 2026
…text (#10654)

* Unbreak main: compare the autoload guard's conditions, not its exact text

Two assertions in test_model_picker_contracts.py slice chat-adapter.ts on the
exact one-line text of the autoload guards. #10508 added a validateFailures
bound to both, which pushed each past the print width, so prettier wrapped them
and both assertions stopped matching. Neither test was updated, so main fails
them today.

Comparing the SET of conditions instead survives a rewrap and survives a later
PR adding another condition, while still failing when a condition is dropped.
Checked both ways: removing the cancellation check from the if, and removing
the attempts bound from the while, each fail the corresponding test.

* Count the complete guards, and keep the operator

Three problems with the first version, all reproduced before fixing:

Splitting on both || and && discarded the operator, so flipping the if-guard
from OR to AND still passed. Stopping at the first ) truncated the body when a
condition held a call, and taking the first if in the slice parsed an unrelated
earlier guard, both failing on a legitimate edit.

Balanced parentheses and a required operator fix those, but scanning for the
first guard that matches introduced a fourth: this slice carries the guard
twice, so a condition dropped from one copy was masked by the other. Requiring
every guard that mentions a condition to hold them all is wrong the other way,
since a nearby guard legitimately tests a subset. Counting the complete ones
catches a drop in either copy and leaves the neighbours alone.

* Strip comments and respect string literals when reading a guard

Scanning the raw source counted a commented-out copy of the old guard as live,
so dropping a condition from the real one kept the count at two and the test
passed. Reproduced before fixing. It now reads through _code_only, which this
file already used for the same reason.

The depth scan also treated a parenthesis inside a string as syntax, so a
condition like reason.includes(")") truncated the body and failed the test on
a legitimate edit. Both the balance scan and the operator split now track quote
state, including escapes.

* Blank comments and literal contents in one pass

Two more holes, both reproduced first. A guard-shaped string, such as a
diagnostic message quoting the guard, was counted as a live guard, so a real
condition dropped from the actual guard kept the count at two and the test
passed. And a live guard holding a URL string lost its tail, because the
comment strip removed everything after the // inside the quotes.

Handling comments and quotes separately cannot fix either: each pass needs the
other's answer. One scan now blanks comment bodies and literal contents while
preserving length, so delimiters and offsets still line up. Regex literals are
left alone and the docstring says so; distinguishing them from division needs
real parsing, and a guard holding one would be read with its slashes intact,
which is visible rather than silent.

* Pin the desktop startup gate to its condition, not its variable name

test_desktop_startup_waits_for_auth_without_intermediate_handoff asserted the
exact line 'const showApp = status === "running" && desktopAuthReady;'. That
binding has since been renamed to canMountApp and showApp now also requires
appShellReady, so the assertion fails on a clean checkout of main even though
the contract it protects is intact.

Match the condition and require the resulting binding to condition the mount in
the markup. Removing desktopAuthReady, removing the status check, or taking the
gate out of the mount all still fail; renaming the binding no longer does.

* Measure the unified-memory pool rule instead of reading it back as text

memory-unified-apu.test.ts pinned the panel's non-Apple unified-memory branch
with two source anchors and a 160 character budget between them. #10627
(ab28823) rewrote that branch to return a record rather than a number, so the
second anchor no longer exists anywhere in the file and the test has failed on
main ever since. The rule it guards survived the rewrite and got stricter: the
old Math.max fell back to the carved GPU window whenever the host RAM reading
was missing, which is the substitution the assertion message forbids, and the
new code reports known: false instead.

Move the rule into gpu-vram.ts as resolveFreeGpuCapacityGb, beside the
aggregates it is built from and reachable from the test runner, and have the
panel call it. The test now runs the rule: a non-Apple unified pool answers from
the host view rather than the window, an unread host figure is reported unread
rather than replaced by the window, and Apple and discrete hosts still answer
from their own free VRAM. One source assertion remains, for the one thing that
is still not reachable from here, which flags the panel hands over, and it no
longer depends on the distance between them.

* Move the guard-reading helpers into tests/studio/_js_source.py and fix three holes

Both contract files grew their own copy of the same scan, and the copies had
drifted. One module now, beside the other _-prefixed helpers in this directory.

Three defects went with the move, each reproduced first:

- A ternary was accepted without looking at its arms, so {gate ? null : <Shell />}
  passed while mounting the shell exactly when the gate is false. The true arm is
  now checked.
- The gate declaration was matched as exact text, so rewrapping it across lines
  turned a behaviour-preserving edit red. That is the failure this branch exists
  to fix, reintroduced two tests over. Operands are compared instead.
- Splitting stopped at depth zero, so (a || b) || c reported no complete guard.
  Same-operator groups are flattened and redundant operand parens stripped.

binding_joining locates declarations in the blanked source but reads operands from
the original at the same offsets: blanking empties string literals, and
status === "running" is a required operand.

Matrix, both call sites: drop a condition FAIL, flip the operator FAIL, gate out of
the mount FAIL, inverted ternary FAIL; rename, rewrap, redundant grouping and an
added prerequisite all PASS.

---------

Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant