* 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>
1454 lines
58 KiB
Python
1454 lines
58 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-only
|
|
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
|
|
|
|
"""Unit tests for core/inference/passthrough_healing.py: promoting text-form
|
|
tool calls back into structured calls on the client-tool passthrough. The
|
|
route-level wiring (OpenAI / Anthropic / Responses endpoints) is covered in
|
|
their own endpoint test files; this file exercises the shared state machine
|
|
and helpers directly.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sys
|
|
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)
|
|
|
|
from core.inference.passthrough_healing import ( # noqa: E402
|
|
StreamToolCallHealer,
|
|
heal_gate,
|
|
heal_openai_message,
|
|
nudge_messages,
|
|
nudge_should_retry,
|
|
response_has_promotable_calls,
|
|
)
|
|
|
|
TOOLS = [
|
|
{"type": "function", "function": {"name": "Bash", "parameters": {}}},
|
|
{"type": "function", "function": {"name": "Read", "parameters": {}}},
|
|
]
|
|
|
|
BASH_COMMAND_TOOL = {
|
|
"type": "function",
|
|
"function": {
|
|
"name": "Bash",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {"command": {"type": "string"}},
|
|
"required": ["command"],
|
|
},
|
|
},
|
|
}
|
|
XML_BASH = '<tool_call>{"name":"Bash","arguments":{"cmd":"ls"}}</tool_call>'
|
|
XML_UNDECLARED = '<tool_call>{"name":"Nuke","arguments":{}}</tool_call>'
|
|
|
|
|
|
def _events_text(events):
|
|
return "".join(text for kind, text in events if kind == "text")
|
|
|
|
|
|
def _events_calls(events):
|
|
return [call for kind, call in events if kind == "tool_call"]
|
|
|
|
|
|
class TestHealGate:
|
|
def test_returns_declared_names(self):
|
|
assert heal_gate(None, TOOLS) == {"Bash", "Read"}
|
|
assert heal_gate(True, TOOLS) == {"Bash", "Read"}
|
|
|
|
def test_opt_out_and_no_tools(self):
|
|
assert heal_gate(False, TOOLS) is None
|
|
assert heal_gate(None, []) is None
|
|
assert heal_gate(None, None) is None
|
|
|
|
def test_malformed_tool_entries_ignored(self):
|
|
assert heal_gate(None, ["nonsense", {"function": "x"}, {}]) is None
|
|
|
|
def test_tool_choice_none_disables(self):
|
|
assert heal_gate(None, TOOLS, "none") is None
|
|
|
|
def test_tool_choice_forced_function_narrows_allowlist(self):
|
|
forced = {"type": "function", "function": {"name": "Bash"}}
|
|
assert heal_gate(None, TOOLS, forced) == {"Bash"}
|
|
|
|
def test_tool_choice_forced_undeclared_function_disables(self):
|
|
forced = {"type": "function", "function": {"name": "Nuke"}}
|
|
assert heal_gate(None, TOOLS, forced) is None
|
|
|
|
def test_tool_choice_auto_and_required_keep_full_set(self):
|
|
assert heal_gate(None, TOOLS, "auto") == {"Bash", "Read"}
|
|
assert heal_gate(None, TOOLS, "required") == {"Bash", "Read"}
|
|
|
|
def test_tool_choice_unrecognized_dict_keeps_full_set(self):
|
|
assert heal_gate(None, TOOLS, {"type": "function"}) == {"Bash", "Read"}
|
|
|
|
|
|
class TestHealOpenaiMessage:
|
|
def test_promotes_xml_and_strips_content(self):
|
|
msg = {"role": "assistant", "content": XML_BASH}
|
|
assert heal_openai_message(msg, {"Bash"}) is True
|
|
assert msg["content"] is None
|
|
(call,) = msg["tool_calls"]
|
|
assert call["function"]["name"] == "Bash"
|
|
assert json.loads(call["function"]["arguments"]) == {"cmd": "ls"}
|
|
|
|
def test_keeps_surrounding_prose(self):
|
|
msg = {"role": "assistant", "content": f"Let me check.\n{XML_BASH}"}
|
|
assert heal_openai_message(msg, {"Bash"}) is True
|
|
assert msg["content"] == "Let me check."
|
|
|
|
def test_undeclared_name_not_promoted(self):
|
|
msg = {"role": "assistant", "content": XML_UNDECLARED}
|
|
assert heal_openai_message(msg, {"Bash"}) is False
|
|
assert msg["content"] == XML_UNDECLARED
|
|
assert "tool_calls" not in msg
|
|
|
|
def test_structured_calls_untouched(self):
|
|
msg = {"role": "assistant", "content": XML_BASH, "tool_calls": [{"id": "x"}]}
|
|
assert heal_openai_message(msg, {"Bash"}) is False
|
|
assert msg["content"] == XML_BASH
|
|
|
|
def test_prose_only_untouched(self):
|
|
msg = {"role": "assistant", "content": "just an answer"}
|
|
assert heal_openai_message(msg, {"Bash"}) is False
|
|
|
|
def test_bare_string_arguments_use_schema_key(self):
|
|
msg = {
|
|
"role": "assistant",
|
|
"content": '<tool_call>{"name":"Bash","arguments":"echo hi"}</tool_call>',
|
|
}
|
|
assert heal_openai_message(msg, {"Bash"}, [BASH_COMMAND_TOOL]) is True
|
|
args = json.loads(msg["tool_calls"][0]["function"]["arguments"])
|
|
assert args == {"command": "echo hi"}
|
|
|
|
def test_bare_string_arguments_decline_ambiguous_schema(self):
|
|
msg = {
|
|
"role": "assistant",
|
|
"content": '<tool_call>{"name":"Bash","arguments":"echo hi"}</tool_call>',
|
|
}
|
|
assert heal_openai_message(msg, {"Bash"}, TOOLS) is False
|
|
assert "tool_calls" not in msg
|
|
|
|
def test_mixed_declared_and_undeclared_promotes_declared_keeps_undeclared_text(self):
|
|
# Span-exact removal: only the promoted Bash markup is dropped; the
|
|
# undeclared Nuke call's text stays in the content byte-intact.
|
|
content = f"pre {XML_BASH} mid {XML_UNDECLARED} post"
|
|
msg = {"role": "assistant", "content": content}
|
|
assert heal_openai_message(msg, {"Bash"}) is True
|
|
(call,) = msg["tool_calls"]
|
|
assert call["function"]["name"] == "Bash"
|
|
assert XML_UNDECLARED in msg["content"]
|
|
assert "pre" in msg["content"] and "post" in msg["content"]
|
|
assert XML_BASH not in msg["content"]
|
|
|
|
def test_multiple_declared_calls_all_promoted(self):
|
|
content = f"{XML_BASH} and {XML_BASH}"
|
|
msg = {"role": "assistant", "content": content}
|
|
assert heal_openai_message(msg, {"Bash"}) is True
|
|
assert len(msg["tool_calls"]) == 2
|
|
|
|
def test_mixed_formats_promote_in_document_order(self):
|
|
func_read = "<function=Read><parameter=path>a.txt</parameter></function>"
|
|
content = f"{func_read} then {XML_BASH}"
|
|
msg = {"role": "assistant", "content": content}
|
|
assert heal_openai_message(msg, {"Bash", "Read"}) is True
|
|
assert [call["function"]["name"] for call in msg["tool_calls"]] == ["Read", "Bash"]
|
|
assert msg["content"] == "then"
|
|
|
|
def test_unparseable_closed_block_not_deleted(self):
|
|
# A closed <tool_call> block whose body never parses is model output,
|
|
# not a promotable call; it must survive promotion of its neighbor.
|
|
garbage = "<tool_call>not json at all</tool_call>"
|
|
content = f"{XML_BASH} {garbage}"
|
|
msg = {"role": "assistant", "content": content}
|
|
assert heal_openai_message(msg, {"Bash"}) is True
|
|
assert garbage in msg["content"]
|
|
|
|
|
|
class TestStreamHealer:
|
|
def test_plain_text_passes_through(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed("hello ") + healer.feed("world") + healer.finalize()
|
|
assert _events_text(events) == "hello world"
|
|
assert not _events_calls(events)
|
|
|
|
def test_complete_call_in_one_chunk(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed(f"On it. {XML_BASH}") + healer.finalize()
|
|
assert _events_text(events) == "On it. "
|
|
(call,) = _events_calls(events)
|
|
assert call["function"]["name"] == "Bash"
|
|
assert healer.healed
|
|
|
|
def test_signal_split_across_chunks(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = []
|
|
for piece in ["<tool", '_call>{"name":"Bash",', '"arguments":{}}</tool_call>']:
|
|
events += healer.feed(piece)
|
|
events += healer.finalize()
|
|
assert _events_text(events) == ""
|
|
assert len(_events_calls(events)) == 1
|
|
|
|
def test_closed_malformed_tool_block_flushes_immediately(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed("<tool_call>not json</tool_call> after")
|
|
assert _events_text(events) == "<tool_call>not json</tool_call> after"
|
|
assert not _events_calls(events)
|
|
|
|
def test_mixed_formats_stream_in_document_order(self):
|
|
healer = StreamToolCallHealer({"Bash", "Read"})
|
|
func_read = "<function=Read><parameter=path>a.txt</parameter></function>"
|
|
events = healer.feed(f"{func_read} then {XML_BASH}") + healer.finalize()
|
|
assert [call["function"]["name"] for call in _events_calls(events)] == ["Read", "Bash"]
|
|
assert _events_text(events).strip() == "then"
|
|
|
|
def test_false_alarm_html_flushes(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed("use the <div> tag") + healer.finalize()
|
|
assert _events_text(events) == "use the <div> tag"
|
|
assert not _events_calls(events)
|
|
|
|
def test_partial_signal_tail_held_then_flushed_at_end(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed("trailing <tool")
|
|
assert _events_text(events) == "trailing " # tail held back
|
|
events += healer.finalize()
|
|
assert _events_text(events) == "trailing <tool"
|
|
|
|
def test_mixed_calls_promote_declared_flush_undeclared_in_order(self):
|
|
# Declared + undeclared in the same buffer: the declared call is
|
|
# promoted, the undeclared markup flushes as text, and event order
|
|
# follows document order (call first here, since it came first).
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
text = f"{XML_BASH} then {XML_UNDECLARED} post"
|
|
events = healer.feed(text) + healer.finalize()
|
|
assert [k for k, _ in events if k == "tool_call"] == ["tool_call"]
|
|
assert events[0][0] == "tool_call"
|
|
joined = _events_text(events)
|
|
assert XML_UNDECLARED in joined
|
|
assert "then" in joined and "post" in joined
|
|
|
|
def test_text_between_two_healed_calls_keeps_document_order(self):
|
|
# call A, " middle ", call B in ONE buffer must stream as
|
|
# call A -> text -> call B, never both calls then the text.
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed(f"{XML_BASH} middle {XML_BASH}") + healer.finalize()
|
|
kinds = [k for k, _ in events]
|
|
assert kinds == ["tool_call", "text", "tool_call"]
|
|
assert events[1][1] == " middle "
|
|
|
|
def test_undeclared_then_declared_keeps_document_order(self):
|
|
# The undeclared block precedes the declared call; its raw text must
|
|
# be emitted BEFORE the promoted call event, never after.
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed(f"{XML_UNDECLARED} then {XML_BASH}") + healer.finalize()
|
|
kinds = [k for k, _ in events]
|
|
assert kinds.index("tool_call") == len(kinds) - 1
|
|
(call,) = _events_calls(events)
|
|
assert call["function"]["name"] == "Bash"
|
|
assert XML_UNDECLARED in _events_text(events)
|
|
|
|
def test_declared_promoted_then_late_undeclared_flushes_raw(self):
|
|
# Streaming causality: the declared call completed and was already
|
|
# emitted before the undeclared one arrived. The undeclared markup
|
|
# must still reach the client as raw text (no data loss).
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed(f"{XML_BASH} then ")
|
|
assert len(_events_calls(events)) == 1
|
|
events += healer.feed(XML_UNDECLARED) + healer.finalize()
|
|
assert XML_UNDECLARED in _events_text(events)
|
|
assert len(_events_calls(events)) == 1
|
|
|
|
def test_undeclared_tool_flushes_raw(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed(XML_UNDECLARED) + healer.finalize()
|
|
assert _events_text(events) == XML_UNDECLARED
|
|
assert not _events_calls(events)
|
|
|
|
def test_two_calls_and_text_between(self):
|
|
healer = StreamToolCallHealer({"Bash", "Read"})
|
|
xml_read = '<tool_call>{"name":"Read","arguments":{"path":"f"}}</tool_call>'
|
|
events = healer.feed(f"{XML_BASH} then {xml_read}") + healer.finalize()
|
|
calls = _events_calls(events)
|
|
assert [c["function"]["name"] for c in calls] == ["Bash", "Read"]
|
|
assert [c["id"] for c in calls] == ["call_0", "call_1"]
|
|
assert _events_text(events).strip() == "then"
|
|
|
|
def test_mistral_array_multiple_calls_all_promoted_in_stream(self):
|
|
# A canonical Mistral [TOOL_CALLS] array carries several calls under a
|
|
# SINGLE signal. Draining only the first call would leave the residue
|
|
# starting at ",{...}]" (no signal), so later calls in the same array
|
|
# must be promoted in the same pass, not flushed as raw text.
|
|
healer = StreamToolCallHealer({"get_weather", "get_time"})
|
|
array = (
|
|
'[TOOL_CALLS][{"name":"get_weather","arguments":{"city":"Paris"}},'
|
|
'{"name":"get_time","arguments":{"tz":"UTC"}}]'
|
|
)
|
|
events = healer.feed(array) + healer.finalize()
|
|
calls = _events_calls(events)
|
|
assert [c["function"]["name"] for c in calls] == ["get_weather", "get_time"]
|
|
assert [c["id"] for c in calls] == ["call_0", "call_1"]
|
|
assert _events_text(events) == ""
|
|
|
|
def test_mistral_array_multiple_calls_promoted_char_by_char(self):
|
|
healer = StreamToolCallHealer({"get_weather", "get_time"})
|
|
array = (
|
|
'[TOOL_CALLS][{"name":"get_weather","arguments":{"city":"Paris"}},'
|
|
'{"name":"get_time","arguments":{"tz":"UTC"}}]'
|
|
)
|
|
events = []
|
|
for ch in array:
|
|
events += healer.feed(ch)
|
|
events += healer.finalize()
|
|
calls = _events_calls(events)
|
|
assert [c["function"]["name"] for c in calls] == ["get_weather", "get_time"]
|
|
assert _events_text(events) == ""
|
|
|
|
def test_mistral_array_undeclared_middle_kept_as_text_others_promoted(self):
|
|
# A mid-array element for a tool that is not declared must survive as
|
|
# text while the declared neighbours on either side still promote in
|
|
# document order.
|
|
healer = StreamToolCallHealer({"a", "c"})
|
|
array = (
|
|
'[TOOL_CALLS][{"name":"a","arguments":{}},'
|
|
'{"name":"b","arguments":{}},{"name":"c","arguments":{}}]'
|
|
)
|
|
events = healer.feed(array) + healer.finalize()
|
|
assert [c["function"]["name"] for c in _events_calls(events)] == ["a", "c"]
|
|
assert '"b"' in _events_text(events)
|
|
|
|
def test_mistral_array_then_trailing_prose(self):
|
|
healer = StreamToolCallHealer({"a", "b"})
|
|
array = '[TOOL_CALLS][{"name":"a","arguments":{}},{"name":"b","arguments":{}}]'
|
|
events = healer.feed(f"{array} all done") + healer.finalize()
|
|
assert [c["function"]["name"] for c in _events_calls(events)] == ["a", "b"]
|
|
assert "all done" in _events_text(events)
|
|
|
|
def test_incomplete_call_healed_at_finalize(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed('<tool_call>{"name":"Bash","arguments":{"cmd":"ls"}}')
|
|
assert events == [] # held
|
|
events = healer.finalize()
|
|
(call,) = _events_calls(events)
|
|
assert call["function"]["name"] == "Bash"
|
|
|
|
def test_teaching_text_flushes_at_finalize(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
events = healer.feed("<tool_call> is the marker syntax") + healer.finalize()
|
|
assert _events_text(events) == "<tool_call> is the marker syntax"
|
|
assert not _events_calls(events)
|
|
|
|
def test_hold_bound_flushes(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
blob = "<tool_call>" + "x" * (64 * 1024 + 10)
|
|
events = healer.feed(blob) + healer.finalize()
|
|
assert _events_text(events) == blob
|
|
assert not _events_calls(events)
|
|
|
|
def test_dormant_after_structured_delta(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
held = healer.feed("prefix <tool")
|
|
flush = healer.structured_tool_call_seen()
|
|
after = healer.feed(XML_BASH) + healer.finalize()
|
|
assert _events_text(held + flush + after) == f"prefix <tool{XML_BASH}"
|
|
assert not _events_calls(after)
|
|
|
|
|
|
class TestNudgeHelpers:
|
|
def _resp(
|
|
self,
|
|
content,
|
|
tool_calls = None,
|
|
):
|
|
msg = {"role": "assistant", "content": content}
|
|
if tool_calls:
|
|
msg["tool_calls"] = tool_calls
|
|
return {"choices": [{"message": msg, "finish_reason": "stop"}]}
|
|
|
|
def test_retry_on_unparseable_signal(self):
|
|
# Signal present but the JSON never parses and no declared name matches.
|
|
data = self._resp("<tool_call>call Bash somehow???")
|
|
assert nudge_should_retry(data, {"Read"}) is True
|
|
|
|
def test_no_retry_on_clean_prose(self):
|
|
assert nudge_should_retry(self._resp("all done"), {"Bash"}) is False
|
|
|
|
def test_no_retry_when_heal_would_succeed(self):
|
|
assert nudge_should_retry(self._resp(XML_BASH), {"Bash"}) is False
|
|
|
|
def test_no_retry_with_structured_calls(self):
|
|
data = self._resp("", tool_calls = [{"id": "x"}])
|
|
assert nudge_should_retry(data, {"Bash"}) is False
|
|
|
|
def test_no_retry_when_healing_disabled(self):
|
|
assert nudge_should_retry(self._resp("<tool_call>???"), None) is False
|
|
|
|
def test_nudge_messages_shape(self):
|
|
data = self._resp("<tool_call>garbage")
|
|
suffix = nudge_messages(data, {"Bash", "Read"})
|
|
assert [m["role"] for m in suffix] == ["assistant", "user"]
|
|
assert suffix[0]["content"] == "<tool_call>garbage"
|
|
assert "`Bash` or `Read`" in suffix[1]["content"]
|
|
|
|
def test_retry_with_undeclared_structured_call_is_not_an_improvement(self):
|
|
# The retry replaces the original only when it carries a USABLE call:
|
|
# a structured call naming an undeclared tool must not count.
|
|
undeclared = [
|
|
{"id": "x", "type": "function", "function": {"name": "Nuke", "arguments": "{}"}}
|
|
]
|
|
declared = [
|
|
{"id": "y", "type": "function", "function": {"name": "Bash", "arguments": "{}"}}
|
|
]
|
|
assert response_has_promotable_calls(self._resp("", undeclared), {"Bash"}) is False
|
|
assert response_has_promotable_calls(self._resp("", declared), {"Bash"}) is True
|
|
|
|
def test_retry_with_mixed_structured_calls_is_not_an_improvement(self):
|
|
# ALL structured calls must be declared: the caller forwards the whole
|
|
# list (and a parallel cap could keep only the FIRST), so a mixed retry
|
|
# could still hand the client an undeclared tool.
|
|
mixed = [
|
|
{"id": "x", "type": "function", "function": {"name": "Nuke", "arguments": "{}"}},
|
|
{"id": "y", "type": "function", "function": {"name": "Bash", "arguments": "{}"}},
|
|
]
|
|
assert response_has_promotable_calls(self._resp("", mixed), {"Bash"}) is False
|
|
assert (
|
|
response_has_promotable_calls(self._resp("", list(reversed(mixed))), {"Bash"}) is False
|
|
)
|
|
|
|
@pytest.mark.parametrize(
|
|
"data",
|
|
[
|
|
None,
|
|
"not a dict",
|
|
{},
|
|
{"choices": []},
|
|
{"choices": [{}]},
|
|
{"choices": [{"message": None}]}, # llama-server error bodies do this
|
|
{"choices": [{"message": "not a dict"}]},
|
|
{"choices": [{"message": {"content": None}}]},
|
|
{"error": {"message": "boom"}},
|
|
],
|
|
)
|
|
def test_malformed_response_shapes_never_raise(self, data):
|
|
# A malformed upstream body must degrade to "nothing to heal/nudge",
|
|
# never crash the request with an AttributeError.
|
|
assert nudge_should_retry(data, {"Bash"}) is False
|
|
assert response_has_promotable_calls(data, {"Bash"}) is False
|
|
suffix = nudge_messages(data, {"Bash"})
|
|
assert suffix[0] == {"role": "assistant", "content": ""}
|
|
|
|
|
|
# ── Route-level wiring (OpenAI passthrough) ─────────────────────────────
|
|
# Mirrors the fake-llama-server patterns in test_openai_tool_passthrough.py.
|
|
|
|
import asyncio # noqa: E402
|
|
import threading # noqa: E402
|
|
from types import SimpleNamespace # noqa: E402
|
|
|
|
import httpx # noqa: E402
|
|
|
|
from core.inference.api_monitor import ApiMonitor # noqa: E402
|
|
from models.inference import ChatCompletionRequest, ChatMessage # noqa: E402
|
|
from routes.inference import ( # noqa: E402
|
|
_openai_passthrough_non_streaming,
|
|
_openai_passthrough_stream,
|
|
)
|
|
|
|
LOOKUP_TOOL = {
|
|
"type": "function",
|
|
"function": {"name": "lookup", "parameters": {"type": "object", "properties": {}}},
|
|
}
|
|
LOOKUP_XML = '<tool_call>{"name":"lookup","arguments":{"q":"x"}}</tool_call>'
|
|
|
|
|
|
def _payload(**kwargs):
|
|
defaults = dict(
|
|
model = "default",
|
|
messages = [ChatMessage(role = "user", content = "hi")],
|
|
tools = [LOOKUP_TOOL],
|
|
)
|
|
defaults.update(kwargs)
|
|
return ChatCompletionRequest(**defaults)
|
|
|
|
|
|
def _llama_backend():
|
|
return SimpleNamespace(
|
|
base_url = "http://llama.test",
|
|
context_length = 4096,
|
|
_request_reasoning_kwargs = lambda *_args, **_kwargs: None,
|
|
)
|
|
|
|
|
|
def _upstream_message(
|
|
content,
|
|
tool_calls = None,
|
|
finish_reason = "stop",
|
|
):
|
|
message = {"role": "assistant", "content": content}
|
|
if tool_calls is not None:
|
|
message["tool_calls"] = tool_calls
|
|
return {
|
|
"id": "chatcmpl-up",
|
|
"object": "chat.completion",
|
|
"created": 1,
|
|
"model": "gguf",
|
|
"choices": [{"index": 0, "message": message, "finish_reason": finish_reason}],
|
|
"usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
|
|
}
|
|
|
|
|
|
class ScriptedClient:
|
|
"""Fake upstream client returning scripted JSON bodies, counting POSTs."""
|
|
|
|
def __init__(self, bodies):
|
|
self.bodies = list(bodies)
|
|
self.posts = []
|
|
self.closed = False
|
|
|
|
async def post(
|
|
self,
|
|
_url,
|
|
json = None,
|
|
timeout = None,
|
|
headers = None,
|
|
):
|
|
self.posts.append(json)
|
|
return httpx.Response(200, json = self.bodies[min(len(self.posts) - 1, len(self.bodies) - 1)])
|
|
|
|
async def aclose(self):
|
|
# The Anthropic pass-through owns its client and closes it in a finally.
|
|
self.closed = True
|
|
|
|
|
|
async def _drive_non_streaming(monkeypatch, payload, bodies):
|
|
import routes.inference as inf_mod
|
|
|
|
client = ScriptedClient(bodies)
|
|
monkeypatch.setattr(inf_mod, "nonstreaming_client", lambda: client)
|
|
response = await _openai_passthrough_non_streaming(
|
|
_llama_backend(), payload, "gguf", monitor_id = None
|
|
)
|
|
return client, json.loads(response.body)
|
|
|
|
|
|
async def _drive_stream(monkeypatch, payload, lines):
|
|
import routes.inference as inf_mod
|
|
|
|
class Request:
|
|
async def is_disconnected(self):
|
|
return False
|
|
|
|
async def fake_send(*_args, **_kwargs):
|
|
return httpx.Response(200, content = b"")
|
|
|
|
async def fake_items(*_args, **_kwargs):
|
|
for line in lines:
|
|
yield line
|
|
|
|
monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
|
|
monkeypatch.setattr(inf_mod, "_aiter_llama_stream_items", fake_items)
|
|
monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))
|
|
response = await _openai_passthrough_stream(
|
|
Request(),
|
|
threading.Event(),
|
|
_llama_backend(),
|
|
payload,
|
|
"gguf",
|
|
"chatcmpl-test",
|
|
monitor_id = None,
|
|
)
|
|
return [chunk async for chunk in response.body_iterator]
|
|
|
|
|
|
def _stream_payloads(chunks):
|
|
out = []
|
|
for chunk in chunks:
|
|
for line in chunk.splitlines():
|
|
if line.startswith("data: ") and line[6:] != "[DONE]":
|
|
out.append(json.loads(line[6:]))
|
|
return out
|
|
|
|
|
|
class TestOpenaiNonStreamingRoute:
|
|
def test_heals_xml_to_tool_calls(self, monkeypatch):
|
|
async def _run():
|
|
client, data = await _drive_non_streaming(
|
|
monkeypatch, _payload(), [_upstream_message(LOOKUP_XML)]
|
|
)
|
|
choice = data["choices"][0]
|
|
assert choice["finish_reason"] == "tool_calls"
|
|
(call,) = choice["message"]["tool_calls"]
|
|
assert call["function"]["name"] == "lookup"
|
|
assert json.loads(call["function"]["arguments"]) == {"q": "x"}
|
|
assert choice["message"]["content"] is None
|
|
assert data["usage"]["total_tokens"] == 3 # usage preserved
|
|
assert len(client.posts) == 1 # healing never re-requests
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_bare_string_uses_client_schema_key(self, monkeypatch):
|
|
async def _run():
|
|
content = '<tool_call>{"name":"Bash","arguments":"echo hi"}</tool_call>'
|
|
_, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(tools = [BASH_COMMAND_TOOL]),
|
|
[_upstream_message(content)],
|
|
)
|
|
(call,) = data["choices"][0]["message"]["tool_calls"]
|
|
assert json.loads(call["function"]["arguments"]) == {"command": "echo hi"}
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_opt_out_relays_verbatim(self, monkeypatch):
|
|
async def _run():
|
|
_, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(auto_heal_tool_calls = False),
|
|
[_upstream_message(LOOKUP_XML)],
|
|
)
|
|
choice = data["choices"][0]
|
|
assert choice["message"]["content"] == LOOKUP_XML
|
|
assert "tool_calls" not in choice["message"]
|
|
assert choice["finish_reason"] == "stop"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_no_tools_untouched(self, monkeypatch):
|
|
async def _run():
|
|
_, data = await _drive_non_streaming(
|
|
monkeypatch, _payload(tools = None), [_upstream_message(LOOKUP_XML)]
|
|
)
|
|
assert data["choices"][0]["message"]["content"] == LOOKUP_XML
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_undeclared_tool_not_promoted(self, monkeypatch):
|
|
async def _run():
|
|
xml = '<tool_call>{"name":"rogue","arguments":{}}</tool_call>'
|
|
_, data = await _drive_non_streaming(monkeypatch, _payload(), [_upstream_message(xml)])
|
|
assert data["choices"][0]["message"]["content"] == xml
|
|
assert "tool_calls" not in data["choices"][0]["message"]
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_structured_calls_untouched(self, monkeypatch):
|
|
async def _run():
|
|
native = [
|
|
{
|
|
"id": "call_up",
|
|
"type": "function",
|
|
"function": {"name": "lookup", "arguments": "{}"},
|
|
}
|
|
]
|
|
_, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(),
|
|
[_upstream_message("", tool_calls = native, finish_reason = "tool_calls")],
|
|
)
|
|
assert data["choices"][0]["message"]["tool_calls"] == native
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_length_finish_reason_preserved(self, monkeypatch):
|
|
async def _run():
|
|
# Truncated generation: the healed call stays attached but the
|
|
# client must still see the truncation, so length is never
|
|
# upgraded to tool_calls.
|
|
_, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(),
|
|
[_upstream_message(LOOKUP_XML, finish_reason = "length")],
|
|
)
|
|
choice = data["choices"][0]
|
|
assert choice["finish_reason"] == "length"
|
|
(call,) = choice["message"]["tool_calls"]
|
|
assert call["function"]["name"] == "lookup"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_tool_choice_none_relays_verbatim(self, monkeypatch):
|
|
async def _run():
|
|
_, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(tool_choice = "none"),
|
|
[_upstream_message(LOOKUP_XML)],
|
|
)
|
|
message = data["choices"][0]["message"]
|
|
assert message["content"] == LOOKUP_XML
|
|
assert "tool_calls" not in message
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_tool_choice_forcing_other_function_not_promoted(self, monkeypatch):
|
|
async def _run():
|
|
_, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(tool_choice = {"type": "function", "function": {"name": "other"}}),
|
|
[_upstream_message(LOOKUP_XML)],
|
|
)
|
|
message = data["choices"][0]["message"]
|
|
assert message["content"] == LOOKUP_XML
|
|
assert "tool_calls" not in message
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_mixed_declared_and_undeclared_promotes_and_keeps_text(self, monkeypatch):
|
|
async def _run():
|
|
rogue = '<tool_call>{"name":"rogue","arguments":{}}</tool_call>'
|
|
mixed = f"{LOOKUP_XML} also {rogue}"
|
|
_, data = await _drive_non_streaming(
|
|
monkeypatch, _payload(), [_upstream_message(mixed)]
|
|
)
|
|
choice = data["choices"][0]
|
|
(call,) = choice["message"]["tool_calls"]
|
|
assert call["function"]["name"] == "lookup"
|
|
assert rogue in choice["message"]["content"]
|
|
assert choice["finish_reason"] == "tool_calls"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_healed_then_native_stream_indexes_disjoint(self, monkeypatch):
|
|
async def _run():
|
|
# A healed text-form call goes out first (index 0); a native
|
|
# structured delta follows. Clients merge deltas by index, so the
|
|
# native call must be shifted off index 0 or the two would merge.
|
|
native_line = (
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{"tool_calls":'
|
|
'[{"index":0,"id":"call_native","type":"function","function":'
|
|
'{"name":"lookup","arguments":"{}"}}]}}]}'
|
|
)
|
|
lines = [
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{"content":'
|
|
+ json.dumps(LOOKUP_XML)
|
|
+ "}}]}",
|
|
native_line,
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}',
|
|
"data: [DONE]",
|
|
]
|
|
chunks = await _drive_stream(monkeypatch, _payload(stream = True), lines)
|
|
indexes = {}
|
|
for payload_data in _stream_payloads(chunks):
|
|
for ch in payload_data.get("choices", []):
|
|
for tc in (ch.get("delta") or {}).get("tool_calls") or []:
|
|
indexes.setdefault(tc["index"], tc.get("id"))
|
|
assert indexes.get(0, "").startswith("call_") and indexes[0] != "call_native"
|
|
assert indexes.get(1) == "call_native"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_role_delta_precedes_healed_stream_content(self, monkeypatch):
|
|
async def _run():
|
|
lines = [
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":'
|
|
+ json.dumps(LOOKUP_XML)
|
|
+ "}}]}",
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
|
|
"data: [DONE]",
|
|
]
|
|
chunks = await _drive_stream(monkeypatch, _payload(stream = True), lines)
|
|
payloads = _stream_payloads(chunks)
|
|
first_delta = payloads[0]["choices"][0]["delta"]
|
|
assert first_delta == {"role": "assistant"}
|
|
assert "tool_calls" in payloads[1]["choices"][0]["delta"]
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_same_chunk_role_content_finish_delays_finish_until_after_healed_tool(
|
|
self, monkeypatch
|
|
):
|
|
async def _run():
|
|
lines = [
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":'
|
|
+ json.dumps(LOOKUP_XML)
|
|
+ '},"finish_reason":"stop"}]}',
|
|
"data: [DONE]",
|
|
]
|
|
chunks = await _drive_stream(monkeypatch, _payload(stream = True), lines)
|
|
payloads = _stream_payloads(chunks)
|
|
assert payloads[0]["choices"][0]["finish_reason"] is None
|
|
assert payloads[0]["choices"][0]["delta"] == {"role": "assistant"}
|
|
assert "tool_calls" in payloads[1]["choices"][0]["delta"]
|
|
assert payloads[-1]["choices"][0]["finish_reason"] == "tool_calls"
|
|
|
|
asyncio.run(_run())
|
|
|
|
|
|
GARBAGE_SIGNAL = "<tool_call>call lookup somehow???"
|
|
|
|
|
|
class TestNudgeRetryOpenai:
|
|
def test_retry_recovers_call(self, monkeypatch):
|
|
async def _run():
|
|
client, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(nudge_tool_calls = True),
|
|
[_upstream_message(GARBAGE_SIGNAL), _upstream_message(LOOKUP_XML)],
|
|
)
|
|
assert len(client.posts) == 2 # exactly one retry
|
|
# Prefix byte-identical, nudge suffix appended (KV-cache reuse guard).
|
|
original, retry = client.posts
|
|
assert retry["messages"][: len(original["messages"])] == original["messages"]
|
|
suffix = retry["messages"][len(original["messages"]) :]
|
|
assert [m["role"] for m in suffix] == ["assistant", "user"]
|
|
assert suffix[0]["content"] == GARBAGE_SIGNAL
|
|
# The healed retry response is returned.
|
|
(call,) = data["choices"][0]["message"]["tool_calls"]
|
|
assert call["function"]["name"] == "lookup"
|
|
assert data["choices"][0]["finish_reason"] == "tool_calls"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_retry_still_garbage_returns_original(self, monkeypatch):
|
|
async def _run():
|
|
client, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(nudge_tool_calls = True),
|
|
[_upstream_message(GARBAGE_SIGNAL), _upstream_message(GARBAGE_SIGNAL + "2")],
|
|
)
|
|
assert len(client.posts) == 2
|
|
assert data["choices"][0]["message"]["content"] == GARBAGE_SIGNAL
|
|
assert "tool_calls" not in data["choices"][0]["message"]
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_default_off_single_post(self, monkeypatch):
|
|
async def _run():
|
|
client, _ = await _drive_non_streaming(
|
|
monkeypatch, _payload(), [_upstream_message(GARBAGE_SIGNAL)]
|
|
)
|
|
assert len(client.posts) == 1
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_no_retry_on_clean_prose(self, monkeypatch):
|
|
async def _run():
|
|
client, _ = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(nudge_tool_calls = True),
|
|
[_upstream_message("all done")],
|
|
)
|
|
assert len(client.posts) == 1
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_no_retry_when_heal_succeeds(self, monkeypatch):
|
|
async def _run():
|
|
client, data = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(nudge_tool_calls = True),
|
|
[_upstream_message(LOOKUP_XML)],
|
|
)
|
|
assert len(client.posts) == 1
|
|
assert data["choices"][0]["message"]["tool_calls"]
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_heal_opt_out_disables_nudge_too(self, monkeypatch):
|
|
async def _run():
|
|
client, _ = await _drive_non_streaming(
|
|
monkeypatch,
|
|
_payload(auto_heal_tool_calls = False, nudge_tool_calls = True),
|
|
[_upstream_message(GARBAGE_SIGNAL)],
|
|
)
|
|
assert len(client.posts) == 1
|
|
|
|
asyncio.run(_run())
|
|
|
|
|
|
class TestNudgeRetryAnthropic:
|
|
async def _drive(
|
|
self,
|
|
monkeypatch,
|
|
bodies,
|
|
nudge = None,
|
|
):
|
|
import routes.inference as inf_mod
|
|
from routes.inference import _anthropic_passthrough_non_streaming
|
|
|
|
client = ScriptedClient(bodies)
|
|
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
|
|
response = await _anthropic_passthrough_non_streaming(
|
|
_llama_backend(),
|
|
[{"role": "user", "content": "hi"}],
|
|
[LOOKUP_TOOL],
|
|
0.7,
|
|
0.95,
|
|
None,
|
|
256,
|
|
"msg_test",
|
|
"gguf",
|
|
nudge_tool_calls = nudge,
|
|
)
|
|
return client, json.loads(response.body)
|
|
|
|
def test_retry_recovers_tool_use(self, monkeypatch):
|
|
async def _run():
|
|
client, data = await self._drive(
|
|
monkeypatch,
|
|
[_upstream_message(GARBAGE_SIGNAL), _upstream_message(LOOKUP_XML)],
|
|
nudge = True,
|
|
)
|
|
assert len(client.posts) == 2
|
|
(block,) = [b for b in data["content"] if b["type"] == "tool_use"]
|
|
assert block["name"] == "lookup"
|
|
assert data["stop_reason"] == "tool_use"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_healed_tool_use_precedes_trailing_text(self, monkeypatch):
|
|
async def _run():
|
|
_, data = await self._drive(monkeypatch, [_upstream_message(f"{LOOKUP_XML} done")])
|
|
assert [block["type"] for block in data["content"]] == ["tool_use", "text"]
|
|
assert data["content"][1]["text"] == "done"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_default_off(self, monkeypatch):
|
|
async def _run():
|
|
client, _ = await self._drive(monkeypatch, [_upstream_message(GARBAGE_SIGNAL)])
|
|
assert len(client.posts) == 1
|
|
|
|
asyncio.run(_run())
|
|
|
|
|
|
class TestAnthropicPassthroughHealingText:
|
|
"""Non-streaming Anthropic passthrough must relay unpromoted (undeclared)
|
|
text-form calls as text, matching the OpenAI passthrough contract. Once
|
|
heal_openai_message promotes the declared call it span-trims only that
|
|
markup and deliberately leaves the undeclared bytes in the content; the
|
|
legacy blanket _TOOL_XML_RE strip must not delete them.
|
|
"""
|
|
|
|
async def _drive(self, monkeypatch, upstream):
|
|
import routes.inference as inf_mod
|
|
from routes.inference import _anthropic_passthrough_non_streaming
|
|
|
|
client = ScriptedClient([upstream])
|
|
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
|
|
response = await _anthropic_passthrough_non_streaming(
|
|
_llama_backend(),
|
|
[{"role": "user", "content": "hi"}],
|
|
[LOOKUP_TOOL],
|
|
0.7,
|
|
0.95,
|
|
None,
|
|
256,
|
|
"msg_test",
|
|
"gguf",
|
|
)
|
|
return json.loads(response.body)
|
|
|
|
def test_mixed_declared_and_undeclared_relays_undeclared_as_text(self, monkeypatch):
|
|
async def _run():
|
|
content = f"Running now. {LOOKUP_XML} then {XML_UNDECLARED} done."
|
|
data = await self._drive(monkeypatch, _upstream_message(content))
|
|
# Declared lookup call is promoted into a structured tool_use block.
|
|
(tool_use,) = [b for b in data["content"] if b["type"] == "tool_use"]
|
|
assert tool_use["name"] == "lookup"
|
|
text = " ".join(b["text"] for b in data["content"] if b["type"] == "text")
|
|
assert XML_UNDECLARED in text
|
|
assert "Running now." in text and "done." in text
|
|
assert LOOKUP_XML not in text
|
|
|
|
asyncio.run(_run())
|
|
|
|
|
|
class TestAnthropicEmitterHealing:
|
|
def _events(
|
|
self,
|
|
emitter,
|
|
chunks,
|
|
finish = True,
|
|
):
|
|
lines = []
|
|
for chunk in chunks:
|
|
lines += emitter.feed_chunk(chunk)
|
|
if finish:
|
|
lines += emitter.finish()
|
|
return [json.loads(ln.split("data: ", 1)[1]) for ln in lines if "data: " in ln]
|
|
|
|
def _emitter(
|
|
self,
|
|
allowed = ("lookup",),
|
|
**kwargs,
|
|
):
|
|
from core.inference.anthropic_compat import AnthropicPassthroughEmitter
|
|
|
|
emitter = AnthropicPassthroughEmitter()
|
|
emitter.enable_healing(set(allowed), **kwargs)
|
|
return emitter
|
|
|
|
def _chunk(
|
|
self,
|
|
content = None,
|
|
tool_calls = None,
|
|
finish_reason = None,
|
|
):
|
|
delta = {}
|
|
if content is not None:
|
|
delta["content"] = content
|
|
if tool_calls is not None:
|
|
delta["tool_calls"] = tool_calls
|
|
return {"choices": [{"delta": delta, "finish_reason": finish_reason}]}
|
|
|
|
def test_xml_becomes_tool_use_block_and_stop_reason(self):
|
|
events = self._events(
|
|
self._emitter(),
|
|
[
|
|
self._chunk(content = LOOKUP_XML),
|
|
self._chunk(finish_reason = "stop"),
|
|
],
|
|
)
|
|
starts = [e for e in events if e.get("type") == "content_block_start"]
|
|
(tool_start,) = [e for e in starts if e["content_block"]["type"] == "tool_use"]
|
|
assert tool_start["content_block"]["name"] == "lookup"
|
|
assert tool_start["content_block"]["id"].startswith("toolu_")
|
|
(args,) = [
|
|
e["delta"]["partial_json"]
|
|
for e in events
|
|
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "input_json_delta"
|
|
]
|
|
assert json.loads(args) == {"q": "x"}
|
|
(message_delta,) = [e for e in events if e.get("type") == "message_delta"]
|
|
assert message_delta["delta"]["stop_reason"] == "tool_use"
|
|
|
|
def test_mid_block_signal_closes_text_block_first(self):
|
|
events = self._events(
|
|
self._emitter(),
|
|
[
|
|
self._chunk(content = f"Let me check {LOOKUP_XML}"),
|
|
self._chunk(finish_reason = "stop"),
|
|
],
|
|
)
|
|
kinds = [
|
|
(e["type"], (e.get("content_block") or e.get("delta") or {}).get("type"))
|
|
for e in events
|
|
if e["type"].startswith("content_block")
|
|
]
|
|
# text opens, streams the safe prefix, closes; then the tool_use block.
|
|
assert kinds[0] == ("content_block_start", "text")
|
|
assert kinds[1] == ("content_block_delta", "text_delta")
|
|
assert kinds[2] == ("content_block_stop", None)
|
|
assert kinds[3] == ("content_block_start", "tool_use")
|
|
texts = [
|
|
e["delta"]["text"]
|
|
for e in events
|
|
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
|
|
]
|
|
assert "".join(texts) == "Let me check "
|
|
|
|
def test_false_alarm_streams_as_text(self):
|
|
events = self._events(
|
|
self._emitter(),
|
|
[self._chunk(content = "use the <div> tag"), self._chunk(finish_reason = "stop")],
|
|
)
|
|
texts = [
|
|
e["delta"]["text"]
|
|
for e in events
|
|
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
|
|
]
|
|
assert "".join(texts) == "use the <div> tag"
|
|
(message_delta,) = [e for e in events if e.get("type") == "message_delta"]
|
|
assert message_delta["delta"]["stop_reason"] == "end_turn"
|
|
|
|
def test_signal_split_across_chunks(self):
|
|
events = self._events(
|
|
self._emitter(),
|
|
[
|
|
self._chunk(content = "<tool"),
|
|
self._chunk(content = '_call>{"name":"lookup","arguments":{}}'),
|
|
self._chunk(finish_reason = "stop"),
|
|
],
|
|
)
|
|
starts = [e for e in events if e.get("type") == "content_block_start"]
|
|
assert [e["content_block"]["type"] for e in starts] == ["tool_use"]
|
|
texts = [
|
|
e
|
|
for e in events
|
|
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
|
|
]
|
|
assert texts == []
|
|
|
|
def test_max_tokens_wins_over_healed_stop_reason(self):
|
|
events = self._events(
|
|
self._emitter(),
|
|
[self._chunk(content = LOOKUP_XML), self._chunk(finish_reason = "length")],
|
|
)
|
|
(message_delta,) = [e for e in events if e.get("type") == "message_delta"]
|
|
assert message_delta["delta"]["stop_reason"] == "max_tokens"
|
|
|
|
def test_structured_deltas_disable_healing_and_flush(self):
|
|
structured = [
|
|
{
|
|
"index": 0,
|
|
"id": "call_up",
|
|
"function": {"name": "lookup", "arguments": "{}"},
|
|
}
|
|
]
|
|
events = self._events(
|
|
self._emitter(),
|
|
[
|
|
self._chunk(content = "held <tool"),
|
|
self._chunk(tool_calls = structured),
|
|
self._chunk(finish_reason = "tool_calls"),
|
|
],
|
|
)
|
|
texts = [
|
|
e["delta"]["text"]
|
|
for e in events
|
|
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
|
|
]
|
|
assert "".join(texts) == "held <tool" # nothing swallowed
|
|
starts = [e for e in events if e.get("type") == "content_block_start"]
|
|
assert [e["content_block"]["type"] for e in starts] == ["text", "tool_use"]
|
|
|
|
def test_disable_parallel_caps_healed_calls(self):
|
|
two = LOOKUP_XML + '<tool_call>{"name":"lookup","arguments":{"q":"y"}}</tool_call>'
|
|
events = self._events(
|
|
self._emitter(disable_parallel_tool_use = True),
|
|
[self._chunk(content = two), self._chunk(finish_reason = "stop")],
|
|
)
|
|
starts = [
|
|
e
|
|
for e in events
|
|
if e.get("type") == "content_block_start" and e["content_block"]["type"] == "tool_use"
|
|
]
|
|
assert len(starts) == 1
|
|
|
|
def test_disable_parallel_drops_native_after_healed(self):
|
|
# A healed call consumed the single allowed slot; a later native
|
|
# structured call (index 0, so it survives the caller's chunk-level
|
|
# cap) must not open a second tool_use block.
|
|
structured = [
|
|
{
|
|
"index": 0,
|
|
"id": "call_up",
|
|
"function": {"name": "lookup", "arguments": "{}"},
|
|
}
|
|
]
|
|
events = self._events(
|
|
self._emitter(disable_parallel_tool_use = True),
|
|
[
|
|
self._chunk(content = LOOKUP_XML),
|
|
self._chunk(tool_calls = structured),
|
|
self._chunk(finish_reason = "tool_calls"),
|
|
],
|
|
)
|
|
starts = [
|
|
e
|
|
for e in events
|
|
if e.get("type") == "content_block_start" and e["content_block"]["type"] == "tool_use"
|
|
]
|
|
assert len(starts) == 1
|
|
|
|
def test_no_healing_means_verbatim_text(self):
|
|
from core.inference.anthropic_compat import AnthropicPassthroughEmitter
|
|
|
|
emitter = AnthropicPassthroughEmitter() # enable_healing never called
|
|
events = self._events(
|
|
emitter,
|
|
[self._chunk(content = LOOKUP_XML), self._chunk(finish_reason = "stop")],
|
|
)
|
|
texts = [
|
|
e["delta"]["text"]
|
|
for e in events
|
|
if e.get("type") == "content_block_delta" and e["delta"]["type"] == "text_delta"
|
|
]
|
|
assert "".join(texts) == LOOKUP_XML
|
|
|
|
|
|
class TestAnthropicNonStreamingRoute:
|
|
async def _drive(
|
|
self,
|
|
monkeypatch,
|
|
bodies,
|
|
auto_heal = None,
|
|
tools = None,
|
|
tool_choice = "auto",
|
|
):
|
|
import routes.inference as inf_mod
|
|
from routes.inference import _anthropic_passthrough_non_streaming
|
|
|
|
client = ScriptedClient(bodies)
|
|
monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
|
|
response = await _anthropic_passthrough_non_streaming(
|
|
_llama_backend(),
|
|
[{"role": "user", "content": "hi"}],
|
|
tools if tools is not None else [LOOKUP_TOOL],
|
|
0.7,
|
|
0.95,
|
|
None,
|
|
256,
|
|
"msg_test",
|
|
"gguf",
|
|
tool_choice = tool_choice,
|
|
auto_heal_tool_calls = auto_heal,
|
|
)
|
|
return client, json.loads(response.body)
|
|
|
|
def test_promotes_xml_to_tool_use(self, monkeypatch):
|
|
async def _run():
|
|
_, data = await self._drive(monkeypatch, [_upstream_message(LOOKUP_XML)])
|
|
(block,) = [b for b in data["content"] if b["type"] == "tool_use"]
|
|
assert block["name"] == "lookup"
|
|
assert block["input"] == {"q": "x"}
|
|
assert data["stop_reason"] == "tool_use"
|
|
assert not any(b["type"] == "text" for b in data["content"])
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_opt_out_keeps_legacy_strip(self, monkeypatch):
|
|
async def _run():
|
|
_, data = await self._drive(
|
|
monkeypatch, [_upstream_message(f"plan {LOOKUP_XML}")], auto_heal = False
|
|
)
|
|
assert data["stop_reason"] == "end_turn"
|
|
(block,) = data["content"]
|
|
assert block["type"] == "text"
|
|
assert block["text"] == "plan" # XML stripped, nothing promoted
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_undeclared_tool_not_promoted(self, monkeypatch):
|
|
async def _run():
|
|
xml = '<tool_call>{"name":"rogue","arguments":{}}</tool_call>'
|
|
_, data = await self._drive(monkeypatch, [_upstream_message(xml)])
|
|
assert data["stop_reason"] == "end_turn"
|
|
assert not any(b["type"] == "tool_use" for b in data["content"])
|
|
# Healing preserves what it does not promote: the undeclared call
|
|
# reaches the client as text instead of being silently stripped.
|
|
(text_block,) = [b for b in data["content"] if b["type"] == "text"]
|
|
assert text_block["text"] == xml
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_mixed_undeclared_text_preserved_after_heal(self, monkeypatch):
|
|
async def _run():
|
|
# Declared call promoted to tool_use; the undeclared call's markup
|
|
# stays in the text block (the legacy strip must not run after a
|
|
# span-exact heal), matching the OpenAI passthrough.
|
|
rogue = '<tool_call>{"name":"rogue","arguments":{}}</tool_call>'
|
|
_, data = await self._drive(monkeypatch, [_upstream_message(f"{LOOKUP_XML} {rogue}")])
|
|
(tool_block,) = [b for b in data["content"] if b["type"] == "tool_use"]
|
|
assert tool_block["name"] == "lookup"
|
|
(text_block,) = [b for b in data["content"] if b["type"] == "text"]
|
|
assert rogue in text_block["text"]
|
|
assert data["stop_reason"] == "tool_use"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_length_beats_tool_use(self, monkeypatch):
|
|
async def _run():
|
|
_, data = await self._drive(
|
|
monkeypatch, [_upstream_message(LOOKUP_XML, finish_reason = "length")]
|
|
)
|
|
assert data["stop_reason"] == "max_tokens"
|
|
assert any(b["type"] == "tool_use" for b in data["content"])
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_tool_choice_none_keeps_legacy_strip(self, monkeypatch):
|
|
async def _run():
|
|
# Anthropic {"type": "none"} arrives here converted to "none":
|
|
# the request forbade tool calls, so nothing is promoted and the
|
|
# legacy XML strip applies as before healing existed.
|
|
_, data = await self._drive(
|
|
monkeypatch,
|
|
[_upstream_message(f"plan {LOOKUP_XML}")],
|
|
tool_choice = "none",
|
|
)
|
|
assert data["stop_reason"] == "end_turn"
|
|
(block,) = data["content"]
|
|
assert block["type"] == "text"
|
|
assert block["text"] == "plan"
|
|
|
|
asyncio.run(_run())
|
|
|
|
|
|
class TestOpenaiStreamingRoute:
|
|
def test_heals_streamed_xml(self, monkeypatch):
|
|
async def _run():
|
|
pieces = ["<tool_call>", '{"name":"lookup",', '"arguments":{"q":"x"}}', "</tool_call>"]
|
|
lines = [
|
|
'data: {"id":"c1","model":"gguf","created":1,"choices":[{"index":0,"delta":{"content":%s}}]}'
|
|
% json.dumps(p)
|
|
for p in pieces
|
|
]
|
|
lines += [
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
|
|
"data: [DONE]",
|
|
]
|
|
chunks = await _drive_stream(monkeypatch, _payload(), lines)
|
|
payloads = _stream_payloads(chunks)
|
|
tool_deltas = [
|
|
tc
|
|
for p in payloads
|
|
for c in p.get("choices", [])
|
|
for tc in (c.get("delta") or {}).get("tool_calls") or []
|
|
]
|
|
(call,) = tool_deltas
|
|
assert call["function"]["name"] == "lookup"
|
|
assert json.loads(call["function"]["arguments"]) == {"q": "x"}
|
|
finishes = [
|
|
c["finish_reason"]
|
|
for p in payloads
|
|
for c in p.get("choices", [])
|
|
if c.get("finish_reason")
|
|
]
|
|
assert finishes == ["tool_calls"]
|
|
# None of the XML leaked as visible content.
|
|
text = "".join(
|
|
(c.get("delta") or {}).get("content") or ""
|
|
for p in payloads
|
|
for c in p.get("choices", [])
|
|
)
|
|
assert "<tool_call>" not in text
|
|
assert chunks[-1] == "data: [DONE]\n\n"
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_parallel_cap_drops_native_after_healed(self, monkeypatch):
|
|
async def _run():
|
|
# parallel_tool_calls=false: a healed call consumed the single
|
|
# allowed slot, and the upstream SSE cap keeps native index 0, so
|
|
# the route must drop the later native call itself.
|
|
xml = '<tool_call>{"name":"lookup","arguments":{"q":"x"}}</tool_call>'
|
|
native = (
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{"tool_calls":'
|
|
'[{"index":0,"id":"call_up","type":"function","function":'
|
|
'{"name":"lookup","arguments":"{}"}}]}}]}'
|
|
)
|
|
lines = [
|
|
'data: {"id":"c1","model":"gguf","created":1,"choices":'
|
|
'[{"index":0,"delta":{"content":%s}}]}' % json.dumps(xml),
|
|
native,
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}',
|
|
"data: [DONE]",
|
|
]
|
|
chunks = await _drive_stream(monkeypatch, _payload(parallel_tool_calls = False), lines)
|
|
payloads = _stream_payloads(chunks)
|
|
tool_deltas = [
|
|
tc
|
|
for p in payloads
|
|
for c in p.get("choices", [])
|
|
for tc in (c.get("delta") or {}).get("tool_calls") or []
|
|
]
|
|
(call,) = tool_deltas
|
|
assert call["id"] == "call_0" # the healed call; native was dropped
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_false_alarm_text_flushes(self, monkeypatch):
|
|
async def _run():
|
|
lines = [
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{"content":"use the <div> tag"}}]}',
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
|
|
"data: [DONE]",
|
|
]
|
|
chunks = await _drive_stream(monkeypatch, _payload(), lines)
|
|
payloads = _stream_payloads(chunks)
|
|
text = "".join(
|
|
(c.get("delta") or {}).get("content") or ""
|
|
for p in payloads
|
|
for c in p.get("choices", [])
|
|
)
|
|
assert text == "use the <div> tag"
|
|
finishes = [
|
|
c["finish_reason"]
|
|
for p in payloads
|
|
for c in p.get("choices", [])
|
|
if c.get("finish_reason")
|
|
]
|
|
assert finishes == ["stop"]
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_incomplete_xml_healed_at_done(self, monkeypatch):
|
|
async def _run():
|
|
# No close tag and no finish chunk: healed at the [DONE] boundary,
|
|
# synthetic finish must say tool_calls.
|
|
lines = [
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{"content":"<tool_call>{\\"name\\":\\"lookup\\",\\"arguments\\":{}}"}}]}',
|
|
"data: [DONE]",
|
|
]
|
|
chunks = await _drive_stream(monkeypatch, _payload(), lines)
|
|
payloads = _stream_payloads(chunks)
|
|
tool_deltas = [
|
|
tc
|
|
for p in payloads
|
|
for c in p.get("choices", [])
|
|
for tc in (c.get("delta") or {}).get("tool_calls") or []
|
|
]
|
|
assert len(tool_deltas) == 1
|
|
finishes = [
|
|
c["finish_reason"]
|
|
for p in payloads
|
|
for c in p.get("choices", [])
|
|
if c.get("finish_reason")
|
|
]
|
|
assert finishes == ["tool_calls"]
|
|
|
|
asyncio.run(_run())
|
|
|
|
def test_structured_upstream_calls_relay_verbatim(self, monkeypatch):
|
|
async def _run():
|
|
line = (
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{"tool_calls":'
|
|
'[{"index":0,"id":"call_up","type":"function","function":'
|
|
'{"name":"lookup","arguments":"{}"}}]}}]}'
|
|
)
|
|
lines = [
|
|
line,
|
|
'data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}',
|
|
"data: [DONE]",
|
|
]
|
|
chunks = await _drive_stream(monkeypatch, _payload(), lines)
|
|
assert chunks[0] == line + "\n\n" # byte-for-byte relay
|
|
|
|
asyncio.run(_run())
|
|
|
|
|
|
class TestHealerSignalAlignment:
|
|
"""The passthrough healer buffers only formats its parser can promote.
|
|
The loops' bare [ARGS] rehearsal signal is gated on active tool names
|
|
there; ungated in the healer it would stall legitimate prose until
|
|
finalization without ever producing a promotable call."""
|
|
|
|
def test_heal_signals_are_promotable_formats_only(self):
|
|
from core.inference.passthrough_healing import _HEAL_SIGNALS
|
|
assert set(_HEAL_SIGNALS) == {
|
|
"<tool_call>",
|
|
"<|tool_call>",
|
|
"<function=",
|
|
"[TOOL_CALLS]",
|
|
"<|content_invoke_tool_json|>",
|
|
}
|
|
|
|
def test_prose_with_bare_args_marker_streams_through(self):
|
|
healer = StreamToolCallHealer({"Bash"})
|
|
chunks = [
|
|
"Use the pattern foo",
|
|
"[ARGS] in templates when calling tools, ",
|
|
"and remember to close it.",
|
|
]
|
|
streamed = ""
|
|
for chunk in chunks:
|
|
streamed += _events_text(healer.feed(chunk))
|
|
# Incremental relay: nothing withheld for finalize.
|
|
assert streamed == "".join(chunks)
|
|
final = healer.finalize()
|
|
assert not _events_calls(final)
|
|
assert not healer.healed
|
|
|
|
def test_bracket_tool_calls_still_promote_in_stream(self):
|
|
healer = StreamToolCallHealer({"web_search"})
|
|
events = healer.feed('[TOOL_CALLS]web_search{"query": "unsloth docs"}') + healer.finalize()
|
|
(call,) = _events_calls(events)
|
|
assert call["function"]["name"] == "web_search"
|
|
assert healer.healed
|