fix(content-router): keep list-form tool_result text blocks on separate lines (#4739)

## Description

A `tool_result` whose `content` is a list of several `text` blocks gets
flattened with `"".join(...)` in `ContentRouter` before the
read-protection check and before compression. MCP tools that return more
than one `TextContent` and litellm-style clients send this shape. When a
block does not end with a newline, the last line of one block and the
first line of the next one become a single line. The compressed result
is written back as one block, so the model sees a line the tool never
produced.

This PR joins the blocks with a newline unless the block already ends
with one, at both flatten sites.

Fixes #4729

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/transforms/content_router.py`: new helper
`_join_tool_result_text_blocks()` that joins list-form `text` blocks
with `\n`, skipping the separator when a block already ends with a
newline. Empty blocks add no extra line.
- Used at both places that flattened with `""`: the read-protection
check and the compression path. The wire shape does not change (the
existing `[{"type": "text", ...}]` re-wrap is kept), and results that
are not compressed keep their original blocks.
- `tests/test_transforms/test_content_router.py`: one `router.apply`
test with a two-block log `tool_result` that asserts that the output was
compressed and that every log line in it is a line the tool actually
returned, plus four parametrized cases for the helper.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

Exact source: head `5305d8acb5f505e635d1287cae30ed7f8d9eb595`, base
`c05fbdddc873078dd97cb9ede841e75ef7ed0bef`. The PR has three commits:
`f273fbb9` (the fix, written on `1da8930a`) and two merges of `main`
(`2cba6c5b`, `5305d8ac`), both without conflicts. `git diff
c05fbddd...5305d8ac` still touches only the two files listed above.

Upstream CI on `5305d8ac`, all `completed` / `success`: CI
[43338122484](https://github.com/headroomlabs-ai/headroom/actions/runs/43338122484),
Merge Conflicts
[43338122336](https://github.com/headroomlabs-ai/headroom/actions/runs/43338122336),
Changelog Guard
[43338122370](https://github.com/headroomlabs-ai/headroom/actions/runs/43338122370),
rust
[43338122318](https://github.com/headroomlabs-ai/headroom/actions/runs/43338122318),
Evaluation Suite
[43338122592](https://github.com/headroomlabs-ai/headroom/actions/runs/43338122592),
Security
[43338122460](https://github.com/headroomlabs-ai/headroom/actions/runs/43338122460).

Local runs below were built from `git archive 5305d8ac` in a
`python:3.13-slim-bookworm` image with `uv sync --frozen --extra proxy
--extra dev`. ruff ran on the two touched files and mypy on
`content_router.py`. pytest ran on the content router test modules. For
the reverse check, `content_router.py` was replaced with the copy from
`c05fbddd` and the tests kept.

A wider run over the 122 test files that touch the content router gave 9
failed / 2669 passed on `5305d8ac` and 9 failed / 2664 passed on
`c05fbddd`. The 9 failures are the same set on both (memory_bridge,
offline_egress docs, tabular; they come from the test image, not this
change), and the extra 5 passes are the new tests.

### Test Output

```text
== RUFF CHECK RC 0
== RUFF FORMAT RC 0
== MYPY RC 0
# new tests, 5 consecutive runs, all identical:
======================= 5 passed, 66 deselected in 5.01s =======================
# test_content_router.py + test_content_router_ccr_retrieve_exemption.py + test_content_router_shell_small_results.py:
============================= 125 passed in 5.61s ==============================
# with content_router.py restored to c05fbddd (fix removed):
E   AssertionError: assert ['2026-11-10T...er-0 retry 0'] == []
FAILED tests/test_transforms/test_content_router.py::test_list_form_tool_result_blocks_are_not_fused
FAILED tests/test_transforms/test_content_router.py::test_join_tool_result_text_blocks[texts0-a\nb\nc]
FAILED tests/test_transforms/test_content_router.py::test_join_tool_result_text_blocks[texts1-a\nb]
FAILED tests/test_transforms/test_content_router.py::test_join_tool_result_text_blocks[texts2-a\nb]
FAILED tests/test_transforms/test_content_router.py::test_join_tool_result_text_blocks[texts3-only]
================== 5 failed, 1 passed, 65 deselected in 1.88s ==================
```

The four `test_join_tool_result_text_blocks` cases fail on the base
because the helper does not exist there. The passing test in the last
run is the control
`test_anthropic_tool_result_lossy_without_marker_stays_verbatim`.

## Real Behavior Proof

- Environment: Linux container, Python 3.13, headroom installed from
this branch with `uv sync --frozen --extra proxy`. Upstream is a local
stdlib HTTP server on 127.0.0.1:9911 that records the `/v1/messages`
body it receives and returns a fixed `ok` message. Dummy API key, no
real provider.
- Exact command / steps: `python -m headroom.cli proxy --host 127.0.0.1
--port 8799 --no-telemetry --no-rate-limit --anthropic-api-url
http://127.0.0.1:9911`, run once with the default mode and once with
`--mode token`. Then POST `/v1/messages` with a `tool_result` whose
content is two `text` blocks of 150 log lines each, the first block not
ending in a newline. Same steps against `main` for comparison.
- Observed result: the proxy compressed the tool result in all four runs
(`content_router: 3 msgs — 1 compressed (tool:log:0.03)`) and the client
got `200` with `ok`. On `main` the body forwarded upstream had 1 fused
line, `2026-11-10T10:29:00Z INFO worker-2 processed batch 149
ok2026-11-10T11:00:00Z WARN worker-0 retrying batch 0`. With this patch
it had 0 fused lines in both modes.
- Not tested: a real Anthropic or OpenAI endpoint, SSE streaming
responses, Bedrock, the OpenAI `/v1/chat/completions` handler (it goes
through the same `ContentRouter`), Windows and macOS.

## Runtime Rollout Safety

- Rollout-managed feature(s): N/A, this is a bug fix in the existing
compression path with no flag.
- Minimum rollout channel: N/A, no rollout-managed feature.
- Stable/default behavior changed: Yes, only for list-form `tool_result`
content with more than one `text` block: the blocks are now joined with
a newline instead of nothing before compression.
- Kill switch / disable path: N/A, no flag. Disabling compression for
the tool, as today, skips this path.
- Unsafe override required: No.
- Qualification impact: None expected. Single-block and string
`tool_result` content takes the same path as before.
- Rollback path: Revert this commit.

## 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 commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`; it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

Documentation is N/A, there is no user-facing change to document. I
checked the other provider paths: OpenAI `role: "tool"` messages with
list content are handled block by block and are not joined, so they do
not have this bug. "New and existing unit tests pass locally" refers to
the content router test modules listed above, run in the container.

Written with help from Claude Code.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4739"
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: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Aiman Malib
2026-11-16 23:25:28 -06:00
committed by GitHub
co-authored by Claude Opus 5.5 JD Davis
parent 3aafdf2dcc
commit f4e3ad4b11
2 changed files with 83 additions and 4 deletions
+20 -4
View File
@@ -2319,6 +2319,24 @@ def _mcp_result_min_chars() -> int:
_MCP_NAME_PREFIXES = ("mcp_", "mcp--")
def _join_tool_result_text_blocks(blocks: list[Any]) -> str:
"""Flatten list-form ``tool_result`` text blocks into one string.
Each block is a separate piece of tool output (an MCP server returning
several ``TextContent`` items, for example), so a newline goes between
blocks unless the block already ends with one. A bare ``"".join`` fuses
the last line of one block with the first line of the next, and the
line-oriented compressors then emit a line the tool never produced.
"""
parts: list[str] = []
for i, b in enumerate(blocks):
text = b.get("text", "")
parts.append(text)
if i < len(blocks) - 1 and text and not text.endswith("\n"):
parts.append("\n")
return "".join(parts)
def _is_small_mcp_result(tool_name: Any, text: Any) -> bool:
"""True when ``text`` is an MCP tool's output short enough to keep verbatim.
@@ -8044,7 +8062,7 @@ class ContentRouter(Transform):
and all(isinstance(b, dict) and b.get("type") == "text" for b in _tr_content)
)
_tr_text = (
"".join(b.get("text", "") for b in _tr_content)
_join_tool_result_text_blocks(_tr_content)
if _tr_list_form_early
else _tr_content
)
@@ -8149,9 +8167,7 @@ class ContentRouter(Transform):
and all(isinstance(b, dict) and b.get("type") == "text" for b in tool_content)
)
tool_text = (
"".join(b.get("text", "") for b in tool_content)
if _tr_list_form
else tool_content
_join_tool_result_text_blocks(tool_content) if _tr_list_form else tool_content
)
# Small MCP results stay verbatim (see _is_small_mcp_result).
@@ -412,6 +412,69 @@ def test_anthropic_tool_result_lossy_without_marker_stays_verbatim(router, token
assert result.messages[0]["content"][0]["content"] == tool_content
def _multi_block_tool_result_messages(blocks: list[dict]) -> list[dict]:
return [
{"role": "user", "content": "fetch the worker logs"},
{
"role": "assistant",
"content": [{"type": "tool_use", "id": "tu1", "name": "mcp__logs__fetch", "input": {}}],
},
{
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": "tu1", "content": blocks}],
},
{"role": "user", "content": "any errors?"},
]
def test_list_form_tool_result_blocks_are_not_fused(router, tokenizer):
"""A list-form tool_result with several text blocks (an MCP tool returning
more than one TextContent) is flattened for the compressors. The blocks
must stay on separate lines: joining them with "" fused the last line of
one block with the first line of the next (#4729)."""
lines_a = [
f"2026-11-10T10:{i % 60:02d}:00Z INFO worker-{i % 3} batch {i} ok" for i in range(150)
]
lines_b = [f"2026-11-10T11:{i % 60:02d}:00Z WARN worker-{i % 3} retry {i}" for i in range(150)]
blocks = [
{"type": "text", "text": "\n".join(lines_a)},
{"type": "text", "text": "\n".join(lines_b)},
]
result = router.apply(
_multi_block_tool_result_messages(blocks),
tokenizer,
compress_user_messages=True,
min_tokens_to_compress=10,
read_protection_window=0,
)
out = result.messages[2]["content"][0]["content"]
assert isinstance(out, list) and len(out) == 1 and out[0]["type"] == "text"
text = out[0]["text"]
assert text != "\n".join(lines_a + lines_b), "compressor did not run"
original = set(lines_a) | set(lines_b)
emitted = [line for line in text.splitlines() if line.startswith("2026-11-10T")]
assert emitted, "no log lines survived compression"
assert [line for line in emitted if line not in original] == []
@pytest.mark.parametrize(
("texts", "expected"),
[
(["a\nb", "c"], "a\nb\nc"),
(["a\n", "b"], "a\nb"),
(["a", "", "b"], "a\nb"),
(["only"], "only"),
],
)
def test_join_tool_result_text_blocks(texts, expected):
from headroom.transforms.content_router import _join_tool_result_text_blocks
blocks = [{"type": "text", "text": t} for t in texts]
assert _join_tool_result_text_blocks(blocks) == expected
# =============================================================================
# TestContentRouterConfig
# =============================================================================