diff --git a/docs/LESSONS_LEARNED.md b/docs/LESSONS_LEARNED.md index 95ba2d3..c03fdcd 100644 --- a/docs/LESSONS_LEARNED.md +++ b/docs/LESSONS_LEARNED.md @@ -800,6 +800,21 @@ diagnosis, because "ILSpy was never attached", "ILSpy was defeated" and "ILSpy was killed before it started" are indistinguishable downstream and all want the same answer: read the bytes. It fails toward pivoting. +**Follow-up (shipped): the governor now bounds tokens, not just executions.** +The validation run made the case better than the incident did. On the *same* +sample, with nothing failing and no cap reached, the workbench went from 49 +executions costing 5.19M tokens to **91 costing 11.6M** โ€” the run total doubling +from 7.7M to 18.3M. Peak context reached 228k, above the *old* 200k ceiling, so +the raise had gone from precaution to load-bearing in one run. + +So `run_python_budget_guard` gained a second axis: a token ceiling measured from +the workbench's *own* first script, so a sample with an expensive triage does not +arrive with its allowance already spent. It is a backstop rather than a routine +limit โ€” set above both observed healthy runs so it never truncates work that was +going to succeed, and below a further doubling so a genuine runaway stops. Both +measured runs are pinned as tests, because a ceiling that cuts short a good run +is a worse failure than the one it was written to prevent. + **Lesson:** A resource governor must bound the resource that is actually scarce. Counting invocations is a proxy for cost, and a proxy that is wrong by two orders of magnitude is not a bound at all โ€” it is a number that makes everyone feel diff --git a/src/reverse_engineering/tools/workbench/budget.py b/src/reverse_engineering/tools/workbench/budget.py index 9a91127..adb31a7 100644 --- a/src/reverse_engineering/tools/workbench/budget.py +++ b/src/reverse_engineering/tools/workbench/budget.py @@ -2,10 +2,27 @@ This is the second, loop-level layer of the ยง4.5 two-layer governor. The first layer is enforced by the sandbox itself (per-exec timeout, memory cgroup, output -cap); this layer bounds *how many* times the agent may run a script at all, across -the whole case. The count is a **global** session-state counter so it spans every -deobfuscation-loop round rather than resetting per iteration -- a hard sample that -nests many packer layers cannot escape the cap by re-entering the loop. +cap); this layer bounds what the agent may spend across the whole case, along +**two** axes: + +* *how many* scripts it may run, and +* *what those scripts cost in tokens*. + +Both counters are **global** session state so they span every deobfuscation-loop +round rather than resetting per iteration -- a hard sample that nests many packer +layers cannot escape either cap by re-entering the loop. + +The token axis exists because the count alone was a proxy that was wrong by two +orders of magnitude. Measured on one sample across two runs: 49 executions cost +5.19M tokens, then 91 cost 11.6M. Neither hit the 100-execution cap, and the +second still doubled. What ends a run is not the number of scripts but the +conversation they grow, which every later stage inherits -- LESSONS_LEARNED #20 +records the ILSpy stage being killed before its first tool call for exactly this +reason, while the stage that had spent the budget looked perfectly successful. + +The token budget is measured from this stage's own first script, not from the +start of the run, so a sample with an expensive triage does not arrive at the +workbench with its allowance already gone. It is wired as a ``before_tool`` callback on ``run_python``: ADK invokes it before the tool runs, so once the cap is reached the guard returns a short-circuit result @@ -19,17 +36,54 @@ from typing import TYPE_CHECKING +from arema.runtime.sessions import SessionKeys from reverse_engineering.tools.workbench.state import ( RUN_PYTHON_TOOL_NAME, WORKBENCH_EXEC_COUNT_KEY, WORKBENCH_MAX_EXECUTIONS, + WORKBENCH_MAX_TOKENS, + WORKBENCH_TOKEN_BASELINE_KEY, ) if TYPE_CHECKING: + from collections.abc import Callable + from google.adk.tools.base_tool import BaseTool from google.adk.tools.tool_context import ToolContext +def _tokens_spent(getter: Callable[..., object]) -> int: + """Total tokens this run has accumulated so far, or 0 when unknown. + + Reads the same accumulator the usage report renders from + (``SessionKeys.MODEL_USAGE``), so the governor and the report can never + disagree about what a run cost. Degrades to 0 rather than raising: a budget + that cannot read usage must let work through, never block it. + """ + acc = getter(SessionKeys.MODEL_USAGE, None) + if not isinstance(acc, dict): + return 0 + by_model = acc.get("by_model") + if not isinstance(by_model, dict): + return 0 + total = 0 + for row in by_model.values(): + if isinstance(row, dict): + total += sum(v for v in row.values() if isinstance(v, int) and not isinstance(v, bool)) + return total + + +def _exhausted_result(reason: str) -> dict[str, object]: + """A ``run_python``-shaped result telling the agent to finalize, not retry.""" + return { + "exit_code": 1, + "stdout": "", + "stderr": f"run_python budget exhausted ({reason}); finalize the best artifact you have and report.", + "truncated": False, + "spilled_artifact_id": "", + } + + def run_python_budget_guard( tool: BaseTool, args: dict[str, object], tool_context: ToolContext ) -> dict[str, object] | None: @@ -57,15 +111,18 @@ def run_python_budget_guard( raw_used = getter(WORKBENCH_EXEC_COUNT_KEY) used = raw_used if isinstance(raw_used, int) and not isinstance(raw_used, bool) else 0 if used >= WORKBENCH_MAX_EXECUTIONS: - return { - "exit_code": 1, - "stdout": "", - "stderr": ( - f"run_python budget exhausted ({WORKBENCH_MAX_EXECUTIONS} executions); " - "finalize the best artifact you have and report." - ), - "truncated": False, - "spilled_artifact_id": "", - } + return _exhausted_result(f"{WORKBENCH_MAX_EXECUTIONS} executions") + + # The token ceiling, measured from this stage's own first script rather than + # from the start of the run -- an expensive triage must not spend the + # workbench's allowance before it has run anything. + spent = _tokens_spent(getter) + raw_baseline = getter(WORKBENCH_TOKEN_BASELINE_KEY) + if isinstance(raw_baseline, int) and not isinstance(raw_baseline, bool): + if spent - raw_baseline >= WORKBENCH_MAX_TOKENS: + return _exhausted_result(f"{WORKBENCH_MAX_TOKENS:,} tokens") + else: + setter(WORKBENCH_TOKEN_BASELINE_KEY, spent) + setter(WORKBENCH_EXEC_COUNT_KEY, used + 1) return None diff --git a/src/reverse_engineering/tools/workbench/state.py b/src/reverse_engineering/tools/workbench/state.py index 6ad9c74..0fed9fa 100644 --- a/src/reverse_engineering/tools/workbench/state.py +++ b/src/reverse_engineering/tools/workbench/state.py @@ -18,6 +18,24 @@ # bounding a runaway. WORKBENCH_MAX_EXECUTIONS = 100 +# Tokens spent since the workbench's first script, and the ceiling on them. +# +# The execution cap above bounds how MANY scripts run and says nothing about what +# they cost, which is a proxy that was wrong by two orders of magnitude. Measured +# on one sample across two runs: 49 executions cost 5.19M tokens, then 91 cost +# 11.6M -- the second run hit no cap, broke nothing, and still doubled. What ends +# a run is not the count; it is that every later stage inherits the conversation +# these scripts grew, so an unbounded workbench starves the stages behind it (see +# LESSONS_LEARNED #20, where the ILSpy stage was killed before its first call). +# +# The ceiling is a backstop, not a routine limit: it sits above both observed +# healthy runs so it never truncates work that was going to succeed, and below +# the next doubling so a genuine runaway stops. A baseline is snapshotted at the +# first script so this measures the workbench's OWN spend, not a run that merely +# had an expensive triage. +WORKBENCH_TOKEN_BASELINE_KEY = "workbench:token_baseline" +WORKBENCH_MAX_TOKENS = 16_000_000 + # The workbench tool ids, kept beside the other workbench constants as the single # source of truth: the SanitizationMembrane's binary-origin set (``profiles.py``) # and the per-tool budget guard (``budget.py``) both import them rather than diff --git a/tests/reverse_engineering/test_workbench_budget.py b/tests/reverse_engineering/test_workbench_budget.py index cdd10e1..3b9074c 100644 --- a/tests/reverse_engineering/test_workbench_budget.py +++ b/tests/reverse_engineering/test_workbench_budget.py @@ -12,10 +12,13 @@ from __future__ import annotations +from arema.runtime.sessions import SessionKeys from reverse_engineering.tools.workbench.budget import run_python_budget_guard from reverse_engineering.tools.workbench.state import ( WORKBENCH_EXEC_COUNT_KEY, WORKBENCH_MAX_EXECUTIONS, + WORKBENCH_MAX_TOKENS, + WORKBENCH_TOKEN_BASELINE_KEY, ) @@ -134,3 +137,117 @@ def test_workbench_tools_are_sanitized() -> None: from reverse_engineering.profiles import _BINARY_ORIGIN_TOOLS assert {"run_python", "register_unpacked_artifact"} <= _BINARY_ORIGIN_TOOLS + + +# --- the token axis ----------------------------------------------------------- +# +# The execution cap counts scripts and says nothing about what they cost, which +# is a proxy that was wrong by two orders of magnitude. Measured on one sample +# across two runs: 49 executions cost 5.19M tokens, then 91 cost 11.6M. Neither +# hit the 100-execution cap. What ends a run is the conversation those scripts +# grow, which every later stage inherits -- LESSONS_LEARNED #20. + + +def _usage(total: int) -> dict[str, object]: + """A MODEL_USAGE accumulator carrying `total` tokens, in the real shape.""" + return { + "run_id": "r1", + "by_model": {"m": {"input": total, "cached": 0, "output": 0, "thinking": 0}}, + } + + +def _ctx(state: _State) -> object: + return type("C", (), {"state": state})() + + +_TOOL = type("T", (), {"name": "run_python"})() + + +def test_the_first_script_snapshots_a_baseline_rather_than_charging_the_run() -> None: + """An expensive triage must not arrive at the workbench having already spent + its allowance -- the ceiling measures this stage's own work.""" + state = _State({SessionKeys.MODEL_USAGE: _usage(3_000_000)}) + + assert run_python_budget_guard(_TOOL, {}, _ctx(state)) is None + assert state[WORKBENCH_TOKEN_BASELINE_KEY] == 3_000_000 + + +def test_spend_below_the_ceiling_proceeds() -> None: + state = _State({SessionKeys.MODEL_USAGE: _usage(1_000_000)}) + run_python_budget_guard(_TOOL, {}, _ctx(state)) # baseline at 1M + + state[SessionKeys.MODEL_USAGE] = _usage(1_000_000 + WORKBENCH_MAX_TOKENS - 1) + + assert run_python_budget_guard(_TOOL, {}, _ctx(state)) is None + + +def test_spend_at_the_ceiling_short_circuits() -> None: + state = _State({SessionKeys.MODEL_USAGE: _usage(1_000_000)}) + run_python_budget_guard(_TOOL, {}, _ctx(state)) + + state[SessionKeys.MODEL_USAGE] = _usage(1_000_000 + WORKBENCH_MAX_TOKENS) + blocked = run_python_budget_guard(_TOOL, {}, _ctx(state)) + + assert blocked is not None + assert "tokens" in str(blocked["stderr"]) + assert "finalize" in str(blocked["stderr"]) + + +def test_the_token_block_matches_run_python_result_shape() -> None: + """A before_tool return value IS the tool response, so a wrong shape would + reach the model as a malformed result rather than an advisory.""" + state = _State({SessionKeys.MODEL_USAGE: _usage(0)}) + run_python_budget_guard(_TOOL, {}, _ctx(state)) + state[SessionKeys.MODEL_USAGE] = _usage(WORKBENCH_MAX_TOKENS) + blocked = run_python_budget_guard(_TOOL, {}, _ctx(state)) + + assert set(blocked) == {"exit_code", "stdout", "stderr", "truncated", "spilled_artifact_id"} + assert blocked["exit_code"] == 1 + + +def test_both_observed_healthy_runs_stay_under_the_ceiling() -> None: + """The ceiling is a backstop, not a routine limit. Truncating work that was + going to succeed would be a worse failure than the one being fixed.""" + for measured in (5_190_000, 11_642_265): + state = _State({SessionKeys.MODEL_USAGE: _usage(0)}) + run_python_budget_guard(_TOOL, {}, _ctx(state)) + state[SessionKeys.MODEL_USAGE] = _usage(measured) + + assert run_python_budget_guard(_TOOL, {}, _ctx(state)) is None, measured + + +def test_a_runaway_beyond_the_next_doubling_is_stopped() -> None: + """11.6M doubling again is the case this exists for.""" + state = _State({SessionKeys.MODEL_USAGE: _usage(0)}) + run_python_budget_guard(_TOOL, {}, _ctx(state)) + state[SessionKeys.MODEL_USAGE] = _usage(11_642_265 * 2) + + assert run_python_budget_guard(_TOOL, {}, _ctx(state)) is not None + + +def test_unreadable_usage_lets_work_through_rather_than_blocking_it() -> None: + """A governor that cannot read usage must fail open. Blocking on missing + telemetry would turn an observability gap into a stalled analysis.""" + for acc in (None, "junk", {}, {"by_model": "junk"}, {"by_model": {"m": "junk"}}): + state = _State({SessionKeys.MODEL_USAGE: acc}) + assert run_python_budget_guard(_TOOL, {}, _ctx(state)) is None + + +def test_the_execution_cap_still_applies_independently() -> None: + """Two axes, either of which can stop the stage.""" + state = _State( + {SessionKeys.MODEL_USAGE: _usage(0), WORKBENCH_EXEC_COUNT_KEY: WORKBENCH_MAX_EXECUTIONS} + ) + blocked = run_python_budget_guard(_TOOL, {}, _ctx(state)) + + assert blocked is not None + assert "executions" in str(blocked["stderr"]) + + +def test_a_foreign_tool_neither_charges_nor_snapshots() -> None: + state = _State({SessionKeys.MODEL_USAGE: _usage(9_000_000)}) + other = type("T", (), {"name": "ghidra_decompile"})() + + assert run_python_budget_guard(other, {}, _ctx(state)) is None + assert WORKBENCH_TOKEN_BASELINE_KEY not in state + assert WORKBENCH_EXEC_COUNT_KEY not in state