Skip to content

"Vibe-Trading: Your Personal Trading Agent"

test(loop): cover the call site that re-opens the dedup ledger (#1343)

Haozhe Wu5a6eb80db8fc
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 7db7c901e..0ae571d32 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -1170,13 +1170,7 @@ class AgentLoop:
# tool history available for the model to reference instead of
# having every result past the most recent few cleared.
if tokens > int(_token_threshold() * 0.5):
- unreadable_tools = _microcompact(messages)
- if unreadable_tools:
- # The dedup ledger may only point the model at results
- # that are still in context; a cleared result is not,
- # so those tools become callable again.
- self._called_ok.difference_update(unreadable_tools)
- trace.write({"type": "microcompact_cleared", "iter": iteration, "tools": unreadable_tools})
+ self._microcompact_and_unblock(messages, trace, iteration)
tokens = estimate_tokens(messages)
# Layer 2: context collapse (fold long text, zero API cost)
@@ -2507,6 +2501,36 @@ class AgentLoop:
"file write is a failure."
)
+ def _microcompact_and_unblock(self, messages: list, trace: TraceWriter, iteration: int) -> list[str]:
+ """Run layer-1 microcompact and re-open the tools it made unreadable.
+
+ The dedup ledger may only point the model at a result that is still in
+ context. Once microcompact clears every result a tool produced, the
+ "already completed successfully, use the previous result" skip is
+ pointing at ``[cleared]``, which is how #1343 deadlocked: the model
+ needed the numbers, could not see them, re-called, and was blocked 44
+ times.
+
+ Args:
+ messages: Message list, mutated in place by the compaction.
+ trace: Run trace; a ``microcompact_cleared`` event is written
+ whenever the ledger is re-opened, because this layer used to
+ act silently and left no evidence for diagnosis.
+ iteration: Current ReAct iteration, recorded on the trace event.
+
+ Returns:
+ The tool names re-opened, for callers and tests to assert on.
+ """
+ unreadable_tools = _microcompact(messages)
+ if unreadable_tools:
+ self._called_ok.difference_update(unreadable_tools)
+ trace.write({
+ "type": "microcompact_cleared",
+ "iter": iteration,
+ "tools": unreadable_tools,
+ })
+ return unreadable_tools
+
def _identical_call_key(self, tool_name: str, arguments: Mapping[str, Any]) -> tuple[str, str] | None:
"""Build a stable key identifying a deterministic tool invocation.
diff --git a/agent/tests/test_agent_loop_repeatable_tools.py b/agent/tests/test_agent_loop_repeatable_tools.py
index e408caf79..d255a737d 100644
--- a/agent/tests/test_agent_loop_repeatable_tools.py
+++ b/agent/tests/test_agent_loop_repeatable_tools.py
@@ -12,6 +12,7 @@ from src.agent.context import ContextBuilder
from src.agent.loop import AgentLoop
from src.agent.tools import ToolRegistry
from src.agent.trace import TraceWriter
+from src.tools.fund_flow_tool import FundFlowTool
from src.tools.get_fundamentals_tool import GetFundamentalsTool
from src.tools.market_data_tool import MarketDataTool
from src.tools.market_screener_tool import MarketScreenerTool
@@ -115,3 +116,81 @@ def test_repeatable_query_executes_again_with_different_arguments(
assert not any(
event["type"] == "tool_skipped" for event in TraceWriter.read(run_dir)
)
+
+
+def test_cleared_result_reopens_the_dedup_gate(monkeypatch, tmp_path: Path) -> None:
+ """#1343: a non-repeatable tool blocked by the dedup ledger must become
+ callable again once microcompact has cleared its only result.
+
+ This drives the real gate in ``_process_tool_calls`` rather than only the
+ return value of ``_microcompact``: the first call fills ``_called_ok``, the
+ second is correctly skipped while the result is still readable, and the
+ third must actually execute once the result has been cleared. Without the
+ ledger update at the call site the third call is skipped too, which is the
+ 44-blocked-retries deadlock this fixes.
+ """
+ from src.agent.loop import KEEP_RECENT
+
+ calls: list[dict[str, object]] = []
+ # One of the five tools #1343 actually saw blocked; GetFundamentalsTool
+ # above is repeatable and therefore has no gate to exercise.
+ tool = FundFlowTool()
+ assert not tool.repeatable, "test needs a non-repeatable tool to have a gate at all"
+
+ def _execute(**kwargs: object) -> str:
+ calls.append(kwargs)
+ # Long enough that microcompact clears it (>100 chars).
+ return json.dumps({"status": "ok", "rows": ["x" * 200]})
+
+ monkeypatch.setattr(tool, "execute", _execute)
+ registry = ToolRegistry()
+ registry.register(tool)
+ agent = AgentLoop(registry=registry, llm=SimpleNamespace(), max_iterations=5)
+
+ run_dir = tmp_path / "run"
+ run_dir.mkdir()
+ agent.memory.run_dir = str(run_dir)
+ trace = TraceWriter(run_dir)
+ messages: list[dict[str, object]] = []
+ react_trace: list[dict[str, object]] = []
+ args = {"code": "600584.SH"}
+
+ def _call(call_id: str, iteration: int) -> None:
+ agent._process_tool_calls(
+ [SimpleNamespace(id=call_id, name=tool.name, arguments=dict(args))],
+ ContextBuilder,
+ messages,
+ trace,
+ react_trace,
+ iteration,
+ )
+
+ _call("call_1", 1)
+ assert len(calls) == 1, "first call must execute"
+
+ _call("call_2", 2)
+ assert len(calls) == 1, "second call must be skipped while the result is readable"
+
+ # Pad past KEEP_RECENT so the real result is old enough to be cleared, then
+ # run the actual production path rather than reaching into _called_ok.
+ for i in range(KEEP_RECENT + 1):
+ messages.append({
+ "role": "tool",
+ "tool_call_id": f"pad_{i}",
+ "name": "padding_tool",
+ "content": "y" * 200,
+ })
+ reopened = agent._microcompact_and_unblock(messages, trace, 3)
+ assert tool.name in reopened, f"{tool.name} should have been re-opened, got {reopened}"
+
+ _call("call_3", 4)
+ trace.close()
+
+ assert len(calls) == 2, (
+ "third call must execute: its only result was cleared from context, so "
+ "'use the previous result' points at [cleared]"
+ )
+ events = TraceWriter.read(run_dir)
+ assert any(e["type"] == "microcompact_cleared" for e in events), (
+ "the clear must leave a trace event; this layer used to act silently"
+ )