Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): reconcile compacted results by exact call identity

saju01358752572d8d
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 29a9187d6..8b6502d59 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -468,10 +468,9 @@ def _microcompact(messages: list) -> list:
messages: Message list (mutated in place).
Returns:
- Names of tools whose every result just became unreadable. The caller
- drops these from the dedup ledger: blocking a re-call with "use the
- previous result" only makes sense while that result is still in
- context, and a cleared result is not.
+ Names of tools whose every result just became unreadable (legacy
+ helper contract). The loop reconciles its dedup ledger separately by
+ exact successful call identity, not by these tool names.
"""
tool_msgs = [m for m in messages if m.get("role") == "tool"]
if len(tool_msgs) <= KEEP_RECENT:
@@ -1074,6 +1073,9 @@ class AgentLoop:
# deterministic cache uses, so the block path and the cache path can
# never disagree about what 'the same call' means.
self._called_ok: set[tuple[str, str]] = set()
+ # Capture successful identities before context collapse can stub args.
+ # Skipped/error call IDs never enter this ledger.
+ self._successful_call_keys: dict[str, tuple[str, str]] = {}
self._cancel_event = threading.Event()
self._previous_summary: str = ""
self._persistent_memory = persistent_memory
@@ -1179,6 +1181,7 @@ class AgentLoop:
else:
self._has_run = True
self._called_ok = set()
+ self._successful_call_keys = {}
self._previous_summary = ""
self._released_fallback = False
self._released_fallback_reason = None
@@ -2119,6 +2122,8 @@ class AgentLoop:
if cache_key is not None and cache_key in self._called_identical:
cached = self._called_identical[cache_key]
messages.append(context.format_tool_result(tc.id, tc.name, cached))
+ self._successful_call_keys[tc.id] = cache_key
+ self._called_ok.add(cache_key)
trace.write({
"type": "tool_result_cached",
"iter": iteration,
@@ -2641,14 +2646,12 @@ class AgentLoop:
)
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.
+ """Run layer-1 microcompact and re-open lost readonly call identities.
- 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.
+ A readable result for another argument variant, or a synthetic skip,
+ cannot satisfy "use the previous result". Keep an exact call gated if
+ any successful copy survives; never re-open mutating tools just because
+ their results were compacted away.
Args:
messages: Message list, mutated in place by the compaction.
@@ -2660,18 +2663,10 @@ class AgentLoop:
Returns:
The tool names re-opened, for callers and tests to assert on.
"""
- unreadable_tools = _microcompact(messages)
+ readable_before = self._readable_success_keys(messages)
+ _microcompact(messages)
+ unreadable_tools = self._unblock_lost_readonly_results(messages, readable_before)
if unreadable_tools:
- # The ledger is keyed by (tool name, canonical arguments), so a
- # name cannot be subtracted from it directly: a plain
- # ``difference_update`` of names against tuples removes nothing and
- # the unblock silently becomes a no-op. Drop EVERY argument variant
- # of a cleared tool — microcompact only reports a name once no
- # readable result of any variant survives.
- cleared = set(unreadable_tools)
- self._called_ok = {
- key for key in self._called_ok if key[0] not in cleared
- }
trace.write({
"type": "microcompact_cleared",
"iter": iteration,
@@ -2679,6 +2674,27 @@ class AgentLoop:
})
return unreadable_tools
+ def _readable_success_keys(self, messages: list) -> set[tuple[str, str]]:
+ """Identify surviving successful results, not synthetic skip/stub calls."""
+ return {
+ self._successful_call_keys[msg["tool_call_id"]]
+ for msg in messages
+ if msg.get("role") == "tool"
+ and msg.get("tool_call_id") in self._successful_call_keys
+ and not _result_data_gone(msg.get("content"))
+ }
+
+ def _unblock_lost_readonly_results(
+ self, messages: list, readable_before: set[tuple[str, str]]
+ ) -> list[str]:
+ """Recover only lost exact queries; context loss cannot replay writes."""
+ lost = readable_before - self._readable_success_keys(messages)
+ reopened = {
+ key for key in lost & self._called_ok if self._is_tool_readonly(key[0])
+ }
+ self._called_ok.difference_update(reopened)
+ return sorted({key[0] for key in reopened})
+
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.
@@ -2734,6 +2750,7 @@ class AgentLoop:
recorded_key = self._identical_call_key(tc.name, tc.arguments)
if recorded_key is not None:
self._called_ok.add(recorded_key)
+ self._successful_call_keys[tc.id] = recorded_key
if tc.name == "backtest":
try:
_archive_backtest_result(result, self.memory.run_dir)
@@ -2834,6 +2851,7 @@ class AgentLoop:
for msg in messages:
f.write(json.dumps(msg, default=str, ensure_ascii=False) + "\n")
+ readable_before = self._readable_success_keys(messages)
system_msg = messages[0]
body = messages[1:]
@@ -2975,6 +2993,7 @@ class AgentLoop:
# Fix orphaned tool pairs in the reconstructed message list
_fix_tool_pairs(messages)
+ self._unblock_lost_readonly_results(messages, readable_before)
def _emit(self, event_type: str, data: Dict[str, Any]) -> None:
"""Fire an event via the callback."""
diff --git a/agent/tests/test_compaction_call_identity.py b/agent/tests/test_compaction_call_identity.py
new file mode 100644
index 000000000..4d3bf970c
--- /dev/null
+++ b/agent/tests/test_compaction_call_identity.py
@@ -0,0 +1,281 @@
+"""Compaction may recover lost readonly results, never replay side effects."""
+
+from __future__ import annotations
+
+import json
+from itertools import count
+from types import SimpleNamespace
+
+import pytest
+
+from src.agent.context import ContextBuilder
+from src.agent.loop import (
+ AgentLoop,
+ COLLAPSE_TEXT_MIN,
+ KEEP_RECENT,
+ _STUB_RESULT_CONTENT,
+ _context_collapse,
+ _fix_tool_pairs,
+ _is_cleared,
+)
+from src.agent.tools import BaseTool, ToolRegistry
+from src.agent.trace import TraceWriter
+
+
+class _Query(BaseTool):
+ name = "get_financial_statements"
+ repeatable = False
+ is_readonly = True
+
+ def __init__(self):
+ self.calls = []
+
+ def execute(self, **kwargs):
+ self.calls.append(kwargs)
+ return json.dumps({"status": "ok", "rows": ["x" * 200]})
+
+
+def harness(tmp_path):
+ tool = _Query()
+ registry = ToolRegistry()
+ registry.register(tool)
+ agent = AgentLoop(
+ registry=registry,
+ llm=SimpleNamespace(chat=lambda *a, **kw: SimpleNamespace(content="summary")),
+ )
+ agent.memory.run_dir = str(tmp_path)
+ trace = TraceWriter(tmp_path)
+ messages = [{"role": "system", "content": "system"}]
+ react = []
+ call_ids = count()
+
+ def call(arguments, name=None):
+ call_id = f"call_{next(call_ids)}"
+ name = name or tool.name
+ messages.append(
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": call_id,
+ "type": "function",
+ "function": {"name": name, "arguments": json.dumps(arguments)},
+ }
+ ],
+ }
+ )
+ agent._process_tool_calls(
+ [SimpleNamespace(id=call_id, name=name, arguments=arguments)],
+ ContextBuilder,
+ messages,
+ trace,
+ react,
+ 1,
+ )
+ return messages[-1]
+
+ def pad(count=KEEP_RECENT):
+ for i in range(count):
+ call({"padding": i}, name="padding_tool")
+
+ yield SimpleNamespace(
+ tool=tool,
+ agent=agent,
+ trace=trace,
+ messages=messages,
+ call=call,
+ pad=pad,
+ run_dir=tmp_path,
+ )
+ trace.close()
+
+
+def test_microcompact_reopens_only_lost_argument_variant(harness):
+ h = harness
+ income = h.call({"statement": "income"})
+ balance = h.call({"statement": "balance"})
+ h.pad(KEEP_RECENT - 1)
+
+ h.agent._microcompact_and_unblock(h.messages, h.trace, 2)
+
+ assert _is_cleared(income["content"])
+ assert not _is_cleared(balance["content"])
+ h.call({"statement": "income"})
+ assert len(h.tool.calls) == 3, "lost income must execute despite readable balance"
+ result = h.call({"statement": "balance"})
+ assert json.loads(result["content"])["skipped"] is True
+ assert len(h.tool.calls) == 3, "readable balance must remain gated"
+
+
+def test_variants_clear_separately_and_second_pass_is_idempotent(harness):
+ h = harness
+ income_args = {"statement": "income", "large": "a" * (COLLAPSE_TEXT_MIN + 1)}
+ h.call(income_args)
+ income_call = h.messages[1]["tool_calls"][0]
+ h.call({"statement": "balance"})
+ h.pad(KEEP_RECENT - 1)
+ assert h.agent._microcompact_and_unblock(h.messages, h.trace, 2) == [h.tool.name]
+ assert h.agent._microcompact_and_unblock(h.messages, h.trace, 3) == []
+ h.pad(1)
+ assert h.agent._microcompact_and_unblock(h.messages, h.trace, 4) == [h.tool.name]
+ assert h.agent._microcompact_and_unblock(h.messages, h.trace, 5) == []
+
+ _context_collapse(h.messages)
+ assert income_call["function"]["arguments"] == "{}"
+ # Layer 2's lossy arguments must not change the captured identity.
+ h.agent._auto_compact(h.messages, h.run_dir, h.trace)
+ h.call(income_args)
+ h.call({"statement": "balance"})
+ assert len(h.tool.calls) == 4
+ assert json.loads(h.call(income_args)["content"])["skipped"] is True
+ assert len(h.tool.calls) == 4
+
+
[email protected]("compact", ["micro", "auto"])
[email protected]("duplicate", ["success", "skipped", "error", "stub"])
+def test_only_real_readable_duplicate_keeps_lock(
+ harness, monkeypatch, compact, duplicate
+):
+ h = harness
+ args = {"statement": "income"}
+ original = h.call(args)
+ if duplicate != "skipped":
+ h.tool.repeatable = True
+ if duplicate == "error":
+ monkeypatch.setattr(h.tool, "execute", lambda **kw: '{"status":"error"}')
+ second = h.call(args)
+ h.tool.repeatable = False
+ if duplicate == "error":
+ monkeypatch.undo()
+ if duplicate == "stub":
+ h.messages.remove(second)
+ _fix_tool_pairs(h.messages)
+ second = h.messages[-1]
+ assert second["content"] == _STUB_RESULT_CONTENT
+ calls_before = len(h.tool.calls)
+ if compact == "micro":
+ h.pad(KEEP_RECENT - 1)
+ h.agent._microcompact_and_unblock(h.messages, h.trace, 2)
+ assert _is_cleared(original["content"])
+ else:
+ h.agent._auto_compact(h.messages, h.run_dir, h.trace)
+ assert original not in h.messages
+ assert second in h.messages
+ result = h.call(args)
+ if duplicate == "success":
+ assert json.loads(result["content"])["skipped"] is True
+ assert len(h.tool.calls) == calls_before
+ else:
+ assert json.loads(result["content"])["status"] == "ok"
+ assert len(h.tool.calls) == calls_before + 1
+
+
[email protected]("compact", ["micro", "auto"])
+def test_compaction_never_replays_mutating_tool(harness, compact):
+ h = harness
+ h.tool.name = "place_order"
+ h.tool.is_readonly = False
+ h.agent.registry.register(h.tool)
+ args = {"symbol": "TEST", "quantity": 1}
+ original = h.call(args)
+ h.pad()
+ if compact == "micro":
+ assert h.agent._microcompact_and_unblock(h.messages, h.trace, 2) == []
+ assert _is_cleared(original["content"])
+ else:
+ h.agent._auto_compact(h.messages, h.run_dir, h.trace)
+ assert original not in h.messages
+ result = h.call(args)
+ assert json.loads(result["content"])["skipped"] is True
+ assert len(h.tool.calls) == 1, "losing context must never replay an order"
+
+
+def test_compaction_uses_same_run_dir_identity_as_gate(harness):
+ h = harness
+ h.call({"statement": "income"})
+ h.pad()
+ h.agent._microcompact_and_unblock(h.messages, h.trace, 2)
+ h.call({"run_dir": ".", "statement": "income"})
+ assert len(h.tool.calls) == 2
+ result = h.call({"statement": "income", "run_dir": str(h.run_dir)})
+ assert json.loads(result["content"])["skipped"] is True
+ assert len(h.tool.calls) == 2
+
+
+def test_none_canonical_key_never_creates_lock(harness, monkeypatch):
+ h = harness
+ monkeypatch.setattr(h.agent, "_identical_call_key", lambda *args: None)
+ h.call({"statement": "income"})
+ h.pad()
+ h.agent._microcompact_and_unblock(h.messages, h.trace, 2)
+ h.agent._auto_compact(h.messages, h.run_dir, h.trace)
+ h.call({"statement": "income"})
+ h.call({"statement": "income"})
+ assert len(h.tool.calls) == 3
+ assert not h.agent._called_ok
+ assert not h.agent._successful_call_keys
+
+
+def test_recovered_cached_result_restores_identical_call_gate(harness):
+ h = harness
+ h.tool.deterministic = True
+ args = {"statement": "income"}
+ h.call(args)
+ h.pad()
+ h.agent._microcompact_and_unblock(h.messages, h.trace, 2)
+ assert json.loads(h.call(args)["content"])["status"] == "ok"
+ assert len(h.tool.calls) == 1, "recovery must use the deterministic cache"
+ assert json.loads(h.call(args)["content"]).get("skipped") is True
+ assert len(h.tool.calls) == 1
+
+
+def test_readable_cached_duplicate_keeps_exact_key_locked(harness):
+ h = harness
+ # A repeatable deterministic tool can have two successful readable copies,
+ # including one served by the cache, before the gate becomes applicable.
+ h.tool.repeatable = True
+ h.tool.deterministic = True
+ original = h.call({"statement": "income"})
+ cached = h.call({"statement": "income"})
+ h.tool.repeatable = False
+ h.pad(KEEP_RECENT - 1)
+
+ reopened = h.agent._microcompact_and_unblock(h.messages, h.trace, 2)
+
+ assert _is_cleared(original["content"])
+ assert not _is_cleared(cached["content"])
+ assert h.tool.name not in reopened
+ result = h.call({"statement": "income"})
+ assert json.loads(result["content"])["skipped"] is True
+ assert len(h.tool.calls) == 1
+
+
[email protected]("degraded", [False, True])
+def test_auto_compact_reopens_head_but_preserves_tail_gate(
+ harness, monkeypatch, degraded
+):
+ h = harness
+ h.call({"statement": "income"})
+ balance = h.call({"statement": "balance"})
+ # All messages fit: the real fallback split folds the income pair and
+ # retains the balance pair, without mocking the tail selector.
+ if degraded:
+
+ def fail_summary(*args, **kwargs):
+ raise RuntimeError("offline summary failure")
+
+ monkeypatch.setattr(h.agent.llm, "chat", fail_summary)
+ monkeypatch.setattr("src.agent.loop._llm_timeout_seconds", lambda: 1)
+
+ h.agent._auto_compact(h.messages, h.run_dir, h.trace)
+
+ assert balance in h.messages
+ if degraded:
+ assert "compaction degraded" in h.messages[1]["content"]
+ h.call({"statement": "income"})
+ assert len(h.tool.calls) == 3, "summary is not readable original income data"
+ result = h.call({"statement": "balance"})
+ assert json.loads(result["content"])["skipped"] is True
+ assert len(h.tool.calls) == 3