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.

perf(compression/code): avoid a UTF-8 copy per code block in byte-to-char mapping (#3169)

Abhay Singhd5e5534b4763
diff --git a/headroom/compression/handlers/code_handler.py b/headroom/compression/handlers/code_handler.py
index 9caeec8c8..3e98f3d96 100644
--- a/headroom/compression/handlers/code_handler.py
+++ b/headroom/compression/handlers/code_handler.py
@@ -605,16 +605,24 @@ class CodeStructureHandler(BaseStructureHandler):
returned unchanged. Otherwise a byte->char table is built once
and every span endpoint is remapped.
"""
- n_bytes = len(content.encode("utf-8"))
- if n_bytes == len(content):
+ # ASCII fast path: every byte is one character, so tree-sitter's byte
+ # offsets are already character offsets. ``content.isascii()`` checks
+ # this in C without allocating, where ``len(content.encode("utf-8"))``
+ # built (and discarded) a full UTF-8 copy of the content on every code
+ # block just to compare lengths.
+ if content.isascii():
return spans
# byte_to_char[b] = index of the character containing byte b;
- # byte_to_char[n_bytes] = len(content) so exclusive ends map.
+ # byte_to_char[n_bytes] = len(content) so exclusive ends map. A
+ # character's UTF-8 width is derived from its code point (1-4 bytes)
+ # rather than re-encoding every character individually in the loop.
+ n_bytes = len(content.encode("utf-8"))
byte_to_char = [0] * (n_bytes + 1)
byte_pos = 0
for char_idx, ch in enumerate(content):
- ch_width = len(ch.encode("utf-8"))
+ cp = ord(ch)
+ ch_width = 1 if cp < 0x80 else 2 if cp < 0x800 else 3 if cp < 0x10000 else 4
for b in range(byte_pos, byte_pos + ch_width):
byte_to_char[b] = char_idx
byte_pos += ch_width
diff --git a/tests/test_compression/test_code_handler.py b/tests/test_compression/test_code_handler.py
index c0acb1147..20d42abfc 100644
--- a/tests/test_compression/test_code_handler.py
+++ b/tests/test_compression/test_code_handler.py
@@ -353,3 +353,40 @@ class TestTreeSitterContainers:
f"class code preserved {result.preservation_ratio:.0%} — "
"container bodies are leaking into the structural mask"
)
+
+
+class TestByteSpanToCharSpan:
+ """_byte_spans_to_char_spans must map tree-sitter byte offsets to character
+ offsets. The ASCII fast path returns spans unchanged (byte == char) without
+ allocating a UTF-8 copy; the non-ASCII path derives each character's width
+ from its code point instead of re-encoding it."""
+
+ def test_ascii_returns_spans_unchanged(self):
+ from headroom.compression.handlers.code_handler import CodeSpan
+
+ spans = [
+ CodeSpan(start=0, end=5, role="sig", is_structural=True),
+ CodeSpan(start=6, end=11, role="body", is_structural=False),
+ ]
+ out = CodeStructureHandler._byte_spans_to_char_spans(spans, "def f():\n pass\n")
+ assert [(s.start, s.end) for s in out] == [(0, 5), (6, 11)]
+
+ def test_non_ascii_remaps_byte_offsets_to_char_offsets(self):
+ from headroom.compression.handlers.code_handler import CodeSpan
+
+ # café (é = 2 bytes), 🚀 (4 bytes), 语言 (3 bytes each).
+ content = "x = 'café 🚀 语言'\n"
+ enc = content.encode("utf-8")
+ # A structural span covering the whole line, plus one covering 'return'-like
+ # region: give byte offsets and expect character offsets back.
+ whole = CodeSpan(start=0, end=len(enc), role="body", is_structural=True)
+ # byte offset of the closing quote vs its character offset
+ quote_byte = enc.rindex(b"'")
+ quote_char = content.rindex("'")
+ marker = CodeSpan(start=quote_byte, end=len(enc), role="sig", is_structural=True)
+
+ out = CodeStructureHandler._byte_spans_to_char_spans([whole, marker], content)
+ assert out[0].start == 0
+ assert out[0].end == len(content) # exclusive end maps to char length
+ assert out[1].start == quote_char # byte offset correctly remapped
+ assert out[1].end == len(content)