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(compression): measure short-value threshold on payload, not token (#889)

Ashish65b0e8c58dbb
diff --git a/headroom/compression/handlers/json_handler.py b/headroom/compression/handlers/json_handler.py
index 67e41af37..80d4f7ec5 100644
--- a/headroom/compression/handlers/json_handler.py
+++ b/headroom/compression/handlers/json_handler.py
@@ -231,14 +231,17 @@ class JSONStructureHandler(BaseStructureHandler):
# In deep array, be more aggressive
return False
+ # Strip quotes once: thresholds apply to the payload, not
+ # the token. Counting the quote characters made a "20-char
+ # threshold" effectively 18 chars of value.
+ value = token.text.strip('"')
+
# Preserve short values
- if self.preserve_short_values and len(token.text) <= self.short_value_threshold:
+ if self.preserve_short_values and len(value) <= self.short_value_threshold:
return True
# Preserve high-entropy values (UUIDs, hashes)
if self.preserve_high_entropy:
- # Strip quotes for entropy calculation
- value = token.text.strip('"')
# Entropy targets identifiers (UUIDs, hashes, API keys).
# Self-normalized entropy also scores English prose >0.85,
# so gate on the cheapest identifier signal: no spaces.
diff --git a/tests/test_compression/test_json_handler.py b/tests/test_compression/test_json_handler.py
index c86b7e20f..404babbf7 100644
--- a/tests/test_compression/test_json_handler.py
+++ b/tests/test_compression/test_json_handler.py
@@ -222,6 +222,26 @@ class TestJSONStructureHandler:
"UUID value should be preserved via entropy"
)
+ def test_short_value_threshold_excludes_quotes(self):
+ """The short-value threshold measures the payload, not the token.
+
+ Regression: len(token.text) included both quote characters, so a
+ value of exactly threshold length was rejected (off-by-2).
+ """
+ handler = JSONStructureHandler(
+ preserve_short_values=True,
+ short_value_threshold=20,
+ preserve_high_entropy=False,
+ )
+ exact = "x" * 20 # exactly at threshold — must be preserved
+ content = f'{{"key": "{exact}"}}'
+ result = handler.get_mask(content)
+
+ start = content.index(exact)
+ assert all(result.mask.mask[i] for i in range(start, start + len(exact))), (
+ "value of exactly threshold length should be preserved"
+ )
+
def test_metadata_contains_key_count(self, handler):
"""Test that metadata includes key count."""
content = '{"a": 1, "b": 2, "c": 3}'