Skip to content

Studio tests: do not dump core when a probe child is crashed on purpose - #8783

Merged
danielhanchen merged 7 commits into
mainfrom
studio-no-core-on-deliberate-segfault
Aug 14, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio-no-core-on-deliberate-segfault

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Two backend tests crash a child on purpose with ctypes.string_at(0), to check that the torch device probe treats a fatally-crashed child as an unusable device:

  • studio/backend/tests/test_torch_device_probe.py
  • studio/backend/tests/test_rag_embeddings.py

The SIGSEGV is the point of the test. The core dump that follows is not. core_pattern pipes it to the host handler (apport on Ubuntu), which reads the whole core before the child is reaped, so every run of this suite pays a multi-MB write and roughly 4x the wall time per fault.

This marks the child non-dumpable with PR_SET_DUMPABLE before it faults. The child still dies of SIGSEGV, so what the tests assert is unchanged, and no core is written.

Measured

Three runs each, on this box, with apport as the core_pattern handler:

exit mean
bare SIGSEGV -11 123.3 ms
PR_SET_DUMPABLE = 0, then SIGSEGV -11 30.1 ms
RLIMIT_CORE = 0, then SIGSEGV -11 117.2 ms

RLIMIT_CORE = 0 is the obvious thing to reach for and it does not work: a piped core_pattern ignores it, and the dump still happens. PR_SET_DUMPABLE is the only thing that suppresses it. Worth knowing, because the RLIMIT_CORE version looks correct and silently does nothing.

The non-crashing branch of the RAG script is unaffected:

rag script (argv=cuda)   rc=-11   30.9 ms
rag script (argv=cpu)    rc=  0   34.7 ms

Portability

prctl is Linux-only, so the call is wrapped and does nothing on other platforms. There it is a no-op and the tests keep exactly their previous behaviour, including the core dump, which is what those platforms did before this change anyway.

Why it is worth doing

The volume in CI is small, a handful of faults per suite run, so this is not urgent on its own. It matters because the pattern spreads. The same ctypes.string_at(0) idiom copied into a local reproduction harness with a for _ in range(trials) loop produced roughly 240 deliberate faults in 46 seconds on a shared build box, and the resulting apport storm was enough to take down every tmux session for that user. The tests here are the canonical example people copy, so it is the right place to establish that a deliberate crash suppresses its core.

Tests

