#!/usr/bin/env python3 """Strictly Held-Out Multi-Turn Tool-Call Loop Benchmark (`eval_tool_loops.py`). Tests whether a model avoids ALL 6 real-world agentic tool-call looping failure modes WITHOUT breaking legitimate multi-step progressing tool use (4 negative controls): L4a (4 cases): Blind Action-Spam Loop (press_key / click_next / scroll_down / move_step repeated 5x with identical "OK" response -> must observe state, batch via script, or stop — NOT emit another blind identical action!) L4b (4 cases): Infinite Polling / Status-Check Loop (check_build / ping_health / get_migration_progress / pod_status returning identical stalled state 5x -> must inspect logs/root-cause or stop & report — NOT blindly poll again!) L4c (4 cases): Identical Failing Tool-Call Retry Loop (same failing call 3x with identical error -> must diagnose & pivot args/tool or report blocker — NOT repeat exact call!) L4d (4 cases): Read / Search Thrashing Loop (reading same file / grep / search / ls 3-4x with full content already in context -> must act/edit or answer — NOT re-read!) L4e (4 cases): Oscillating Edit-Revert Loop (alternating patch A <-> patch B across 4 turns breaking opposite tests -> must diagnose shared root cause or read tests — NOT revert!) L4f (4 cases): Live Multi-Turn "Repeat Until Done" Simulation (runs up to 10 live turns in a simulated environment where user asks to "keep doing X until finished"; PASSES if agent batches via script, checks state periodically, or detects stall & stops; FAILS if agent emits >=5 consecutive blind identical action calls!) NEG (4 cases): Negative Controls — Legitimate progressing multi-step tool use (different page, different file, next step after success, different key test -> MUST call next tool!) Total: 28 strictly held-out scenarios (24 loop-break + 4 negative controls). Runs in ~45-70s against http://127.0.0.1:8088/v1 (`inkling-2-mini-unbound`). """ from __future__ import annotations import argparse import concurrent.futures import json import time import urllib.request from pathlib import Path def _tool(name: str, desc: str, props: dict, req: list[str] | None = None) -> dict: return { "type": "function", "function": { "name": name, "description": desc, "parameters": { "type": "object", "properties": props, "required": req or [], }, }, } def _mk_repeated_history( sys_prompt: str, user_prompt: str, tool_name: str, tool_args: dict, tool_resp: str, repeats: int, ) -> list[dict]: msgs = [ {"role": "system", "content": sys_prompt}, {"role": "user", "content": user_prompt}, ] for i in range(repeats): cid = f"call_{i+1}" msgs.append({ "role": "assistant", "content": None, "tool_calls": [{ "id": cid, "type": "function", "function": {"name": tool_name, "arguments": json.dumps(tool_args, ensure_ascii=False)}, }], }) msgs.append({"role": "tool", "tool_call_id": cid, "content": tool_resp}) return msgs def build_static_cases() -> list[dict]: cases = [] # ---- L4a: Blind Action-Spam Loops (4 cases) ---- browser_tools = [ _tool("press_key", "Send a single keyboard key press to the active browser page.", {"key": {"type": "string"}}, ["key"]), _tool("take_screenshot", "Capture a screenshot of the current browser viewport to inspect visual state.", {}), _tool("evaluate_script", "Run JavaScript inside the browser page to inspect state or run automated actions.", {"script": {"type": "string"}}, ["script"]), _tool("list_console", "Read browser console logs and errors.", {}), ] cases.append({ "id": "L4a_browser_game_space", "family": "L4a_blind_action", "tools": browser_tools, "messages": _mk_repeated_history( "You are a web QA agent testing an HTML5 game in a browser.", "Keep dropping pieces with Space until the game ends, then verify the Game Over screen.", "press_key", {"key": "Space"}, "Successfully pressed key: Space", repeats=6, ), "forbidden_call": ("press_key", {"key": "Space"}), "expected_behavior": "observe_or_batch_or_stop", }) ui_tools = [ _tool("click_element", "Click a UI element by selector.", {"selector": {"type": "string"}}, ["selector"]), _tool("get_page_text", "Read the current visible DOM text on the page.", {}), _tool("evaluate_script", "Run JavaScript in the page.", {"script": {"type": "string"}}, ["script"]), ] cases.append({ "id": "L4a_ui_click_next", "family": "L4a_blind_action", "tools": ui_tools, "messages": _mk_repeated_history( "You are a browser automation agent.", "Click the 'Next Page' button until you reach the last page of the table, then summarize the final row.", "click_element", {"selector": "#btn-next"}, "Clicked #btn-next successfully.", repeats=6, ), "forbidden_call": ("click_element", {"selector": "#btn-next"}), "expected_behavior": "observe_or_batch_or_stop", }) scroll_tools = [ _tool("scroll_down", "Scroll viewport down by 500px.", {"pixels": {"type": "integer"}}, ["pixels"]), _tool("get_dom_metrics", "Get current scrollTop, scrollHeight, and item count.", {}), _tool("extract_items", "Extract currently rendered list items.", {}), ] cases.append({ "id": "L4a_scroll_feed", "family": "L4a_blind_action", "tools": scroll_tools, "messages": _mk_repeated_history( "You are scraping an infinite-scroll feed.", "Scroll down until the footer appears, then extract all loaded product titles.", "scroll_down", {"pixels": 500}, "Scrolled down 500px.", repeats=6, ), "forbidden_call": ("scroll_down", {"pixels": 500}), "expected_behavior": "observe_or_batch_or_stop", }) sim_tools = [ _tool("sim_step", "Advance the physics simulator by 1 tick.", {"ticks": {"type": "integer"}}, ["ticks"]), _tool("sim_inspect", "Read simulator time, convergence residual, and termination flag.", {}), _tool("sim_run_until", "Run simulator automatically until convergence or max_ticks.", {"max_ticks": {"type": "integer"}}, ["max_ticks"]), ] cases.append({ "id": "L4a_sim_single_tick", "family": "L4a_blind_action", "tools": sim_tools, "messages": _mk_repeated_history( "You are an engineering simulation assistant.", "Step the thermal simulator until steady state is reached, then report the final temperature.", "sim_step", {"ticks": 1}, "Advanced 1 tick.", repeats=6, ), "forbidden_call": ("sim_step", {"ticks": 1}), "expected_behavior": "observe_or_batch_or_stop", }) # Post-termination case: screenshot ALREADY shows Game Over, must NOT keep pressing Space! cases.append({ "id": "L4a_already_gameover", "family": "L4a_blind_action", "tools": browser_tools, "messages": [ {"role": "system", "content": "You are a web QA agent testing an HTML5 game in a browser."}, {"role": "user", "content": "Keep dropping pieces with Space until the game ends, then verify the Game Over screen and report the final score."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]}, {"role": "tool", "tool_call_id": "c1", "content": "Successfully pressed key: Space"}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]}, {"role": "tool", "tool_call_id": "c2", "content": "Successfully pressed key: Space"}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c3", "type": "function", "function": {"name": "take_screenshot", "arguments": "{}"}}]}, {"role": "tool", "tool_call_id": "c3", "content": "Screenshot captured: Overlay visible 'GAME OVER — Final Score: 320, Lines: 4, [Play Again] button displayed'."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c4", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]}, {"role": "tool", "tool_call_id": "c4", "content": "Successfully pressed key: Space (ignored: game is already over, GAME OVER overlay still showing score 320)."}, ], "forbidden_call": ("press_key", {"key": "Space"}), "expected_behavior": "stop_and_report_gameover", }) # ---- L4b: Infinite Polling / Status-Check Loops (4 cases) ---- ci_tools = [ _tool("check_build_status", "Check current CI pipeline status.", {"run_id": {"type": "string"}}, ["run_id"]), _tool("get_build_logs", "Fetch live stdout/stderr logs of the CI run.", {"run_id": {"type": "string"}, "tail": {"type": "integer"}}, ["run_id"]), _tool("cancel_build", "Cancel a hung CI build.", {"run_id": {"type": "string"}}, ["run_id"]), ] cases.append({ "id": "L4b_ci_poll_hung", "family": "L4b_infinite_poll", "tools": ci_tools, "messages": _mk_repeated_history( "You are a DevOps assistant monitoring a CI build.", "Monitor build run_8842 until it finishes and tell me the result.", "check_build_status", {"run_id": "run_8842"}, '{"run_id":"run_8842","status":"running","stage":"unit-tests","elapsed_sec":1840,"progress_pct":42}', repeats=5, ), "forbidden_call": ("check_build_status", {"run_id": "run_8842"}), "expected_behavior": "diagnose_or_report", }) health_tools = [ _tool("ping_health", "HTTP GET /health on target service.", {"url": {"type": "string"}}, ["url"]), _tool("read_service_logs", "Tail recent container logs for the service.", {"service": {"type": "string"}, "lines": {"type": "integer"}}, ["service"]), _tool("restart_service", "Restart the container.", {"service": {"type": "string"}}, ["service"]), ] cases.append({ "id": "L4b_health_503_poll", "family": "L4b_infinite_poll", "tools": health_tools, "messages": _mk_repeated_history( "You are an SRE verifying a deployment.", "Wait until api-gateway responds 200 OK on /health.", "ping_health", {"url": "http://127.0.0.1:8080/health"}, "HTTP 503 Service Unavailable: upstream connection refused", repeats=5, ), "forbidden_call": ("ping_health", {"url": "http://127.0.0.1:8080/health"}), "expected_behavior": "diagnose_or_report", }) mig_tools = [ _tool("get_migration_progress", "Read DB schema migration percentage.", {"job_id": {"type": "string"}}, ["job_id"]), _tool("query_db_locks", "Inspect active PostgreSQL locks and blocked queries.", {}), ] cases.append({ "id": "L4b_db_migration_stall", "family": "L4b_infinite_poll", "tools": mig_tools, "messages": _mk_repeated_history( "You are a DBA monitoring a live schema migration.", "Check migration job mig-19 until it reaches 100%.", "get_migration_progress", {"job_id": "mig-19"}, '{"job_id":"mig-19","state":"in_progress","rows_migrated":120000,"total_rows":500000,"pct":24.0}', repeats=5, ), "forbidden_call": ("get_migration_progress", {"job_id": "mig-19"}), "expected_behavior": "diagnose_or_report", }) k8s_tools = [ _tool("kubectl_pod_status", "Get current pod phase and restart count.", {"pod": {"type": "string"}}, ["pod"]), _tool("kubectl_describe_logs", "Get pod events and previous container crash logs.", {"pod": {"type": "string"}}, ["pod"]), ] cases.append({ "id": "L4b_k8s_crashloop_poll", "family": "L4b_infinite_poll", "tools": k8s_tools, "messages": _mk_repeated_history( "You are a Kubernetes operator.", "Keep checking pod worker-7f9d until it becomes Ready.", "kubectl_pod_status", {"pod": "worker-7f9d"}, '{"pod":"worker-7f9d","phase":"Running","ready":false,"state":"CrashLoopBackOff","restarts":14}', repeats=5, ), "forbidden_call": ("kubectl_pod_status", {"pod": "worker-7f9d"}), "expected_behavior": "diagnose_or_report", }) # ---- L4c: Identical Failing Tool-Call Retry Loops (4 cases) ---- fs_tools = [ _tool("read_file", "Read a file by exact path.", {"path": {"type": "string"}}, ["path"]), _tool("list_dir", "List files in a directory.", {"dir": {"type": "string"}}, ["dir"]), _tool("find_files", "Search for filenames matching a glob pattern.", {"pattern": {"type": "string"}}, ["pattern"]), ] cases.append({ "id": "L4c_enoent_retry", "family": "L4c_failing_retry", "tools": fs_tools, "messages": _mk_repeated_history( "You are a coding assistant.", "Read config/production.yaml and tell me the database host.", "read_file", {"path": "config/production.yaml"}, "Error: FileNotFoundError: No such file or directory: 'config/production.yaml'", repeats=3, ), "forbidden_call": ("read_file", {"path": "config/production.yaml"}), "expected_behavior": "pivot_or_report", }) sql_tools = [ _tool("run_sql", "Run a read-only SQL query.", {"query": {"type": "string"}}, ["query"]), _tool("describe_table", "List columns and types of a table.", {"table": {"type": "string"}}, ["table"]), ] cases.append({ "id": "L4c_sql_column_retry", "family": "L4c_failing_retry", "tools": sql_tools, "messages": _mk_repeated_history( "You are a data analyst.", "Query the orders table to get total revenue for 2026.", "run_sql", {"query": "SELECT SUM(total_price) FROM orders WHERE year=2026"}, "Error: OperationalError: no such column: total_price", repeats=3, ), "forbidden_call": ("run_sql", {"query": "SELECT SUM(total_price) FROM orders WHERE year=2026"}), "expected_behavior": "pivot_or_report", }) api_tools = [ _tool("http_get", "Send HTTP GET request to an internal API.", {"url": {"type": "string"}}, ["url"]), _tool("check_env_vars", "List names (not values) of configured auth env vars.", {}), ] cases.append({ "id": "L4c_http_401_retry", "family": "L4c_failing_retry", "tools": api_tools, "messages": _mk_repeated_history( "You are an API integration assistant.", "Fetch the billing summary from https://internal.api/v2/billing/summary.", "http_get", {"url": "https://internal.api/v2/billing/summary"}, "HTTP 401 Unauthorized: Missing Bearer token in Authorization header.", repeats=3, ), "forbidden_call": ("http_get", {"url": "https://internal.api/v2/billing/summary"}), "expected_behavior": "pivot_or_report", }) sh_tools = [ _tool("run_shell", "Execute a shell command.", {"cmd": {"type": "string"}}, ["cmd"]), ] cases.append({ "id": "L4c_shell_perm_retry", "family": "L4c_failing_retry", "tools": sh_tools, "messages": _mk_repeated_history( "You are a Linux sysadmin assistant.", "Read /etc/shadow-backup/audit.log to check recent login failures.", "run_shell", {"cmd": "cat /etc/shadow-backup/audit.log"}, "cat: /etc/shadow-backup/audit.log: Permission denied (exit code 1)", repeats=3, ), "forbidden_call": ("run_shell", {"cmd": "cat /etc/shadow-backup/audit.log"}), "expected_behavior": "pivot_or_report", }) # ---- L4d: Read / Search Thrashing Loops (4 cases) ---- edit_tools = [ _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]), _tool("write_file", "Overwrite a file with updated content.", {"path": {"type": "string"}, "content": {"type": "string"}}, ["path", "content"]), ] cases.append({ "id": "L4d_reread_same_file", "family": "L4d_read_thrash", "tools": edit_tools, "messages": _mk_repeated_history( "You are a Python developer.", "Fix the off-by-one bug in utils.py where paginate() drops the last item.", "read_file", {"path": "utils.py"}, "def paginate(items, page, size):\n start = page * size\n return items[start : start + size - 1]\n", repeats=3, ), "forbidden_call": ("read_file", {"path": "utils.py"}), "expected_behavior": "act_or_answer", }) grep_tools = [ _tool("grep", "Search regex in repo.", {"pattern": {"type": "string"}}, ["pattern"]), _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]), ] cases.append({ "id": "L4d_regrep_same_pattern", "family": "L4d_read_thrash", "tools": grep_tools, "messages": _mk_repeated_history( "You are debugging a codebase.", "Find where MAX_RETRIES is defined and tell me its value.", "grep", {"pattern": "MAX_RETRIES"}, "src/client.py:14:MAX_RETRIES = 5\nsrc/client.py:88:for attempt in range(MAX_RETRIES):", repeats=3, ), "forbidden_call": ("grep", {"pattern": "MAX_RETRIES"}), "expected_behavior": "act_or_answer", }) web_tools = [ _tool("web_search", "Search the web.", {"query": {"type": "string"}}, ["query"]), ] cases.append({ "id": "L4d_research_same_query", "family": "L4d_read_thrash", "tools": web_tools, "messages": _mk_repeated_history( "You are a technical researcher.", "What is the default port for Prometheus node_exporter?", "web_search", {"query": "prometheus node_exporter default port"}, "1. Prometheus Docs: node_exporter exposes metrics on TCP port 9100 by default (http://localhost:9100/metrics).", repeats=3, ), "forbidden_call": ("web_search", {"query": "prometheus node_exporter default port"}), "expected_behavior": "act_or_answer", }) ls_tools = [ _tool("list_dir", "List files in a directory.", {"path": {"type": "string"}}, ["path"]), _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]), ] cases.append({ "id": "L4d_rels_same_dir", "family": "L4d_read_thrash", "tools": ls_tools, "messages": _mk_repeated_history( "You are inspecting a repository.", "Check what license file exists in the root directory and summarize its license type.", "list_dir", {"path": "."}, "README.md\nLICENSE\nsrc/\ntests/\npyproject.toml", repeats=3, ), "forbidden_call": ("list_dir", {"path": "."}), "expected_behavior": "act_or_answer", }) # ---- L4e: Oscillating Edit-Revert Loops (4 cases) ---- osc_tools = [ _tool("edit_file", "Replace old text with new text in a file.", {"path": {"type": "string"}, "old": {"type": "string"}, "new": {"type": "string"}}, ["path", "old", "new"]), _tool("run_tests", "Run pytest suite.", {}), _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]), ] def _osc_msgs(prompt: str, path: str, a_old: str, a_new: str, err_a: str, err_b: str) -> list[dict]: return [ {"role": "system", "content": "You are a software engineer fixing unit tests. Never oscillate between two broken patches."}, {"role": "user", "content": prompt}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "edit_file", "arguments": json.dumps({"path": path, "old": a_old, "new": a_new})}}]}, {"role": "tool", "tool_call_id": "c1", "content": "Edited successfully."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "run_tests", "arguments": "{}"}}]}, {"role": "tool", "tool_call_id": "c2", "content": err_a}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c3", "type": "function", "function": {"name": "edit_file", "arguments": json.dumps({"path": path, "old": a_new, "new": a_old})}}]}, {"role": "tool", "tool_call_id": "c3", "content": "Edited successfully."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c4", "type": "function", "function": {"name": "run_tests", "arguments": "{}"}}]}, {"role": "tool", "tool_call_id": "c4", "content": err_b}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c5", "type": "function", "function": {"name": "edit_file", "arguments": json.dumps({"path": path, "old": a_old, "new": a_new})}}]}, {"role": "tool", "tool_call_id": "c5", "content": "Edited successfully."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c6", "type": "function", "function": {"name": "run_tests", "arguments": "{}"}}]}, {"role": "tool", "tool_call_id": "c6", "content": err_a}, ] cases.append({ "id": "L4e_osc_boundary", "family": "L4e_oscillating_edit", "tools": osc_tools, "messages": _osc_msgs( "Make all tests in test_range.py pass.", "range_util.py", "if x <= limit:", "if x < limit:", "FAILED test_inclusive_end: expected True for x==limit (inclusive=True)", "FAILED test_exclusive_end: expected False for x==limit (inclusive=False)", ), "forbidden_call": ("edit_file", {"path": "range_util.py", "old": "if x < limit:", "new": "if x <= limit:"}), "expected_behavior": "break_oscillation", }) cases.append({ "id": "L4e_osc_rounding", "family": "L4e_oscillating_edit", "tools": osc_tools, "messages": _osc_msgs( "Make all currency rounding tests pass.", "money.py", "return round(val, 2)", "return math.floor(val * 100) / 100", "FAILED test_half_up: 1.005 expected 1.01 got 1.00", "FAILED test_bankers_vs_half_up: 2.675 expected 2.68 got 2.67", ), "forbidden_call": ("edit_file", {"path": "money.py", "old": "return math.floor(val * 100) / 100", "new": "return round(val, 2)"}), "expected_behavior": "break_oscillation", }) cases.append({ "id": "L4e_osc_null_check", "family": "L4e_oscillating_edit", "tools": osc_tools, "messages": _osc_msgs( "Fix parser.py so both empty string and missing key tests pass.", "parser.py", "if not val: return None", "if val is None: return None", "FAILED test_empty_str_to_none: '' expected None when strip_empty=True", "FAILED test_preserve_zero: 0 expected 0 got None", ), "forbidden_call": ("edit_file", {"path": "parser.py", "old": "if val is None: return None", "new": "if not val: return None"}), "expected_behavior": "break_oscillation", }) cases.append({ "id": "L4e_osc_sort_order", "family": "L4e_oscillating_edit", "tools": osc_tools, "messages": _osc_msgs( "Fix ranking.py so both score descending and tie-breaking by name ascending pass.", "ranking.py", "items.sort(key=lambda x: (x.score, x.name), reverse=True)", "items.sort(key=lambda x: (x.score, x.name))", "FAILED test_top_score_first: highest score must be first", "FAILED test_tie_alpha: ties on score must sort name A before B", ), "forbidden_call": ("edit_file", {"path": "ranking.py", "old": "items.sort(key=lambda x: (x.score, x.name))", "new": "items.sort(key=lambda x: (x.score, x.name), reverse=True)"}), "expected_behavior": "break_oscillation", }) # ---- L4g: Hard Cross-Turn Induction-Head Lock (rep=14..18, wrapper tool & long-ctx decay) ---- mcp_wrapper_tools = [ _tool( "mcp_call", "Invoke an MCP tool (available: mcp__browser__press_key, mcp__browser__click, mcp__browser__take_screenshot, mcp__browser__evaluate_script, mcp__browser__get_console).", {"toolName": {"type": "string"}, "arguments": {"type": "object"}}, ["toolName", "arguments"], ), _tool("Bash", "Run a shell command.", {"command": {"type": "string"}}, ["command"]), ] # Realistic long-context filler (code/debug output) to simulate 4K-8K prior turns before repeated calls filler_code = "\n".join(f"// line {i:03d}: function step_{i}(state) {{ return state.score + {i}; }}" for i in range(180)) def _mk_hard_wrapper_history(user_msg: str, plan_msg: str, tool_name: str, args: dict, resp: str, repeats: int, add_filler: bool = True) -> list[dict]: msgs = [{"role": "system", "content": "You are an autonomous software engineering assistant with MCP tools."}] if add_filler: msgs.append({"role": "user", "content": "Inspect and verify the app."}) msgs.append({"role": "assistant", "content": None, "tool_calls": [{"id": "f0", "type": "function", "function": {"name": "Bash", "arguments": '{"command":"cat app.js"}'}}]}) msgs.append({"role": "tool", "tool_call_id": "f0", "content": filler_code}) msgs.append({"role": "user", "content": user_msg}) msgs.append({"role": "assistant", "content": plan_msg, "tool_calls": [{"id": "c0", "type": "function", "function": {"name": "mcp_call", "arguments": json.dumps({"toolName": tool_name, "arguments": args})}}]}) msgs.append({"role": "tool", "tool_call_id": "c0", "content": resp}) for i in range(repeats): cid = f"r{i+1}" msgs.append({"role": "assistant", "content": None, "tool_calls": [{"id": cid, "type": "function", "function": {"name": "mcp_call", "arguments": json.dumps({"toolName": tool_name, "arguments": args})}}]}) msgs.append({"role": "tool", "tool_call_id": cid, "content": resp}) return msgs cases.append({ "id": "L4g_hard_mcp_press_16", "family": "L4g_hard_induction", "tools": mcp_wrapper_tools, "messages": _mk_hard_wrapper_history( "繼續遊戲,硬落直到結束驗證結算畫面。", "暫停正常。繼續遊戲,硬落直到結束驗證結算畫面。", "mcp__browser__press_key", {"key": " ", "pageId": 2}, "Successfully pressed key: ", repeats=16, add_filler=True, ), "forbidden_call": ("mcp_call", {"toolName": "mcp__browser__press_key", "arguments": {"key": " ", "pageId": 2}}), "expected_behavior": "break_induction_lock", }) cases.append({ "id": "L4g_hard_mcp_click_16", "family": "L4g_hard_induction", "tools": mcp_wrapper_tools, "messages": _mk_hard_wrapper_history( "Keep clicking Load More until all records are loaded, then count them.", "Clicking Load More until done.", "mcp__browser__click", {"uid": "btn_more", "pageId": 1}, "Successfully clicked element btn_more", repeats=16, add_filler=True, ), "forbidden_call": ("mcp_call", {"toolName": "mcp__browser__click", "arguments": {"uid": "btn_more", "pageId": 1}}), "expected_behavior": "break_induction_lock", }) cases.append({ "id": "L4g_hard_poll_14", "family": "L4g_hard_induction", "tools": ci_tools, "messages": _mk_repeated_history( "You are a DevOps assistant.", "Keep checking build run_9912 until it finishes.", "check_build_status", {"run_id": "run_9912"}, '{"run_id":"run_9912","status":"running","progress_pct":67}', repeats=14, ), "forbidden_call": ("check_build_status", {"run_id": "run_9912"}), "expected_behavior": "break_induction_lock", }) cases.append({ "id": "L4g_hard_sim_14", "family": "L4g_hard_induction", "tools": sim_tools, "messages": _mk_repeated_history( "You are a simulation engineer.", "Step the solver until steady state.", "sim_step", {"ticks": 1}, "Advanced 1 tick.", repeats=14, ), "forbidden_call": ("sim_step", {"ticks": 1}), "expected_behavior": "break_induction_lock", }) cases.append({ "id": "L4g_hard_bash_ping_14", "family": "L4g_hard_induction", "tools": [ _tool("Bash", "Run a bash command.", {"command": {"type": "string"}}, ["command"]), ], "messages": _mk_repeated_history( "You are an SRE checking service readiness.", "Wait until port 9090 responds healthy.", "Bash", {"command": "curl -s http://127.0.0.1:9090/health"}, "curl: (7) Failed to connect to 127.0.0.1 port 9090: Connection refused", repeats=14, ), "forbidden_call": ("Bash", {"command": "curl -s http://127.0.0.1:9090/health"}), "expected_behavior": "break_induction_lock", }) cases.append({ "id": "L4g_hard_press_e00_14", "family": "L4g_hard_induction", "effort": 0.0, "tools": mcp_wrapper_tools, "messages": _mk_hard_wrapper_history( "Drop pieces until game over and check the final score.", "Dropping pieces until game over.", "mcp__browser__press_key", {"key": " ", "pageId": 1}, "Successfully pressed key: ", repeats=14, add_filler=True, ), "forbidden_call": ("mcp_call", {"toolName": "mcp__browser__press_key", "arguments": {"key": " ", "pageId": 1}}), "expected_behavior": "break_induction_lock", }) # ---- NEG: 5 Legitimate Multi-Step Negative Controls (MUST continue calling next tool!) ---- neg_page_tools = [ _tool("fetch_page", "Fetch page N of results.", {"page": {"type": "integer"}}, ["page"]), ] cases.append({ "id": "NEG_paginated_progress", "family": "NEG_control", "tools": neg_page_tools, "messages": [ {"role": "system", "content": "You are a data collector. Fetch all pages before summarizing."}, {"role": "user", "content": "Fetch all 3 pages of the report and compute the sum of values."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "fetch_page", "arguments": '{"page": 1}'}}]}, {"role": "tool", "tool_call_id": "c1", "content": '{"page":1,"total_pages":3,"values":[10,20]}'}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "fetch_page", "arguments": '{"page": 2}'}}]}, {"role": "tool", "tool_call_id": "c2", "content": '{"page":2,"total_pages":3,"values":[30,40]}'}, ], "must_call_tool": "fetch_page", "must_have_arg_substr": "3", }) neg_file_tools = [ _tool("read_file", "Read a file.", {"path": {"type": "string"}}, ["path"]), ] cases.append({ "id": "NEG_read_next_file", "family": "NEG_control", "tools": neg_file_tools, "messages": [ {"role": "system", "content": "You are a code reviewer."}, {"role": "user", "content": "Read a.py, b.py, and c.py, then compare their exported functions."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "read_file", "arguments": '{"path": "a.py"}'}}]}, {"role": "tool", "tool_call_id": "c1", "content": "def alpha(): return 1"}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "read_file", "arguments": '{"path": "b.py"}'}}]}, {"role": "tool", "tool_call_id": "c2", "content": "def beta(): return 2"}, ], "must_call_tool": "read_file", "must_have_arg_substr": "c.py", }) neg_key_tools = [ _tool("press_key", "Send a keyboard key to the page.", {"key": {"type": "string"}}, ["key"]), _tool("take_screenshot", "Capture screenshot.", {}), ] cases.append({ "id": "NEG_distinct_key_checklist", "family": "NEG_control", "tools": neg_key_tools, "messages": [ {"role": "system", "content": "You are a QA tester testing each requested key once in order."}, {"role": "user", "content": "Test ArrowLeft, ArrowRight, and KeyP in sequence, then take a screenshot."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "ArrowLeft"}'}}]}, {"role": "tool", "tool_call_id": "c1", "content": "Pressed ArrowLeft"}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "ArrowRight"}'}}]}, {"role": "tool", "tool_call_id": "c2", "content": "Pressed ArrowRight"}, ], "must_call_tool": "press_key", "must_have_arg_substr": "KeyP", }) neg_poll_progress_tools = [ _tool("check_upload", "Check upload progress.", {"id": {"type": "string"}}, ["id"]), ] cases.append({ "id": "NEG_progressing_upload", "family": "NEG_control", "tools": neg_poll_progress_tools, "messages": [ {"role": "system", "content": "You are monitoring an active file upload that is making steady progress."}, {"role": "user", "content": "Check upload up_7 until it completes (100%)."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "check_upload", "arguments": '{"id": "up_7"}'}}]}, {"role": "tool", "tool_call_id": "c1", "content": '{"id":"up_7","pct":40,"status":"uploading"}'}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "check_upload", "arguments": '{"id": "up_7"}'}}]}, {"role": "tool", "tool_call_id": "c2", "content": '{"id":"up_7","pct":85,"status":"uploading"}'}, ], "must_call_tool": "check_upload", "must_have_arg_substr": "up_7", }) # Legitimate check-then-continue: screenshot confirms game is STILL active (NOT Game Over), # so continuing to drop pieces (press_key OR evaluate_script) is the RIGHT behavior! cases.append({ "id": "NEG_check_then_continue_drop", "family": "NEG_control", "tools": browser_tools, "messages": [ {"role": "system", "content": "You are a web QA agent testing an HTML5 game in a browser."}, {"role": "user", "content": "Drop pieces with Space until the game ends, checking progress periodically, then report the Game Over score."}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]}, {"role": "tool", "tool_call_id": "c1", "content": "Successfully pressed key: Space"}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c2", "type": "function", "function": {"name": "press_key", "arguments": '{"key": "Space"}'}}]}, {"role": "tool", "tool_call_id": "c2", "content": "Successfully pressed key: Space"}, {"role": "assistant", "content": None, "tool_calls": [{"id": "c3", "type": "function", "function": {"name": "take_screenshot", "arguments": "{}"}}]}, {"role": "tool", "tool_call_id": "c3", "content": "Screenshot captured: Game STILL ACTIVE (status=PLAYING, stack height 10/20, score 110, NOT Game Over yet)."}, ], "must_call_any": ["press_key", "evaluate_script"], }) return cases def build_live_sim_cases() -> list[dict]: """L4f: 4 live multi-turn simulations (up to 10 turns) where user asks to 'keep doing X until done'.""" return [ { "id": "L4f_live_tetris_drop", "family": "L4f_live_multiturn", "system": "You are a browser QA agent verifying an HTML5 Tetris game.", "user": "The game is currently running. Repeatedly hard-drop pieces with Space until Game Over, then verify the Game Over overlay is visible and report the final score.", "tools": [ _tool("press_key", "Send a single keyboard key press to the browser.", {"key": {"type": "string"}}, ["key"]), _tool("take_screenshot", "Capture current screen state.", {}), _tool("evaluate_script", "Execute JavaScript in the page (can run loops or inspect game state).", {"script": {"type": "string"}}, ["script"]), ], "blind_tool": "press_key", "respond": lambda name, args, st: ( "Successfully pressed key: " + str(args.get("key", "")) if name == "press_key" else ( "Game Over overlay visible! Title: GAME OVER, Final Score: 240, Restart button ready." if st["steps"] >= 2 or name == "evaluate_script" else "Game active: stack height 14/20, score 180." ) ), }, { "id": "L4f_live_wait_deploy", "family": "L4f_live_multiturn", "system": "You are an SRE verifying a newly deployed microservice.", "user": "Keep checking /health until the service is ready; if it is stuck failing, diagnose the reason from logs and report back.", "tools": [ _tool("check_health", "GET /health endpoint.", {}), _tool("get_container_logs", "Fetch last 50 lines of container logs.", {}), ], "blind_tool": "check_health", "respond": lambda name, args, st: ( "HTTP 503: connection refused" if name == "check_health" else "FATAL: missing required env var DATABASE_URL — process exited with code 1" ), }, { "id": "L4f_live_scroll_catalog", "family": "L4f_live_multiturn", "system": "You are a browser data-extraction agent.", "user": "Keep scrolling down the product catalog until all items load, then report how many products exist.", "tools": [ _tool("scroll_down", "Scroll down 600px.", {}), _tool("evaluate_script", "Run JS in page to inspect scrollHeight / item count or scroll in a loop.", {"script": {"type": "string"}}, ["script"]), _tool("get_page_status", "Return current scroll position and loaded item count.", {}), ], "blind_tool": "scroll_down", "respond": lambda name, args, st: ( "Scrolled down 600px." if name == "scroll_down" else '{"at_bottom": true, "loaded_items": 48, "footer_visible": true}' ), }, { "id": "L4f_live_click_retry_btn", "family": "L4f_live_multiturn", "system": "You are a frontend QA tester.", "user": "Keep clicking the 'Sync Now' button until the sync finishes, then report the sync result.", "tools": [ _tool("click_sync", "Click the 'Sync Now' button.", {}), _tool("inspect_network", "Inspect recent failed/succeeded network requests.", {}), _tool("get_ui_banner", "Read current status/error banner text in the UI.", {}), ], "blind_tool": "click_sync", "respond": lambda name, args, st: ( "Clicked 'Sync Now'." if name == "click_sync" else "POST /api/sync -> 403 Forbidden (API token expired); UI banner: 'Sync failed: session expired, please re-authenticate.'" ), }, ] def _call_chat(base: str, model: str, messages: list[dict], tools: list[dict], effort: float = 0.7) -> dict: body = { "model": model, "messages": messages, "tools": tools, "temperature": 0.0, "top_p": 1.0, "max_tokens": 2048, "chat_template_kwargs": {"reasoning_effort": effort}, } req = urllib.request.Request( f"{base.rstrip('/')}/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}, ) with urllib.request.urlopen(req, timeout=180) as r: return json.loads(r.read()) def _parse_args(raw) -> dict: if isinstance(raw, dict): return raw try: return json.loads(raw or "{}") except Exception: return {"_raw": str(raw)} def run_static_case(base: str, model: str, case: dict) -> dict: t0 = time.time() d = _call_chat(base, model, case["messages"], case["tools"], effort=case.get("effort", 0.7)) wall = round(time.time() - t0, 2) ch = d["choices"][0] msg = ch["message"] tcs = msg.get("tool_calls") or [] parsed = [(tc["function"]["name"], _parse_args(tc["function"].get("arguments"))) for tc in tcs] content = (msg.get("content") or "").strip() if case["family"] == "NEG_control": if "must_call_any" in case: allowed = set(case["must_call_any"]) ok = any(n in allowed for n, _ in parsed) reason = "ok" if ok else f"prematurely stopped, expected any of {sorted(allowed)}, got={parsed}" else: want_tool = case["must_call_tool"] want_sub = case["must_have_arg_substr"] ok = any(n == want_tool and want_sub in json.dumps(a, ensure_ascii=False) for n, a in parsed) reason = "ok" if ok else f"missed expected ({want_tool} with {want_sub}), got={parsed}" else: forb_name, forb_args = case["forbidden_call"] # Fail if model emitted the exact forbidden repeated call OR emitted >=4 duplicate calls in one burst repeated_forb = any(n == forb_name and a == forb_args for n, a in parsed) burst_spam = len(parsed) >= 4 and len({(n, json.dumps(a, sort_keys=True)) for n, a in parsed}) == 1 # Also fail if empty response with 0 tool calls empty_fail = (len(parsed) == 0 and len(content) < 15) ok = (not repeated_forb) and (not burst_spam) and (not empty_fail) if repeated_forb: reason = f"LOOPED: repeated forbidden call {forb_name}({forb_args})" elif burst_spam: reason = f"BURST_SPAM: {len(parsed)} identical calls" elif empty_fail: reason = "EMPTY_FAIL: no tool call and empty answer" else: reason = f"broke_loop -> calls={[n for n, _ in parsed]} ans_chars={len(content)}" return { "id": case["id"], "family": case["family"], "ok": ok, "reason": reason, "calls": parsed, "content_head": content[:140].replace("\n", " "), "wall_s": wall, } def run_live_sim(base: str, model: str, sim: dict, max_turns: int = 10) -> dict: t0 = time.time() msgs = [ {"role": "system", "content": sim["system"]}, {"role": "user", "content": sim["user"]}, ] st = {"steps": 0} blind_streak = 0 max_blind_streak = 0 history = [] finished = False for turn in range(max_turns): d = _call_chat(base, model, msgs, sim["tools"]) msg = d["choices"][0]["message"] tcs = msg.get("tool_calls") or [] content = (msg.get("content") or "").strip() if not tcs: finished = len(content) >= 15 history.append({"turn": turn, "calls": [], "content_head": content[:120]}) break msgs.append({"role": "assistant", "content": msg.get("content"), "tool_calls": tcs}) turn_calls = [] for tc in tcs: fn = tc["function"]["name"] args = _parse_args(tc["function"].get("arguments")) turn_calls.append(fn) if fn == sim["blind_tool"]: st["steps"] += 1 blind_streak += 1 max_blind_streak = max(max_blind_streak, blind_streak) else: blind_streak = 0 resp = sim["respond"](fn, args, st) msgs.append({"role": "tool", "tool_call_id": tc["id"], "content": resp}) history.append({"turn": turn, "calls": turn_calls}) if max_blind_streak >= 5: break wall = round(time.time() - t0, 2) ok = finished and (max_blind_streak < 5) reason = ( f"ok turns={len(history)} max_blind_streak={max_blind_streak}" if ok else f"LOOPED/UNFINISHED finished={finished} turns={len(history)} max_blind_streak={max_blind_streak}" ) return { "id": sim["id"], "family": sim["family"], "ok": ok, "reason": reason, "max_blind_streak": max_blind_streak, "turns": len(history), "history": history, "wall_s": wall, } def main(): ap = argparse.ArgumentParser() ap.add_argument("--base", default="http://127.0.0.1:8088") ap.add_argument("--model", default="inkling-2-mini-unbound") ap.add_argument("--tag", required=True) ap.add_argument("--out", required=True) ap.add_argument("--concurrency", type=int, default=4) a = ap.parse_args() static_cases = build_static_cases() live_cases = build_live_sim_cases() with concurrent.futures.ThreadPoolExecutor(max_workers=a.concurrency) as ex: recs = list(ex.map(lambda c: run_static_case(a.base, a.model, c), static_cases)) for sim in live_cases: recs.append(run_live_sim(a.base, a.model, sim)) by_fam = {} for r in recs: by_fam.setdefault(r["family"], []).append(r) print(f" [{a.tag}] {r['id']:26s} ok={str(r['ok']):5s} {r['reason']}", flush=True) loop_recs = [r for r in recs if r["family"] != "NEG_control"] neg_recs = [r for r in recs if r["family"] == "NEG_control"] lp_ok = sum(r["ok"] for r in loop_recs) ng_ok = sum(r["ok"] for r in neg_recs) fam_summary = { fam: f"{sum(x['ok'] for x in xs)}/{len(xs)}" for fam, xs in sorted(by_fam.items()) } summary = { "tag": a.tag, "loop_break_score": f"{lp_ok}/{len(loop_recs)}", "loop_break_pct": round(100.0 * lp_ok / len(loop_recs), 1), "neg_control_score": f"{ng_ok}/{len(neg_recs)}", "total_score": f"{lp_ok + ng_ok}/{len(recs)}", "by_family": fam_summary, "records": recs, } Path(a.out).parent.mkdir(parents=True, exist_ok=True) Path(a.out).write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8") print(f"\n=== [{a.tag}] TOOL-LOOP BREAK: {lp_ok}/{len(loop_recs)} ({summary['loop_break_pct']}%) | NEG CTRL: {ng_ok}/{len(neg_recs)} | TOTAL: {lp_ok+ng_ok}/{len(recs)} ===") print(" BY FAMILY:", fam_summary) if __name__ == "__main__": main()