Skip to content

Studio: report the real error instead of "Unknown tool" - #9640

Merged
danielhanchen merged 4 commits into
unslothai:mainfrom
NilayYadav:fix-tool-finally-swallow
Aug 25, 2026
Merged

danielhanchen merged 4 commits into
unslothai:mainfrom
NilayYadav:fix-tool-finally-swallow

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

Give the python tool a bad argument and the model gets told "Unknown tool: python". The tool exists. The error was thrown and then thrown away.

_session_in_flight has a return inside a finally, which drops whatever exception was on its way out. The normal path always hits it, so this happens on every python, terminal, and edit_file call.

Calling the python tool with {"code": 42}:

before: Unknown tool: python
after: AttributeError: 'int' object has no attribute 'strip'

studio_tool_loop already catches this and passes it back to the model, and it re-raises CancelledError first, so cancelling still works the same. Changing the check to if pending: keeps the cleanup as it was and just removes the return.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Review + GitHub Actions A/B evidence

Pinned review: cffaffd0046bae32f1aee08200fa2b6a493437db — no blocking code findings.

Reproduced on ubuntu-latest / Python 3.13 in a single job so both legs share one runner, one dependency set, and one copy of the test file (blob 5d777919). The only variable is studio/backend/core/inference/tools.py, swapped between the base blob 0edefc3f and the PR blob a03408eb:

Full A/B run — every leg asserted strictly, all 12 steps green.

leg tools.py new tests execute_tool("python", {"code": 42}) chat tool-card text
BEFORE 0edefc3f (pre-fix) 2 failed — DID NOT RAISE returns 'Unknown tool: python' 'Unknown tool: python'
AFTER a03408eb (PR fix) 2 passed raises AttributeError: 'int' object has no attribute 'strip' "Error: tool raised an exception: 'int' object has no attribute 'strip'"

terminal behaves identically ('Unknown tool: terminal' → the same real error).

The card column is the user-visible payload: it is produced by running the real stream_tool_execution wrapper — so the exception genuinely survives the worker-thread hop — and then applying the exact handler studio_tool_loop wraps it in. That is what renders in the chat tool card.

What I checked beyond the diff

  • Blast radius. _session_in_flight guards exactly three dispatch arms: python, terminal, edit_file. Every loop that can reach them already handles a raising tool — studio_tool_loop (except asyncio.CancelledError: raise then except Exception → reported to the model), safetensors_agentic (same shape), and llama_cpp (enclosing handler that resolves provisional tool cards before re-raising). research_runs has no enclosing handler but only ever calls web_search / search_knowledge_base, neither of which is guarded, so it is unaffected. Cancellation is unchanged: CancelledError is re-raised ahead of the generic handler.
  • Completeness. An AST sweep of the backend (excluding vendor/tests) finds no remaining return inside a finally, so this was the last instance of the swallow. The five surviving break/continue occurrences are all loop-local inside a while that is itself in the finally, which does not discard an in-flight exception. CPython 3.14 also flags the old line directly: SyntaxWarning: 'return' in a 'finally' block.
  • Regression scope. test_studio_tool_loop, test_llama_cpp_tool_loop, test_safetensors_tool_loop, test_tool_stream_generator_drain, test_sandbox_tools, test_secure_tools_execute, test_tool_loop_controller — 763 passed; the single failure is a missing optional ddgs import, unrelated to this change. Nine failures in test_sandbox_files_and_storage_roots.py are byte-identical on the base commit and are pre-existing.
  • The pre-existing note at tools.py:9387 already described this exact symptom (a write error "swallowed upstream into Unknown tool: edit_file"), so this removes the root cause behind that workaround.

Conclusion: the swallow and its fix are both verified with real values on Actions, and I found no blocker. No screenshots: this is a backend change with no frontend delta, so the visible effect is the tool-card string reported above rather than a layout difference.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: cffaffd004

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@mahiatlinux

mahiatlinux commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Review report

Tested refs: base 785a68dc4d193cc0a7f4706dcfe7b14a5e433e2f, original PR head cffaffd0046bae32f1aee08200fa2b6a493437db, and repaired/current head d6b8f4e772909ea486f7fc76494f3b1b2a8def06.

Before: On the base, _session_in_flight returned from finally when cleanup emptied the active-session map. That suppressed exceptions raised inside the context manager. The isolated 11-case A/B harness failed 8 cases: ValueError, cancellation, Python/terminal/edit-file failures, malformed Python/terminal arguments, and the streamed worker error. A malformed Python call was consequently reported as Unknown tool: python.