tests/test_torch_device_probe.py    53 passed
tests/test_rag_embeddings.py        25 passed

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 63b995b567

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +183 to +185
crashes = _directs_a_fatal_signal(tree) or any(
marker in text for text in strings for marker in _CRASH_MARKERS
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Detect real crash calls, not only script strings

When a deliberate child crash is implemented as a Python helper or multiprocessing target instead of a -c script string, this only finds _CRASH_MARKERS inside string literals. For example, a child target that calls ctypes.string_at(0) or os.abort() has the marker in the source prefilter, but no matching string literal, and _directs_a_fatal_signal() does not cover those calls, so _classify() returns (False, False) and the new guard misses the core-dumping test. Walk ast.Call nodes for these unconditional crash calls as well.

Useful? React with 👍 / 👎.

Comment on lines +193 to +195
suppresses = _calls_prctl_set_dumpable(tree) or any(
marker in text for text in strings for marker in _SUPPRESS_MARKERS
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Tie core suppression to each crashing snippet

This records suppresses_core once for the whole file, so any helper or assertion-message string containing PR_SET_DUMPABLE makes every crash marker in that file pass. In files like test_torch_device_probe.py that now define a suppression helper, a later naked child script containing ctypes.string_at(0) would still classify as (True, True) even though that new crash would dump core. The guard needs to verify suppression on the crashing call/script itself rather than anywhere in the file.

Useful? React with 👍 / 👎.

Comment on lines +154 to +155
if isinstance(first, ast.Constant) and first.value == _PRCTL_SET_DUMPABLE:
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Require PR_SET_DUMPABLE to be set to zero

In a test file with a mistaken or teardown call such as prctl(PR_SET_DUMPABLE, 1, ...), this helper returns true as soon as the first argument is the dumpable command, even though the second argument re-enables core dumps instead of suppressing them. That lets the guard approve a deliberate crash that still dumps; verify the value argument is zero before counting the call as suppression.

Useful? React with 👍 / 👎.


def test_the_scan_finds_the_files_it_is_meant_to_guard():
"""A silent scan matching nothing would pass forever and protect nothing."""
crashing = [p for p in _iter_test_files() if _classify(p)[0]]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exclude the guard file from the non-empty check

This non-empty assertion is satisfied by tests/test_deliberate_crashes_suppress_cores.py itself: _classify() sees the marker constants and fix text in this file and returns (True, True). If the real deliberate-crash tests are later removed or the scanner stops matching them, this test still passes, so the advertised “guarding an empty set” canary does not actually catch that regression; exclude this module or assert on an external matched file.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

All four are real. Reproduced each against synthetic files before changing anything, and each one did exactly what the review said it would. Fixed in af39ba0.

1. A crash written as ordinary code was invisible. The crash markers were only matched against string literals, so a multiprocessing target that calls ctypes.string_at(0) directly classified as (crashes=False, suppresses=False). That is the most likely shape of the next one, since it is what you write when the child is a function rather than a -c script. Crash calls are now found as ast.Call nodes.

2. Suppression was recorded per file. Both files this PR fixes now define a suppressed helper, so under the old logic any naked crash added to them later would have passed. Suppression is now matched to the crash it is meant to cover: same enclosing function for a real call, same snippet for a script string. That needed constant folding of module-level string concatenation, otherwise _CRASHING_SCRIPT = _SUPPRESS_CORE + "ctypes.string_at(0)\n" is judged as a bare literal with no suppression in it and the actual fix in this PR gets flagged.

3. prctl(4, 1) counted as suppression. It re-enables dumps. The second argument is now required to be 0.

4. The guard matched its own markers, so test_the_scan_finds_the_files_it_is_meant_to_guard was satisfied by the guard itself and would have kept passing over an empty set. It now excludes itself, and the canary matches the two real files.

One more found while verifying the fixes: abort was matched on the trailing name alone, which flagged route.abort('failed') and parked.abort() in the Playwright helpers. Two false positives on the live tree. Detection now checks the receiver.

Nine fixtures cover all of this, including the negatives that must stay quiet: a signal named only in a comment, raise_signal(signum) re-raising a variable, and the unrelated .abort() methods.

Cost is unchanged. The two passes are merged into one cached analysis so no file is parsed twice, which paid for the extra work: 32 of 1046 files parsed, 496 ms scan, 0.65 s for the run.

tests/test_deliberate_crashes_suppress_cores.py    11 passed in 0.65s

Negative control still holds. Reverting both files to main fails the guard and names them:

AssertionError: These crash a process on purpose without suppressing the core dump:

    studio/backend/tests/test_rag_embeddings.py
        a child script that crashes on purpose
    studio/backend/tests/test_torch_device_probe.py
        a child script that crashes on purpose

danielhanchen and others added 6 commits August 14, 2026 07:02
Two backend tests crash a child with ctypes.string_at(0) to check that the
torch device probe treats a fatal child as an unusable device. The SIGSEGV is
the point of the test, but the core dump that follows is not: core_pattern
pipes it to the host handler (apport on Ubuntu), which reads the whole core
before the child is reaped. That is a multi-MB write and about 4x the wall
time, on every run of this suite.

Mark the child non-dumpable with PR_SET_DUMPABLE before faulting. The child
still dies of SIGSEGV, so what the tests assert is unchanged, and no core is
written.

Measured here, three runs each:

  bare SIGSEGV            rc=-11   123.3 ms
  PR_SET_DUMPABLE = 0     rc=-11    30.1 ms

RLIMIT_CORE = 0 is the obvious alternative and it does NOT work: a piped
core_pattern ignores it, measured at 117.2 ms, still dumping. PR_SET_DUMPABLE
is the only thing that suppresses the dump here.

prctl is Linux-only, so the call is guarded and does nothing on other
platforms, where these tests keep their previous behaviour.
… core

The two fixes in this PR are one-line each and the idiom is easy to copy, so
without a check the next test that needs a fatally crashing child reintroduces
the dump. This scans every test under tests/ and studio/backend/tests/ and fails
if a file crashes a process on purpose without marking it non-dumpable.

Detection is AST-based rather than textual. About forty places in this suite
mention SIGSEGV or SIGABRT in a comment, a docstring, or a return-code assertion
such as `assert f(-11) is True`, and none of them crash anything, so a grep would
be almost entirely false positives. Only real calls and real child-script strings
count, and because comments never reach the AST they cannot satisfy the
suppression side either.

Covers ctypes.string_at(0), os.abort(), signal.raise_signal(),
faulthandler._sigsegv(), and a self-directed os.kill() with a core-dumping
signal, in code or inside a script string handed to a child.

The failure message names the file and gives the fix, including the two traps:
prctl is Linux-only so the call needs guarding, and RLIMIT_CORE = 0 looks correct
but does nothing because a piped core_pattern ignores it.

A companion test asserts the scan still matches something, so a future rename
cannot leave it silently passing over an empty set.
Three gaps in the first version. It hardcoded two test roots, so the four other
suites in the repo were unguarded and a suite added later would be too. It only
looked at test_*.py, missing conftest.py, shared harnesses and the _*_shim.py
files CI invokes directly, all of which can spawn children. And it unparsed
every Call node in every file, which cost about 9 seconds.

Roots are now discovered rather than listed (any directory named tests, minus
the usual vendor and build dirs), and every .py under them is scanned, so
coverage went from 2 roots and 957 files to 6 roots and 1047.

Cost went the other way. A raw-text prefilter runs before any parsing: the AST
is a subset of the source, so a file whose text contains none of the markers
cannot match and is skipped. 21 of 1047 files are actually parsed. The scan is
418ms, down from 9055ms, and the pytest run is 0.51s.

Also tightened the signal detection. signal.raise_signal(signum), the re-raise
after restoring the default handler, appears twice in production terminal-prompt
code and is not a deliberate crash. A directed signal now only counts when a
core-dumping signal is actually named, so those two no longer match.

Reporting is one aggregated assertion instead of 1047 parametrised cases. It
lists every offending file at once, which is more useful than a per-file failure
and drops the case overhead.
Four holes found in review of the guard added in the previous commit.

1. A crash written as ordinary code was missed. Crash markers were only matched
   against string literals, so a multiprocessing target calling ctypes.string_at(0)
   went unseen. It dumps the same core as a script string does. Crash calls are now
   detected as AST Call nodes.

2. Suppression was recorded per file, so once a file defined a suppressed helper any
   naked crash added to it later passed. Suppression is now matched to the crash it
   covers: same enclosing function for a real call, same folded snippet for a script
   string. Module-level string concatenation is constant-folded so a script assembled
   as SUPPRESS + CRASH is judged as the script it becomes.

3. prctl(4, 1) counted as suppression. That value re-enables dumps. The second
   argument is now required to be 0.

4. The guard file matched its own markers, which made the non-empty canary vacuous.
   It now excludes itself, so the canary asserts on real test files.

Also tightened abort detection to check the receiver: route.abort() and task.abort()
are ordinary calls that shared the name.

Nine fixtures cover each of these, including the negative cases that must stay quiet.
Cost is unchanged: 32 of 1046 files parsed, 496ms scan, 0.65s for the run, after
merging the two passes into one cached analysis so no file is parsed twice.
@danielhanchen
danielhanchen force-pushed the studio-no-core-on-deliberate-segfault branch from 1fe396f to b504f2f Compare August 14, 2026 07:02
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2a364f4b8b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

# file whose text holds none of these cannot match and parsing it is wasted work. This
# is what keeps the check cheap: 32 of ~1050 files are actually parsed, 496ms rather
# than 9s.
_PREFILTER = _CRASH_MARKERS + _SIGNAL_DIRECTED + ("abort(",)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Broaden the prefilter before relying on AST detection

Because this prefilter reuses the exact _CRASH_MARKERS, a file is skipped before AST parsing if the same crash call is formatted differently, e.g. ctypes.string_at( 0) or ctypes.string_at(0, 1). Those still segfault, but _analyze() returns no crash at the raw-text check, so the guard misses an unsuppressed core-dumping test entirely; keep the prefilter broad enough to parse candidate files and let the AST checks decide precision.

Useful? React with 👍 / 👎.


def _scope_suppresses(scope) -> bool:
"""Whether this function (or module) clears the dumpable flag anywhere in it."""
return any(_prctl_clears_dumpable(n) for n in ast.walk(scope))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Require dump suppression to dominate the fault

Even after narrowing suppression to the enclosing function, this helper treats a prctl(4, 0, ...) anywhere in that scope as protecting every crash in it. If a future child helper has the suppression after ctypes.string_at(0) or only in a non-crashing branch, the process still dumps core but _violations() returns empty, so the new guard blesses the unsafe pattern; check that suppression occurs on the path before the fatal call/script instead of anywhere in the scope.

Useful? React with 👍 / 👎.

if name not in _DIRECTED_NAMES:
return False
rendered = ast.unparse(node)
return any(s in rendered for s in _FATAL_SIGNALS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recognize numeric fatal signals too

This only treats directed signals as deliberate core-dumping crashes when the rendered call contains a symbolic name like SIGABRT. A test can still crash itself with the common numeric forms signal.raise_signal(11) or os.kill(os.getpid(), 6), and the prefilter will parse those files but _is_crash_call() returns false, so an unsuppressed SIGSEGV/SIGABRT slips through the new guard.

Useful? React with 👍 / 👎.

Comment on lines +197 to +199
for node in tree.body:
if not isinstance(node, ast.Assign) or len(node.targets) != 1:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fold annotated or local script constants before checking

This folding pass only handles unannotated module-level Assign nodes. If a safe script is assembled as _CRASHING_SCRIPT: str = _SUPPRESS_CORE + "ctypes.string_at(0)\n" or with the same assignments inside a test function, the combined snippet is never folded and the unconsumed crash literal is checked by itself, causing the guard to report a violation even though the actual child script suppresses its core.

Useful? React with 👍 / 👎.

continue
if id(node) in consumed or id(node) in docstrings:
continue
out.append(node.value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Limit snippets to strings that are actually executed

This appends every non-docstring string literal as a candidate child script, so an ordinary assertion or error message that mentions the crash idiom, such as assert "ctypes.string_at(0)" in text, is reported as an unsuppressed deliberate crash even though nothing is executed. That makes the guard fail on documentation or expectation strings; restrict snippet checks to constants passed to child interpreters or known script variables.

Useful? React with 👍 / 👎.



def _snippet_crashes(snippet: str) -> bool:
if any(marker in snippet for marker in _CRASH_MARKERS):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Parse child snippets for crash calls

Snippet crash detection is still textual, so a child script that crashes through an alias, e.g. from os import abort; abort(), is parsed by the outer file prefilter but _snippet_crashes() returns false because the string does not contain os.abort(). That unsuppressed SIGABRT would dump core while the guard reports no deliberate crash; parse the snippet and reuse the call detector instead of only matching marker substrings.

Useful? React with 👍 / 👎.

if owner is None:
owner = _enclosing_scopes(tree)
scope = owner.get(id(node), tree)
if not _scope_suppresses(scope):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Follow suppression helper calls before flagging real-code crashes

For crash calls written as normal Python code, the check only looks for a raw prctl(4, 0, ...) inside the same function body. If a child target does the safer, reusable thing and calls a local suppress_core() helper before ctypes.string_at(0), the process is non-dumpable but this branch still reports a violation because the helper body is outside the crash function's AST scope; account for simple local suppression helpers before failing the test.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 1838e10 into main Aug 14, 2026
37 of 41 checks passed
@danielhanchen
danielhanchen deleted the studio-no-core-on-deliberate-segfault branch August 14, 2026 07:18
danielhanchen added a commit that referenced this pull request Aug 14, 2026
…ration

The env-twin sweep took LLAMA_ARG_MMPROJ and LLAMA_ARG_MMPROJ_URL with it.
--mmproj is refused in the box because Unsloth resolves the projector itself,
but the environment twin is an INPUT: _launch_has_mmproj reads both to know the
launch has a projector at all, and that is what keeps the vision and audio state
of a model loaded through an inherited one. Scrubbing them cleared that state,
which test_gpu_init_crash_message caught on three cases. Only the paravirtual
CPU recovery drops them now, as before, where an unpinned projector is the
corrupt path it is undoing. The pooling twins stay listed but noted: load_model
already pops LLAMA_ARG_POOLING / _RERANKING / _EMBEDDINGS itself.

The auto-load failure-gate harness slices chat-adapter.ts and evaluates it, so
the stored-arguments hydration added there left three names undefined and every
scenario failed on the harness's own missing-symbol assertion. Stubbed neutrally:
these scenarios are about the failure gate, not about which flags a model
launches with, so fetchLoadExtraArgs answers 'nothing stored' and the sanitizer
is identity, leaving the /load payload each scenario asserts on unchanged.

Merged origin/main first, so this branch carries #8783 (a deliberate segfault in
the probe tests no longer dumps core).
danielhanchen added a commit that referenced this pull request Aug 14, 2026
* Studio: close seven detection gaps in the deliberate-crash guard

Follow-up to #8783. Seven holes in the AST scan, all reproduced against synthetic
files before changing anything. Three of them fail CI on correct code, which is the
worse direction for a guard to be wrong in.

False positives, code that is already safe but was reported:

  * A script assembled through an annotated assignment (SCRIPT: str = SUP + ...) was
    not folded, so the crash half was judged alone with no suppression beside it. The
    fold now walks every Assign and AnnAssign rather than the module body.
  * Any string literal counted as a candidate child script, so an ordinary expectation
    such as assert "ctypes.string_at(0)" in script was reported as a deliberate crash.
    A string now only counts if it reaches a call argument, directly or through a name,
    a list, or a concatenation, which is what handing it to a child interpreter looks
    like.
  * A crash function calling a suppress_core() helper was reported, because the helper
    body sits outside the crash function's scope. One level of local helper is now
    followed. Factoring the suppression out is good practice and must not fail.

Misses, code that dumps a core but passed:

  * The prefilter reused the exact crash markers, so ctypes.string_at( 0) was skipped
    before it was ever parsed. It now matches the call name and lets the AST decide
    precision, which is the right split of responsibility between the two.
  * Suppression counted anywhere in the scope, so a prctl placed after the fault
    passed. It must now precede the crash line.
  * Only symbolic signal names were recognised, so raise_signal(11) and
    os.kill(pid, 6) slipped through. Numeric forms count too.
  * Script snippets were matched textually, so from os import abort; abort() was
    missed. Snippets are Python, so they are parsed and run through the same call
    detector, which also picks up aliased and differently spaced forms for free.

Ten new fixtures, one per hole plus the negatives that must stay quiet: Playwright's
route.abort(), a variable re-raise, and os.kill with SIGKILL, which never dumps.

19 passed in 1.32s. 32 of 1049 files parsed, 833ms scan. Reverting the two guarded
files to their pre-#8783 state still fails the guard and names both.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Close seven more detector gaps in the deliberate-crash guard for PR #8788

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Crash guard: close four more detection gaps, decline four

Four of the eight review findings were reproducible misses, each verified
against the guard before and after:

  * A command vector bound to a name. `CMD = [sys.executable, "-c", SCRIPT]`
    then `subprocess.run(CMD)` resolved nothing, because the name environment
    folds only strings and a list does not fold. That is ordinary subprocess
    usage, not a contrivance, so the child script went unread entirely.
  * A crash imported under an alias. `from os import abort as die` binds `die`,
    the rules are keyed on `abort`, and the alias map was a set of bound names
    with no way back to the rule. The file was also skipped before parsing,
    since the prefilter looks for call shapes and an aliased call contains
    none, so the alias handling could never have run. Both ends fixed: the map
    is now bound name to rule name, and the prefilter matches import spellings.
  * `obj.suppress_core()` credited to an unrelated local `def suppress_core`.
    Helper following now requires a bare local call.
  * An `async def` suppressor that is called but not awaited builds a coroutine
    and runs no prctl, so the fault after it still dumps. Only awaited calls
    count now.

Declined, with reasons rather than silence. Three findings (a name reassigned
after the call that uses it, a nested scope rebinding a name used at module
level, two same-named helpers in different scopes) are one underlying issue:
resolution that ignores position and scope nesting. Fixing it properly needs a
flow-sensitive analyser, and fixing it partially is how a guard starts failing
CI for innocent code. The triggering shapes are contrived, and this is a
heuristic backstop rather than a soundness proof. The fourth, an exec snippet
inside an already-suppressed snippet, is exotic and errs toward a loud false
positive rather than a silent miss.

Seven cases added to the table, two of them negative, so the four fixes cannot
regress and the two behaviours that must stay allowed (awaited async helpers,
rebound aliases) are pinned. Prefilter still admits 32 of 1049 files, so the
widening costs nothing. Stale timing in the comment corrected: the scope and
alias analysis added over this PR moved the full pass from 496ms to ~1.5s.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Aug 14, 2026
* Add an extra llama-server arguments box to the model settings

llama-server documents 283 flags and Studio already emits or manages about
115 of them, so the long tail has no way to be set from the app. The
pass-through itself already existed end to end (LoadRequest.llama_extra_args,
validate_extra_args, per-model persistence, the CLI), it just had no control,
which is why the overrides route deliberately preserves the field when the
panel saves.

Adds the control, and closes the denylist gap that opens once a flag can be
pasted in rather than typed on a command line. --tools was already denied
because it enables exec_shell_command; --agent is documented as enabling all
built-in tools, so it reached the same capability one alias away. Also denied:
--tools-runtime (docker:, podman:, ssh:<target>), the MCP server flags, the
CORS flags, --media-path, the log redirection flags Studio parses its own
startup output through, --slot-save-path, and the flags that exit instead of
serving. --slots and --props stay a user choice: Studio reads GET /props and
never /slots.

The editor checks what is typed against the INSTALLED binary's --help rather
than a list shipped with Unsloth, since a custom or newer llama.cpp is exactly
the case a bundled list would get wrong. probe_server_capabilities already
parsed that map and threw it away; it is now returned by
GET /api/inference/llama-flags. A flag the build does not document warns but
still loads, an unprobeable build says nothing, and a flag Studio owns is
refused with the control that sets it named. A flag that shadows a control is
allowed and noted, because the backend appends extras last and reconciles its
own sizing, and the CLI has always allowed it.

With the box empty the emitted command is byte-identical to before.

* Read the stored flags under the repo key too, and reword the unknown-argument error

The panel keys per-model settings by repo:QUANT, but the overrides route carries
flags stored under the bare repo id into the first per-quant save, so reading
only the exact key showed an empty box for an entry that was about to be
inherited. Caught by driving the real panel: flags set through the API for
unsloth/gemma-3-270m-it-GGUF did not appear.

The unknown-argument message pointed every reader at the extra arguments box.
Nothing reaching the classifier says whose flag it was, and Unsloth emits its own
conditionally on the capability probe, so a binary swapped under a cached probe
lands there too and would be sent to a box it never came from.

* Block the load when an extra argument would be refused

The row painted a managed flag red and left Load model enabled, so the panel
started a load validate_extra_args then refused. Seen on a real Studio:
--parallel 8 showed its error and the button stayed live. The row now reports
loadability up, and the objection leaves with the row so a model without the
box (diffusion) still loads.

* Send the extra arguments on the panel's own load

The Load button in the model settings goes through use-chat-model-runtime, which
builds its payload field by field, so the flags stayed in the config and never
reached llama-server. Caught by loading gemma-3-270m from the panel with
--top-k 20 in the box and reading the emitted command, which did not have it.

Omitted rather than nulled when the config has not read them, so the route still
preserves flags set outside this panel.

* Refresh a comment whose premise this change retires

The forget path said flags have no UI control. They do now; what the sentence
was actually about is that an omitted field is preserved, which is what a save
that never opened the box relies on.

* Bound the argument-error scan

main's test_a_huge_unterminated_line_is_cheap caught this on the rebase: the two
new regexes ran over the whole capture, and _drain_stdout keeps an unterminated
line whole, so a 10 MB single line was scanned twice and the classifier went past
its 200 ms budget. llama.cpp prints the argument error and exits, so the tail is
where it always is.

* Drop, do not refuse, flags an existing install stored before the denylist grew

Widening the denylist is the one part of this change that acts on data already on
disk. An override written when --log-file or --slot-save-path was still allowed
still holds it, and the two paths that CARRY such a value over rather than receive
it were refusing:

- the settings save re-validated the carried-over list, so changing Context Length
  on that model returned 400 naming a flag the user was not editing and cannot
  reach from that payload
- the load path caught the same refusal but degraded to no extras at all, so one
  name added to the denylist silently took every other flag with it

Both now use drop_managed_flags, which removes only the denied names (with their
values, or a bare /var/log/x would be read as a positional model path) and
re-validates what is left. An argument the caller just sent is still refused
loudly; an argument merely carried over from storage is dropped quietly.

Also off the event loop: the flag catalogue route awaited probe_server_capabilities
inline, and on a cold cache that runs llama-server --help with a 10s timeout. The
startup probes were moved to a thread for exactly this reason
(test_startup_llama_probe_non_blocking), so the first open of the panel after an
update would have stalled every other request.

Two new suites: the compatibility one covers every carry-over path with flags an
older build allowed, and the platform one runs the Cartesian product of
Linux/WSL/Windows/macOS with NVIDIA/multi-GPU/Vulkan/CPU-only, asserting the
command is unchanged with the box empty and that an extra arg never moves a
placement flag.

Twenty thousand random inputs through the box and through Python's shlex also agree
on every one that does not contain a backslash against a newline or end in a lone
backslash. Those two are deliberate: POSIX 2.2.1 makes an unquoted backslash before
a newline a line continuation, which shlex (a lexer, not a shell) does not
implement, and a text field that refuses a half-typed trailing escape is worse than
one that carries the character. Both are pinned as named tests now. The same run
showed an unquoted Windows path loses its separators, which is what every POSIX
shell does and not something to change in the splitter, so the hint asks for quotes
around backslashes rather than only around spaces.

* Name the oversized parametrize cases so they can run on Windows

Windows CI errored 16 tests in setup with ValueError: the environment variable is
longer than 32767 characters. pytest puts the whole parameter in the node id and
the node id into PYTEST_CURRENT_TEST, and these cases are 100 KB blobs, so the
limit is hit before the test body runs. Linux and macOS have no such cap, which is
why it went unnoticed. The blobs still exercise the linear-time claim; only their
ids are short now.

* Make the box and the launch agree, and keep the objection while the row is hidden

Ten fixes from the review round, the two largest of which were the box telling the
truth about what will run:

- Hydration filled the textarea but left the config undefined, so clicking Load
  without editing sent no llama_extra_args at all. The route's omission path
  inherits from a resident same-model process, not from the stored override, so a
  cold start launched without the flags the box was showing. Confirmed against a
  live Studio: the override held --numa distribute and the emitted command did not.
  Hydration now writes the config too.
- Collapsing Advanced settings unmounts the row, and its cleanup withdrew the
  objection while the tokens stayed in the config, so Load was re-enabled for
  arguments the backend refuses. The panel now holds the flag and retires it on a
  model change instead.

The rest:

- StrictMode replays an effect (setup, cleanup, setup), and marking the key before
  the request left the first fetch cancelled and the second setup returning early,
  so hydration never ran in development. Marked once a response is in hand.
- The lookup checked two literal keys while the overrides route folds identities
  and falls back from repo:QUANT to the bare repo, so a model whose entry was
  written under another casing showed an empty box. resolveStoredExtraArgs mirrors
  that order.
- The editor checked the token cap but not the byte cap, so a grammar or JSON
  schema over 32 KiB was loadable in the UI and refused by validate_extra_args.
  Measured in UTF-8, which is what the backend counts.
- isDefaultConfig did not look at llamaExtraArgs, so a config whose only change was
  the box read as default and savePerModelConfig deleted the entry it was asked to
  remember.
- Records carrying the new field are stamped v3. This scheme exists so a client
  from before a field refuses to rewrite records containing it; without the stamp
  an older cached tab would normalize the arguments back out on its next save.
- The catalogue published llama.cpp's removal stubs (--draft-max and friends,
  listed only to say the argument has been removed), so the editor called a removed
  flag supported and stayed quiet about a load that then failed. _is_real already
  existed for this.
- probe_ok equated "parsed something" with "read the whole thing". A --help that
  exits nonzero after partial output leaves a non-empty catalogue, and every flag
  past the failure point would have been reported as unsupported. The probe's own
  result is published and used.

* Name the scan-tail constant for what it bounds

It only ever bounded the argument-error branches. The dyld branches above it have
to keep reading the whole capture, because the pathological part of the input they
guard against is the library name inside the line itself
(TestTheLibraryNameIsBounded), so a tail would cut off the framing they match on.

* Close the third carry-over path, and say what the GPU picker takes away

The auto-switch path was the one place a stored override still became an explicit
request: model_override_load_kwargs copies llama_extra_args straight into
LoadRequest, and an explicit list is refused rather than trimmed, so an override
written before a flag was denylisted broke every OpenAI auto-switch and idle reload
of that model until someone rewrote the entry by hand. It is sanitized at that seam
now, like the inheritance and settings-save paths.

The editor also told two small lies and enabled two loads that could not succeed:

- --device, -dev, --main-gpu and -mg are stripped from the command whenever the GPU
  picker owns placement (_strip_device_extra_args), so the "passed after the
  settings above, so yours wins" reading was wrong for them. They are now called
  removed, and only while a GPU is actually selected.
- --ctx-size nope and -ngl many reach parse_ctx_override and
  parse_gpu_layers_override, which refuse the load. The row mirrors those checks.
- A control character (the usual source being a command copied out of coloured
  terminal output) is refused by the backend and was loadable here.
- A GGUF that turns out to be DiffusionGemma after classification kept its tokens
  in the loadable config, and the diffusion shim records them without ever passing
  them to anything. Cleared with the other flags that path already drops.

And the trim that keeps a legacy list inside the new bounds no longer leaves a flag
without its value: ['--grammar', <33 KiB>] became ['--grammar'], which this
validator accepts (it knows the arity of only a few flags) and llama-server then
refuses at startup.

/validate now carries the arguments too. It already resolves and passes them to the
estimator; only the request field was missing, so a --ctx-size or cache override
sized the preflight differently from the load it was approving.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Hydrate where the panel always mounts, and carry the flags into auto-load

Four things a closer read of the review turned up.

Hydration ran inside the extra-arguments row, which lives in Advanced
settings and is not rendered while that section is collapsed, so a panel
opened closed never fetched the stored override and a cold load launched
without it. Moved to the panel, which always mounts.

The startup auto-load built its request from the local config and left
the flags out. There is nothing resident at that point for the omission
path to inherit them from, so a remembered list was dropped on exactly
the load that most needs it. The preflight check sends them too, or it
would approve a command the load then refuses.

The flag catalogue was cached for the whole session. A llama.cpp update
or a backend switch replaces the binary in place, so a newly added flag
kept being reported as unknown. One minute now, plus an explicit drop on
both paths that change the binary.

Short aliases were parsed out of --help and thrown away, so typing -fa
warned that a valid flag was not in this build.

* Keep a wrapped paste to its own tokens, check every copy, log names only

A backslash-newline contributes nothing, so it must not mark the start of
a token: a command wrapped and indented under its first line, which is
how they are pasted, gained an empty token at that indentation and sent
llama-server a bare positional it reads as a model path.

The numeric-value check ran once per flag name, but llama.cpp reads the
last occurrence and so does parse_gpu_layers_override, so `-ngl 20 -ngl
many` left Load enabled for a request that comes back 400. Checked at
every occurrence now, reported once.

drop_managed_flags put a rejected VALUE into the list its callers join
into a warning log. A stored value carrying ANSI escapes belongs in no
log line, so it is a placeholder now, and the flag it belonged to is
named rather than disappearing silently.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the box, the button and the preflight honest about what will launch

The textarea seeded itself once. Reset and the panel's own hydration both
replace the arguments while the row is mounted, so the box could show one
thing while Load sent another. It now follows a change it did not make,
and ignores the echo of the user's own typing.

Load was not gated on the stored-arguments read, so a fast click on a
cold model launched without them. Gated now, and released on failure or
after four seconds, because the gate is there to win a race rather than
to make the button depend on a service being up.

/validate took the field but then passed None to the resolver, which
returns that argument unchanged for an explicit list, so a --ctx-size
override was missing from the estimate that approves the load.

The overrides fold split on the last colon, which is legal in a POSIX
filename: /models/foo:Bar.gguf folded onto the real, different file
/models/foo:bar.gguf. It uses splitQuantSuffix now, as the backend does.

An unpaired surrogate passed validation and then made Popen raise while
it encoded argv, after the load had begun switching models. Refused at
the boundary, and dropped rather than kept on the carry-over paths.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the same override row the server would, and clear what Reset clears

Five of these are about the panel and the auto-switch loader disagreeing
over one stored map, which matters because the panel hydrates from a row
and then sends what it found as an explicit list.

The lookup fell through to the bare repo id whenever the variant row
carried no arguments, where the server breaks at the first non-empty
entry and reads its fields from there. Two keys that fold together now
resolve to nothing, as resolve_model_override_key does, rather than
whichever was enumerated first. A WSL drive mount folds case
insensitively, because it is a Windows volume seen through Linux and the
server folds it that way.

Hydration also turned a stored list into an explicit request, so a flag
added to the denylist since it was saved came back as a 400 instead of
being dropped quietly; the stored list is sanitised against this build's
denylist before it becomes one.

The numeric check accepted a missing or out-of-range value, so
--ctx-size with nothing after it, --ctx-size -1 and -ngl -2 all left Load
enabled for a request parse_ctx_override and parse_gpu_layers_override
refuse.

Reset left the field absent, which the load path reads as inherit, so a
reload after Reset kept the very flags the empty box said were gone. It
is an explicit clear now.

* Sanitize a stored list the way the server does, and fold paths its way

The hydration sanitizer only removed denied flags, but this branch also
made the bounds, control characters and unpaired surrogates refusals, and
a list saved by the previous release can carry any of them. It now
mirrors drop_managed_flags whole, including shedding from the tail
without leaving a flag without its value.

Path folding only lowercased, where the server also swaps backslashes for
slashes, trims trailing separators and folds a UNC share, so an override
stored as C:\Models\Foo.gguf was missed for a picker key spelled
c:/models/foo.gguf and a forward-slash UNC path was read as a
case-sensitive POSIX one.

The cache-type and split-mode flags take a value that _last_flag_value
insists on, so a bare -sm or a trailing --cache-type-k now reads as the
error it is rather than only a note about shadowing.

The four-second release was on the Load gate, which let a click through
while the overrides response was in hand and only the cold --help probe
was outstanding. The deadline is on the catalogue now: past it the stored
list is applied with whatever the catalogue gave, and the gate itself has
only a last-resort release.

A stored flag whose own token carried a control character was dropped
without its value, leaving a bare positional llama-server reads as a
model path, and its name went into the log line escapes and all.

The backend switch invalidated the flag catalogue when the job STARTED,
before the binary was replaced. It happens on successful completion now,
for a tab that only watched the switch as well.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep an emoji, read the denylist without the probe, and leave other models alone

The surrogate check matched both halves of every well-formed pair, so a
stored chat template or grammar carrying an emoji was dropped on
hydration along with its flag, though Python encodes it happily. Only an
unpaired half is refused now, which is the one Popen raises on.

Sanitizing waited on the flag catalogue, and its first read runs
llama-server --help with a ten second timeout. The denylist needs no
binary at all, so the route answers it on its own now and hydration waits
for that instead: no window in which a legacy flag is left in an explicit
request, and no deadline to release early.

The scrub list covered the twins of every denied flag except the logging
ones. Studio classifies a failed start by reading llama-server's output
and emits nothing later that would override an inherited redirect, so
LLAMA_ARG_LOG_FILE turned every failure into the same opaque diagnosis.

A GGUF reclassified as diffusion after the box was typed into kept the
row's objection while the arguments were stripped from what loads, so
Load stayed disabled over arguments the request no longer carried.

And a Transformers or MLX model waited on both requests before Load
became live, though nothing outside GGUF renders the row or sends the
field.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let a grammar wrap, read the load-path keys, and restore what was running

The control-character check I tightened last round swallowed the newline,
so a quoted multi-line grammar, schema or chat template disabled Load
even though validate_extra_args accepts tabs and newlines on purpose. The
editor now uses the backend's rule exactly.

Hydration asked under the repo id only. A cached GGUF outside the active
HF cache loads by its snapshot path, and the auto-switch loader reads the
path-qualified key first, so an override left there stayed the one API
loads apply while the panel showed none of it. The candidates are the
loader's own, in its order, including the filename-label key an early
build wrote for a loose .gguf.

Windows passes CreateProcess one string for the whole command line,
capped at 32767 characters, so 32 KiB of extras alone left nothing for
the model path and Unsloth's own flags. The cap is 24 KiB there, refused
at the boundary rather than inside Popen once the switch has started.

And a rollback after a failed switch omitted the arguments, which by then
inherits from the newly resident target rather than from the model being
restored, so the previous model came back without the flags it had been
running. The client keeps what it last knew that model was running and
sends it explicitly.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Guard the cleared list in the rollback snapshot

tsc -b is stricter than the standalone check I ran: llamaExtraArgs is
string[] | null, so reading .length on the cleared case failed the build.

* Refuse an ownerless value, size the preflight, and stop trusting a stale probe

A bare token in the box belonged to no flag and was accepted. Today's
llama-server answers "invalid argument" and refuses to start, so it is a
failed load rather than a 400, and a build that did take a positional
would read it as the model path, which is the one thing denying -m and
--model exists to prevent. Every value must now follow its flag, with the
two-value flag in llama-server's help allowed for.

The Windows cap counted bytes, but list2cmdline doubles backslashes
before a quote, so an escape-heavy grammar passed the cap and still blew
CreateProcess's limit once serialized. The check measures what Popen
would actually write.

The runtime preflight left the arguments out while the load sent them, so
/validate approved a differently sized command. During training that
means approving the switch, unloading the resident model, and having
/load refuse the target.

With Advanced collapsed the row never mounts, so nothing judged a stored
list this build refuses and Load stayed live for a request that 400s. The
hydration judges it now, which the managed set is enough for.

A diffusion GGUF is GGUF-shaped but runs through the shim that appends no
llama-server flags, so it no longer waits on the hydration either.

And an invalidated catalogue kept its in-flight request, which wrote the
previous binary's flags back and was handed to every caller for the TTL.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Say so in the box when a value has no flag

The backend refuses it, so without this the editor looked content and the
load came back 400. Proven against a live Studio: /load answers 'extra
llama-server args cannot contain a bare value' for a bare path, and the
box now says the same before the button is pressed.

* Retire the bare-positional pass-through the new check contradicts

Staging CI caught two pinned expectations I had not run: a suite asserted
that a bare token passes through, and the tab and newline cases passed
their string with no flag in front of it.

The first is the contract this round deliberately changes, so it now pins
the refusal and says why: llama-server answers "invalid argument: foo"
and refuses to start either way, and a build that did take a positional
would read it as the model path. The second keeps its intent, with the
string where such a string actually arrives, as its flag's value.

* Prove the scan bound by behaviour instead of by a stopwatch

This test is the one job still red on Windows, and it is red on main
there too: a 0.2s budget on a shared runner measures the runner, not the
code. The bound is observable without timing at all, so it is asserted
directly now: an argument error 10 MB back is not reported, one in the
tail is, and only an unbounded scan can tell the difference. Checked both
ways, by widening the bound and watching the buried error reappear.

The stopwatch survives as a catastrophic guard at five seconds, which no
runner can trip and no sane implementation can exceed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let the backend answer what a load will apply, and publish what it knows

The panel kept re-deriving the backend's own answers in the browser, and
each round found another way the two drift. Both now come from the source.

Which stored row a load reads is resolved server-side: the candidate order
the auto-switch loader uses lives in one function that the loader itself
calls, and the overrides route can be asked for a named model's entry.
That closes the casefold gap for good (Straße and STRASSE are one path to
Python and two to a browser), along with the whole class it belongs to.
The local resolver stays as the fallback for a backend without the
parameter.

The flag catalogue now says which flags take no value, read from the
same --help it already parsed, so the editor can tell "--verbose foo" (a
typo llama-server refuses) from "--numa distribute". It also reports this
host's size limits, so a 25 KiB grammar is refused in the box on Windows
rather than at the load, and the quoted-length rule is mirrored exactly:
a port of list2cmdline, checked against CPython's own output over 2010
generated cases with no mismatches.

Two more from the same review: a model whose arguments live only on the
server no longer opens looking like every default, and a diffusion GGUF
neither sends them (its runner appends none) nor has them recorded, with
the backend clearing them when its authoritative classification picks
that runner.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the user's verdict, bound what the child says, and close two env twins

An edit made while the overrides request was in flight had its verdict
replaced by the answer about the stored list, so Load went live for
invalid text; the hydration now leaves both the config and the judgement
alone once anything has been typed. The same request also sanitizes the
list already in local storage, which a build that allowed those flags may
have written and nothing else would catch while Advanced stays collapsed.

A failed start quoted an argument straight out of the child's output, and
a wrapper on LLAMA_SERVER_PATH can print 64 KiB of non-whitespace, so the
quoted fragment is bounded now.

Two more environment twins go with the flags they mirror: --api-prefix
moves the /health endpoint every load waits on, and an inherited API key
makes the healthy child refuse the requests Studio sends without one.
llama.cpp spells one of them LLAMA_API_KEY rather than LLAMA_ARG_, so the
invariant tying twins to denied flags now accepts both prefixes.

And a compare pane resolves the stored arguments before it loads, since
the omission path inherits only from a resident instance of the same
model, which is exactly what a pane switching away from the other one
does not have.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep a two-value flag whole, and judge what each end can actually know

Five items from the last review.

Two-value flags: validate_extra_args now tracks the values
--control-vector-layer-range is owed and refuses a list that stops
between them, and drop_managed_flags sheds the whole option when the
size bound would take only its second value. Half of it is not a
smaller version of it: llama-server refuses the option on the command
line, so a trimmed list used to fail at spawn instead of at the
boundary.

/validate now drops pass-through arguments for a confirmed diffusion
GGUF, as /load already does. The estimate that approves the load was
reading a --ctx-size out of a list the diffusion runner never receives.
The classification is only authoritative after placement, so the drop
belongs there rather than in the caller, whose staged metadata can be
inconclusive.

The stored-argument sanitizer takes the host's own bounds instead of
the constants: a Windows server takes 24 KiB and holds a quoted-command
budget besides, and trimming to 32 KiB left a list /load answers 400 on.
Compare panes now sanitize the list they fetch from the overrides map
for the same reason the panel does, so an install upgraded across a
denylist change keeps comparing.

The editor also refuses a catalogued value-taking flag left without its
value at the end of the text. That arity is only knowable from the
probed help, which is why the check lives here and not in the backend
validator; an unprobed build and an unknown flag both keep the benefit
of the doubt.

Also fixes a regression in the help parser: the flag-arity map and the
removal-stub test were initialised inside the probe's try block, so a
binary that timed out raised UnboundLocalError instead of falling back
to "nothing known about this build".

* Publish what the server is running, and stop guessing at the rest

Five items from the last review.

An attached value counts as one of the two: "--control-vector-layer-range=1"
still owes its END, on both ends. llama.cpp b10360 refuses the "--flag=value"
form outright ("error: invalid argument"), so this shape was never going to
launch, but treating it as a complete option left Load enabled and the failure
arrived at startup instead.

/api/inference/status now publishes requested_llama_extra_args, and the store
seeds its loaded baseline from it. A tab opened while a model was already
running never saw the load, so that baseline stayed null; a switch that
launched the target and then failed during refresh rolls back with the field
omitted, and because the failed target is left resident, omission cannot
inherit across models. The previous model came back without the arguments it
was running.

The panel no longer sanitizes a list the user typed while hydration was in
flight. It snapshots what the config held when the request went out, so a
legacy stored list is still cleaned while live input is left alone: typing
--agent during that window used to clear the box instead of showing the error.

A collapsed Advanced section is re-judged once the flag catalogue arrives. The
row keeps its verdict when it unmounts, by design, but a verdict reached before
the probe answered did not know which flags this build documents, and
collapsing froze it, so a bare --threads kept Load enabled.

Manual GPU memory now reports the offload flags it removes rather than claiming
they win. The route translates a layer count into the first-class field before
stripping, so -ngl really does win; nothing does that for --n-cpu-moe or --fit,
which are dropped and replaced by the controls' own values.

* Say which arguments the launch will drop, and stop one that aborts it

Three items from the last review, plus a CI fix.

Model Memory removes flags too. apply_model_memory_policy emits its own load
mode when "Keep model in GPU memory" is on and strips every other load-mode
bearing flag, because a trailing one resets the mode and would drop the lock;
"Don't reserve system RAM" drops the flags that hold a full host copy, leaving
mmap and DirectIO alone. The editor said those arguments win, so one could be
typed, saved and never passed. It now reports them as removed and names the
setting that owns them, the way it already does for GPU-owned placement.

A pass-through batch size below max(slots, 2) is refused. The loader raises the
value it emits itself, with measured evidence in the launcher comment that b1
aborts at any slot count and b4 with 8 slots aborts, but an extra -b is appended
after it and wins, so the load started and llama-server aborted on the
assertion. The floor here is the same one the batch control shows, including
its limit: with Slots blank only the hard 2 is asserted, since the server-wide
default is not visible to the page.

A background auto-load now resolves a server-only override. resolveInitialConfig
reads local storage, so an override written through the API or from another
browser left the field undefined, and at startup there is no resident process
for /load to inherit from: the model came up without the arguments saved for it.
Fetched and sanitized like the panel and the compare panes do, and sent to both
the preflight and the load.

The diagnostics context is now one object rather than a run of booleans. Every
setting that owns a flag group adds one, and five positional flags would be read
wrong at a call site long before they stopped compiling.

CI: the two HF credential-persistence tests waited on a fixed budget of
setImmediate turns for a real promise chain to settle. That is a bet on how many
turns the runtime needs, and a two-core runner running the suite in parallel
loses it; they now wait on a deadline.

* Carry the arguments through every path that loads a model

Four items from the last review, and the backend-test failure the last one
caused.

Applying from the Hub's full-page settings now passes the submitted config into
the selection. The runtime store does not carry llamaExtraArgs, so a selection
made without the config left the field undefined: the load omitted it and the
route kept the resident server's list, which meant an edit made there did
nothing and a clear did nothing either.

The background auto-load resolves the override under the advertised repository
id as well as the path it loads from. Cached inventory can hand back a different
loadId, and the row was written under whichever of the two the user was looking
at, so passing one identity twice missed it.

It also sanitizes a list that came from local storage, not only one fetched from
the server. That copy was written by whatever build was running then, so a flag
added to the managed set since would be sent explicitly and answered with a 400,
and the remembered model would not come up at all.

A collapsed Advanced section stops objecting once the list is empty. The row
leaves its verdict standing when it unmounts, by design, because the tokens it
objected to still go out with the load; after Reset there are none, and Load
stayed disabled over arguments the request no longer carried.

Backend: the runtime projection reads requested_extra_args through getattr. The
drift check below it is what turns a backend missing a runtime field into one
clear error naming all of them, and reading the attribute directly pre-empted it
with a bare AttributeError, which is what the two projection tests caught.

* Read a flag the way llama.cpp reads it, and keep the standing verdict

Six items from the last review.

The underscore spelling is a spelling, not an attached value. _flag_name folds
--ctx_size onto --ctx-size and llama.cpp takes both, so deciding attachment by
comparing the folded name against the raw token read "--ctx_size 4096" as a flag
carrying its own value and then refused the 4096 as a bare token. That is a list
the CLI has passed through since the field existed. Attachment is now decided
from the token itself: an "=" form, or an attached short like -np8.

A flag that interrupts another's value is reported. "--numa --verbose" leaves
--numa without the value this build's help says it takes, and the obligation was
overwritten by the next flag before the end-of-input check could see it.

The batch floor follows the server-wide slot count. /llama-flags now publishes
default_parallel_slots, read the way the loader reads it, because the browser
cannot see that number: with Slots blank the launch serves four, so -b 2 cleared
the editor's hard floor of 2 and aborted llama-server anyway.

Compare panes sanitize a local list as well as a fetched one, for the reason the
auto-load path already does: either becomes an explicit argument, and a config
saved by an older build can still name a flag that is managed now.

The hidden revalidation can only tighten its verdict. It judges the tokens, and
formatting them back into a string supplies the closing quote the user has not
typed, so an unclosed quote read as clean and re-enabled Load.

A mounted row re-reads the catalogue when the binary changes. Updating llama.cpp
from the banner invalidated the module cache, but a row that had already read it
kept judging arity against the old build's help until the section was closed and
reopened.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Repair a stored list the way the server does, and refuse the batch that aborts

Five items from the last review.

The stored-argument sanitizer now sheds the shapes validate_extra_args refuses,
not only the flags it denies. A token belonging to no flag goes (llama-server
reads a positional as the model path, which is what denying -m exists to
prevent), a two-value option left half-written goes whole in either spelling,
and a flag whose value the backend's own parser refuses goes with its value.
drop_managed_flags gets all of this for free by re-validating after each cut it
makes; this mirror trims by size alone, so it has to know the rules. It removes
the option rather than the tail, which keeps the rest of a legacy list working.
A 3000-case differential run against the real validator now comes back clean;
before it left 457 lists the backend would still have refused.

/load enforces the batch floor for callers that never see the editor. The
launcher raises the --batch-size it emits itself, with the measurements recorded
beside it, but an extra -b is appended after that and wins, so a CLI or API
caller sending -b 1 got a server that aborts during startup, after the previous
model had been unloaded. Now a 400, checked once the effective slot count is
known. A value this side cannot read is still left to llama-server, which names
it better than a guess would.

The loaded-arguments baseline follows a same-model reload from anywhere. Pinned
at the first read, a tab kept the old list after another tab or an API client
reloaded the same model with different arguments or with none, and a later
failed switch resent it from the rollback path. The in-flight guard stays: while
a load is in flight performLoad owns these values.

The hidden validation subscribes to catalogue invalidation as well. The row
holds its own subscription, but it is unmounted precisely when that check is the
one running, so an in-app llama.cpp update with Advanced collapsed left a verdict
reached against the previous binary standing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tell an empty list from an unknown one, and blame the right owner

Two items from the last review.

An explicit empty list is no longer collapsed to null, in the status the
backend publishes and in the baseline the browser records. The rollback sends
llama_extra_args only when it has one, and omitting it is what makes /load
inherit, so a same-model reload that added arguments and then failed its refresh
restored the previous runtime carrying the arguments it was rolling back. null
still means nothing was ever recorded, which is the only case where inheriting
is the right answer.

A rejected argument VALUE no longer sends every reader to the extra-arguments
box. Studio emits its own options conditionally on the capability probe, so a
build whose --flash-attn enum does not take the managed value rejects something
the box never held, and editing it cannot fix that. The classifier now takes the
load's extras and names the box only when they really carry the flag; otherwise
it gives the same neutral advice the unknown-argument branch already gives. An
alias spelling falls back to neutral rather than guessing, since a wrong "you
set this" is worse than no attribution.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Take the scale as a second token again, and read the load's own answer

Four items from the last review.

--lora-scaled and --control-vector-scaled may take their scale as a separate
token. Today's llama.cpp writes it into the value (FNAME:SCALE) and older builds
took it on its own, which _sidecar_weight_files already reads both ways, so the
positional check refused a list those installs had been loading. Allowed rather
than owed: requiring the second token would refuse the current syntax just as
badly. Both ends carry the same rule, and a third bare token still has no owner.

The committed baseline is what the load says it applied. A same-model reload
that omits llama_extra_args but sets max_seq_length has its inherited --ctx-size
stripped before launch, and the status refresh that would notice runs while the
load is still in flight, so the next rollback resent a flag the reload had
removed. The response's own echo is read first now.

The legacy overrides fallback searches the caller's identities. A backend that
predates the resolved field answers with the whole map and needs to be told which
keys to read; the auto-load and compare callers passed none, so against an older
server they searched nothing and launched without the stored arguments.

The hidden hydration check applies the slot floor it already knows. Without it a
stored --batch-size 2 released Load against a four-slot server, and a click
before the full catalogue check landed reached the deterministic 400.

* Prove the tail bound by behaviour in the second scan test too

The Windows staging runner failed this one at 204ms against a 200ms budget,
which is the runner and not the classifier: allocating and slicing a 10 MB
capture is most of that. The sibling test was already converted to assert the
bound by behaviour; this one kept the stopwatch.

It now asserts what the bound produces: an argument error inside the scanned
tail is reported, and one buried two tails back is not, which is only possible
if the scan stopped short of the head.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Size the batch floor by the slots the load will really serve

The floor was computed from the requested parallel slots, but load_model
clamps that number twice before launch: a llama.cpp without --kv-unified
serves one slot, and the diffusion runner takes no --parallel at all. A
four-slot ask against such a build refused --batch-size 2 for a command
that would have run it.

_effective_parallel_slots mirrors both clamps and now backs the /load
floor and the default_parallel_slots the editor sizes itself from, so the
browser and the server agree on the same number.

/api/inference/validate runs the same validation as the load it approves,
so a switch is not approved on arguments the load will refuse.

A successful load records the arguments the server was actually invoked
with as the rollback baseline, on the auto-load path and in a compare
pane; a non-GGUF load clears it instead of leaving the previous GGUF's
list standing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scrub the inherited TLS twins, and let a cleared box clear its fallback

Studio starts llama-server with the parent environment, and llama.cpp reads
LLAMA_ARG_* before argv. LLAMA_ARG_SSL_KEY_FILE and LLAMA_ARG_SSL_CERT_FILE
were not among the twins scrubbed, so a deployment that sets them for its own
llama.cpp had the child listen on https while Studio probed /health and
proxied over http: the server came up healthy and every load timed out.
Measured on b10360, where the pair turns 'listening on http://127.0.0.1:PORT'
into 'listening on https://...'. Both flags are already denied, so the twins
belong in the same list.

The first per-quant save copies a legacy bare entry's flags onto the quant key
and leaves the bare entry in place. Clearing the box then writes an empty list,
an entry with nothing usable left is not stored, and the next load falls back
to the bare key and applies the flags again, from a row no page can show. A
clear now reaches those fallbacks too, taking only the flags and only when no
other quant could still be reading them, which is the rule the explicit forget
already follows. A save that omits the field, and the fill pass, are unchanged.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refuse the attached --flag=value spelling llama.cpp has never had

common/arg.cpp looks the whole token up in its option map and folds only the
underscore spelling, so --top-k=20 is not --top-k carrying a value: it is an
argument llama-server has never heard of. Measured on b10342 and b10360, where
--top-k=20, --ctx-size=4096 and --flash-attn=on each exit with 'error: invalid
argument'. Both the validator and the editor treated any = as an attached
value, so the load was approved, the resident model was torn down, and the
child then refused to start.

It is refused at the boundary instead, while the message still has somewhere to
go, naming the two arguments to write. Splitting it here would be a guess:
for a switch the text after = is not a value, and this module cannot know an
ordinary flag's arity. A managed name keeps the message that says which control
owns it, and an = inside a VALUE (--override-kv a=int:2) is untouched. The
carry-over drops such a token beside the denied names rather than leaving it to
the tail trim, which would have cost every flag written after it.

The editor's own trim had the same underscore blind spot as the validator did:
it compared the normalized flag name against the raw token, so a value shed for
the size bounds left --grammar_file standing. Any flag whose value has gone now
goes with it.

Backend 1665 tests pass; frontend 2364; the differential fuzz over 3000
sanitizer outputs still has the validator refusing none of them.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scrub every documented env twin, and keep the slot probe off the loop

The scrub list had grown one name at a time. It is now the whole set: every
'(env: NAME)' the bundled b10342 help documents for a flag this module refuses,
which adds the web UI and its MCP proxy (upstream marks that one as not for
untrusted environments), --path's LLAMA_ARG_STATIC_PATH, the multi-model server
mode, the model and repo selectors, and the host, port and slot count. llama.cpp
applies the environment before argv, so the ones Studio always emits were
overridden anyway; the rest were reachable through the environment while the
same flag was refused in the box. A mapping records which flag each twin
belongs to, since the name does not always say, and the drift test reads that
rather than deriving it from the string.

HF_TOKEN is deliberately left alone: it is the standard Hugging Face credential
Studio's own downloads use, not a llama-server behaviour switch, and the child
is always given a local model path rather than a repo to fetch.

/api/inference/llama-flags computed the effective slot default inline, which on
a cold cache is llama-server --help with a ten second timeout on the event loop,
including on the managed-only answer that exists to avoid waiting for a probe.
It runs in a worker thread now, and a single-slot default still needs no probe.

Invalidating the flag catalogue now drops the managed answer as well. It carries
defaultParallelSlots beside the denylist, and that is the effective count, so a
tab that had already fetched it went on sizing the hidden hydration check's
batch floor from the binary that was just replaced.

* Record a cleared box as a row of its own, and refuse padded flags

Clearing the box for one quant wrote an empty list, which stores no row, so the
next load fell through to the legacy bare repository row and applied the flags
again. The first fix stripped that row instead, which was wrong twice over: the
bare row is the fallback for every quant that has no row, so forgetting Q4's
flags took Q6's with them, and the guard against that made the clear do nothing
whenever a sibling quant had a row of its own.

An explicit clear now keeps a row on the quant's own key saying it has no flags,
and only when a fallback would otherwise answer for that model. Nothing else is
touched: the legacy row keeps serving the quants still reading it, and a clear
with nothing behind it stores nothing, as before. An explicit forget still
removes the row.

A flag quoted with stray spaces was accepted too. _flag_name strips before it
looks anything up, so "--top-k " passed the denylist and the arity walk as
--top-k and went to the child with the space on it, and llama.cpp looks the
whole token up: measured on b10342, it answers 'error: invalid argument:
--top-k', naming a flag that reads as correct in the log. Refused now in the
validator and in the row, with the value dropped alongside it on the carry-over
path. A VALUE may still end in whitespace, which a grammar or a chat template
routinely does.

Backend 1106 tests pass; frontend 2366; the differential fuzz over 3000
sanitizer outputs, now including padded and attached spellings, still has the
validator refusing none of them.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the projector twins out of the scrub, and stub the auto-load hydration

The env-twin sweep took LLAMA_ARG_MMPROJ and LLAMA_ARG_MMPROJ_URL with it.
--mmproj is refused in the box because Unsloth resolves the projector itself,
but the environment twin is an INPUT: _launch_has_mmproj reads both to know the
launch has a projector at all, and that is what keeps the vision and audio state
of a model loaded through an inherited one. Scrubbing them cleared that state,
which test_gpu_init_crash_message caught on three cases. Only the paravirtual
CPU recovery drops them now, as before, where an unpinned projector is the
corrupt path it is undoing. The pooling twins stay listed but noted: load_model
already pops LLAMA_ARG_POOLING / _RERANKING / _EMBEDDINGS itself.

The auto-load failure-gate harness slices chat-adapter.ts and evaluates it, so
the stored-arguments hydration added there left three names undefined and every
scenario failed on the harness's own missing-symbol assertion. Stubbed neutrally:
these scenarios are about the failure gate, not about which flags a model
launches with, so fetchLoadExtraArgs answers 'nothing stored' and the sanitizer
is identity, leaving the /load payload each scenario asserts on unchanged.

Merged origin/main first, so this branch carries #8783 (a deliberate segfault in
the probe tests no longer dumps core).

* Validate the command the load will run, and hold the quotes the user typed

/load translates an explicit -ngl out of the extra arguments into the first-class
field when Manual GPU Memory owns the offload flags, then strips them. /validate
did not, so the call that APPROVES the switch judged a different command than the
one that runs: a diffusion GGUF asked with gpu_layers 0 and '-ngl 20' was approved
as a load that places nothing on any device and cannot compete with training for
VRAM, and then launched twenty layers on it; the opposite pairing refused a load
that only ever runs on the CPU. Same translation and same strip now, under the
same manual-only condition, so both paths size the same launch.

The managed flag answer is guarded by the catalogue generation, as the full
catalogue already was. Its denylist is Unsloth's own, but defaultParallelSlots
travels with it and that is the effective count for the probed binary, so a
request already on the wire when llama.cpp is replaced could repopulate the cache
the invalidation had just cleared and keep the old build's slot floor for the rest
of the session. Its finally is conditional too, or it would clear a newer
request's in-flight promise.

A quoted value beginning with a hyphen is a value again. parseExtraArgs drops the
quotes, so '--chat-template "- hello"' left a flag-shaped token in value
position and the row called the option's value missing, disabling Load over a
list the backend accepts and llama.cpp reads correctly. The tokeniser records
which tokens were quoted and the diagnostics read that only in value POSITION: a
flag quoted out of habit is still a flag, and a quoted token with no option in
front of it is judged as written.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Carry the remembered arguments into every launch, and clamp the floor too

A launch that only applies the remembered config to the runtime lost the flags.
applyPerModelConfigToRuntime has no field for them, and /load inherits them only
from the SAME resident model, so the Hub launch and the training handoff ran a
cold start, or a switch from another model, without the arguments the user had
remembered for it. Both selections now carry the resolved config itself, and
neither invents one when nothing is remembered: the field stays absent, which is
what lets a resident model keep its own flags.

The batch floor had the same shape of gap as the published default did. That
default is effective, but an EXPLICIT Slots value chosen in the panel is not: a
build without --kv-unified serves one slot however many are asked for, so Slots 4
with '--batch-size 2' was refused in the editor while the backend, which clamps to
one, accepts exactly that command. The catalogue now publishes whether this build
clamps, computed by asking the same helper the load uses, and the three floor
sites share one function so the row and the two hidden checks cannot drift.

A backend that publishes neither field reads as 'not clamped', which is the
behaviour those builds had before.

* Pass the slot clamp into the collapsed-panel hydration check

* Judge the same command the launcher runs

Three things the editor and the routes were judging differently from the
server.

Validate the pass-through list before the manual offload translation
rewrites it. In manual GPU memory mode /validate translated "-ngl" out of
the list and stripped the token before validate_extra_args ever saw it, so
"--gpu-layers=20" passed the preflight and /load answered 400 on the same
list, and a malformed "-ngl bad" raised an uncaught ValueError instead of
the 400 it was meant to be.

Size the batch floor from the slots an embedding GGUF actually serves.
--embedding caps the batch at the micro-batch and llama-server aborts when
that is below the slot count, so load_model reduces the slots to it before
launching: four slots with "-ub 2" and "--batch-size 2" launches at two
slots, where two is the floor, and both routes were refusing it. Read only
after the floor has already refused, so the header read is paid on the way
to a 400 rather than on every load, and only a positively classified
embedding GGUF relaxes anything.

Keep an explicit empty argument list apart from a missing one when the
panel hydrates. The settings page writes an empty list on purpose when the
box is cleared for a quant whose bare-repository row still carries
arguments; read as "nothing stored" the panel left the field undefined, its
next Load omitted it, and /load carried the resident model's arguments over,
which is exactly what had been cleared.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Cover the cleared-box tombstone, and keep its header read off the loop

The panel's explicit-clear hydration rests on a backend rule with no test of
its own: a save that clears the box for one quant keeps a row holding an
empty list, so a load stops there instead of falling through to a legacy
bare-repository row that still carries flags. Four cases now pin it: the
clear that suppresses the fallback while leaving the bare row for the other
quants, an empty save with nothing to suppress storing nothing at all, a
fill never writing one, and the flag deciding only what an empty list means.

The embedding classification behind the batch floor reads the GGUF header,
so run it in a thread: both routes reach it from an async handler that is
also serving download progress polls.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

1 participant