Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(transforms): recognise code fences whose info string is not a bare word (#4291)

Rudy Mizrahi Celeklia8df6f919f1c
diff --git a/headroom/transforms/mixed_content.py b/headroom/transforms/mixed_content.py
index e359ef485..999c3d35e 100644
--- a/headroom/transforms/mixed_content.py
+++ b/headroom/transforms/mixed_content.py
@@ -29,7 +29,12 @@ class ContentSection:
atomic: bool = False
-_CODE_FENCE_PATTERN = re.compile(r"^```(\w*)\s*$", re.MULTILINE)
+# Group 1 is the whole info string: any text without a backtick, so
+# ``c++``, ``c#``, ``objective-c``, ``js {1,3}`` and `` c++`` (space first) all
+# open a fence. ``\w*`` missed such openers and then took the closing fence
+# for one. A single quantifier keeps a long line linear; the language is the
+# info string's first word (see ``_fence_language``).
+_CODE_FENCE_PATTERN = re.compile(r"^```([^\n`]*)$", re.MULTILINE)
# ``[^\S\n]*``, not ``\s*``: under MULTILINE, ``^\s*`` rescans every
# following blank line from each line start (quadratic in a blank run).
_JSON_BLOCK_START = re.compile(r"^[^\S\n]*[\[{]", re.MULTILINE)
@@ -37,6 +42,12 @@ _SEARCH_RESULT_PATTERN = re.compile(r"^\S+:\d+:", re.MULTILINE)
_PROSE_PATTERN = re.compile(r"[A-Z][a-z]+\s+\w+\s+\w+")
+def _fence_language(info_string: str) -> str:
+ """First word of a fence info string, or ``"unknown"`` for a bare fence."""
+ words = info_string.split()
+ return words[0] if words else "unknown"
+
+
def _is_search_line(line: str) -> bool:
"""True for grep match lines and ``-A``/``-B``/``-C`` context lines.
@@ -150,7 +161,7 @@ def split_into_sections(content: str, *, isolate: tuple[str, ...] = ()) -> list[
continue
if match := _CODE_FENCE_PATTERN.match(line):
- language = match.group(1) or "unknown"
+ language = _fence_language(match.group(1))
code_lines = []
start_line = i
i += 1
diff --git a/tests/test_mixed_content_sections.py b/tests/test_mixed_content_sections.py
index 822a530a4..92c765895 100644
--- a/tests/test_mixed_content_sections.py
+++ b/tests/test_mixed_content_sections.py
@@ -1,3 +1,5 @@
+import pytest
+
from headroom.transforms.content_detector import ContentType
from headroom.transforms.mixed_content import (
_extract_json_block,
@@ -49,6 +51,60 @@ def test_split_into_sections_preserves_typed_boundaries():
assert sections[3].start_line == 5
+ ("info_string", "language"),
+ [
+ ("c++", "c++"),
+ ("c#", "c#"),
+ ("objective-c", "objective-c"),
+ ("js {1,3}", "js"),
+ ('python title="app.py"', "python"),
+ (" c++", "c++"),
+ ("python\r", "python"),
+ ],
+)
+def test_split_accepts_fence_info_strings_beyond_word_characters(info_string, language):
+ content = "\n".join(
+ [
+ "Here is the header file we wrote today.",
+ f"```{info_string}",
+ "int add(int a, int b);",
+ "```",
+ "Please review this carefully and tell me what you think.",
+ '{"name": "demo", "version": 1}',
+ ]
+ )
+
+ sections = split_into_sections(content)
+
+ assert [section.content_type for section in sections] == [
+ ContentType.PLAIN_TEXT,
+ ContentType.SOURCE_CODE,
+ ContentType.PLAIN_TEXT,
+ ContentType.JSON_ARRAY,
+ ]
+ assert sections[1].language == language
+ assert sections[1].content == "int add(int a, int b);"
+ assert sections[1].is_code_fence is True
+ assert sections[2].content == "Please review this carefully and tell me what you think."
+
+
+def test_fence_pattern_stays_linear_on_a_long_unclosed_fence_line():
+ import time
+
+ from headroom.transforms.mixed_content import _CODE_FENCE_PATTERN
+
+ line = "```" + "a" * 50_000 + "`"
+ best = float("inf")
+ for _ in range(3):
+ start = time.perf_counter()
+ assert _CODE_FENCE_PATTERN.match(line) is None
+ best = min(best, time.perf_counter() - start)
+ # Linear: well under 1 ms here. A quadratic pattern takes seconds, so a
+ # generous budget still catches it on a loaded runner.
+ assert best < 0.5, f"{best * 1000:.1f}ms on a 50,000-character fence line"
+
+
def test_split_carves_grep_context_lines_into_search_sections():
"""Regression (#3580): prose + ``grep -A`` output keeps code out of text.