"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(context): keep system prompt byte-stable across runs for prefix cache
Jackzigendf776a1b7554
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.pyindex 1791cf563..f8d83b985 100644--- a/agent/src/agent/context.py+++ b/agent/src/agent/context.py@@ -79,10 +79,6 @@ skill document, not recalled memory. They are not defaults to be tuned.{skill_descriptions}-## State--{memory_summary}-## Task RoutingDecide which workflow to use based on the request:@@ -345,7 +341,6 @@ class ContextBuilder:data_source_count=self._count_data_sources(),tool_descriptions=self._format_tool_descriptions(),skill_descriptions=self.skills_loader.get_descriptions(),- memory_summary=self.memory.to_summary(),memory_section=memory_section,strategy_discovery_routing=routing,current_datetime=now.strftime("%A, %B %d, %Y %H:%M UTC"),@@ -374,6 +369,11 @@ class ContextBuilder:user message as context. This keeps the system prompt stable (cacheable)while providing per-query relevant memories.+ Volatile workspace state (run_dir, tool counters) is injected the same+ way: run_dir changes on every run and counters change on every tool+ call, so rendering them into the system prompt invalidated the provider+ prefix cache on every turn (issue #1707).+Args:user_message: User message.history: Prior conversation messages.@@ -402,6 +402,16 @@ class ContextBuilder:except Exception as exc:logger.debug("Auto-recall failed: %s", exc)+ # Volatile workspace state rides in the first user message so the+ # system prompt stays byte-stable across turns (prefix cache stays+ # valid). Same envelope convention as recalled-memories above.+ state_summary = self.memory.to_summary()+ if state_summary and state_summary != "(empty state)":+ enriched = (+ f"<agent-state>\n{state_summary}\n</agent-state>\n\n"+ f"{enriched}"+ )+messages.append({"role": "user", "content": enriched})return messagesdiff --git a/agent/tests/test_agent_output_discipline.py b/agent/tests/test_agent_output_discipline.pyindex 7b7fd0ef9..8dac5d440 100644--- a/agent/tests/test_agent_output_discipline.py+++ b/agent/tests/test_agent_output_discipline.py@@ -137,11 +137,14 @@ class TestOutputPrinciplesCannotBeOverriddenBySession:assert blocks[0] == blocks[1] == blocks[2]def test_the_block_sits_before_any_per_session_content(self) -> None:- """It is in the cacheable prefix, ahead of memory and the timestamp."""+ """It is in the cacheable prefix, ahead of the timestamp. Per-run+ workspace state no longer reaches the system prompt at all — it rides+ the first user message (see test_system_prompt_cache_stability.py,+ issue #1707)."""prompt = _rendered_prompt()- assert prompt.index("## Output Principles") < prompt.index("## State")assert prompt.index("## Output Principles") < prompt.index("## Current Date & Time")+ assert "## State" not in prompt# ---------------------------------------------------------------------------diff --git a/agent/tests/test_system_prompt_cache_stability.py b/agent/tests/test_system_prompt_cache_stability.pynew file mode 100644index 000000000..479f45a2b--- /dev/null+++ b/agent/tests/test_system_prompt_cache_stability.py@@ -0,0 +1,115 @@+"""System-prompt cache stability (issue #1707).++``WorkspaceMemory.to_summary()`` renders ``run_dir`` (a fresh+``timestamp_uuid`` directory per run) and tool ``counters`` (bumped on every+tool call). Rendering that summary into the system prompt meant the prompt+bytes changed on every turn and every tool call, invalidating the provider+prefix cache — including the ``cache_control`` block the Anthropic adapter+marks on the system message — for everything after the ``## State`` section.++The fix: the volatile summary rides the first **user** message wrapped in an+``<agent-state>`` envelope (same convention as ``<recalled-memories>``), and+the system template no longer has a ``## State`` section. The system prompt is+now byte-identical across runs as long as the registry, skills, and date+minute do not change.+"""++from __future__ import annotations++import pytest++from src.agent.context import ContextBuilder+from src.agent.memory import WorkspaceMemory+from src.agent.tools import ToolRegistry++pytestmark = pytest.mark.unit+++def _builder(memory: WorkspaceMemory) -> ContextBuilder:+ return ContextBuilder(ToolRegistry(), memory)+++class TestSystemPromptCacheStability:+ def test_prompt_is_byte_identical_when_run_dir_and_counters_change(self) -> None:+ """Different run_dir / counters must not change the system prompt."""+ m1 = WorkspaceMemory()+ m1.run_dir = "/runs/20260101_000000_abcdef"+ m1.increment("get_market_data")++ m2 = WorkspaceMemory()+ m2.run_dir = "/runs/20260102_111111_fedcba"+ m2.increment("get_market_data")+ m2.increment("get_market_data")+ m2.increment("backtest")++ # Freeze the clock so only run_dir/counters differ between the two.+ import src.agent.context as ctx+ from datetime import datetime, timezone++ frozen = datetime(2026, 10, 6, 12, 0, 0, tzinfo=timezone.utc)+ orig = ctx.datetime++ class _FrozenDatetime:+ @staticmethod+ def now(tz=None):+ return frozen if tz is not None else frozen.replace(tzinfo=None)++ try:+ ctx.datetime = _FrozenDatetime # type: ignore[assignment]+ p1 = _builder(m1).build_system_prompt("hello")+ p2 = _builder(m2).build_system_prompt("hello")+ finally:+ ctx.datetime = orig++ assert p1 == p2++ def test_state_section_removed_from_system_template(self) -> None:+ assert "## State" not in _builder(WorkspaceMemory()).build_system_prompt("x")++ def test_volatile_state_rides_first_user_message(self) -> None:+ m = WorkspaceMemory()+ m.run_dir = "/runs/20260101_000000_abcdef"+ m.increment("backtest")++ messages = _builder(m).build_messages("analyze AAPL")++ assert messages[0]["role"] == "system"+ # The template's static Task Routing text may mention the literal+ # "run_dir" parameter; what must NOT appear is the volatile value.+ assert "/runs/20260101_000000_abcdef" not in messages[0]["content"]+ assert "counters:" not in messages[0]["content"]+ user = messages[-1]["content"]+ assert user.startswith("<agent-state>")+ assert "- run_dir: /runs/20260101_000000_abcdef" in user+ assert "counters: backtest=1" in user+ assert "analyze AAPL" in user++ def test_empty_state_leaves_user_message_untouched(self) -> None:+ messages = _builder(WorkspaceMemory()).build_messages("analyze AAPL")++ assert messages[-1]["content"] == "analyze AAPL"++ def test_state_envelope_sits_before_recalled_memories(self) -> None:+ class _Recall:+ title = "prefers conciseness"+ memory_type = "preference"+ body = "keep answers short"++ class _PersistentMemory:+ snapshot = None++ def find_relevant(self, query: str, max_results: int = 3):+ return [_Recall()]++ m = WorkspaceMemory()+ m.run_dir = "/runs/x"+ builder = ContextBuilder(ToolRegistry(), m, persistent_memory=_PersistentMemory())++ user = builder.build_messages("analyze AAPL")[-1]["content"]++ # Both envelopes ride the same user message; order between them does+ # not matter, but both must precede the raw user text.+ assert "<agent-state>" in user+ assert "<recalled-memories>" in user+ assert user.index("<agent-state>") < user.index("analyze AAPL")+ assert user.index("<recalled-memories>") < user.index("analyze AAPL")