Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Nilaybbcba92a6d51
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 0f61aa53bcd..146f9593083 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -25795,12 +25795,30 @@ class LlamaCppBackend:
**kwargs,
)
- result = yield from stream_tool_execution(
- _invoke_tool,
- tool_name = decision.tool_name,
- tool_call_id = decision.tool_call_id,
- cancel_event = cancel_event,
- )
+ # Without this the handler below re-raises and a bad
+ # argument kills the whole answer. A raising tool is the
+ # tool's failure; the other two loops hand it back.
+ try:
+ result = yield from stream_tool_execution(
+ _invoke_tool,
+ tool_name = decision.tool_name,
+ tool_call_id = decision.tool_call_id,
+ cancel_event = cancel_event,
+ )
+ except _LlamaStreamCancelled:
+ # Subclasses Exception, so the arm below would eat
+ # the cancel signal. CancelledError needs no arm:
+ # a BaseException passes straight through.
+ raise
+ except Exception as _tool_exc:
+ if cancel_event is not None and cancel_event.is_set():
+ raise
+ logger.exception(
+ "Tool %s raised: %s",
+ decision.tool_name,
+ _tool_exc,
+ )
+ result = f"Error: tool raised an exception: {_tool_exc}"
if decision.tool_name in RAG_SEARCH_TOOLS:
_kb_search_count += 1
completion = tool_controller.record_result(decision, result)
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 0edefc3fbea..d256278e0af 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -7336,7 +7336,6 @@ def _session_in_flight(session_id: "str | None"):
# rename away. Only this session waits; every other chat is untouched.
while key in _removing_sessions:
_sessions_free.wait()
- first = _active_sessions.get(key, 0) == 0
_active_sessions[key] = _active_sessions.get(key, 0) + 1
try:
yield
@@ -7350,22 +7349,23 @@ def _session_in_flight(session_id: "str | None"):
_removing_sessions.add(key)
else:
_active_sessions[key] -= 1
- if not pending:
- return
- # Outside the lock: deciding whether the tree holds files can take
- # seconds, and no other chat could start a call meanwhile. This session
- # stays closed, so nothing starts in the directory being removed.
- try:
- for pending_id, pending_files in pending.items():
- if _thread_exists(pending_id, unknown = True):
- # Recreated while that call ran: this delete belongs to the
- # chat that went, and the folder is the new one's now.
- continue
- _remove_session_sandbox_locked(pending_id, pending_files)
- finally:
- with _sessions_free:
- _removing_sessions.discard(key)
- _sessions_free.notify_all()
+ # Not `if not pending: return` -- a return here swallows whatever the
+ # tool raised, and the caller reports it as an unknown tool instead.
+ if pending:
+ # Outside the lock: deciding whether the tree holds files can take
+ # seconds, and no other chat could start a call meanwhile. This
+ # session stays closed, so nothing starts in the directory removed.
+ try:
+ for pending_id, pending_files in pending.items():
+ if _thread_exists(pending_id, unknown = True):
+ # Recreated while that call ran: this delete belongs to
+ # the chat that went, the folder is the new one's now.
+ continue
+ _remove_session_sandbox_locked(pending_id, pending_files)
+ finally:
+ with _sessions_free:
+ _removing_sessions.discard(key)
+ _sessions_free.notify_all()
# Non-matching session_ids collapse to ``_invalid`` to block cross-session escapes.
diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
index 5d1646528bc..5d777919299 100644
--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py
+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
@@ -6308,5 +6308,27 @@ class _WholeSecondMtime:
return getattr(self._stat, name)
+def test_session_in_flight_does_not_swallow_tool_exceptions(tmp_path, monkeypatch):
+ """A tool that raises must surface, not be reported as an unknown tool."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ session = "__LOCALID_raises1"
+ with pytest.raises(ValueError, match = "boom"):
+ with tools._session_in_flight(session):
+ raise ValueError("boom")
+
+ assert tools._session_key(session) not in tools._active_sessions
+
+
+def test_execute_tool_reports_a_bad_arg_instead_of_unknown_tool(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+ with pytest.raises(AttributeError):
+ tools.execute_tool("python", {"code": 42}, session_id = "__LOCALID_badarg1")
+
+
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-q", "-s"]))
diff --git a/studio/backend/tests/test_session_guard_exception_paths.py b/studio/backend/tests/test_session_guard_exception_paths.py
new file mode 100644
index 00000000000..d297152a1e9
--- /dev/null
+++ b/studio/backend/tests/test_session_guard_exception_paths.py
@@ -0,0 +1,311 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``_session_in_flight``'s state machine when the guarded body raises.
+
+The guard used to ``return`` from its ``finally``, discarding whatever the tool
+raised. Dropping that return is only safe if the cleanup still runs as before:
+the refcount, the queued deletes, and the condition other calls wait on. Every
+case asserts the full invariant set afterwards, so a leak fails here instead of
+hanging some later test. Barriers and bounded joins, no sleep-based timing.
+"""
+
+from __future__ import annotations
+
+import faulthandler
+import random
+import sys
+import threading
+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 import tools # noqa: E402
+
+DEADLINE = 30.0
+
+
+def _cleanup_explodes(session_id, delete_files):
+ """A cleanup that fails.
+
+ A plain function, not a generator ``.throw()`` one-liner: that would reset
+ ``__context__`` and hide the thing one of these tests checks.
+ """
+ raise OSError("disk gone")
+
+
[email protected](autouse = True)
+def clean_lifecycle_state():
+ """Start and finish with the module maps empty, whatever the test did."""
+ tools._active_sessions.clear()
+ tools._pending_removals.clear()
+ tools._removing_sessions.clear()
+ yield
+ tools._active_sessions.clear()
+ tools._pending_removals.clear()
+ tools._removing_sessions.clear()
+
+
+def assert_idle(message = ""):
+ assert dict(tools._active_sessions) == {}, f"_active_sessions leaked {message}"
+ assert dict(tools._pending_removals) == {}, f"_pending_removals leaked {message}"
+ assert set(tools._removing_sessions) == set(), f"_removing_sessions leaked {message}"
+
+
+def removals(monkeypatch):
+ """Record every sandbox removal instead of touching the filesystem."""
+ seen: list[str] = []
+
+ def _remove(session_id, delete_files):
+ seen.append(session_id)
+
+ monkeypatch.setattr(tools, "_remove_session_sandbox_locked", _remove)
+ monkeypatch.setattr(tools, "_thread_exists", lambda *a, **k: False)
+ return seen
+
+
+def queue_removal(session_id, *, files = True):
+ key = tools._session_key(session_id)
+ tools._pending_removals.setdefault(key, {})[session_id] = files
+
+
+# ── The exception path, with and without a queued delete ──────────
+
+
+def test_an_exception_leaves_no_lifecycle_state(removals):
+ sentinel = ValueError("boom")
+ with pytest.raises(ValueError) as caught:
+ with tools._session_in_flight("plain"):
+ raise sentinel
+ assert caught.value is sentinel
+ assert removals == []
+ assert_idle("after a plain failure")
+
+
+def test_a_queued_delete_still_runs_once_when_the_body_raises(removals):
+ """The cleanup is the whole reason the finally exists. It must still fire."""
+ queue_removal("doomed")
+ with pytest.raises(ValueError):
+ with tools._session_in_flight("doomed"):
+ raise ValueError("boom")
+ assert removals == ["doomed"], removals
+ assert_idle("after a failure with a queued delete")
+
+
+def test_a_recreated_chat_keeps_its_folder_even_when_the_body_raises(monkeypatch):
+ """A chat recreated during the call owns the directory; skip the delete."""
+ seen: list[str] = []
+ monkeypatch.setattr(
+ tools,
+ "_remove_session_sandbox_locked",
+ lambda s, f: seen.append(s),
+ )
+ monkeypatch.setattr(tools, "_thread_exists", lambda *a, **k: True)
+ queue_removal("recreated")
+ with pytest.raises(ValueError):
+ with tools._session_in_flight("recreated"):
+ raise ValueError("boom")
+ assert seen == []
+ assert_idle("after a skipped delete")
+
+
+# ── Nesting and case folding ──────────────────────────────────────
+
+
+def test_a_nested_guard_deletes_only_at_the_outer_exit(removals):
+ queue_removal("nested")
+ key = tools._session_key("nested")
+ with tools._session_in_flight("nested"):
+ with tools._session_in_flight("nested"):
+ assert tools._active_sessions[key] == 2
+ assert removals == [], "the inner exit deleted a sandbox still in use"
+ assert tools._active_sessions[key] == 1
+ assert removals == ["nested"]
+ assert_idle("after a nested guard")
+
+
+def test_a_nested_guard_deletes_once_even_when_the_inner_body_raises(removals):
+ queue_removal("nested-raise")
+ with pytest.raises(ValueError):
+ with tools._session_in_flight("nested-raise"):
+ with tools._session_in_flight("nested-raise"):
+ raise ValueError("boom")
+ assert removals == ["nested-raise"], removals
+ assert_idle("after a nested failure")
+
+
+def test_case_variant_ids_share_one_lifecycle_key(removals):
+ """One directory on Windows and on a default macOS volume."""
+ key = tools._session_key("CasePair")
+ assert key == tools._session_key("casepair")
+ with pytest.raises(ValueError):
+ with tools._session_in_flight("CasePair"):
+ with tools._session_in_flight("casepair"):
+ assert tools._active_sessions[key] == 2
+ raise ValueError("boom")
+ assert_idle("after a case-variant failure")
+
+
+# ── Cleanup that itself fails ─────────────────────────────────────
+
+
+def test_a_failing_cleanup_still_releases_the_session(monkeypatch):
+ """A cleanup error must never strand the chat.
+
+ A key left in ``_removing_sessions`` blocks every later call for it forever.
+ """
+ monkeypatch.setattr(tools, "_remove_session_sandbox_locked", _cleanup_explodes)
+ monkeypatch.setattr(tools, "_thread_exists", lambda *a, **k: False)
+ queue_removal("cleanup-fails")
+ with pytest.raises(OSError):
+ with tools._session_in_flight("cleanup-fails"):
+ pass
+ assert_idle("after a failing cleanup")
+
+
+def test_a_failing_cleanup_masks_the_tool_error_but_keeps_it_as_context(monkeypatch):
+ """Pins the policy rather than asserting a preference.
+
+ Standard semantics: a ``finally`` exception replaces the one in flight and
+ keeps it as ``__context__``. Predates this change (it already happened
+ whenever a delete was queued), so it is pinned, not altered.
+ """
+ monkeypatch.setattr(tools, "_remove_session_sandbox_locked", _cleanup_explodes)
+ monkeypatch.setattr(tools, "_thread_exists", lambda *a, **k: False)
+ queue_removal("masked")
+ tool_error = ValueError("the real tool failure")
+ with pytest.raises(OSError) as caught:
+ with tools._session_in_flight("masked"):
+ raise tool_error
+ assert caught.value.__context__ is tool_error
+ assert_idle("after a masked tool error")
+
+
+def test_a_failing_cleanup_wakes_a_waiter_for_the_same_chat(monkeypatch):
+ """The condition variable must be notified on the error path too."""
+ entered = threading.Event()
+ release = threading.Event()
+
+ def _slow_failing_remove(session_id, delete_files):
+ entered.set()
+ release.wait(DEADLINE)
+ raise OSError("disk gone")
+
+ monkeypatch.setattr(tools, "_remove_session_sandbox_locked", _slow_failing_remove)
+ monkeypatch.setattr(tools, "_thread_exists", lambda *a, **k: False)
+ queue_removal("waited-on")
+
+ def _first():
+ try:
+ with tools._session_in_flight("waited-on"):
+ pass
+ except OSError:
+ pass
+
+ first = threading.Thread(target = _first, name = "pr9640-first")
+ first.start()
+ assert entered.wait(DEADLINE), "cleanup never started"
+
+ waiter_in = threading.Event()
+
+ def _second():
+ with tools._session_in_flight("waited-on"):
+ waiter_in.set()
+
+ second = threading.Thread(target = _second, name = "pr9640-waiter")
+ second.start()
+ # The waiter must be blocked while the removal is in progress.
+ assert not waiter_in.wait(0.5), "a call started inside a folder being deleted"
+
+ release.set()
+ assert waiter_in.wait(DEADLINE), "the waiter was never woken after a failed cleanup"
+ first.join(DEADLINE)
+ second.join(DEADLINE)
+ assert not first.is_alive() and not second.is_alive()
+ assert_idle("after a woken waiter")
+
+
+def test_one_failing_delete_does_not_silently_drop_the_others(monkeypatch):
+ """Pre-existing behaviour, pinned so a fix is a deliberate choice.
+
+ ``_pending_removals.pop`` takes the whole batch before iterating, so one
+ raising entry leaves the rest neither attempted nor queued. Not introduced
+ here, but the exception path makes it easy to hit.
+ """
+ attempted: list[str] = []
+
+ def _remove(session_id, delete_files):
+ attempted.append(session_id)
+ if session_id == "b":
+ raise OSError("disk gone")
+
+ monkeypatch.setattr(tools, "_remove_session_sandbox_locked", _remove)
+ monkeypatch.setattr(tools, "_thread_exists", lambda *a, **k: False)
+ key = tools._session_key("a")
+ # Same lifecycle key, three exact ids queued behind it.
+ tools._pending_removals[key] = {"a": True, "b": True, "c": True}
+ with pytest.raises(OSError):
+ with tools._session_in_flight("a"):
+ pass
+ assert "b" in attempted
+ assert attempted != [
+ "a",
+ "b",
+ "c",
+ ], "the batch now completes past a failure -- update this test and say so"
+ assert_idle("after a partially failed batch")
+
+
+# ── Concurrency ───────────────────────────────────────────────────
+
+
[email protected]("seed", list(range(100)))
+def test_randomised_schedules_leave_no_lifecycle_state(seed, removals):
+ """100 seeds mixing successes, failures, deletes and case variants.
+
+ Joins have a deadline and faulthandler is armed, so a deadlock leaves
+ stacks rather than a silent CI timeout.
+ """
+ rng = random.Random(seed)
+ ids = ["alpha", "Alpha", "beta", "BETA", "gamma"]
+ errors: list[BaseException] = []
+ start = threading.Barrier(8, timeout = DEADLINE)
+
+ def worker(i):
+ session = rng.choice(ids)
+ fail = rng.random() < 0.5
+ cancel = rng.random() < 0.2
+ if rng.random() < 0.3:
+ queue_removal(session)
+ try:
+ start.wait()
+ with tools._session_in_flight(session):
+ if cancel:
+ raise KeyboardInterrupt("stop")
+ if fail:
+ raise ValueError(f"boom-{i}")
+ except (ValueError, KeyboardInterrupt):
+ pass
+ except BaseException as exc: # noqa: BLE001
+ errors.append(exc)
+
+ faulthandler.dump_traceback_later(DEADLINE, exit = False)
+ try:
+ threads = [
+ threading.Thread(target = worker, args = (i,), name = f"pr9640-{seed}-{i}") for i in range(8)
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(DEADLINE)
+ assert not any(t.is_alive() for t in threads), f"deadlock at seed {seed}"
+ finally:
+ faulthandler.cancel_dump_traceback_later()
+
+ assert errors == [], f"unexpected exception at seed {seed}: {errors}"
+ assert_idle(f"at seed {seed}")
diff --git a/studio/backend/tests/test_tool_loop_exception_contracts.py b/studio/backend/tests/test_tool_loop_exception_contracts.py
new file mode 100644
index 00000000000..2e70ae64a97
--- /dev/null
+++ b/studio/backend/tests/test_tool_loop_exception_contracts.py
@@ -0,0 +1,303 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""What each tool loop does when a local tool raises.
+
+``_session_in_flight`` no longer swallows exceptions, so a failing ``python`` /
+``terminal`` / ``edit_file`` call now propagates instead of coming back as
+``"Unknown tool: <name>"``. ``studio_tool_loop`` and ``safetensors_agentic``
+already turned that into a model-visible result; ``llama_cpp`` did not, so a bad
+argument killed the whole GGUF answer.
+
+Each loop is asserted against its own contract, not forced into one shape.
+Reuses the fake llama-server and fake-transport harnesses next door, so no
+model, subprocess, GPU or network is involved.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+# Backend root plus the tests dir: the two harnesses this borrows sit alongside
+# and import as top-level modules.
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+for _entry in (_BACKEND_DIR, _TESTS_DIR):
+ if _entry not in sys.path:
+ sys.path.insert(0, _entry)
+
+from test_llama_cpp_tool_loop import ( # noqa: E402
+ _done,
+ _make_backend,
+ _sse,
+ _structured_tool_call,
+)
+
+# The reported call: `code` is a number, so `_python_exec` fails on `.strip()`
+# before anything runs.
+BAD_PYTHON = {"code": 42}
+REAL_ERROR = "'int' object has no attribute 'strip'"
+
+
+def _gguf_events(
+ monkeypatch,
+ arguments,
+ tool_name = "python",
+):
+ first = _structured_tool_call(tool_name, arguments, "call_bad_arg")
+ second = [_sse({"content": "I will fix the argument."}), _done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [first, second], payloads)
+ return list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "run some python"}],
+ tools = [{"type": "function", "function": {"name": tool_name}}],
+ max_tool_iterations = 2,
+ )
+ ), payloads
+
+
+ "tool_name, arguments",
+ [("python", BAD_PYTHON), ("terminal", {"command": 42})],
+)
+def test_a_raising_local_tool_does_not_kill_the_gguf_answer(monkeypatch, tool_name, arguments):
+ """The GGUF loop must report the tool's failure and keep answering.
+
+ Unguarded, the per-iteration handler re-raises, the route reports a generic
+ internal error, and the user loses a reply the model could have corrected.
+ """
+ events, _payloads = _gguf_events(monkeypatch, arguments, tool_name)
+
+ ends = [e for e in events if e.get("type") == "tool_end"]
+ assert len(ends) == 1, f"expected exactly one tool_end, got {ends}"
+ assert REAL_ERROR in ends[0]["result"], ends[0]["result"]
+ assert ends[0]["result"].startswith("Error: tool raised an exception:")
+ assert "Unknown tool" not in ends[0]["result"]
+
+ content = "".join(e.get("text", "") for e in events if e.get("type") == "content")
+ assert (
+ "I will fix the argument." in content
+ ), "the loop stopped instead of letting the model recover"
+
+
+def test_the_gguf_loop_still_reports_a_genuinely_unknown_tool(monkeypatch):
+ """The unknown-tool contract itself is untouched."""
+ events, _payloads = _gguf_events(
+ monkeypatch,
+ {"x": 1},
+ tool_name = "no_such_tool_at_all",
+ )
+ ends = [e for e in events if e.get("type") == "tool_end"]
+ assert len(ends) == 1
+ assert ends[0]["result"] == "Unknown tool: no_such_tool_at_all"
+
+
+def test_the_failing_tool_result_reaches_the_model(monkeypatch):
+ """The error must be in the next request, or the model cannot correct it."""
+ _events, payloads = _gguf_events(monkeypatch, BAD_PYTHON)
+ assert len(payloads) >= 2, "no second turn: the loop did not continue"
+ tool_messages = [m for m in payloads[1]["messages"] if m.get("role") == "tool"]
+ assert tool_messages, payloads[1]["messages"]
+ assert REAL_ERROR in json.dumps(tool_messages)
+
+
+# ── The external-provider loop ────────────────────────────────────
+
+
+def test_the_studio_loop_reports_the_real_error_and_continues(monkeypatch):
+ """stream_with_studio_tools already had the handler; prove it end to end."""
+ import test_studio_tool_loop as studio_h
+ from core.inference import studio_tool_loop as loop_mod
+
+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)
+ monkeypatch.setattr(loop_mod, "is_high_risk_tool_call", lambda name, args: False)
+
+ transport = studio_h.FakeTransport(
+ [
+ [
+ studio_h._sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_bad_arg",
+ "type": "function",
+ "function": {
+ "name": "python",
+ "arguments": json.dumps(BAD_PYTHON),
+ },
+ }
+ ]
+ }
+ ),
+ studio_h._DONE,
+ ],
+ [studio_h._sse({"content": "I will fix the argument."}), studio_h._DONE],
+ ]
+ )
+ lines = studio_h._run(transport, tools = [studio_h.PY], permission_mode = "off")
+
+ ends = studio_h._events(lines, "tool_end")
+ assert len(ends) == 1, ends
+ assert ends[0]["result"].startswith("Error: tool raised an exception:")
+ assert REAL_ERROR in ends[0]["result"]
+ assert "Unknown tool" not in ends[0]["result"]
+ assert "I will fix the argument." in studio_h._visible_text(lines)
+
+
+def test_the_studio_loop_still_reports_a_genuinely_unknown_tool(monkeypatch):
+ import test_studio_tool_loop as studio_h
+ from core.inference import studio_tool_loop as loop_mod
+
+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)
+ monkeypatch.setattr(loop_mod, "is_high_risk_tool_call", lambda name, args: False)
+
+ unknown = studio_h._tool("no_such_tool_at_all")
+ transport = studio_h.FakeTransport(
+ [
+ [
+ studio_h._sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_unknown",
+ "type": "function",
+ "function": {
+ "name": "no_such_tool_at_all",
+ "arguments": "{}",
+ },
+ }
+ ]
+ }
+ ),
+ studio_h._DONE,
+ ],
+ [studio_h._sse({"content": "ok"}), studio_h._DONE],
+ ]
+ )
+ lines = studio_h._run(transport, tools = [unknown], permission_mode = "off")
+ ends = studio_h._events(lines, "tool_end")
+ assert len(ends) == 1
+ assert ends[0]["result"] == "Unknown tool: no_such_tool_at_all"
+
+
+# ── The duplicate-call ledger ─────────────────────────────────────
+
+
+def test_a_repeated_failing_call_stays_bounded(monkeypatch):
+ """The result's classification changes, so check the loop still ends.
+
+ ``"Unknown tool: python"`` matches no ``TOOL_ERROR_PREFIXES``, so a failed
+ call was filed as a *success* and an identical retry refused. ``"Error:
+ ..."`` is a failure, so the retry is allowed -- right, since the model can
+ now see what went wrong, but only while the loop stays bounded.
+ """
+ import test_studio_tool_loop as studio_h
+ from core.inference import studio_tool_loop as loop_mod
+
+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)
+ monkeypatch.setattr(loop_mod, "is_high_risk_tool_call", lambda name, args: False)
+
+ executions: list[dict] = []
+ real_execute = loop_mod.execute_tool
+
+ def _counting_execute(name, arguments, **kwargs):
+ executions.append({"name": name, "arguments": arguments})
+ return real_execute(name, arguments, **kwargs)
+
+ monkeypatch.setattr(loop_mod, "execute_tool", _counting_execute)
+
+ bad_turn = [
+ studio_h._sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_same",
+ "type": "function",
+ "function": {
+ "name": "python",
+ "arguments": json.dumps(BAD_PYTHON),
+ },
+ }
+ ]
+ }
+ ),
+ studio_h._DONE,
+ ]
+ max_calls = 4
+ # More identical turns scripted than the budget allows.
+ transport = studio_h.FakeTransport([list(bad_turn) for _ in range(max_calls + 6)])
+ lines = studio_h._run(
+ transport,
+ tools = [studio_h.PY],
+ permission_mode = "off",
+ max_calls = max_calls,
+ )
+
+ assert len(executions) <= max_calls, (
+ f"the loop ran the same failing call {len(executions)} times "
+ f"with a budget of {max_calls}"
+ )
+ ends = studio_h._events(lines, "tool_end")
+ assert ends, "no tool_end at all"
+ # Every execution reports the real error; the trailing card is the
+ # controller's budget notice, which is how the loop says it stopped.
+ executed_ends = [e for e in ends if REAL_ERROR in e["result"]]
+ assert len(executed_ends) == len(executions), [e["result"] for e in ends]
+ assert "limit was reached" in ends[-1]["result"], ends[-1]["result"]
+ assert not any("Unknown tool" in e["result"] for e in ends)
+ assert transport.turns, "the loop consumed every scripted turn instead of stopping"
+
+
+# ── research_runs stays outside the blast radius ──────────────────
+
+
+def test_research_only_calls_tools_that_are_not_session_guarded():
+ """research_runs has no enclosing tool handler, so it must stay clear.
+
+ Its safety is a property of which tools it names. Grow that list with a
+ guarded tool and this fails until research_runs handles them too.
+ """
+ import ast
+ import inspect
+
+ from core import research_runs
+
+ guarded = {"python", "terminal", "edit_file"}
+ tree = ast.parse(inspect.getsource(research_runs))
+ named: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ # execute_tool(name, ...) directly, or via asyncio.to_thread(execute_tool, name, ...)
+ if getattr(func, "id", None) == "execute_tool" and node.args:
+ first = node.args[0]
+ elif (
+ getattr(func, "attr", None) == "to_thread"
+ and len(node.args) >= 2
+ and getattr(node.args[0], "id", None) == "execute_tool"
+ ):
+ first = node.args[1]
+ else:
+ continue
+ if isinstance(first, ast.Constant) and isinstance(first.value, str):
+ named.add(first.value)
+ else:
+ named.add(f"<dynamic:{ast.dump(first)[:60]}>")
+
+ assert named, "no execute_tool call sites found; the scan is broken"
+ assert not (named & guarded), (
+ f"research_runs now calls a session-guarded tool: {sorted(named & guarded)}. "
+ "It has no enclosing tool-exception handler, so give it one first."
+ )
+ assert all(
+ not n.startswith("<dynamic:") for n in named
+ ), f"a research_runs tool name is computed, so this scan cannot vouch for it: {named}"