After: The original PR head passed all 11 backend cases and propagated the real tool exception through direct dispatch and the streamed tool loop. That exposed a second defect: tool-ui-python.tsx called split() on a non-string code value, so Chat became blank even though the provider received the correct exception. The repaired head guards the argument type. The Python card now shows Error: tool raised an exception: 'int' object has no attribute 'strip', and the final model reply remains visible.

Verdict: Real. The same harness failed on the exact base for the claimed reason and passed on the original head. The UI defect also reproduced on the original head and passed on the repaired head with identical loopback-provider input.

Regression risk:

  • The 11-case harness also covers successful and nested guards, queued deletion cleanup, unknown-tool behavior, all three guarded dispatchers, cancellation, and the worker-thread path.
  • Both PR regression tests passed.
  • The frontend regression preserves string code and safely handles numeric or absent code.
  • node --experimental-strip-types --test tests/python-tool-args.test.ts and npm run build passed on the repaired head and on GitHub's synthetic merge plus the repair.
  • Current-head CI completed without failures, including backend Python 3.11/3.13, frontend build, Windows frontend/UI/API/GGUF jobs, macOS Studio/UI jobs, Linux startup/Tauri, and repository CPU tests. The GPU jobs were skipped.

Compatibility: Local A/B and UI tests ran on macOS 27.0 arm64 with CPython 3.12.13, Node 24.16.0, and Playwright 1.57.0. The repaired UI scene passed in Playwright Chromium and WebKit. This change does not alter hardware selection, model execution, persisted data, or dependency formats.

UI evidence: In both composites, the original head receives the exception but leaves Chat blank. The repaired head renders the Python error card and Tool result received. with no browser page errors in Chromium. The same visible result appears in WebKit.

Chromium before and after

WebKit before and after

Fixes: The PR's backend fix is b25fe89440; formatting produced original head cffaffd004. The UI repair is d6b8f4e77 in python-tool-args.ts, tool-ui-python.tsx, and python-tool-args.test.ts. Current PR head is the repaired commit.

Gaps: The exact malformed-tool UI scene was not run natively on Linux or Windows. Branded Firefox was blocked by its nested macOS sandbox; branded Chrome and Edge were unavailable; native Safari was not run, and WebKit is not Safari proof. The UI test used a deterministic loopback provider rather than an external model provider. No performance, stress, or soak run was needed for this exception-path change.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: d6b8f4e772

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this on main, where studio/backend/core/inference/tools.py:7353 still returns from inside the finally in _session_in_flight and drops the real exception, so a failing python or terminal call comes back as "Unknown tool". The backend half is the valuable part here; the tool-ui-python.tsx guard overlaps #9641, so we should reconcile the two before either lands.

@Imagineer99 Imagineer99 self-assigned this Aug 25, 2026
_session_in_flight returned from inside its finally, which discards a
propagating exception. Because it is a @contextmanager, contextlib reads the
resulting StopIteration as "handled", so execute_tool fell past the remaining
arms and answered "Unknown tool: python" for every failing python, terminal or
edit_file call. The comment at tools.py:9386 already described this from the
field. Python 3.14 flags the line directly (PEP 765).

Using `if pending:` keeps the cleanup exactly as it was and just removes the
return. The refcount decrement, the _removing_sessions release and the
notify_all all already ran on the exception path, so no lifecycle state
changes; only the exception survives now. Also drops a dead local.

Once exceptions propagate the three tool loops disagreed. studio_tool_loop and
safetensors_agentic already turn a raising tool into
"Error: tool raised an exception: ...", hand it to the model and let it
recover. llama_cpp had no handler around stream_tool_execution, so the
enclosing per-iteration handler re-raised and a bad argument killed the whole
GGUF answer. It gets the same arm as the other two, re-raising
_LlamaStreamCancelled first because that subclasses Exception and is not a
tool error.

Tests cover the guard's state machine on the exception path (queued deletes,
nesting, case-folded ids, a failing cleanup, waiter wakeup, 100 randomised
concurrent schedules) and each loop's exception contract, including that
research_runs still names only unguarded tools.
@danielhanchen
danielhanchen force-pushed the fix-tool-finally-swallow branch from d6b8f4e to 3aae7e7 Compare August 25, 2026 11:29
@danielhanchen

Copy link
Copy Markdown
Member

Verification, and two changes pushed to the branch

Reproduced this end to end and pushed the result: the branch is rebased on main, the conflict is gone (mergeable: true), and the diff is backend only.

The bug is real and was still live on main. A/B on the real code, importing core.inference.tools from each worktree, no reimplementation of anything under test:

probe base 785a68dc4 head
_session_in_flight body raises ValueError returned None (swallowed) raises the same object
body raises CancelledError returned None (swallowed) propagates
exception identity across the guard SWALLOWED same object out
execute_tool("python", {"code": 42}) 'Unknown tool: python' AttributeError: 'int' object has no attribute 'strip'
execute_tool("terminal", {"command": 42}) 'Unknown tool: terminal' the real AttributeError
edit_file with the implementation raising 'Unknown tool: edit_file' the sentinel
genuinely unknown tool 'Unknown tool: no_such_tool_at_all' unchanged
through stream_tool_execution (worker-thread hop) 'Unknown tool: python' the real AttributeError, worker on another thread

Worth adding to the description: the swallow was intermittent, not universal. return was only reached when pending was empty, so a call that happened to have a queued sandbox delete behind it already propagated. And it ate CancelledError too, so cancelling a running python call was also degrading to the unknown-tool string.

Python 3.14 confirms the diagnosis at the exact line. -W error::SyntaxWarning:

base   PyCompileError: tools.py:7354: SyntaxWarning: 'return' in a 'finally' block
head   compiles clean

An independent AST sweep of the whole backend agrees with your completeness claim: one occurrence, this one.


What I changed

1. llama_cpp.py: a raising local tool was killing the whole GGUF answer.

This is the one thing that would have broken on merge. Once exceptions propagate the three loops disagree:

loop file on a raising local tool
external providers studio_tool_loop.py:1332 Error: tool raised an exception: ..., model recovers
safetensors safetensors_agentic.py:1429 same
llama.cpp / GGUF llama_cpp.py:25798 no handler; the per-iteration except Exception at :25910 re-raises

The innermost try around stream_tool_execution there is the big per-iteration one at 24570-25924, which re-raises, and the route turns that into a generic internal error. Same test file, three states:

test base your head head + this fix
GGUF, python {"code": 42} FAIL, Unknown tool: python reaches the model FAIL, AttributeError escapes generate_chat_completion_with_tools PASS
GGUF, terminal {"command": 42} FAIL FAIL PASS
GGUF, genuinely unknown tool PASS PASS PASS
error reaches the model's next turn FAIL FAIL PASS
external-provider loop, real error FAIL, Unknown tool PASS PASS

So the middle column is the regression: the PR alone traded a wrong message for a dead chat on the flagship local path. It now gets the same arm the other two have, re-raising _LlamaStreamCancelled first because that subclasses Exception and a bare except Exception would eat the cancel signal. No CancelledError arm: it is a BaseException, so it passes through, same as in safetensors_agentic.

2. Dropped the frontend half. #9641 merged and already covers tool-ui-python.tsx with the general toolArgText, which is what made this CONFLICTING. getPythonCode is also the weaker of the two: toolArgText(42) renders 42, getPythonCode({code: 42}) returns "" and paints a blank card. And resolving the conflict the other way fails CI on ubuntu and windows-latest. I ran it:

