The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(review): bound same-model background review replay
Finn7634202a508fdd9
diff --git a/agent/background_review.py b/agent/background_review.pyindex f79a01959db..fffa9028929 100644--- a/agent/background_review.py+++ b/agent/background_review.py@@ -204,6 +204,21 @@ def cancel_background_review_for_live_turn(agent: Any) -> None:# Historical hardcoded iteration budget for the review fork._REVIEW_MAX_ITERATIONS = 16+# Default aggregate INPUT-token budget for one review fork (#93057). The+# fork's first request replays the full snapshot — a warm prompt-cache read+# that is cheap and intended (cache parity). After that, detached in-memory+# compaction bounds each request to roughly the compression threshold, but+# nothing capped the SUM across the review's tool loop: one production+# review made 8 requests replaying 1,487,951 input tokens total (four of+# them at 350k-384k). This budget caps the aggregate; the review tool loop+# stops before the provider call that would cross it (see+# ``_review_input_budget_exhausted`` in agent/conversation_loop.py).+# 2x the historical 300k foreground trigger keeps legitimate reviews+# comfortable while capping the pathological case. Override with+# ``auxiliary.background_review.max_input_tokens``; 0 or a negative value+# disables the cap (unbounded = pre-fix behavior).+_REVIEW_MAX_INPUT_TOKENS_DEFAULT = 600_000+def _background_review_task_config(task_cfg: Optional[Dict[str, Any]] = None,@@ -226,6 +241,26 @@ def _background_review_task_config(return task if isinstance(task, dict) else {}+def _review_input_token_budget(+ task_cfg: Optional[Dict[str, Any]] = None,+) -> Optional[int]:+ """Aggregate input-token budget for one review fork (None = unlimited).++ Reads ``auxiliary.background_review.max_input_tokens``; falls back to+ :data:`_REVIEW_MAX_INPUT_TOKENS_DEFAULT`. ``0`` or a negative value+ disables the cap explicitly.+ """+ task = _background_review_task_config(task_cfg)+ raw = task.get("max_input_tokens", _REVIEW_MAX_INPUT_TOKENS_DEFAULT)+ try:+ budget = int(raw)+ except (TypeError, ValueError):+ budget = _REVIEW_MAX_INPUT_TOKENS_DEFAULT+ if budget <= 0:+ return None+ return budget++def load_background_review_settings() -> tuple[bool, Dict[str, Any]]:"""Single config read for the automatic-review gate + task block.@@ -1273,17 +1308,61 @@ def _run_review_in_thread(# conversation (the review fires every ~10 turns). Leave session# finalization to the real owner (CLI close / gateway reset / cron).review_agent._end_session_on_close = False- # Never let the review fork compress. It shares the parent's- # session_id, so if it won a compression race it would rotate the- # parent into a NEW child that the gateway never adopts (the fork- # is single-lifecycle and dies right after this run_conversation).- # The foreground turn would then start from the stale parent and- # compress it again, leaving the same parent with two sibling- # children (issue #38727). Review also needs full context to- # produce a good memory/skill summary — compressing would strip- # detail. Both compression triggers in conversation_loop.py gate on- # agent.compression_enabled, so this short-circuits both paths.- review_agent.compression_enabled = False+ # DETACHED IN-MEMORY COMPACTION (issue #93057). The fork shares+ # the parent's session_id (pinned above for prefix-cache parity),+ # so the historical guard here was ``compression_enabled = False``:+ # if the fork ran the ordinary compression path it could rotate /+ # archive the parent's live session — the sibling-session race+ # behind #38727. But disabling compaction was a proxy for+ # detachment, and it removed the ONLY bound on the review's+ # private snapshot: as the review performs tool calls, every+ # follow-up provider request replayed the snapshot plus the+ # growing review tool loop (350k-384k input tokens per request in+ # production, 1.49M total across one 8-request review).+ #+ # The fix is detachment, not disablement:+ # • Persistence is already off above (_persist_disabled /+ # _session_db=None), so the commit site in compress_context+ # (``if agent._session_db:``) skips every durable write and+ # compaction can only ever rewrite the fork's private+ # in-memory transcript.+ # • The compressor's OWN session binding still needs severing:+ # AIAgent.__init__ bound it to the parent's SessionDB and+ # session_id before this function nulled the agent-level+ # binding, so durable cooldown/streak/ineffective-count+ # writes would otherwise land on the parent's row. Rebinding+ # with session_db=None / session_id="" makes every+ # compressor persist guard a no-op.+ # • Force in-place mode (never rotation) even if the parent's+ # config selected rotation, and re-enable compression so the+ # trigger gates in conversation_loop.py can fire.+ _review_compressor = getattr(review_agent, "context_compressor", None)+ _bind_review_compressor = getattr(+ _review_compressor, "bind_session_state", None+ )+ if callable(_bind_review_compressor):+ try:+ # Plugin/third-party context engines may not accept these+ # kwargs; they own their own persistence policy, so a+ # failed rebind leaves the pre-existing flags in place+ # and must never abort the review (same tolerance as the+ # init-time binding in agent_init.py).+ _bind_review_compressor(session_db=None, session_id="")+ except Exception:+ logger.debug(+ "background-review compressor detachment failed; "+ "keeping the engine's existing session binding",+ exc_info=True,+ )+ review_agent.compression_in_place = True+ review_agent.compression_enabled = True+ # Aggregate input budget: compaction bounds any single request;+ # this bounds the WHOLE review. Iterations are already capped by+ # _REVIEW_MAX_ITERATIONS. Checked in agent/conversation_loop.py+ # via _review_input_budget_exhausted (issue #93057).+ review_agent._review_input_token_budget = _review_input_token_budget(+ task_cfg+ )# Register this fork on the PARENT's _active_children (the same# list interrupt() fans out to for subagent delegation) anddiff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 200ddd22168..4f717cd835f 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -120,6 +120,26 @@ RUN_BUDGET_WRAPUP_NOTICE = ()+def _review_input_budget_exhausted(agent: Any) -> bool:+ """True when a detached review fork has replayed its aggregate input budget.++ Only forks carrying an explicit ``_review_input_token_budget`` (the+ background-review path, #93057) are gated; every other agent returns+ False and is unaffected. ``session_input_tokens`` accumulates from+ provider usage after each response, so the check fires at the top of the+ NEXT tool-loop iteration — the budget-crossing request is admitted and+ completes (its tool writes land), then the loop stops before any further+ provider call. This caps the review's total replayed input, complementing+ the per-request bound provided by detached in-memory compaction and the+ ``_REVIEW_MAX_ITERATIONS`` iteration cap.+ """+ budget = getattr(agent, "_review_input_token_budget", None)+ if not isinstance(budget, int) or isinstance(budget, bool) or budget <= 0:+ return False+ used = getattr(agent, "session_input_tokens", 0)+ return isinstance(used, int) and not isinstance(used, bool) and used >= budget++def _maybe_inject_run_budget_wrapup(agent: Any, messages: List[Dict[str, Any]]) -> bool:"""Inject the one-time wall-clock wrap-up notice when past 80% of budget.@@ -2014,6 +2034,21 @@ def run_conversation(if not agent.quiet_mode:agent._safe_print("\n⚡ Breaking out of tool loop due to interrupt...")break++ # Aggregate input budget for detached auxiliary forks (background+ # review, #93057): compaction bounds each request; this bounds the+ # review as a whole. Fires between iterations — the budget-crossing+ # request completed (its tool writes landed), and the tool loop stops+ # before the next provider call, mirroring the iteration-budget exit.+ if _review_input_budget_exhausted(agent):+ _turn_exit_reason = "review_input_budget_exhausted"+ if not agent.quiet_mode:+ agent._safe_print(+ f"\n⏹️ Review input budget exhausted "+ f"({int(agent.session_input_tokens):,} tokens) — stopping "+ f"the review tool loop before the next provider call."+ )+ breakapi_call_count += 1agent._api_call_count = api_call_countdiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 6c6f11f7449..61e8edc24d9 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1266,6 +1266,13 @@ DEFAULT_CONFIG = {"timeout": 120,"extra_body": {},"reasoning_effort": "", # per-task thinking level: none|minimal|low|medium|high|xhigh|max|ultra (empty = provider default)+ # Aggregate INPUT-token budget for one review fork (issue #93057).+ # The fork compacts an oversized snapshot in memory before further+ # provider calls; this caps the SUM of input tokens replayed+ # across the whole review tool loop (iterations are separately+ # capped at 16). The loop stops before the provider call that+ # would cross the budget. 0 or a negative value = unlimited.+ "max_input_tokens": 600000,},"moa_reference": {"provider": "auto",diff --git a/tests/agent/test_compression_concurrent_fork.py b/tests/agent/test_compression_concurrent_fork.pyindex b0100c5ed33..d9fc1c82deb 100644--- a/tests/agent/test_compression_concurrent_fork.py+++ b/tests/agent/test_compression_concurrent_fork.py@@ -36,6 +36,7 @@ import sqlite3import threadingimport timefrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport pytest@@ -1188,74 +1189,190 @@ def test_real_lock_api_internal_errors_fail_closed_skips_compression(-def test_review_fork_disables_compression_to_prevent_stale_parent_fork(tmp_path: Path) -> None:- """The background-review fork must set ``compression_enabled = False``- so it can never compress the parent it shares a session_id with- (issue #38727).+def test_review_fork_compacts_oversized_snapshot_in_memory(tmp_path: Path) -> None:+ """An oversized review snapshot compacts in memory without mutating the parent.- The per-session compression lock only serialises a SAME-WINDOW concurrent- race. It does NOT stop a stale parent from being compressed again in a- LATER turn: if ``review_agent`` had won the race, its new child session is- never adopted by the gateway (the fork is single-lifecycle and dies right- after one ``run_conversation``), so the foreground path would start the- next turn from the stale parent and compress it AGAIN — leaving the same- parent with two sibling children.+ Regression for #93057: the fork historically pinned ``compression_enabled =+ False`` because it shares the parent's session_id (issue #38727). That+ left the review's private snapshot unbounded — every follow-up request in+ the review tool loop replayed the whole snapshot (350k-384k input tokens+ per request in production). The fix detaches the fork's compressor from+ the parent's SessionDB/session_id and enables in-memory-only compaction.- The fix makes the review fork never trigger compression at all. Both- compression trigger sites in ``agent/conversation_loop.py`` gate on- ``agent.compression_enabled`` BEFORE calling ``_compress_context``:- • preflight (``if agent.compression_enabled and len(messages) > ...``)- • mid-loop (``if agent.compression_enabled and _compressor.should_compress(...)``)- so a fork with the flag cleared never reaches the rotation path.-- This test pins the contract at the source: ``_run_review_in_thread``- must set ``review_agent.compression_enabled = False`` on the fork it- builds. It calls the real worker synchronously with- ``AIAgent.run_conversation`` patched (so no LLM call happens) and- captures the constructed review agent to assert the flag.+ This test drives the REAL ``_run_review_in_thread`` + ``run_conversation``+ with a threshold-crossing snapshot and asserts:+ • compression actually fired (a real threshold crossing, not just+ construction-time flag state);+ • the outbound provider request carries the compaction summary and none+ of the middle snapshot turns;+ • the fork keeps the parent's session_id (prompt-cache parity) but its+ agent-level AND compressor-level session bindings are detached;+ • the parent's durable transcript, session row, and child-session graph+ are byte-for-byte unchanged after the compaction ran."""import agent.background_review as br- captured = {}-- def _fake_run_conversation(self, *_a, **_k):- captured["compression_enabled"] = self.compression_enabled- captured["session_id"] = self.session_id- return {"final_response": "", "messages": []}-- parent_sid = "REVIEW_FORK_FLAG_TEST"+ parent_sid = "REVIEW_FORK_IN_MEMORY_COMPACTION_93057"db = SessionDB(db_path=tmp_path / "state.db")db.create_session(parent_sid, source="discord")+ db.append_message(parent_sid, role="user", content="durable parent turn")+ durable_before = db.get_messages(parent_sid)+ session_row_before = tuple(+ db._conn.execute(+ "SELECT id, parent_session_id, ended_at, end_reason FROM sessions WHERE id = ?",+ (parent_sid,),+ ).fetchone()+ )parent = _build_agent_with_db(db, parent_sid)+ parent._cached_system_prompt = "stable parent prompt"- # The worker does a local ``from run_agent import AIAgent``; patching- # the class method covers that import path.+ snapshot = [+ {+ "role": "user" if i % 2 == 0 else "assistant",+ "content": f"review turn {i} " + "x" * 200,+ }+ for i in range(24)+ ]++ captured = {}++ def _final_response():+ return SimpleNamespace(+ choices=[+ SimpleNamespace(+ index=0,+ message=SimpleNamespace(+ role="assistant",+ content="review complete",+ tool_calls=None,+ reasoning_content=None,+ ),+ finish_reason="stop",+ )+ ],+ usage=SimpleNamespace(+ prompt_tokens=100, completion_tokens=10, total_tokens=110+ ),+ model="test/model",+ )++ # The worker does a local ``from run_agent import AIAgent``; patching the+ # class method covers that import path.from run_agent import AIAgent- with patch.object(AIAgent, "run_conversation", _fake_run_conversation):- br._run_review_in_thread(- parent,- [{"role": "user", "content": "hi"}],- "review this conversation",+ real_run_conversation = AIAgent.run_conversation++ def _run_threshold_crossing_review(self, *args, **kwargs):+ captured["compression_enabled"] = self.compression_enabled+ captured["compression_in_place"] = self.compression_in_place+ captured["session_id"] = self.session_id+ captured["session_db"] = self._session_db+ captured["input_budget"] = getattr(+ self, "_review_input_token_budget", "missing"+ )+ captured["compressor_session_db"] = getattr(+ self.context_compressor, "_session_db", "missing")+ captured["compressor_session_id"] = getattr(+ self.context_compressor, "_session_id", "missing"+ )+ # Stub the fork's compressor so compaction output is deterministic+ # and no aux-LLM call happens; the trigger/commit paths stay real.+ self.context_compressor.threshold_tokens = 1+ self.context_compressor.protect_first_n = 1+ self.context_compressor.protect_last_n = 1+ self.context_compressor.compress = MagicMock(+ return_value=[+ {"role": "user", "content": "[CONTEXT COMPACTION] review summary"},+ {"role": "assistant", "content": "summary acknowledged"},+ ]+ )+ self.context_compressor.should_compress = MagicMock(+ side_effect=lambda _tokens: True+ )+ self.context_compressor.should_compress_info = MagicMock(+ return_value=(True, "over threshold")+ )+ self.context_compressor.should_compress_preflight = MagicMock(+ return_value=True+ )+ self.context_compressor.should_defer_preflight_to_real_usage = MagicMock(+ return_value=False+ )+ self.context_compressor.get_active_compression_failure_cooldown = MagicMock(+ return_value=None+ )+ self.context_compressor.select_context = MagicMock(return_value=None)+ self._compression_feasibility_checked = True+ self.client = MagicMock()+ self.client.chat.completions.create.side_effect = [_final_response()]+ self._disable_streaming = True+ self._use_prompt_caching = False++ result = real_run_conversation(self, *args, **kwargs)+ captured["compression_calls"] = self.context_compressor.compress.call_count+ captured["create_calls"] = self.client.chat.completions.create.call_count+ last_call = self.client.chat.completions.create.call_args+ captured["outbound"] = (+ last_call.kwargs.get("messages") if last_call else None+ )+ return result- assert captured, (- "_run_review_in_thread never reached run_conversation — the spawn path "- "changed; update this test to capture the review AIAgent."- )- assert captured["session_id"] == parent_sid, (- "Review fork should inherit the parent's session_id (shared id is the "- "whole reason compression must be disabled)."- )- assert captured["compression_enabled"] is False, (- "FIX REGRESSION: background-review fork did NOT disable compression. "- "It shares the parent's session_id, so an enabled fork can rotate the "- "parent into an orphan child (issue #38727). The trigger gates in "- "conversation_loop.py only short-circuit when compression_enabled is "- "False — this flag MUST be cleared on the review fork."- )- db.close()+ try:+ with patch.object(AIAgent, "run_conversation", _run_threshold_crossing_review):+ br._run_review_in_thread(parent, snapshot, "review this conversation")++ assert captured["compression_calls"] >= 1, (+ "FIX REGRESSION: the review fork did not compact its oversized "+ "snapshot. compression_enabled was historically set False on the "+ "fork, which removed the only bound on the replayed snapshot "+ "(issue #93057)."+ )+ assert captured["create_calls"] >= 1+ outbound_contents = [+ str(m.get("content", "")) for m in captured["outbound"]+ ]+ assert any(+ "[CONTEXT COMPACTION] review summary" in text+ for text in outbound_contents+ ), f"outbound request did not contain the compaction summary: {outbound_contents!r}"+ assert not any("review turn 12" in text for text in outbound_contents), (+ "outbound request still replays the middle of the snapshot — "+ "the review replayed an unbounded transcript despite compaction"+ )+ assert captured["session_id"] == parent_sid, (+ "Review fork should inherit the parent's session_id for "+ "prompt-cache parity."+ )+ assert captured["session_db"] is None, (+ "Review fork must keep its agent-level SessionDB detached "+ "(_session_db=None) so compaction can never persist."+ )+ assert captured["compressor_session_db"] is None, (+ "Review fork's compressor must be detached from the parent "+ "SessionDB, otherwise durable cooldown/streak writes land on "+ "the parent's row (issue #93057)."+ )+ assert captured["compressor_session_id"] == ""+ assert captured["compression_enabled"] is True+ assert captured["compression_in_place"] is True+ assert isinstance(captured["input_budget"], int) and captured["input_budget"] > 0++ # Parent session must be byte-for-byte unchanged after the review+ # compacted its private snapshot.+ assert parent.session_id == parent_sid+ assert db.get_messages(parent_sid) == durable_before+ session_row_after = tuple(+ db._conn.execute(+ "SELECT id, parent_session_id, ended_at, end_reason FROM sessions WHERE id = ?",+ (parent_sid,),+ ).fetchone()+ )+ assert session_row_after == session_row_before+ assert _count_children(db, parent_sid) == 0+ finally:+ db.close()# ── Lease-refresher bounded-failure tolerance (salvage follow-up, #54465) ────diff --git a/tests/run_agent/test_background_review_input_budget.py b/tests/run_agent/test_background_review_input_budget.pynew file mode 100644index 00000000000..40a9ad279b8--- /dev/null+++ b/tests/run_agent/test_background_review_input_budget.py@@ -0,0 +1,239 @@+"""Regression tests for the background-review aggregate input budget (#93057).++The review fork replays its snapshot on every provider request in its tool+loop. Detached in-memory compaction bounds any SINGLE request; the aggregate+input budget (``_review_input_token_budget``, set by+``_run_review_in_thread`` from ``auxiliary.background_review.max_input_tokens``)+bounds the WHOLE review: the tool loop stops before the provider call that+would cross it, mirroring the iteration-budget exit.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from run_agent import AIAgent+++def _tool_call() -> SimpleNamespace:+ return SimpleNamespace(+ id="call_1",+ type="function",+ function=SimpleNamespace(name="web_search", arguments='{"query": "x"}'),+ )+++def _tool_response(prompt_tokens: int) -> SimpleNamespace:+ message = SimpleNamespace(+ content=None,+ reasoning_content=None,+ reasoning=None,+ tool_calls=[_tool_call()],+ )+ return SimpleNamespace(+ choices=[SimpleNamespace(message=message, finish_reason="tool_calls")],+ model="test/model",+ usage=SimpleNamespace(+ prompt_tokens=prompt_tokens,+ completion_tokens=1,+ total_tokens=prompt_tokens + 1,+ ),+ )+++def _final_response() -> SimpleNamespace:+ message = SimpleNamespace(+ content="done",+ reasoning_content=None,+ reasoning=None,+ tool_calls=None,+ )+ return SimpleNamespace(+ choices=[SimpleNamespace(message=message, finish_reason="stop")],+ model="test/model",+ usage=None,+ )+++def _tool_definition() -> dict:+ return {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web",+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ },+ }+++def _make_loop_agent():+ with (+ patch("run_agent.get_tool_definitions", return_value=[_tool_definition()]),+ patch("run_agent.check_toolset_requirements", return_value={}),+ patch("run_agent.OpenAI"),+ patch("agent.model_metadata.get_model_context_length", return_value=256_000),+ patch("agent.context_compressor.get_model_context_length", return_value=256_000),+ ):+ agent = AIAgent(+ api_key="test-key-1234567890",+ base_url="https://openrouter.ai/api/v1",+ model="test/model",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ max_iterations=10,+ )++ agent.client = MagicMock()+ agent._cached_system_prompt = "You are helpful."+ agent._use_prompt_caching = False+ agent._disable_streaming = True+ agent.tool_delay = 0+ agent.save_trajectories = False+ agent.max_compression_attempts = 1++ compressor = MagicMock()+ compressor.protect_first_n = 3+ compressor.protect_last_n = 20+ compressor.threshold_tokens = 999_999_999 # never fire compaction here+ compressor.context_length = 1_000_000_000+ compressor.last_prompt_tokens = -1+ compressor._verify_compaction_cleared_threshold = False+ compressor.awaiting_real_usage_after_compression = False+ compressor.should_compress.return_value = False+ compressor.should_compress_info.return_value = (False, None)+ compressor.should_compress_preflight.return_value = False+ compressor.should_defer_preflight_to_real_usage.return_value = False+ compressor.get_active_compression_failure_cooldown.return_value = None+ compressor.select_context.return_value = None+ compressor.get_automatic_compaction_status_message.return_value = ""+ agent.compression_enabled = False # isolate the budget behavior under test+ agent.context_compressor = compressor++ def _fake_execute_tool_calls(assistant_message, messages, *_args):+ tool_call = assistant_message.tool_calls[0]+ messages.append(+ {+ "role": "tool",+ "name": tool_call.function.name,+ "tool_call_id": tool_call.id,+ "content": "ok",+ }+ )++ agent._execute_tool_calls = _fake_execute_tool_calls+ return agent+++def _run_with_responses(agent, responses):+ agent.client.chat.completions.create.side_effect = responses+ with (+ patch.object(agent, "_flush_messages_to_session_db", return_value=True),+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ result = agent.run_conversation("do some tool work")+ return result+++def test_review_input_budget_stops_tool_loop_before_next_provider_call():+ """Once a fork's cumulative input crosses its budget, no further provider+ call is made — the crossing request completes, then the loop stops."""+ agent = _make_loop_agent()+ agent._review_input_token_budget = 100_000++ responses = [+ _tool_response(50_000),+ _tool_response(50_000), # cumulative 100_000 -> budget crossed+ _tool_response(50_000), # must never be consumed+ _final_response(),+ ]+ result = _run_with_responses(agent, responses)++ create = agent.client.chat.completions.create+ assert create.call_count == 2, (+ f"expected the loop to stop after crossing the input budget, "+ f"but {create.call_count} provider calls were made (budget "+ f"{agent._review_input_token_budget}, "+ f"used {agent.session_input_tokens})"+ )+ assert agent.session_input_tokens == 100_000+ assert result["completed"] is False+++def test_no_budget_attribute_leaves_tool_loop_unbounded():+ """Agents without ``_review_input_token_budget`` (every normal agent)+ are unaffected by the gate and consume all scripted responses."""+ agent = _make_loop_agent()++ responses = [+ _tool_response(50_000),+ _tool_response(50_000),+ _tool_response(50_000),+ _final_response(),+ ]+ result = _run_with_responses(agent, responses)++ assert agent.client.chat.completions.create.call_count == 4+ assert result["completed"] is True+ assert result["final_response"] == "done"+++def test_review_input_budget_exhausted_predicate_edge_cases():+ """The gate only arms for a positive int budget and a real token count."""+ from agent.conversation_loop import _review_input_budget_exhausted++ class _Agent:+ pass++ agent = _Agent()+ assert _review_input_budget_exhausted(agent) is False++ agent._review_input_token_budget = None+ agent.session_input_tokens = 999_999+ assert _review_input_budget_exhausted(agent) is False++ agent._review_input_token_budget = 0+ assert _review_input_budget_exhausted(agent) is False++ agent._review_input_token_budget = -1+ assert _review_input_budget_exhausted(agent) is False++ agent._review_input_token_budget = "100"+ assert _review_input_budget_exhausted(agent) is False++ agent._review_input_token_budget = True+ assert _review_input_budget_exhausted(agent) is False++ agent._review_input_token_budget = 100_000+ agent.session_input_tokens = 99_999+ assert _review_input_budget_exhausted(agent) is False++ agent.session_input_tokens = 100_000+ assert _review_input_budget_exhausted(agent) is True+++ ("config_value", "expected"),+ [+ ({}, 600_000),+ ({"max_input_tokens": 1_000_000}, 1_000_000),+ ({"max_input_tokens": 0}, None),+ ({"max_input_tokens": -5}, None),+ ({"max_input_tokens": "not-a-number"}, 600_000),+ ({"max_input_tokens": "300000"}, 300_000),+ ],+)+def test_review_input_token_budget_resolution(config_value, expected):+ """Config parsing: default, override, explicit disable, garbage fallback."""+ from agent.background_review import _review_input_token_budget++ assert _review_input_token_budget(config_value) == expected