SmartCrusher
Statistical JSON and array compression that keeps important items and drops the rest.
SmartCrusher is Headroom's compressor for JSON tool outputs. This is the compressor that fires automatically when ContentRouter detects JSON arrays.
Lossless-first, not keep/drop-first
By default SmartCrusher tries a lossless compaction first: if the array is cleanly tabular (a consistent set of keys across items), it re-encodes every item into a compact csv-schema form and keeps it if that saves at least 30% of the bytes -- no items are dropped, they're just represented more compactly. Only when that lossless fold doesn't clear the 30% bar (or the array isn't cleanly tabular) does SmartCrusher fall back to the scored keep/drop behavior described below. See headroom/transforms/smart_crusher.py:415-419. Set with_compaction=False on SmartCrusher(...) to force the pre-lossless keep/drop-only path (this is also what Headroom's retention-property tests use).
How It Works
When the lossy keep/drop path runs, SmartCrusher doesn't blindly truncate arrays -- it scores each item across five dimensions:
- First/Last items -- Context for pagination and recency
- Error items -- 100% preservation of error states (never dropped)
- Anomalies -- Statistical outliers (> 2 standard deviations from the mean)
- Relevant items -- Matches to the user's query via BM25/embeddings
- Change points -- Significant transitions in data
On that path, the target size is max_items_after_crush (15 by default): a 1,000-item array becomes ~15 items with all the information the LLM actually needs (measured: a 1,000-item array with with_compaction=False compressed to 16 items).
What Gets Preserved
| Category | Preserved | Why |
|---|---|---|
| Errors | 100% | Critical for debugging |
| First N | 100% | Context and pagination |
| Last N | 100% | Recency |
| Anomalies | All | Unusual values matter |
| Relevant | Top K | Match user's query |
| Others | Sampled | Statistical representation |
JSON objects and unchanged values
Object keys are never sampled or dropped: named fields are not interchangeable array rows. Removing a key without a retrieval marker would make its value unrecoverable. SmartCrusher instead recurses into each value, so nested arrays can still use lossless table compaction or CCR-backed row offload, and opaque strings can still be replaced by retrievable CCR references.
A wide object containing only unchanged values therefore has zero structural compression savings, regardless of how many keys it contains. This is a deliberate reversibility tradeoff, not a promise that every large JSON object will shrink. Key-level offload would need its own retrieval contract before object-key sampling could safely return.
When recursive processing leaves a valid JSON value unchanged, SmartCrusher
returns its original bytes and sets was_modified=False. This applies to
objects, arrays, and scalars, including whitespace, Unicode escapes, and numeric
representations. Actual structural transformations still use compact JSON
serialization.
The routing pipeline then applies the existing Rust JsonMinifier as a separate
lossless step when SmartCrusher leaves routed JSON unchanged. Savings are
attributed to json_minifier, not smart_crusher, and do not create structural
TOIN records. Minification removes only whitespace outside strings: key order,
duplicate keys, string escapes, and number spellings remain byte-stable. Repeating
the same input produces the same output; already-minified JSON is a no-op.
The native live-zone JSON-array arm follows the same explicit step; its existing
content-type and token-reduction gates still apply.
Because no information is offloaded, lossless minification does not store an
original or append a CCR retrieval marker: the forwarded value remains valid
JSON. A mixed document still reports mixed when its sections take different
routes, even if only its JSON section saves tokens.
Minification takes precedence over lossy fallbacks when it saves tokens;
already-compact input can still reach the existing fallback chain. For tool
results with CCR enabled, each changed lossy mixed section must carry its own
retrieval marker. Embedded JSON carries reversibility separately for each adopted
span: lossless minification needs no marker, while a marker on another span or
section does not authorize dropping its data. Candidates rejected by the token
benefit gate do not affect the adopted spans' reversibility. Rejected mixed
results do not enter the tool-result cache.
Comparing historical TOIN data
Unchanged values do not produce new TOIN compression records, even when the
strategy contains a diagnostic about a skipped transformation. Older TOIN
aggregates may include object-scoring strategies, formatting-only changes, or
zero-savings lossless_only decisions from different implementations.
Do not compare those aggregates directly with current object-key-preserving results or treat zero-savings decisions as successful compression. Compare the same corpus and configuration on both revisions, report unchanged wide objects separately from objects with transformed descendants, and identify the engine revision. Existing TOIN history is retained; this change does not rewrite or delete a user's learned state.
Quick Start
import { } from "headroom-ai";
// SmartCrusher fires automatically for JSON tool outputs
const = [
{ : "system" as , : "You are a helpful assistant." },
{ : "user" as , : "Find errors in the last 24 hours" },
{
: "tool" as ,
: .({ : new (1000).({ : "ok" }) }),
: "call_1",
},
];
const = await ();
.(`Tokens saved: ${.tokensSaved}`);
// SmartCrusher keeps errors, anomalies, and relevant itemsRecovered tool output in the Python message transform
SmartCrusher.apply(messages, tokenizer) preserves recognized
headroom_retrieve results byte for byte when their call ID matches the
originating assistant call. The originating identity is resolved with the
shared wrapper parser for both OpenAI tool_calls/arguments and Anthropic
tool_use/input, including Hermes tool_call bridges and retrieval calls
inside execute, exec, or functions.exec.
Other wrapper output remains compressible; an unrecognized or ambiguous
wrapper does not gain a blanket recovery exemption. Keep the originating
assistant call in the message history so the result can be identified.
The context-free crush(json_string) API has no originating-call history and
does not provide this message-level exemption.
Configuration
import { } from "headroom-ai";
// Configure via the Headroom proxy or HeadroomClient
const = await (messages, {
: "gpt-4o",
: 10000, // SmartCrusher will reduce JSON to fit
});
.(`Transforms: ${.transformsApplied}`);
// ["smart_crusher", "cache_aligner"]Configuration Options
| Option | Default | Description |
|---|---|---|
min_tokens_to_crush | 200 | Only compress arrays with more than this many tokens |
min_items_to_analyze | 5 | Minimum items before analyzing for compression |
max_items_after_crush | 15 | Maximum items to keep after compression |
variance_threshold | 2.0 | Statistical variance threshold for analysis |
uniqueness_threshold | 0.1 | Uniqueness threshold for deduplication |
similarity_threshold | 0.8 | Similarity threshold for grouping |
preserve_change_points | True | Preserve significant transitions in data |
first_fraction | 0.3 | Fraction of items always kept from the start |
last_fraction | 0.15 | Fraction of items always kept from the end |
dedup_identical_items | True | Deduplicate identical items |
use_feedback_hints | True | Use TOIN feedback hints for scoring |
Example: Before and After
Consider a tool that returns 1,000 search results:
# Before compression: 45,000 tokens
{
"results": [
{"id": 1, "status": "ok", "message": "Success", "timestamp": "..."},
{"id": 2, "status": "ok", "message": "Success", "timestamp": "..."},
# ... 995 more "ok" results ...
{"id": 998, "status": "error", "message": "Connection timeout", "timestamp": "..."},
{"id": 999, "status": "ok", "message": "Success", "timestamp": "..."},
{"id": 1000, "status": "ok", "message": "Success", "timestamp": "..."},
]
}
# After SmartCrusher's lossy keep/drop path (with_compaction=False):
# ~15-16 items kept -- first items, last items, and the error at id=998The LLM sees the structure, the error, and a representative sample -- everything it needs to answer "find errors in the last 24 hours" without wading through 1,000 identical success responses. Note this specific shape (mostly-identical items, one error) is also exactly what the lossless table fold favors (see the callout above), so with default settings this array is more likely to be re-encoded compactly with every item still present than reduced to ~15 items -- the numbers above illustrate the scored keep/drop path, not a guarantee of which path a given array takes.
Automatic routing
You don't need to call SmartCrusher directly. The ContentRouter detects JSON arrays and routes them to SmartCrusher automatically. Direct usage is available when you want fine-grained control over the configuration.