AssertionError: tool-ui-python.tsx reads code without coercing it;
                a model that sends a number there takes all of Studio down
  actual:   'getPythonCode(args)'
  expected: /^toolArgText\(/

Nothing else is lost by dropping it, so the backend fix stands alone now.

3. Kept your two tests and added two focused files covering what the originals did not: the guard's state machine on the exception path, and each loop's contract.


Does it break anything

Full backend suite, integration tree against pristine main, same interpreter, same pinned venv: the failure sets are byte-identical. 194 items on both, all ModuleNotFoundError for torch / transformers / safetensors, which this CPU-light venv deliberately omits. Zero regressions, and 29191 passed against 29074 on main, the difference being the new tests.

Nothing anywhere matches the "Unknown tool" literal, in production, tests or frontend, so no string contract breaks. The genuinely-unknown-tool path is asserted unchanged on both sides.

State machine, each case asserting the key is absent from _active_sessions, _pending_removals and _removing_sessions afterwards:

  • a queued delete still runs exactly once when the body raises;
  • a chat recreated mid call still keeps its folder;
  • a nested guard deletes only at the outer exit, and only once when the inner body raises;
  • Foo and foo share one lifecycle key, which is what Windows and a default macOS volume need;
  • a cleanup that itself fails still clears _removing_sessions and wakes a waiter blocked on the same chat, verified with a second thread that must not enter while the removal runs and must enter once it fails;
  • 100 randomised concurrent schedules mixing successes, failures, cancellations, queued deletes and case variants, barriers and bounded joins throughout, faulthandler armed so a hang gives stacks. Clean on every seed.

Every one of those on Python 3.10, 3.11, 3.12, 3.13 and 3.14, all five identical: base fails exactly the three propagation cases, head and head-plus-fix pass all 110.

One behaviour change worth naming. "Unknown tool: python" matches none of TOOL_ERROR_PREFIXES, so ToolLoopController filed the failed call as a success and refused an identical retry. Error: tool raised an exception: ... is a failure, so the retry is now allowed. That is the right outcome, the model can finally see what went wrong, but it needs to stay bounded. It does: with a budget of 4 the loop executes 4 times and then emits the budget notice, with scripted turns left unconsumed.

Old installs. Seeded a studio.db with the pre-PR build through the real storage.studio_db API, containing a numeric code, an array command, a null code, a {"toString": null} code, a persisted "Unknown tool: python" result, and a valid call as control. Opened the same database with the new build: 4 of 4 messages read back with identical content hashes, same file size, no migration. The change touches no schema, no persisted data and no dependency format.

Browsers, since #9641 ships alongside this. Real engines running the repository's own tool-arg-text.ts over 25 shapes including {"toString": null}, a null-prototype object, Symbol, BigInt, a lone surrogate, a 500k string, an over-cap object and 100k-deep nesting:

engine version page errors
Chromium 151.0.7922.34 0
Firefox 153.0 0
WebKit 26.5 0
Edge (branded) 151.0.4129.59 0
Chrome (branded) 147.0.7727.101 0

Identical on all five except 100k-deep nesting, where Chromium serialises and Firefox and WebKit hit their recursion limit and return "" through the helper's bare catch. That is the guard working as documented at tool-arg-text.ts:43, not a defect. npm run typecheck clean and 4934 frontend unit tests pass.


Two things I found and deliberately did not change

  • A cleanup failure inside the finally replaces the tool's exception and keeps it as __context__. Standard Python, predates this PR (it already happened whenever a delete was queued), so it is pinned by a test rather than altered.
  • _pending_removals.pop takes the whole batch before iterating, so if one entry raises the rest are neither attempted nor still queued. Also pre-existing and unrelated to the swallow, pinned the same way. Worth its own PR.

Gaps

Everything above ran on Linux x86_64. Native Windows and macOS come from this PR's own CI rather than from me, so read those jobs, not this comment, for them. Playwright WebKit on Linux is not branded Safari and I did not run Safari. No GPU axis applies: the change is control flow in a contextmanager and touches no hardware selection or model execution.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: d946c74a51

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from NilayYadav Aug 25, 2026
@unslothai unslothai deleted a comment from mahiatlinux Aug 25, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: d453a1986e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit bbcba92 into unslothai:main Aug 25, 2026
42 of 43 checks passed
danielhanchen pushed a commit that referenced this pull request Aug 25, 2026
* Studio: stop the session guard from swallowing tool exceptions

_session_in_flight returned from inside its finally, which discards a
propagating exception. Because it is a @contextmanager, contextlib reads the
resulting StopIteration as "handled", so execute_tool fell past the remaining
arms and answered "Unknown tool: python" for every failing python, terminal or
edit_file call. The comment at tools.py:9386 already described this from the
field. Python 3.14 flags the line directly (PEP 765).

Using `if pending:` keeps the cleanup exactly as it was and just removes the
return. The refcount decrement, the _removing_sessions release and the
notify_all all already ran on the exception path, so no lifecycle state
changes; only the exception survives now. Also drops a dead local.

Once exceptions propagate the three tool loops disagreed. studio_tool_loop and
safetensors_agentic already turn a raising tool into
"Error: tool raised an exception: ...", hand it to the model and let it
recover. llama_cpp had no handler around stream_tool_execution, so the
enclosing per-iteration handler re-raised and a bad argument killed the whole
GGUF answer. It gets the same arm as the other two, re-raising
_LlamaStreamCancelled first because that subclasses Exception and is not a
tool error.

Tests cover the guard's state machine on the exception path (queued deletes,
nesting, case-folded ids, a failing cleanup, waiter wakeup, 100 randomised
concurrent schedules) and each loop's exception contract, including that
research_runs still names only unguarded tools.

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

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

* Tighten the comments added by this change

* Drop comments that restate the assertion beside them

---------

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

Imagineer99 commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Independently confirmed this is a genuine bug. Before the fix, exceptions from Python, terminal, and edit_file were swallowed and incorrectly reported as Unknown tool. After the fix, the real error reaches the existing tool-loop handler.

A/B tests passed on Ubuntu, Windows, and macOS. Live Studio UI repros also passed on Chromium, Firefox, and WebKit. Successful tools, genuinely unknown tools, cancellation, cleanup, and concurrency behavior remained unchanged.

OS A/B run · Studio UI A/B run

Genuine fix; no regression found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants