mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(cache): replay every parallel tool result (#4818)
## Description
An Anthropic user message can hold several parallel `tool_result`
blocks. The session compression cache recorded and replayed only the
first one, but a hit for that result could freeze the whole message.
Later results then reached the provider in their raw form instead of the
previously compressed form.
Visit every result when recording, replaying and marking stable content.
Freeze a message only if every result is replayable or textless. Reuse
the existing single-result shape guard, so images, tool references,
multiblock boundaries and text-block metadata retain their established
protection. Cache seeding checks the paired tool-call IDs before
associating original and compressed text.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- Cache and replay each parallel result independently without mutating
caller input.
- Stop the frozen prefix on a later miss or unsupported text layout.
- Cover a textless first result, later text-block metadata, changed IDs
and partial replay. Update the existing later-result limitation test to
assert actual replay.
## Testing
- [x] Relevant unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Formatting passes (`ruff format --check .`)
- [x] Type checking passes (original full-package mypy hook)
- [x] Regression tests added
- [x] Standalone runtime validation completed
### Test Output
```text
New regressions against original production code: 5 failed, 1 passed
pytest tests/test_compression_cache.py tests/test_session_engine.py tests/test_cache_replay_shapes.py tests/test_token_headroom_mode.py tests/test_cache_prefix_safety.py tests/test_proxy_anthropic_cache_stability.py tests/test_prefix_tracker_restart.py:
189 passed
Original pre-commit and commit-msg hooks: passed
Whole-tree Ruff check and format --check: passed
Original pre-push make ci-precheck: passed
Rust workspace: 1749 passed, 3 ignored
Native extension: rebuilt, installed and import-verified
Critical Python: 177 passed, 8 skipped
commitlint: passed
```
Optional-model skips and the existing token-count approximation warning
remain visible in the gate logs. The restart tests also report the
environment's existing Starlette/httpx deprecation warning.
## Real Behavior Proof
- Environment: Windows 11, CPython 3.13.9, existing dev venv; clean
baseline `c05fbdddc873078dd97cb9ede841e75ef7ed0bef`, patch
`a09ad47dc8ceb04b42858a67eecb83a7ee246485`. Explicit checkout on
PYTHONPATH; no provider credentials. Headroom runs offline; the parallel
proof uses a real SDK to send only to its bound loopback receiver.
- Exact command / steps: Save the following script as `proof.py` and run
`python proof.py` from either checkout with `PYTHONPATH=.`. Identical
before/after scripts ran outside pytest.
```python
"""Production cache/session APIs followed by real Anthropic SDK loopback HTTP."""
import copy
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import threading
from anthropic import Anthropic
from headroom.cache.compression_cache import CompressionCache
from headroom.proxy.session_engine import FREEZE_POLICY_REPLAYABLE, prepare_turn
captured = []
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
captured.append(json.loads(self.rfile.read(int(self.headers['Content-Length']))))
data = json.dumps({'id':'local','type':'message','role':'assistant','model':'local-fixture','content':[{'type':'text','text':'received'}],'stop_reason':'end_turn','stop_sequence':None,'usage':{'input_tokens':1,'output_tokens':1}}).encode()
self.send_response(200);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
def log_message(self,*args): pass
def message(a,b):
return {'role':'user','content':[{'type':'tool_result','tool_use_id':'t1','content':a},{'type':'tool_result','tool_use_id':'t2','content':b}]}
server = ThreadingHTTPServer(('127.0.0.1',0),Handler)
thread = threading.Thread(target=server.serve_forever,daemon=True);thread.start()
raw = message('first original '*20,[{'type':'text','text':'second original '*20,'cache_control':{'type':'ephemeral'}}])
short = message('first compressed',[{'type':'text','text':'second compressed','cache_control':{'type':'ephemeral'}}])
messages=[{'role':'assistant','content':[{'type':'tool_use','id':'t1','name':'inspect','input':{}},{'type':'tool_use','id':'t2','name':'inspect','input':{}}]},raw,{'role':'user','content':'continue'}]
before = copy.deepcopy(messages)
cache = CompressionCache();cache.update_from_result([raw],[short])
prep = prepare_turn(cache,messages,policy=FREEZE_POLICY_REPLAYABLE)
try:
with Anthropic(api_key='local-fixture',base_url=f'http://127.0.0.1:{server.server_port}',max_retries=0) as client:
client.messages.create(model='local-fixture',max_tokens=16,messages=prep.pipeline_input)
wire = captured[-1]['messages'][1]
print(json.dumps({'all_results_replayed':wire==short,'second_result':wire['content'][1]['content'],'frozen_count':prep.frozen_message_count,'caller_unchanged':messages==before,'requests':len(captured)},indent=2))
finally:
server.shutdown();server.server_close();thread.join(5)
```
- Observed result: With the same original/compressed message pair, clean
main freezes the two-message prefix but the real Anthropic SDK sends the
second result as its original text. With the patch, the HTTP receiver
gets both compressed results, including the second text block's
cache_control; frozen_count remains 2 and caller_unchanged remains true.
- Not tested: Live Anthropic service acceptance, model inference,
billing, task accuracy, or the complete Python suite. The receiver
records actual SDK JSON and returns a synthetic response.
## Runtime Rollout Safety
- Rollout-managed feature(s): Existing cache behavior; no new feature
flag or channel expansion.
- Minimum rollout channel: Normal release after maintainer review and CI
qualification.
- Stable/default behavior changed: Cached replay covers every tool
result in a message; a later cache miss or unsupported shape keeps that
message mutable.
- Kill switch / disable path: Revert this commit to restore the prior
replay behavior; no new configuration is introduced.
- Unsafe override required: No.
- Qualification impact: Related tests and original local gates passed;
hosted CI is tracked separately.
- Rollback path: Revert this commit; no dependency or storage-schema
change.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have added tests that prove the fix
- [x] Relevant new and existing tests pass locally
- [x] I did **not** edit `CHANGELOG.md`
## Additional Notes
Developed and validated with Codex assistance. I reviewed the changes
and runtime evidence.
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4818"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
JerrettDavis
parent
d7a2fcf092
commit
973c12d2af
Vendored
+71
-32
@@ -40,6 +40,25 @@ def _is_tool_result_message(msg: dict) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _tool_result_units(msg: dict) -> list[tuple[int | None, dict]]:
|
||||
"""Expose each parallel result to the single-result shape/replay helpers.
|
||||
|
||||
The index identifies its block in the original Anthropic message; OpenAI
|
||||
tool messages contain one result and use None. The wrappers borrow their
|
||||
blocks for reading only: rewriting still goes through the copying helper.
|
||||
"""
|
||||
if msg.get("role") == "tool":
|
||||
return [(None, msg)]
|
||||
content = msg.get("content")
|
||||
if not isinstance(content, list):
|
||||
return []
|
||||
return [
|
||||
(i, {"role": msg.get("role"), "content": [block]})
|
||||
for i, block in enumerate(content)
|
||||
if isinstance(block, dict) and block.get("type") == "tool_result"
|
||||
]
|
||||
|
||||
|
||||
def _extract_text_from_blocks(blocks: list) -> str | None:
|
||||
"""Extract joined text from a list-of-blocks content (e.g. Anthropic list-of-text-blocks).
|
||||
|
||||
@@ -281,8 +300,8 @@ class CompressionCache:
|
||||
"""Mark all tool_result hashes in messages[:up_to] as stable."""
|
||||
with self._lock:
|
||||
for msg in messages[:up_to]:
|
||||
if _is_tool_result_message(msg):
|
||||
content = _extract_tool_result_content(msg)
|
||||
for _, unit in _tool_result_units(msg):
|
||||
content = _extract_tool_result_content(unit)
|
||||
if content is not None:
|
||||
self._mark_stable_locked(self.content_hash(content))
|
||||
|
||||
@@ -373,29 +392,29 @@ class CompressionCache:
|
||||
with self._lock:
|
||||
count = 0
|
||||
for msg in messages:
|
||||
if _is_tool_result_message(msg):
|
||||
for _, unit in _tool_result_units(msg):
|
||||
# A joined-text cache/stable hash cannot prove replay for
|
||||
# shapes that apply_cached deliberately leaves untouched.
|
||||
# Anthropic textless results retain their no-rewrite path.
|
||||
if not _can_swap_tool_result_content(msg):
|
||||
if not _can_swap_tool_result_content(unit):
|
||||
break
|
||||
content = _extract_tool_result_content(msg)
|
||||
content = _extract_tool_result_content(unit)
|
||||
if content is not None:
|
||||
h = self.content_hash(content)
|
||||
if h not in self._cache and h not in self._stable_hashes:
|
||||
break
|
||||
elif _carries_tool_result_text(msg):
|
||||
# Text after a textless first tool_result: the cache
|
||||
# keys a message by its first one, so this text was
|
||||
# never stored and cannot be byte-replayed.
|
||||
elif _carries_tool_result_text(unit):
|
||||
break
|
||||
# A tool_result with no text at all (a ToolSearch
|
||||
# tool_reference list, an image) gives the cache nothing
|
||||
# to replay, so it is stable. As a miss it stopped the
|
||||
# count for the rest of the session.
|
||||
# Regular user/assistant/system messages and assistant+tool_use
|
||||
# are always stable — fall through.
|
||||
count += 1
|
||||
else:
|
||||
# A message freezes only when every parallel result can
|
||||
# be replayed. Textless results need no cached replacement.
|
||||
count += 1
|
||||
continue
|
||||
break
|
||||
# Reserve the trailing message as the live zone. `max(0, ...)`
|
||||
# handles the empty-list edge case cleanly.
|
||||
return min(count, max(0, len(messages) - 1))
|
||||
@@ -412,25 +431,31 @@ class CompressionCache:
|
||||
with self._lock:
|
||||
result: list[dict] = []
|
||||
for msg in messages:
|
||||
if not _can_swap_tool_result_content(msg):
|
||||
result.append(msg)
|
||||
continue
|
||||
if _is_tool_result_message(msg):
|
||||
content = _extract_tool_result_content(msg)
|
||||
replacement = msg
|
||||
for index, unit in _tool_result_units(msg):
|
||||
if not _can_swap_tool_result_content(unit):
|
||||
continue
|
||||
content = _extract_tool_result_content(unit)
|
||||
if content is not None:
|
||||
h = self.content_hash(content)
|
||||
compressed = self.get_compressed(h)
|
||||
if compressed is not None:
|
||||
result.append(_swap_tool_result_content(msg, compressed))
|
||||
continue
|
||||
result.append(msg)
|
||||
swapped = _swap_tool_result_content(unit, compressed)
|
||||
if index is None:
|
||||
replacement = swapped
|
||||
else:
|
||||
if replacement is msg:
|
||||
replacement = copy.deepcopy(msg)
|
||||
replacement["content"][index] = swapped["content"][0]
|
||||
result.append(replacement)
|
||||
return result
|
||||
|
||||
def update_from_result(self, originals: list[dict], compressed: list[dict]) -> None:
|
||||
"""Cache new compressions by comparing original and compressed messages.
|
||||
|
||||
Index-aligned: for each position, if both are tool results and the
|
||||
content differs, store the mapping original_hash -> compressed_content.
|
||||
Compare messages by position and parallel results by tool-call ID.
|
||||
Each result gets its own original_hash -> compressed_content mapping;
|
||||
text in a later result must not disappear behind the first result's hit.
|
||||
"""
|
||||
if len(originals) != len(compressed):
|
||||
logger.warning(
|
||||
@@ -444,14 +469,28 @@ class CompressionCache:
|
||||
# (RLock) safely.
|
||||
with self._lock:
|
||||
for orig, comp in zip(originals, compressed):
|
||||
orig_content = _extract_tool_result_content(orig)
|
||||
comp_content = _extract_tool_result_content(comp)
|
||||
if orig_content is None or comp_content is None:
|
||||
orig_units = _tool_result_units(orig)
|
||||
comp_units = _tool_result_units(comp)
|
||||
if len(orig_units) != len(comp_units):
|
||||
continue
|
||||
if orig_content == comp_content:
|
||||
# Content unchanged — mark as stable for frozen count walk
|
||||
self._mark_stable_locked(self.content_hash(orig_content))
|
||||
continue
|
||||
h = self.content_hash(orig_content)
|
||||
tokens_saved = len(orig_content) // 4 - len(comp_content) // 4
|
||||
self.store_compressed(h, comp_content, tokens_saved=max(tokens_saved, 0))
|
||||
for (orig_index, orig_unit), (comp_index, comp_unit) in zip(orig_units, comp_units):
|
||||
if orig_index is None or comp_index is None:
|
||||
aligned = orig_index == comp_index and orig.get("tool_call_id") == comp.get(
|
||||
"tool_call_id"
|
||||
)
|
||||
else:
|
||||
aligned = orig_unit["content"][0].get("tool_use_id") == comp_unit[
|
||||
"content"
|
||||
][0].get("tool_use_id")
|
||||
if not aligned:
|
||||
continue
|
||||
orig_content = _extract_tool_result_content(orig_unit)
|
||||
comp_content = _extract_tool_result_content(comp_unit)
|
||||
if orig_content is None or comp_content is None:
|
||||
continue
|
||||
if orig_content == comp_content:
|
||||
self._mark_stable_locked(self.content_hash(orig_content))
|
||||
continue
|
||||
h = self.content_hash(orig_content)
|
||||
tokens_saved = len(orig_content) // 4 - len(comp_content) // 4
|
||||
self.store_compressed(h, comp_content, tokens_saved=max(tokens_saved, 0))
|
||||
|
||||
@@ -135,7 +135,7 @@ class TestCacheReplayShapes(unittest.TestCase):
|
||||
)
|
||||
self.assertEqual(prep.frozen_message_count, min(confirmed, 1))
|
||||
|
||||
def test_cached_text_after_textless_anthropic_result_remains_mutable(self) -> None:
|
||||
def test_cached_text_after_textless_anthropic_result_is_replayed(self) -> None:
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
@@ -148,10 +148,12 @@ class TestCacheReplayShapes(unittest.TestCase):
|
||||
]
|
||||
before = copy.deepcopy(messages)
|
||||
prep = prepare_turn(self.cache, messages, policy=FREEZE_POLICY_REPLAYABLE)
|
||||
self.assertEqual(prep.frozen_message_count, 0)
|
||||
self.assertEqual(prep.pipeline_input, before)
|
||||
self.assertEqual(prep.frozen_message_count, 1)
|
||||
expected = copy.deepcopy(before)
|
||||
expected[0]["content"][1]["content"] = "short"
|
||||
self.assertEqual(prep.pipeline_input, expected)
|
||||
self.assertEqual(messages, before)
|
||||
self.assertEqual(self.cache.get_stats()["hits"], 0)
|
||||
self.assertEqual(self.cache.get_stats()["hits"], 1)
|
||||
|
||||
def test_supported_stable_hash_and_trailing_live_zone_are_unchanged(self) -> None:
|
||||
cache = CompressionCache()
|
||||
|
||||
@@ -7,6 +7,77 @@ import pytest
|
||||
from headroom.cache.compression_cache import CompressionCache
|
||||
|
||||
|
||||
def _parallel_results(*contents):
|
||||
return {
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "tool_result", "tool_use_id": f"tool-{i}", "content": content}
|
||||
for i, content in enumerate(contents)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_parallel_results_are_all_cached_and_replayed():
|
||||
import copy
|
||||
|
||||
cache = CompressionCache()
|
||||
original = _parallel_results(
|
||||
"first original " * 20,
|
||||
[{"type": "text", "text": "second original " * 20, "cache_control": {"type": "ephemeral"}}],
|
||||
)
|
||||
compressed = _parallel_results(
|
||||
"first compressed",
|
||||
[{"type": "text", "text": "second compressed", "cache_control": {"type": "ephemeral"}}],
|
||||
)
|
||||
untouched = copy.deepcopy(original)
|
||||
cache.update_from_result([original], [compressed])
|
||||
|
||||
assert cache.apply_cached([original]) == [compressed]
|
||||
assert original == untouched
|
||||
assert cache.compute_frozen_count([original, {"role": "user", "content": "next"}]) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("first", ["cached", [{"type": "tool_reference", "tool_name": "Read"}]])
|
||||
def test_a_later_parallel_cache_miss_stops_freezing(first):
|
||||
cache = CompressionCache()
|
||||
cache.mark_stable(cache.content_hash("cached"))
|
||||
original = _parallel_results(first, "not cached")
|
||||
assert cache.compute_frozen_count([original, {"role": "user", "content": "next"}]) == 0
|
||||
|
||||
|
||||
def test_parallel_results_preserve_textless_blocks_and_cache_later_text():
|
||||
cache = CompressionCache()
|
||||
references = [{"type": "tool_reference", "tool_name": "Read"}]
|
||||
original = _parallel_results(references, "original " * 20)
|
||||
compressed = _parallel_results(references, "compressed")
|
||||
cache.update_from_result([original], [compressed])
|
||||
|
||||
assert cache.apply_cached([original]) == [compressed]
|
||||
assert cache.compute_frozen_count([original, {"role": "user", "content": "next"}]) == 1
|
||||
|
||||
|
||||
def test_parallel_replay_does_not_flatten_an_unsupported_later_result():
|
||||
cache = CompressionCache()
|
||||
blocks = [{"type": "text", "text": "part one"}, {"type": "text", "text": "part two"}]
|
||||
original = _parallel_results("original " * 20, blocks)
|
||||
compressed = _parallel_results("compressed", "part one\npart two")
|
||||
cache.update_from_result([original], [compressed])
|
||||
|
||||
replay = cache.apply_cached([original])[0]
|
||||
assert replay["content"][0]["content"] == "compressed"
|
||||
assert replay["content"][1]["content"] == blocks
|
||||
assert cache.compute_frozen_count([original, {"role": "user", "content": "next"}]) == 0
|
||||
|
||||
|
||||
def test_changed_parallel_result_ids_do_not_seed_the_wrong_result():
|
||||
cache = CompressionCache()
|
||||
original = _parallel_results("alpha original", "beta original")
|
||||
compressed = _parallel_results("alpha compressed", "beta compressed")
|
||||
compressed["content"].reverse()
|
||||
cache.update_from_result([original], [compressed])
|
||||
assert cache.apply_cached([original]) == [original]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cache() -> CompressionCache:
|
||||
return CompressionCache()
|
||||
|
||||
Reference in New Issue
Block a user