unsloth/studio/backend/tests/test_tool_xml_strip.py
Daniel Han c608649552
feat(studio): run chats in parallel in the Chat tab (#7455)
* feat(studio): run chats in parallel in the Chat tab

New Chat used to cancel whatever the current conversation was generating.
It now leaves it running, like switching to the Train or Export tab: the
sidebar shows which chats are still going, and Stop is per conversation.

Plain `unsloth studio` launched llama-server with one decode slot, so the
admission queue serialised every chat regardless of what the UI did. Both
entry points now default to the same slot count as `unsloth studio run`.

A model swap still ends every running chat, since they all decode on one
llama-server. /load and /unload now refuse with 409 and name those chats
unless the caller passes force_cancel_active, and the UI asks first.

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

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

* fix(studio): scope the composer tool badge to its own conversation

The green "Running Python: ..." badge above the composer read a single
global store value, so one chat's tool call showed above every other
chat's composer, including a brand-new empty one. Its elapsed counter
also restarted at 0 on every thread switch, and a run ending anywhere
cleared the badge everywhere.

Key the status by thread and store the moment it started, so each
conversation shows only its own tool call and the counter resumes rather
than restarts. Also adds a test that every conversation gets its own
tool sandbox directory, which parallel tool calls depend on.

* Fix stalled tool calls while awaiting approval for PR #7455

Three problems, all from the approval prompt behaving as though only one
chat could ever run.

Arguments were not streamed for a gated call, so the chat stayed blank for
as long as the model took to write the payload, which for a large file is
minutes. Nothing runs before the decision either way, and the code is what
is being approved, so python and terminal now stream their card while
gated. render_html stays suppressed: its card renders the payload.

The status read "Running ..." with a climbing timer while the call had not
started. It now reports that it is waiting for approval, then switches to
running once allowed.

The admission lease was held across the wait, so four unanswered prompts
held all four decode slots and no other chat could start while llama-server
sat idle. A parked run keeps its lease but no longer counts against
capacity.

Measured with four prompts left open: every gated call streamed its code,
none reported running, and a fresh chat answered in 0.4s where it
previously waited 290s and never did.

* Fix duplicated and truncated tool cards for PR #7455

A gated tool call rendered two cards: the provisional one that streams the
arguments, plus a second one keyed by the approval id. Only the second ever
got its tool_end, so the first spun "Running" for the rest of the chat.
Reuse the open part when the approval prompt arrives.

The terminal card also showed nothing but a 60-char trigger label, so a long
heredoc read as no progress at all. It now renders the command the same way
the Python card renders its script, and neither is capped at 10k chars.

Both cells moved inside the collapsible, so one chevron hides the code with
the output and Copy / Download exist only while the card is open. A card
parked on the prompt says so instead of counting up "Running".

* Fix review findings on the parallel-chat gate for PR #7455

Backend:
- /unload rechecks active generations under the lifecycle gate, like /load,
  and lets its 409 through the catch-all instead of rewriting it as a 500.
- /load gates only once _load_model_impl has decided this is a real reload,
  so an Apply on the already-loaded model no longer refuses, and the retry it
  asks for no longer cancels every chat before returning already_loaded.
- The direct /v1/responses stream registers in the cancel registry, so a
  non-forced unload can no longer tear llama-server down under it.
- run_server defaults to the same slot count as the CLI. colab.py calls it
  without the argument, so Colab was still serialising every chat.

Frontend:
- Cancelling a backgrounded chat aborts its own request rather than only
  posting a cancel id, which is the only thing that ends an external-provider
  or audio run.
- The model-swap dialog counts local runs only, and falls back to the backend
  when this tab's map is empty, so a reload or a second tab still gets asked.
- Context usage and the diffusion canvas are scoped to the chat that produced
  them; a compare row reads activity from its member threads.

Tests:
- The extracted-source cancel harnesses supply the active-generations module,
  which the tracked-cancel class now depends on.

* Fix the swap confirmation scope and cancel timing for PR #7455

A forced load cancelled every chat before the model identifier, GPU selection,
training coexistence and download checks had run, so a load that then failed
those checks stopped the chats and replaced nothing. The refusal still happens
early, but the destructive cancel now sits immediately before the teardown it
is paying for, and rechecks under the gate like /unload does.

The swap dialog only reconciled with the backend when this tab looked idle, so
one local chat was enough to hide a second tab's runs. Confirming then sent
force_cancel_active, which cancels every backend run, including the ones the
dialog never mentioned. The backend snapshot is now merged in every time, so
the dialog names what will actually stop. External-provider runs are never
registered there, so the union stays local-only.

Also drops the active-generations docstring claim about restoring sidebar
spinners, which nothing consumes.

* Defer destructive cancels and track every local stream for PR #7455

/unload cancelled the running chats before it had resolved that it unloads
anything. A stale model_path, which a second tab produces routinely, killed
every chat and then no-opped, leaving the resident model up. It now refuses
early and cancels only at each teardown, matching /load.

The swap dialog also stopped every chat locally the moment the user confirmed,
which threw away the two-phase backend behaviour: a load that then failed
identifier resolution, GPU validation or the training guard had already
truncated the replies. The backend now owns the cancel.

Three local streams decoded on llama-server without registering, so a
non-forced unload counted zero generations and tore the server down mid
response: /v1/completions streaming, and the plain and server-tool Anthropic
streams, the first of which is the default /v1/messages path. Note this makes
a non-forced load return 409 during those runs rather than draining quietly,
the same trade the /v1/responses fix made.

The safetensors tool loop still announced a gated call as running while it
waited on a human; only the GGUF loop had been fixed. A source-level parity
test now pins both.

Also drops stopAllChatThreads, which has no callers left.

* Studio: close three load/unload gate races found in review

Re-check the in-flight load guard after the stop-running-chats confirm.
The confirm always GETs active-generations before its zero-running
early-out, so the guard no longer sits atomically ahead of the
reservation and two picks in that window both reached performLoad over
the same refs. ejectModel had the same shape and gets the same re-check.

Reject a sidecar swap immediately before the forced cancel in both load
branches. The previous check was back at the top of preflight, so an
install reserving during identifier resolution, the tier probe, the
training guard or the download check made the post-drain recheck 409 a
load whose chats had already been stopped.

Enter the Anthropic passthrough's cancel tracker inside its body
generator. It was entered eagerly and returned through
_sse_streaming_response, which sets no unstarted_cleanup, so a response
whose body never started left the run registered forever and 409'd every
later non-forced load and unload.

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

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

* Trim comments across the files this PR touches

Tightens the comments and doc blocks in the backend, CLI, tests and frontend
files changed by this PR: collapses multi-line explanations to a single line
where they still read clearly, and drops the ones the code already says.

No code changes, verified by an AST comparison against the previous commit.

* Studio: defer the destructive cancel and close two gate gaps

Move the forced cancel behind every check that can still reject a swap.
The drain now runs first with the runs it is about to cancel discounted,
so it waits only for inference the cancel cannot end, then the sidecar
check decides, then the cancel fires, then a second drain lets those runs
unwind before teardown. A sidecar install reserving during the drain no
longer 409s a load whose chats have already been stopped.

Track the non-streaming /v1/completions proxy. It was the last local
decode path missing from active_generations, so an unload, which runs no
drain, tore llama-server down under it and force_cancel_active could not
signal it. It now uses the same tracked cancel event and dedicated client
as the OpenAI pass-through.

Skip the client's preliminary unload while chats are generating and let
/load evict at its own post-preflight point instead. Forwarding
force_cancel_active there truncated replies before identifier
resolution, the GPU and training guards and the download check had run.

Keep per-thread context usage so returning to a chat whose background run
finished restores its bar instead of leaving it blank until the next turn.

Make the running-flag clear run-specific. Every run without a resolved
thread id shares the "__default" key, so concurrent compare panes could
clear each other's flag and strand a live stop handle.

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

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

* Studio: register the embeddings proxy with the swap gate

/v1/embeddings proxied straight through the pooled client with no tracked
cancel event, so it never appeared in active_generations. /unload runs no
idle drain, so a concurrent non-forced unload counted zero generations and
killed llama-server mid-request, and force_cancel_active had no event to
signal. Mirrors the completions proxy: tracked event, dedicated unpooled
client closed by a cancel/disconnect watcher, unregister in a nested
finally so a close failure cannot leave a phantom generation behind.

* Trim comments on the newest changes in this PR

Comments only, no code changes: shorten the ones added by the load-gate
ordering, embeddings and per-thread usage work down to the same density as
the rest of the diff.

* Studio: register the legacy generate stream with the swap gate

/generate/stream built a cancel event but never entered the tracker, so it
was invisible to active_generations. Being in the keep-warm middleware's
inference suffixes only covers /load, which drains; /unload does not, so a
non-forced unload passed the 409 gate and then blocked on the standard
backend's generation lock, and a forced swap had no event to signal.
Registered inside the body generator under a nested finally so a teardown
failure cannot skip the unregister.

The AST contract test asserted the cleanup finally by overwriting its flag
per Try node, so a nested try made the last one win. Accumulate instead,
which is what the existence claim meant.

* Studio: three more swap-gate gaps found in review

Register /audio/generate with the gate. TTS holds the model for the whole
request and /unload runs no drain, so unregistered a non-forced swap counted
zero generations and tore the model down mid-generation; the orchestrator
path only waits 15s for the generation lock, which real TTS exceeds. No
cancel keys: no backend takes a cancel_event for audio, so the event has no
observer and a forced swap still cannot interrupt audio already in flight.

Thread the tracked cancel event into the /v1/responses admission wait. It
was the only admission caller passing None, so a queued run could not be
reached by cancel_all() and a plain /inference/cancel could not stop it at
all. Same omission fixed at the upstream send there and on /v1/completions.

Let an unforced unload of a stale model path reach the no-op check. Before
this PR that request returned 200 and did nothing; the new gate refused it
with 409 for a request that reaches no teardown branch. Gate both refusal
passes on the disjunction of the route's own teardown conditions, including
not is_loaded, so a mid-load GGUF still refuses.

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

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

* Studio: register the remaining non-streaming decode paths

stream defaults to false on all three of these, so they are the ordinary
shape of their routes, and each holds a local backend for the whole
request. /unload runs no idle drain, so with no registry entry a non-forced
swap counted zero generations and tore the backend down mid-request instead
of returning 409, and a forced one had no event to signal.

Non-streaming /v1/messages: all three helpers ran with an empty registry,
since only the streaming siblings were tracked. Registered at the call site
because the pass-through takes no cancel_event of its own, and with no
cancel keys, matching those siblings.

Non-streaming standard chat and audio-input chat: the trackers in this route
sit inside their `if payload.stream:` arms, so neither else branch was
covered. The GGUF sibling already registers its own non-streaming branch.

Each exit is in a finally on the branch's existing try, so the except arms
are covered too: a leaked entry 409s every later swap until restart.

* Studio: tighten the swap-gate comments

Comment-only pass over the newest swap-gate registrations: collapse the multi-line rationales in /unload, the legacy generate stream, audio generation and the non-streaming chat branches, and the matching test preambles, to the shortest form that still carries the reason. No code changes.

* Studio: stop the reselect dialog promising a stop that never happens

Picking an external provider leaves the local model resident and stops the
status poll mirroring it, so reselecting that model showed the stop-chats
dialog, and /load then answered already_loaded ahead of its cancel hook.
Confirmed with the live backend: the same pick with force_cancel_active set
still returned already_loaded and the chat kept streaming. Not stopping
those chats is right, since the load never interrupts them, so remove the
prompt rather than honour it. Blanket-skipping is unsafe, because the same
id and variant with one sampling setting changed is a real reload and 409s,
so the branch only fires when a status fetch confirms the resident
checkpoint and variant match, and then adopts it without calling /load.

Redact native model paths from the active-generations response. Registering
/generate/stream recorded backend.active_model_name verbatim, which is an
absolute path for a native local model, and this route is the only place
that serialises it. Redacting at the response covers every tracker rather
than the one that surfaced it.

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

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

* Studio: keep hydrated context usage in the per-thread map

The history loader restores a saved conversation's usage through
setContextUsage only, and it runs once per mount, so switching away and
back left the bar blank for a hydrated chat even after the per-thread map
landed. setContextUsage now writes the value through to the visible
thread's own entry and clears that entry when passed null, which covers
both hydration call sites and any future writer.

* Studio: unblock load cancellation and share unresolved thread keys

Run the two stop-loading fast paths ahead of the unload route's pre-gate
refusal. _unload_may_evict returns True for exactly the model being
cancelled, so the refusal was blocking the branch that cancels a load which
has replaced nothing and can interrupt no chat. The client made that
unrecoverable: cancelLoading sends the unload without force, drops the
result, and its abort never reaches /load, which takes no signal, so the
load ran on and could later cancel those chats and swap the model. Nothing
else is exempted; an unload that would tear down a serving model matches
neither fast path and still 409s. The comment claiming the client lets that
409 surface is corrected, since it discards it.

Hold every owner behind a shared thread key. Runs with no resolved thread id
share "__default" (concurrent compare panes, since startCompare clears
activeThreadId), so a single owner slot let a second run replace the first's
token and then delete the shared entry while it was still generating, and
the server-cancel map lost the older handle the same way. Both now hold a
list, the running and local flags survive until the last owner clears, and
stopChatThread stops every handle under the key.

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

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

* Studio: carry a confirmed swap into the sidecar install, key restored usage by thread

Picking a model that needs a newer transformers while chats generate raised the
"stop N chats" prompt, but the answer never reached the install that runs before
the load: /install-latest-transformers refused on those same chats and took no
force flag, so Retry hit the same 409 and nothing in the flow stopped them.

Carry force_cancel_active through the consent dialog into the installer. Only
the pre-gate fast path is skipped: the recheck under the lifecycle gate still
has to pass, so an unconfirmed caller is refused as before. The cancel runs last
inside the gate, after every check that can still reject the install, and the
drain behind it is bounded since it holds the gate and the sidecar reservation.

Also key restored context usage by the thread the loader read. history.load()
captures remoteId before two awaited round trips, so a switch inside that window
filed one thread's usage under another and setActiveThreadId kept re-applying it.

Preserve sibling owners when a run key is cleared without an owner: the image
rejection gate now uses its own token, and the reducer leaves owned runs alone.

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

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

* Studio: bound the post-cancel drains, and make cancellation reach the paths that ignored it

A forced swap cancels the chats it interrupts, then waits for them to unwind.
That wait had no deadline while holding the lifecycle gate, and TTS on the
subprocess backend observes no cancel event at all, so one audio generation
could pin every load, unload and new request for its whole duration. Bound both
post-cancel drains. Pre-cancel drains stay unbounded: the swap can still be
refused there, so shortening them would weaken what they protect.

/unload had the opposite problem and no drain at all, cancelling and tearing
down on the next line, which turned a clean stream end into a dropped
connection. Give it the same bounded wait, gated on the cancel having cancelled
something so an idle Eject pays nothing.

Make the cancel actually land where it can. GGUF TTS now takes a cancel_event
and a watcher closes its client to break the blocking POST. The Anthropic
non-streaming pass-through did the same thing the completions and embeddings
paths used to: register with the gate, then run both POSTs on the pooled client
that cannot be closed. It now uses a per-request client like they do.

Also: park and unpark the admission queue the reservation actually holds, since
queues are keyed by base_url and a reload mints a new port; key tool output by
remoteId on both sides, so the first turn of a New Chat stops writing under one
key and reading another; and give tool status a run owner, so a finishing run
cannot blank the badge a concurrent one is still showing.

Clamp --parallel to 1 on a llama-server without --kv-unified. The new default of
4 would otherwise split -c four ways on such a build, quartering the context
window for a feature it cannot serve.

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

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

* Studio: scope a chat's Stop to its own generation, and clear the way before a confirmed install

Safetensors generation is serialized on _gen_lock and the worker has a single
cancel event, so a chat still queued on that lock owns no generation. Its Stop
handler called reset_generation_state() anyway, which set the shared event and
ended whichever conversation was actually running. Parallel chats is what makes
that reachable.

_generate_inner now records its cancel_event as the current holder once it takes
the lock, and reset_generation_state drops a reset from anyone else. Every route
call site passes its own request event. A reset with no event stays global, so
unload and model switch cannot leave a generation alive, and a reset while
nothing runs still resets, so an error path before generation is not a no-op.
The other two backends take the argument too, or the standard one raises
TypeError on every cancel.

The sidecar install had the mirror of the /load ordering problem: it cancelled
the chats first and drained second, so an unrelated counted request the cancel
cannot reach (a count_tokens, say) was still there for the recheck, which then
refused an install that had already stopped every chat for nothing. Drain the
unreachable remainder first, discounting the registered chats, then cancel.

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

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

* Studio: close the windows the previous round's fixes left open

Three follow-ups, two of them holes in the fixes just before them.

The worker claim went in after _send_cmd, so the command was already running
unclaimed and a queued chat's Stop in that window still reset it. Claim first,
with the send inside the same try, so a failed send releases it too.

Tool status kept one entry per key with an owner. That stops a foreign clear but
not an overwrite: under the shared unresolved-thread key the second run replaced
the first's entry, and its own clear then removed the only one while the first
tool was still running. Keep per-run entries and render the newest.

/unload gated its drain on having cancelled something, so a request that passed
the keep-warm middleware but had not reached its tracker yet was invisible to it
and the teardown landed on an already-admitted request. Drain on the middleware
count instead, which covers that window as well as the cancelled runs, then
re-cancel whatever registered while waiting. Bounded, not a refusal: an unload is
deliberate, and on expiry it proceeds exactly as before.

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

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

* Trim the parallel-chats comments to their reasons

Compress the multi-line rationales added by this branch into shorter forms and drop
restatements of the code below them. The reasons behind the drain bounds, the deferred
cancel, the per-request generation ownership and the thread-scoped tool and usage keys
are kept, just said in fewer lines.

* Studio: own the worker per generation, and make a resumed chat requeue for its slot

Ownership was a single lock holder, so dispatched runs (compare mode bypasses
_gen_lock by design) never claimed it and the guard fell straight through to the
global reset: a Stop on one of them ended its siblings. Track the generations
actually running instead, claimed before the send and released in the same
finally on both paths. A reset still proceeds when nothing is running, so an
error path ahead of generation is not swallowed.

park() hands the freed slot to a waiter, so a chat resuming from a tool approval
could take it back while that waiter was still decoding, putting two holders on
a one-slot server and sending the resumed tool loop past the admission limit.
unpark_async waits for room; the plain unpark stays for a holder tearing down,
which will not decode again.

Audio only observed its cancel event on a forced swap. An explicit Stop just
aborts the fetch, and this route has no cancel id, so llama-server ran on to the
request timeout after the chat reported it stopped. Watch the disconnect.

Also read tool status by remoteId, matching the key the adapter writes and the
fix already made for tool output, and stop an unresolved run from writing its
usage into whichever conversation the user moved to.

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

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

* Studio: let only the generation the worker is running speak for it, and hold a slot for a resuming chat

The ownership list recorded admission, but the subprocess runs generations one
at a time, so a dispatched request queued behind another counted as an owner and
its Stop signalled the shared cancel event, ending the request that was actually
running. Keep admission for release bookkeeping and gate ownership on execution
instead, promoted when the worker first answers that request. Nothing executing
still permits a reset, so an error path ahead of generation is not swallowed.

The worker has one cancel event and no per-request cancellation, so this decides
who may pull the lever rather than making the lever per-request.

A resuming chat also polled for a slot it could never see: release() grants to
the next waiter under the same lock, so later arrivals overtook an approved chat
indefinitely. A pending unpark now reserves the next slot and they queue behind
it.

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

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

* Studio: cover the prefill window, and keep a first turn's tool output readable

Gating worker ownership on execution left the interval between the send and the
first response uncovered: nothing is executing then, and the empty case admitted
anyone, so a queued chat's Stop still ended the one in prefill. Split the empty
case. Nothing claimed at all still permits a reset, so an error path ahead of
generation is not swallowed; claimed but unanswered resolves to the oldest
claim, which is what a FIFO command queue is working on.

Putting both sides of the tool-output scope on remoteId left the first turn of a
New Chat writing under the unresolved scope for its whole life while the readers
recomputed the moment the autosave assigned an id, so the card blanked mid-run.
The readers now fall back to the unresolved scope, which only an unpersisted
first turn can occupy.

* Studio: order the parked approvals, and tie a worker claim to its enqueue

The reservation added for admission fairness was a bare count, so every approved
holder counted against every other: park two chats, approve both, and once the
last decoder released, nothing could ever satisfy the check again. That is a
deadlock where the problem it fixed was only unfairness. Make it a FIFO ticket
so a pending unpark blocks the ones behind it and no others.

_owns_worker reads claim order to decide which request the worker is prefilling,
which only holds if claiming and enqueuing cannot interleave. Hold one lock
across both on the dispatched and the locked path.

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

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

* Studio: follow a first turn's run when its thread gets an id, and key the denoising canvas per chat

A run started before its thread existed filed every handle under "__default". Nothing
moved them once autosave assigned the real id, so the sidebar row showed no spinner and
Stop could not reach the generation, which kept holding a slot.

adoptDefaultThreadRun re-keys the run maps onto the real id from the thread adapter's
initialize(), where the id first exists; anything already filed under that id wins, since
that is a later run. The adapter captures its key once at run start, so it now resolves
the live key per use through runKeyForOwner, looking its own serverCancel up in the owner
map. Without that the migrated entries are stranded and the spinner never clears.

The denoising canvas was one global slot, so two diffusion chats overwrote each other and
the ownership tag then hid the visible preview until that thread emitted again. It is now
activeDiffusionCanvasByThreadId, written and cleared per thread, and the frame no longer
carries a threadId of its own. The bubble reads threadListItem.remoteId, dropping the dead
threadListItem.id arm: the writer tags unstable_threadId, which is exactly remoteId.

Two existing backend tests needed the same treatment. _bare_orchestrator skips __init__, so
it now sets the claim bookkeeping the worker ownership check reads. The Anthropic
passthrough gate test anchored on comment prose that a rewrap had broken; it anchors on the
code instead.

* Studio: hand the worker over cleanly between generations, and stop unresolved runs sharing each other's state

Worker ownership moved off the consumer and onto the dispatcher. Consumers read their
mailbox whenever they get around to it, so a request whose gen_done had been routed still
owned the worker while the next one ran, and a late Stop for it cancelled that one. The
dispatcher is the only place responses arrive in the order the worker produced them: it
now retires a request at its terminal response and promotes the next one, and answering a
request makes it the sole executor, since the subprocess runs one generation at a time.

reserve()'s immediate path ignored the unpark tickets that _grant_waiters_locked already
honours, so a request arriving between a slot freeing and an approved chat's next poll
took it, repeatedly. It applies the same reservation now.

Three places let concurrent first turns share state through the "__default" key. Nothing
links a run filed there to the id its thread later receives, so rather than guess, each
now declines when the key is ambiguous: adoption only re-keys a lone run, the composer
badge only claims a lone status, and the tool-output fallback only applies to a thread
that is still running. That leaves two concurrent first turns where they were before
adoption existed instead of handing one thread the other's handles.

A first turn's usage was never filed, because its key stayed null for the whole run while
autosave moved activeThreadId to the real id, so the context bar went blank after the
first reply. It resolves the adopted key like the cleanup handles do.

Cancelling a forced load left the UI with no model: the previous one stays resident until
/load's teardown, and the cancel path cleared the checkpoint without rolling back. It now
resyncs from the backend, which is right whether or not the load got that far.

The sidecar install drain is weighted 1:4 rather than halved, total unchanged. Only the
second half benefits from patience, and cutting it short refused installs whose chats had
already been stopped for nothing.

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

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

* Studio: give a first turn its real thread id before the run starts

A first turn filed every run handle under a shared unresolved key because
assistant-ui binds unstable_threadId before the thread is persisted. Two of them
overlapping there is unresolvable afterwards, and the last round's migration could
only decline rather than guess, which left neither sidebar row showing its run.

The id is available earlier than I claimed. append() already tracks
threadListItem.initialize() by the user message id, and createPersistedRunAdapter
already awaits that promise before invoking the adapter, so the thread is persisted
by the time the run begins. It was only being discarded: the tracked promise resolved
to void. It now resolves to the assigned id, and the wrapper hands it to the adapter
when assistant-ui had none. An id that is already set is never replaced, since that
would move a running chat's handles out from under the row watching them. The
existing unresolved-key guards stay as a safety net but should no longer carry weight.

The sidebar counted running thread ids rather than rows, so one compare conversation
read as two chats. It folds ids into rows through the same threadIds the row spinner
uses, and still counts a running id that matches no row.

_TrackedCancel always registered kind="chat", so an embeddings or raw completions
request appeared in the model-swap prompt as an unnamed conversation and confirming
cancelled it while calling it a chat. The non-conversation routes now pass their own
kind, and the prompt says "requests" whenever the snapshot is not all chats.

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

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

* Studio: withhold the shared worker cancel from a request the worker has left

Moving ownership to the dispatcher fixed reset_generation_state, but the token loop
signals the shared worker event directly and did not carry the same rule. A dispatched
consumer runs with mark_started off and can still be draining tokens buffered before
its gen_done was routed, so stopping it there ended whichever request the worker had
started next.

It now signals only when _owns_worker agrees, the same predicate reset_generation_state
uses. The local drain and return are unconditional, since those touch nothing but this
stream. The remaining _cancel_generation callers are deliberately global: subprocess
shutdown, the pre-load kill and unload_model.

* Studio: add the AGPL-3.0 header to the first-turn identity test

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

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

* Studio: stop the dispatcher and a _gen_lock stream fighting over the response queue

Nothing stopped the dispatcher starting under a _gen_lock generation, so once compare
was opened while an ordinary chat was still streaming, both consumed _resp_queue and
whichever response the dispatcher took without a mailbox was dropped, gen_done included.
That chat truncated or hung. This PR is what makes it reachable, since navigating into
compare no longer ends the chat behind it.

Delaying the dispatcher would serialise compare behind whatever chat happens to be
streaming, so the direct readers get a mailbox instead. _direct_reader returns a reader,
a cancel drain and a release, and files the mailbox under _direct_mailboxes rather than
_mailboxes, which means "compare requests are in flight" to the unload and distributed
paths and must not count an ordinary chat.

Both directions close. The dispatcher finds the direct reader's mailbox instead of
dropping. And this reader can already be blocked on the queue when a compare request's
dispatcher starts, so a response that is not ours goes to its own mailbox rather than
being consumed, which would have corrupted the chat and hung the pane. All three
_gen_lock readers use it, and the cancel drain goes through it too.

The sidebar's return target still picked a raw pane id while the count grouped by row,
and /chat addresses compare with `compare`, not `thread`. It resolves through the same
items now, so a running compare row returns to its pair.

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

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

* Studio: keep worker ownership honest across audio, API traffic and a replaced worker

The audio-input send got a mailbox last round but stayed unclaimed, so a compare request
queued behind it looked like the oldest owner and stopping that queued request signalled
the shared event into the audio chat. It claims under the send lock and releases in the
finally, like _generate_inner.

Ownership is keyed on cancel-event identity with nothing tying it to a worker generation,
so a consumer still blocked on its mailbox when the process was replaced stayed recorded
as the executor, and a generation on the fresh worker could not be stopped.
_shutdown_subprocess clears that state once the process is confirmed dead, mailboxes
included: nothing routes to them again, and a stale one reads as compare activity to the
unload path. Not on the survived-SIGKILL path, which keeps its handle on purpose.

The four public /v1/messages trackers were registering as chats. The distinction is a
Studio thread, not the protocol, and those branches already say "No thread_id: public API
surface" while the Studio path passes payload.thread_id separately. They carry their own
kind now, so the swap prompt stops calling an external request a chat.

The swap confirmation still counted raw pane ids, so a compare conversation asked to stop
two chats and listed its title twice. It folds panes onto pairId and lowers the count by
what it collapsed, leaving a first turn the backend can count but not name.

Deep Research set runningByThreadId but registered no server-cancel handle, and that map
is how Stop, archive and delete reach a thread that is no longer active. Leaving the
outgoing thread running is this PR's doing, so the run was left unreachable while its
supervisor kept working against a conversation the user could delete.

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

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

* Studio: tighten the parallel-chats comments

* Studio: replay a Deep Research stop that arrived before the run existed

The handle is registered before createResearchRun resolves because the thread can be
stopped while that request is in flight, but it had no id to act on and dropped the stop.
The supervisor then followed a run the user had already stopped, archived or deleted.

It latches instead: a stop with no id yet sets a flag, and the adapter replays it against
the id the moment creation returns rather than starting to follow.

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

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

* Studio: fix worker ownership on a raced reroute, and the stop-chats prompt

Four review findings on the parallel-chats work, all reproduced first.

- _direct_reader hands a foreign response to its own mailbox, but skipped the
  ownership move the dispatcher makes. A _gen_lock reader already blocked on
  resp_queue can beat the compare dispatcher to that request's first response,
  and the compare consumer opts out of marking, so nothing promoted it: the
  direct request stayed the recorded executor, its late reset cancelled the
  compare generation, and the compare chat's own Stop was ignored.
- A chat stopped while queued on _gen_lock was still claimed and sent once the
  lock freed. Cancellation is only checked on a token, so a long prefill, or a
  generation reaching gen_done without one, occupied the worker after Stop.
  Same hole in the audio-input path, which shares the lock.
- The stop-chats prompt counted generation handles, not conversations. One chat
  holds several while a tool continuation registers its next leg before the
  previous unwinds, so it offered to stop two chats and listed one title.
- Ejecting a model confirms through that dialog, which told the user
  "Unloading the model reloads the model" and offered "Stop and reload".
  Confirming calls /unload and leaves nothing loaded.

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

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

* Studio: name the TTS run's thread so the stop prompt counts it once

The audio branch registers its run locally under the thread key but sent no
thread_id, so the backend tracker filed the same generation under no thread.
The stop-chats prompt then had a named local run and an unnamed backend one and,
since e8e7594 started adding unnamed entries to the named ones, counted a single
TTS chat as two requests. The backend already reads payload.thread_id, so
sending it lines both registries up on the same run.

* [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>
2026-07-28 04:40:38 -07:00

917 lines
40 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Tests for `_TOOL_XML_RE` (routes/inference.py) -- strips tool-call XML that
leaks past the speculative buffer in core/inference/llama_cpp.py when the
open/close pair is split across the visible/DRAIN boundary.
"""
from __future__ import annotations
import sys
import types as _types
from pathlib import Path
import pytest
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
# Extract the regex from source (routes module needs heavy stubbing to import).
import re as _re
_src = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")
_m = _re.search(r"_TOOL_XML_RE = _re\.compile\((.*?)\n\)", _src, _re.DOTALL)
assert _m, "could not extract _TOOL_XML_RE source"
# The lazy ``(.*?)\n\)`` could grab a shorter expression if an arm is ever wrapped;
# pin the DeepSeek + bare-Kimi arms so a silent truncation fails loudly here.
assert "_DS_OPEN_SRC" in _m.group(1) and "tool_call_begin" in _m.group(
1
), "extracted _TOOL_XML_RE is missing expected arms (extraction truncated?)"
# The regex reuses the parser's shared DeepSeek opener alternation; provide it so the extracted
# ``_re.compile`` expression resolves the same source.
from core.inference.tool_call_parser import _DEEPSEEK_OPEN_RE_SRC as _DS_OPEN_SRC
from core.inference.tool_call_parser import (
_strip_function_xml_calls,
_strip_gemma_wrapperless_calls,
_strip_glm_calls,
_strip_mistral_closed_calls,
)
from typing import Optional as _Optional
_ns = {
"_re": _re,
"_DS_OPEN_SRC": _DS_OPEN_SRC,
"Optional": _Optional,
"_strip_mistral_closed_calls": _strip_mistral_closed_calls,
"_strip_gemma_wrapperless_calls": _strip_gemma_wrapperless_calls,
"_strip_glm_calls": _strip_glm_calls,
"_strip_function_xml_calls": _strip_function_xml_calls,
}
exec(f"_TOOL_XML_RE = _re.compile({_m.group(1)})", _ns)
_TOOL_XML_RE = _ns["_TOOL_XML_RE"]
# The display helper uses the closed-only variant before the last think block; keep it in scope.
_mc = _re.search(r"_TOOL_XML_CLOSED_RE = _re\.compile\((.*?)\n\)", _src, _re.DOTALL)
assert _mc, "could not extract _TOOL_XML_CLOSED_RE source"
exec(f"_TOOL_XML_CLOSED_RE = _re.compile({_mc.group(1)})", _ns)
_TOOL_XML_CLOSED_RE = _ns["_TOOL_XML_CLOSED_RE"]
# Signatures may span multiple lines and now carry the enabled_tool_names gate; match
# the whole (possibly multi-line) signature up to ``-> str:`` then the indented body.
_xml_helper = _re.search(
r"def _strip_tool_xml\((?:.|\n)*?\) -> str:\n(?: .+\n)+",
_src,
)
assert _xml_helper, "could not extract _strip_tool_xml source"
assert "_strip_mistral_closed_calls" in _xml_helper.group(
0
), "extracted _strip_tool_xml no longer runs the Mistral balanced strip"
exec(_xml_helper.group(0), _ns)
_strip_tool_xml = _ns["_strip_tool_xml"]
# Extract the gate helper and display strip up to the next top-level ``logger =``.
_helper = _re.search(
r"def _display_tool_name_gate\(.*?(?=\nlogger = get_logger)",
_src,
_re.DOTALL,
)
assert _helper, "could not extract display strip helper source"
# The extracted block spans _display_tool_name_gate through _strip_tool_xml (defined before
# ``logger =``); confirm the shared _strip_tool_xml delegate is present.
assert "_strip_tool_xml(" in _helper.group(0), "display helper no longer delegates"
exec(_helper.group(0), _ns)
_strip_tool_xml_for_display = _ns["_strip_tool_xml_for_display"]
_display_tool_name_gate = _ns["_display_tool_name_gate"]
_gate_src = _re.search(
r"def _gemma_strip_gate\((?:.|\n)*?\) -> set:\n(?: .+\n)+",
_src,
)
assert _gate_src, "could not extract _gemma_strip_gate source"
exec(_gate_src.group(0), _ns)
_gemma_strip_gate = _ns["_gemma_strip_gate"]
# ── Well-formed pairs ─────────────────────────────────────────────
def test_route_display_strip_respects_disabled_auto_heal_contract():
text = 'literal <tool_call>{"name":"web_search"}</tool_call> survives'
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = False) == text
assert "<tool_call>" not in _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
def test_route_display_strip_preserves_rehearsal_inside_think():
# A rehearsed bracket call inside think is reasoning: the block is preserved while a real
# call outside it still strips.
text = '<think>plan: search[ARGS]{"q":"x"}</think> answer [TOOL_CALLS]web_search{"q":"y"} tail'
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert '<think>plan: search[ARGS]{"q":"x"}</think>' in out
assert "[TOOL_CALLS]web_search" not in out
assert "answer" in out and "tail" in out
def test_route_display_strip_keeps_bare_args_before_think_block():
# A bare ``foo[ARGS]`` before a think block is prose: EOS-anchored tail arms run only on
# the last segment (earlier segments use the closed-only regex).
text = "Please pass foo[ARGS] <think>pause</think> to the template."
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = True) == text
def test_route_display_strip_removes_complete_call_before_think_block():
# A complete bracket call before a think block still strips (balanced scan runs on every segment).
text = 'before search[ARGS]{"q":"x"} <think>pause</think> after'
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "search[ARGS]" not in out
assert "<think>pause</think>" in out
assert "before" in out and "after" in out
def test_route_display_strip_removes_closed_xml_before_think_block():
# A closed <tool_call> before a think block is removed in the non-last segment.
text = 'pre <tool_call>{"name":"x"}</tool_call> <think>p</think> tail'
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "<tool_call>" not in out
assert "<think>p</think>" in out
assert "pre" in out and "tail" in out
def test_all_route_cleanup_sites_use_protected_display_helper():
# Every route cleanup site must use _strip_tool_xml_for_display (think-preserving,
# balanced); raw _TOOL_XML_RE.sub corrupted think rehearsal and trailing prose. The only
# legitimate raw sub lives inside the helper itself.
raw_sub_lines = [
(i, line)
for i, line in enumerate(_src.splitlines(), 1)
if "_TOOL_XML_RE.sub(" in line and not line.lstrip().startswith("#")
]
assert len(raw_sub_lines) == 1, (
"raw _TOOL_XML_RE.sub must appear only inside _strip_tool_xml_for_display; "
f"found extra call sites: {raw_sub_lines!r}"
)
def test_route_display_strip_removes_mistral_tool_calls_with_nested_json():
# _TOOL_XML_RE has no [TOOL_CALLS] arm, so the helper delegates to _strip_tool_xml for the Mistral
# balanced-brace strip (a non-greedy \{.*?\} would truncate nested JSON).
text = 'ok [TOOL_CALLS]web_search{"filters":{"date":"2024"},"query":"cats"} tail'
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = False) == text
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "[TOOL_CALLS]" not in out and "web_search" not in out, out
assert out == "ok tail"
def test_strips_well_formed_tool_call():
text = (
"Let me search.\n"
"<tool_call>\n"
"<function=web_search>\n"
"<parameter=query>\nBillboard 2015\n</parameter>\n"
"</function>\n"
"</tool_call>\n"
"Here are the songs:"
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "<tool_call>" not in cleaned
assert "<function=" not in cleaned
assert "</tool_call>" not in cleaned
assert "</function>" not in cleaned
assert "Here are the songs:" in cleaned, "non-XML content must survive"
assert "Let me search." in cleaned
def test_strips_function_only_well_formed():
text = "Setup.\n<function=python>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\nDone."
cleaned = _TOOL_XML_RE.sub("", text)
assert "<function=" not in cleaned
assert "Setup." in cleaned
assert "Done." in cleaned
def test_strips_function_attribute_form():
# Attribute form ``<function name="...">`` (MiniCPM-5 / MiniMax-M2) must strip from the route too
# (it previously leaked into the UI); a dotted/hyphenated name also strips.
text = (
'Sure.\n<function name="get_weather">\n'
"<parameter=city>\nSydney\n</parameter>\n</function>\nDone."
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "<function name=" not in cleaned
assert "</function>" not in cleaned
assert "Sure." in cleaned and "Done." in cleaned
dotted = 'A <function name="srv.list-issues">x</function> B'
assert _TOOL_XML_RE.sub("", dotted) == "A B"
# Auto-Heal-disabled display contract still preserves literal markup.
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = False) == text
assert "<function name=" not in _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
# ── Orphan openings ───────────────────────────────────────────────
def test_strips_orphan_tool_call_no_close():
text = (
"Reasoning.\n</think>"
"<tool_call>\n"
"<function=web_search>\n"
"<parameter=query>\nBillboard 2015\n</parameter>\n"
"</function"
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "<tool_call>" not in cleaned
assert "<function=" not in cleaned
assert "Reasoning." in cleaned
def test_strips_orphan_function_no_close():
text = "I'll call python:\n<function=python>\n<parameter=code>\nprint(1)\n</parameter>"
cleaned = _TOOL_XML_RE.sub("", text)
assert "<function=" not in cleaned
assert "I'll call python:" in cleaned
def test_strips_orphan_only_opening_tag():
cleaned = _TOOL_XML_RE.sub("", "Search starting.\n<tool_call>")
assert "<tool_call>" not in cleaned
assert "Search starting." in cleaned
def test_strips_multiple_orphans():
text = (
"First call:\n<tool_call>\n<function=python>\n<parameter=code>\nx=1\n"
"Second call:\n<function=web_search>\n<parameter=query>\nhi\n"
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "<tool_call>" not in cleaned
assert "<function=" not in cleaned
# ── Orphan closes ─────────────────────────────────────────────────
def test_strips_orphan_closing_tag():
# Real shape from Qwen3.6-27B Q8 sweep (open got DRAINED, close leaked).
text = "...the table rows directly.\n</parameter>\n</function>\n</tool_call><think>Continuing</think>"
cleaned = _TOOL_XML_RE.sub("", text)
assert "</tool_call>" not in cleaned
assert "</function>" not in cleaned
# Mid-string </parameter> intentionally preserved (see preserve test).
def test_strips_gemma_native_orphan_closing_tag():
cleaned = _TOOL_XML_RE.sub("", "Tool call drained.<tool_call|>Visible tail.")
assert "<tool_call|>" not in cleaned
assert "Tool call drained." in cleaned
assert "Visible tail." in cleaned
# ── Tail-only </parameter> (PR #5735 follow-up) ───────────────────
def test_strips_tail_only_parameter_orphan():
# Outer </function></tool_call> truncated by EOS, inner <parameter=...> DRAINED.
cleaned = _TOOL_XML_RE.sub("", "and the text is not readable.\n</parameter>\n\n")
assert "</parameter>" not in cleaned
assert "and the text is not readable." in cleaned
def test_strips_tail_only_parameter_orphan_single_newline():
cleaned = _TOOL_XML_RE.sub("", "Global Economic Prospects\n</parameter>\n")
assert "</parameter>" not in cleaned
assert "Global Economic Prospects" in cleaned
def test_strips_tail_only_parameter_orphan_no_trailing_ws():
cleaned = _TOOL_XML_RE.sub("", "Final answer.</parameter>")
assert "</parameter>" not in cleaned
assert "Final answer." in cleaned
def test_strips_complete_bracket_tag_keeps_trailing_prose():
# A complete Mistral call strips only its balanced JSON, leaving following prose intact.
cleaned = _TOOL_XML_RE.sub("", '[TOOL_CALLS]web_search{"q":"x"} and then prose')
assert "[TOOL_CALLS]" not in cleaned
assert "and then prose" in cleaned
def test_strips_unclosed_bracket_tail():
# Close brace lost to EOS: the truncated tail strips to the end instead of leaking.
cleaned = _TOOL_XML_RE.sub("", 'here [TOOL_CALLS]web_search{"query":"weather"')
assert "[TOOL_CALLS]" not in cleaned
assert cleaned.strip() == "here"
def test_strips_unclosed_rehearsal_tail():
cleaned = _TOOL_XML_RE.sub("", 'text python[ARGS]{"code":"print(1)"')
assert "[ARGS]" not in cleaned
assert cleaned.strip() == "text"
def test_strips_hyphenated_mcp_bracket_name():
cleaned = _TOOL_XML_RE.sub("", 'x [TOOL_CALLS]mcp__srv__list-issues{"q":"x"}')
assert "list-issues" not in cleaned
assert cleaned.strip() == "x"
def test_preserves_mid_string_parameter_in_code_sample():
# Tail-anchor on `</parameter>` so doc/example prose survives.
text = (
"Here is the Qwen tool-call format:\n"
"```xml\n"
"<tool_call><function=foo><parameter=arg>value</parameter></function></tool_call>\n"
"```\n"
"Note the closing </parameter> sits inside <function>."
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "Note the closing </parameter> sits inside" in cleaned
def test_strips_well_formed_then_orphan():
text = (
"Round one:\n<tool_call>\n<function=python>\n<parameter=code>\n1\n"
"</parameter>\n</function>\n</tool_call>\n"
"Now round two:\n<tool_call>\n<function=web_search>\n<parameter=query>\n"
"what is X\n</parameter>\n</function"
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "<tool_call>" not in cleaned
assert "<function=" not in cleaned
assert "Round one:" in cleaned
assert "Now round two:" in cleaned
# ── Preservation (no false positives) ────────────────────────────
def test_preserves_plain_text():
text = "1. Animals — Maroon 5\n2. Take Me to Church — Hozier"
assert _TOOL_XML_RE.sub("", text) == text
def test_preserves_code_fences():
text = "```python\nimport sys\nprint(sys.version)\n```"
assert _TOOL_XML_RE.sub("", text) == text
def test_preserves_html_in_prose():
text = "Use the <html> tag for documents."
assert _TOOL_XML_RE.sub("", text) == text
# ── Real-world leak samples from the 2026-05-22 sweep ────────────
REAL_LEAKS = [
# Qwen3.5-35B-A3B UD-Q4_K_XL billboard s22 -- orphan open
'rectly.\n\nLet me try searching for Wikipedia pages that might have weekly chart data for 2015.\n</think><tool_call>\n<function=web_search>\n<parameter=query>\n"Billboard Hot 100" "2015" "weekly" "chart" "position" "3"\n</parameter>\n</function',
# Qwen3.6-27B UD-Q2_K_XL billboard s14 -- orphan open
'arch `site:wikipedia.org "peaked at number 3" "2015" Billboard`\nI\'ll do a quick web search.\n</think><tool_call>\n<function=web_search>\n<parameter=query>\n"peaked at number 3" Billboard Hot 100 2015 list\n</parameter>\n</function',
# Qwen3.6-27B UD-Q2_K_XL billboard s15 -- orphan open
'rd Hot 100 top-ten singles in 2015".\nI\'ll use web_search to find this exact Wikipedia page.\n</think><tool_call>\n<function=web_search>\n<parameter=query>\n"List of Billboard Hot 100 top-ten singles in 2015" wikipedia\n</parameter>\n</function',
# Qwen3.6-27B Q8_0 billboard s02 -- orphan close
"the table rows directly.\n</parameter>\n</function>\n</tool_call><think>The user wants me to list and categorize all songs that charted #3 on the Billboard Hot 100 in 2015. I have been trying to get this data",
# Qwen3.6-35B-A3B Q8_0 billboard s21 -- orphan close
"parse it more carefully.\n</parameter>\n</function>\n</tool_call><think>The user wants a list of songs that charted #3 on the Billboard Hot 100 in 2015, categorized.",
]
@pytest.mark.parametrize(
"leak", REAL_LEAKS, ids = [f"sweep_sample_{i}" for i in range(len(REAL_LEAKS))]
)
def test_real_world_sweep_leaks_get_stripped(leak):
cleaned = _TOOL_XML_RE.sub("", leak)
assert "<tool_call>" not in cleaned, f"leak survived: {cleaned!r}"
assert "<function=" not in cleaned, f"leak survived: {cleaned!r}"
# ── Real-world tail-only </parameter> from gdpval sweep ──────────
# All end-anchored: outer </function></tool_call> truncated by EOS, inner
# <parameter=...> open DRAINED, leaving bare </parameter> tail.
GDPVAL_PARAMETER_LEAKS = [
# Qwen3.5-27B Q8_0 / worldbank s00
"the page contains image data and the text is not readable.\n</parameter>\n\n",
# Qwen3.5-27B Q8_0 / worldbank s42 (preceded by mojibake)
"...some mojibake content here...\n</parameter>\n\n",
# Qwen3.5-27B UD-Q4_K_XL / coppa s07
"blocked, while others may still be in effect. The law is currently under further review by the Ninth Circuit.\n</parameter>\n\n",
# Qwen3.5-27B UD-Q4_K_XL / police_training s00
"comprehensive training report\n</parameter>\n\n",
# Qwen3.5-27B UD-Q4_K_XL / worldbank s00
"Global Economic Prospects\nJune 2025\nGlobal Economic Prospects\n</parameter>\n",
# Qwen3.6-27B Q8_0 / overpass s07
"Let me create a comprehensive query and instructions document.\n</parameter>\n\n",
]
@pytest.mark.parametrize(
"leak",
GDPVAL_PARAMETER_LEAKS,
ids = [f"gdpval_param_orphan_{i}" for i in range(len(GDPVAL_PARAMETER_LEAKS))],
)
def test_gdpval_parameter_orphans_get_stripped(leak):
cleaned = _TOOL_XML_RE.sub("", leak)
assert "</parameter>" not in cleaned, f"leak survived: {cleaned!r}"
# ── Backtracking guards ──────────────────────────────────────────
def test_no_catastrophic_backtracking_on_open_bracket_spam():
# 256KB of '<' must fail fast (literal mismatch char 2), not backtrack.
import time
adv = "<" * (1024 * 256) + "X"
t0 = time.perf_counter()
_TOOL_XML_RE.sub("", adv)
elapsed = time.perf_counter() - t0
assert elapsed < 0.5, f"regex took {elapsed*1000:.0f}ms on 256KB '<' spam"
def test_no_catastrophic_backtracking_on_orphan_opening_spam():
# 1000 unclosed openings: first alt must consume them all greedily.
import time
adv = "<tool_call>X" * 1000
t0 = time.perf_counter()
cleaned = _TOOL_XML_RE.sub("", adv)
elapsed = time.perf_counter() - t0
assert elapsed < 0.1, f"regex took {elapsed*1000:.0f}ms on 1000x orphan opens"
assert "<tool_call>" not in cleaned
# ── Two-level-nested bracket JSON (balanced-scan strip) ──────────
def test_route_strip_two_level_nested_bracket_keeps_trailing_prose():
# Two-level-nested args must be removed whole so the trailing prose survives.
text = 'before [TOOL_CALLS]search{"f":{"g":{"h":1}}} after'
cleaned = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert cleaned == "before after"
assert "[TOOL_CALLS]" not in cleaned
def test_route_strip_two_level_nested_rehearsal_keeps_trailing_prose():
text = 'note python[ARGS]{"a":{"b":{"c":1}}} done'
cleaned = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert cleaned == "note done"
assert "[ARGS]" not in cleaned
def test_route_strip_removes_call_with_literal_think_in_argument():
# A literal <think> inside a call argument strips with the call, not as reasoning.
text = (
'<tool_call>{"name":"write","arguments":'
'{"text":"compare <think> and </think> tags"}}</tool_call>'
)
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "<tool_call>" not in out and '"name"' not in out
def test_route_strip_removes_truncated_mistral_array():
# A canonical array truncated by EOS is stripped by the route fallback like other orphans.
text = 'before [TOOL_CALLS] [{"name":"a","arguments":{"x":1}}' # missing ]
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "[TOOL_CALLS]" not in out and "{" not in out
assert "before" in out
def test_route_strip_keeps_prose_mentioning_args_marker():
# ``foo[ARGS] in a sentence`` is prose; the rehearsal arm must not truncate the line.
text = "Please pass foo[ARGS] to the template and continue reading."
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert out == text
def test_route_strip_handles_mistral_v11_call_id_args_shape():
# v11 [CALL_ID]/[ARGS] shape (Mistral Small 3.2) must strip whole.
text = 'before [TOOL_CALLS]web_search[CALL_ID]abc123[ARGS]{"q":"x"} after'
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "[TOOL_CALLS]" not in out and "[CALL_ID]" not in out and "[ARGS]" not in out
assert "before" in out and "after" in out
# ── Mistral [/TOOL_CALLS] closer + literal <think> inside a call ───────────────
from core.tool_healing import strip_tool_call_markup as _strip_tool_call_markup
def test_core_strip_removes_orphan_tool_calls_closer_array_form():
# The bare v11 [/TOOL_CALLS] closer left by the balanced scan must not leak as content.
text = '[TOOL_CALLS] [{"name":"x","arguments":{}}][/TOOL_CALLS]'
assert _strip_tool_call_markup(text, final = True) == ""
def test_core_strip_removes_orphan_tool_calls_closer_named_form_keeps_tail():
text = '[TOOL_CALLS]web_search{"q":"x"}[/TOOL_CALLS] tail'
assert _strip_tool_call_markup(text, final = True) == "tail"
def test_core_strip_removes_call_with_literal_think_in_argument():
# An unclosed literal <think> inside call arguments strips with the call (argument data).
text = 'before <tool_call>{"name":"write","arguments":{"text":"literal <think> marker"}}</tool_call> after'
assert _strip_tool_call_markup(text, final = True) == "before after"
def test_route_display_strip_removes_orphan_tool_calls_closer_array_form():
text = '[TOOL_CALLS] [{"name":"x","arguments":{}}][/TOOL_CALLS]'
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert out.strip() == ""
def test_route_display_strip_removes_orphan_tool_calls_closer_named_form_keeps_tail():
text = '[TOOL_CALLS]web_search{"q":"x"}[/TOOL_CALLS] tail'
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "[/TOOL_CALLS]" not in out
assert out.strip() == "tail"
def test_incomplete_xml_call_with_literal_think_in_arg_is_stripped():
# An incomplete <tool_call> holding a literal <think> strips to EOS, not as a reasoning
# block (the unclosed tail _tool_call_markup_spans previously missed).
from core.tool_healing import parse_tool_calls_from_text as _parse
from core.tool_healing import strip_tool_call_markup as _strip
text = 'before <tool_call>{"name":"write","arguments":{"text":"literal <think> marker"}} after'
assert [c["function"]["name"] for c in _parse(text)] == ["write"]
assert _strip(text, final = True) == "before"
# A real reasoning block with no tool call is still preserved verbatim.
assert (
_strip("answer <think>real</think> done", final = True) == "answer <think>real</think> done"
)
# A complete call followed by a real reasoning block: call stripped, block kept.
mixed = '<tool_call>{"name":"a","arguments":{}}</tool_call> mid <think>r</think> end'
assert _strip(mixed, final = True) == "mid <think>r</think> end"
# ── enabled-tool gate for the ambiguous bare-rehearsal strip (#5704) ──
def test_display_tool_name_gate_returns_active_names_or_none():
# Empty / no tools -> None (unrestricted; keep the legacy strip-all behavior).
assert _display_tool_name_gate([]) is None
assert _display_tool_name_gate(None) is None
# OpenAI-shaped tool dicts -> set of function names, malformed entries dropped.
tools = [
{"type": "function", "function": {"name": "web_search"}},
{"type": "function", "function": {"name": "run_python"}},
{"type": "function"}, # no name
{"nope": 1}, # no function
]
assert _display_tool_name_gate(tools) == {"web_search", "run_python"}
def test_route_display_strip_keeps_inactive_rehearsal_when_gated():
# P1 #5704: an inactive ``foo[ARGS]{...}`` is prose; the gated strip leaves the sentence intact.
gate = {"web_search"}
text = 'foo[ARGS]{"x":1} is just syntax.'
assert (
_strip_tool_xml_for_display(text, auto_heal_tool_calls = True, enabled_tool_names = gate)
== text
)
# A bare marker with no JSON body is likewise prose when inactive.
assert (
_strip_tool_xml_for_display(
"use foo[ARGS] here", auto_heal_tool_calls = True, enabled_tool_names = gate
)
== "use foo[ARGS] here"
)
def test_route_display_strip_removes_active_rehearsal_when_gated():
# Mirror case: an active tool name is a real rehearsal and still strips.
gate = {"web_search"}
out = _strip_tool_xml_for_display(
'web_search[ARGS]{"query":"x"} done', auto_heal_tool_calls = True, enabled_tool_names = gate
)
assert "web_search[ARGS]" not in out
assert out.strip() == "done"
def test_route_display_strip_ungated_strips_all_rehearsal_unchanged():
# Backwards-compat: with no gate (None) the bare rehearsal strips as before.
text = 'foo[ARGS]{"x":1} is just syntax.'
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = True).strip() == "is just syntax."
assert (
_strip_tool_xml_for_display(
text, auto_heal_tool_calls = True, enabled_tool_names = None
).strip()
== "is just syntax."
)
def test_route_display_strip_control_token_stripped_regardless_of_gate():
# [TOOL_CALLS] is a control token: stripped even when its NAME is not in the gate.
gate = {"web_search"}
out = _strip_tool_xml_for_display(
'[TOOL_CALLS]foo[ARGS]{"x":1} keep', auto_heal_tool_calls = True, enabled_tool_names = gate
)
assert "[TOOL_CALLS]" not in out and "foo[ARGS]" not in out
assert out.strip() == "keep"
def test_core_strip_gates_bare_rehearsal_on_enabled_tools():
# P1 (#5704): the shared strip gate mirrors the parse gate -- inactive names are prose
# and preserved, active names strip, ``None`` keeps legacy strip-all.
from core.tool_healing import strip_tool_call_markup as _strip
text = 'foo[ARGS]{"x":1} is just syntax.'
assert _strip(text, final = True, enabled_tool_names = {"web_search"}) == text
assert (
_strip('web_search[ARGS]{"q":1} done', final = True, enabled_tool_names = {"web_search"})
== "done"
)
assert _strip(text, final = True).strip() == "is just syntax."
assert _strip(text, final = True, enabled_tool_names = None).strip() == "is just syntax."
def test_route_display_strip_gate_preserves_inactive_history_rehearsal():
# The GGUF history sanitiser passes the gate, so a documented inactive shape survives in
# the replayed prompt context.
gate = _display_tool_name_gate([{"function": {"name": "web_search"}}])
text = 'To call it write foo[ARGS]{"x":1} in your reply.'
assert 'foo[ARGS]{"x":1}' in _strip_tool_xml_for_display(
text, auto_heal_tool_calls = True, enabled_tool_names = gate
)
# An ACTIVE name is still stripped as a real rehearsed call.
assert "web_search[ARGS]" not in _strip_tool_xml_for_display(
'Result web_search[ARGS]{"q":"x"} done', auto_heal_tool_calls = True, enabled_tool_names = gate
)
# No gate (legacy) strips every NAME[ARGS]{...}.
assert "foo[ARGS]" not in _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
def test_gguf_history_sanitizer_forwards_enabled_tool_names_gate():
# Wiring guard: the GGUF history strip must forward the display gate like the live strip.
block = _re.search(
r"Strip stale tool-call XML from conversation history.*?\.strip\(\)",
_src,
_re.DOTALL,
)
assert block, "could not locate GGUF history sanitizer block"
assert "enabled_tool_names" in block.group(
0
), "GGUF history sanitizer must pass enabled_tool_names to _strip_tool_xml_for_display"
def test_route_history_and_passthrough_forward_the_display_gate():
# The safetensors/Anthropic history sanitisers and the Anthropic non-stream passthrough
# must forward the gate so inactive examples survive in replayed prompt / final text.
blocks = {
"safetensors history": r"Strip stale tool-call XML from prior assistant turns.*?\.strip\(\)",
"anthropic history": r"Strip stale tool-call XML via the protected display helper.*?\.strip\(\)",
# Anchored on the code, not the comment above it, so rewrapping prose cannot break this.
"anthropic passthrough": r"if not healing_active:.*?\.strip\(\)",
}
for label, pat in blocks.items():
m = _re.search(pat, _src, _re.DOTALL)
assert m, f"could not locate {label} strip block"
assert "enabled_tool_names" in m.group(
0
), f"{label} must forward enabled_tool_names to _strip_tool_xml_for_display"
# ── DeepSeek opener variants + bare Kimi (parse/strip symmetry) ──
def test_strips_deepseek_space_opener_variant():
# The space-separated opener is parsed by the parser, so the display strip
# must remove it too (the shared opener alternation is reused here).
text = (
"pre <tool calls begin><tool▁call▁begin>get_x<tool▁sep>"
'{"a":1}<tool▁call▁end><tool▁calls▁end> post'
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "tool" not in cleaned.replace("post", "").replace("pre", "")
assert cleaned == "pre post"
def test_strips_deepseek_escaped_underscore_opener_variant():
text = (
"pre <tool\\_calls\\_begin><tool▁call▁begin>get_y<tool▁sep>"
'{"a":1}<tool▁call▁end><tool▁calls▁end> post'
)
cleaned = _TOOL_XML_RE.sub("", text)
assert cleaned == "pre post"
def test_strips_bare_kimi_call_without_section_wrapper():
# Kimi can emit a bare <|tool_call_begin|>...<|tool_call_end|> with no
# section wrapper; the parser accepts it, so the strip must cover it.
text = (
"pre <|tool_call_begin|>functions.get_w:0<|tool_call_argument_begin|>"
'{"a":1}<|tool_call_end|> post'
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "tool_call_begin" not in cleaned
assert cleaned == "pre post"
@pytest.mark.parametrize(
"text",
[
# Prose that merely names a Kimi/DeepSeek marker (no real call follows) must
# survive: the call-shaped lookahead fires only on a real call or a bare EOF
# fragment, so an answer discussing the protocol is never truncated.
"See <|tool_call_begin|> in the docs. More prose after it.",
"The <|tool_calls_section_begin|> marker opens a batch. Read on.",
"DeepSeek uses <tool▁calls▁begin> to start a call block, then continues.",
],
)
def test_deepseek_kimi_false_alarm_prose_is_kept(text):
# Regression for the route arm truncating a prose answer that references a marker
# without a following call (parser _TOOL_ALL_PATS already had this lookahead).
assert _TOOL_XML_RE.sub("", text) == text
def test_deepseek_kimi_real_calls_still_strip_after_false_alarm_fix():
# The lookahead must not weaken real-call stripping: closed, truncated, and bare
# EOF-fragment forms all still get removed.
closed = (
"answer <|tool_call_begin|>functions.get_w:0<|tool_call_argument_begin|>"
'{"a":1}<|tool_call_end|> tail'
)
assert _TOOL_XML_RE.sub("", closed) == "answer tail"
eof_fragment = "prefix <|tool_call_begin|>"
assert _TOOL_XML_RE.sub("", eof_fragment) == "prefix "
deepseek = (
"reply <tool▁calls▁begin><tool▁call▁begin>get_x<tool▁sep>"
'{"a":1}<tool▁call▁end><tool▁calls▁end>'
)
assert _TOOL_XML_RE.sub("", deepseek) == "reply "
# ── Llama-3 <|python_tag|> arm bounds on REAL sentinels only ──────
# Llama-3 <|python_tag|> arm bounds on REAL sentinels only
def test_python_tag_strip_consumes_literal_sentinel_in_arg():
# A <|python_tag|> tool call whose JSON argument carries a literal <|...|>
# token (here <|cite|>) must be stripped whole. The old `<(?!\|)` arm stopped
# at any `<|`, leaking the call tail (e.g. `<|cite|> here"}}`) into display.
text = '<|python_tag|>{"name": "send", "parameters": {"text": "use <|cite|> here"}}'
cleaned = _TOOL_XML_RE.sub("", text)
assert cleaned == "", f"python_tag call leaked at literal sentinel: {cleaned!r}"
@pytest.mark.parametrize(
"sentinel",
[
"<|eot_id|>",
"<|eom_id|>",
"<|start_header_id|>",
"<|end_header_id|>",
],
)
def test_python_tag_strip_stops_at_real_sentinel(sentinel):
# A genuine Llama control sentinel still bounds the strip so following
# assistant text is preserved (the arm must not swallow past it).
text = f'<|python_tag|>{{"name": "x", "parameters": {{}}}}{sentinel}visible answer'
cleaned = _TOOL_XML_RE.sub("", text)
assert (
cleaned == f"{sentinel}visible answer"
), f"strip did not stop at real sentinel {sentinel!r}: {cleaned!r}"
def test_python_tag_strip_restarts_on_second_python_tag():
# A second <|python_tag|> opens a new tool-call region, so the whole pair is
# stripped (the arm bounds the first, then the next match consumes the rest).
text = '<|python_tag|>{"name": "a"}<|python_tag|>{"name": "b"}'
cleaned = _TOOL_XML_RE.sub("", text)
assert cleaned == "", f"second python_tag region leaked: {cleaned!r}"
def test_glm_call_with_literal_close_tag_in_arg_value_is_stripped_whole():
# GLM 4.x emits <tool_call>NAME<arg_key>k</arg_key><arg_value>v</arg_value> ...</tool_call>.
text = (
"<tool_call>web_search\n<arg_key>query</arg_key>\n"
"<arg_value>find </tool_call> here</arg_value>\n</tool_call> done"
)
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "</arg_value>" not in out
assert "<arg_key>" not in out
assert out.strip() == "done"
def test_glm_normal_and_qwen_calls_still_stripped_by_route():
# Regression: a normal GLM call (no literal close tag) and a Qwen
# <tool_call>{json}</tool_call> are still stripped; trailing prose is kept.
glm = "<tool_call>get_time\n<arg_key>tz</arg_key>\n<arg_value>UTC</arg_value>\n</tool_call> ok"
assert _strip_tool_xml_for_display(glm, auto_heal_tool_calls = True).strip() == "ok"
qwen = '<tool_call>{"name":"web_search","arguments":{"q":"x"}}</tool_call> after'
assert _strip_tool_xml_for_display(qwen, auto_heal_tool_calls = True).strip() == "after"
def test_route_strip_removes_param_alias_close_tag():
# The parser accepts the <param name="...">...</param> attribute-form alias of
# <parameter=...>; the route tail cleanup must strip an orphan </param> close too.
assert _strip_tool_xml_for_display("answer </param>", auto_heal_tool_calls = True) == "answer "
assert (
_strip_tool_xml_for_display("answer </parameter>", auto_heal_tool_calls = True) == "answer "
)
def test_route_strip_uses_guarded_function_scan_for_literal_nested_markup():
# A literal <function=...></function> in a value must not truncate the strip: the route runs the
# parser's guarded function-XML scan before the regex, matching the core strip.
text = "<function=python><parameter=code><function=evil></function></parameter></function> tail"
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = True).strip() == "tail"
def test_route_strip_gates_wrapperless_gemma_by_enabled_tools():
# The route strip must gate the markerless Gemma call:NAME{...} form on the enabled tool names,
# like the parser/loop, so a disabled/example name in prose is preserved in ...
prose = "To document syntax you write call:foo{query:example}. That shows the format."
assert "call:foo{query:example}" in _strip_tool_xml(prose, {"web_search"})
# An enabled name is still a real call and stripped.
assert "call:web_search" not in _strip_tool_xml(
"Answer. call:web_search{query:x}", {"web_search"}
)
# No gate (legacy) strips every closed call.
assert "call:foo" not in _strip_tool_xml(prose)
def test_gemma_strip_gate_empty_tools_preserves_prose():
# With NO tools enabled the gate must return an EMPTY set (strip nothing), not None: None falls
# back to strip-all and deletes an answer that documents the call:NAME{...} syntax.
assert _gemma_strip_gate([]) == set()
assert _gemma_strip_gate(None) == set()
assert _gemma_strip_gate([{"function": {"name": "web_search"}}]) == {"web_search"}
prose = "To document syntax you write call:foo{query:example}. That shows the format."
assert "call:foo{query:example}" in _strip_tool_xml(prose, _gemma_strip_gate([]))
assert "call:foo{query:example}" in _strip_tool_xml(prose, _gemma_strip_gate(None))
# An enabled tool's real call is still stripped.
assert "call:web_search" not in _strip_tool_xml(
"Answer. call:web_search{query:x}",
_gemma_strip_gate([{"function": {"name": "web_search"}}]),
)
def test_strip_keeps_prose_after_closed_function_call_with_literal_close():
# The call ends at its first non-data close: prose after it survives the
# strip even when it mentions a literal </function>.
from core.inference.tool_call_parser import strip_tool_markup
text = (
"<function=web_search><parameter=query>cats</parameter></function>"
" Done. The tag </function> closes a call."
)
assert strip_tool_markup(text, final = True) == "Done. The tag </function> closes a call."
def test_final_strip_keeps_prose_mentioning_bare_markers():
# A false-alarm marker in a normal answer must not lose everything after
# it; only text that looks like that family's call start drops.
from core.inference.tool_call_parser import strip_tool_markup
for text in (
"See [TOOL_CALLS] docs for details. More prose after.",
"<|python_tag|> is the Llama marker. Explanation continues.",
"The <|tool_call> opener wraps Gemma calls.",
):
assert strip_tool_markup(text, final = True) == text
# A bare marker at end-of-text is a fragment and still drops.
assert strip_tool_markup("Answer text [TOOL_CALLS]", final = True) == "Answer text"
def test_final_strip_still_drops_truncated_marker_calls():
from core.inference.tool_call_parser import strip_tool_markup
for text in (
'[TOOL_CALLS][{"name":"web_search","argu',
'[TOOL_CALLS]web_search[ARGS]{"q":"x',
'<|python_tag|>{"name":"web_search","par',
'<|python_tag|>foo.call(items=["a',
"<|tool_call>call:web_search{query:tru",
):
assert strip_tool_markup(text, final = True) == ""
def test_chained_bare_json_strip_consumes_all_calls():
# The loops keep this text as next-turn history: a leftover executed call
# would be replayed alongside the structured tool_calls.
from core.inference.tool_call_parser import strip_leading_bare_json_call
enabled = {"web_search", "python"}
chained = (
'{"name":"web_search","parameters":{"q":"first"}};'
'{"name":"python","parameters":{"code":"x"}}'
)
assert strip_leading_bare_json_call(chained, enabled_tool_names = enabled) == ""
assert (
strip_leading_bare_json_call(chained + " trailing prose", enabled_tool_names = enabled)
== "trailing prose"
)
# The chain stops at a non-call answer object, which stays visible.
call_then_answer = (
'{"name":"web_search","parameters":{"q":"x"}};{"name":"web_search","result":"data"}'
)
assert (
strip_leading_bare_json_call(call_then_answer, enabled_tool_names = enabled)
== '{"name":"web_search","result":"data"}'
)