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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(smart-crusher): keep non-dict arrays and object keys whole under lossless_only (#3628)
Suliman Abdulrazzaq58c7f7210637
diff --git a/crates/headroom-core/src/transforms/smart_crusher/config.rs b/crates/headroom-core/src/transforms/smart_crusher/config.rsindex 69956e9e4..0b7d0070e 100644--- a/crates/headroom-core/src/transforms/smart_crusher/config.rs+++ b/crates/headroom-core/src/transforms/smart_crusher/config.rs@@ -83,7 +83,9 @@ pub struct SmartCrusherConfig {/// Strict lossless mode. When `true`, lossless tabular compaction/// still applies, but any path that would otherwise need a CCR/// marker — the lossy row-drop sentinel AND opaque-blob offload —- /// leaves the content uncompacted instead. The result is always+ /// leaves the content uncompacted instead. The string, number and+ /// mixed-array crushers and the object-key crusher, which drop items+ /// without any marker, keep every item too. The result is always/// marker-free and byte-recoverable: rows are never dropped and/// opaque cells render inline. Default `false` (markers allowed).pub lossless_only: bool,diff --git a/crates/headroom-core/src/transforms/smart_crusher/crusher.rs b/crates/headroom-core/src/transforms/smart_crusher/crusher.rsindex f89d59324..a247890a2 100644--- a/crates/headroom-core/src/transforms/smart_crusher/crusher.rs+++ b/crates/headroom-core/src/transforms/smart_crusher/crusher.rs@@ -980,6 +980,13 @@ impl SmartCrusher {return (items.to_vec(), "mixed:passthrough".to_string());}+ // Strict lossless mode: the string and number groups below are+ // sampled without a CCR marker, so keep every item instead. (The+ // dict group would already be kept whole by `crush_array`.)+ if self.config.lossless_only {+ return (items.to_vec(), "mixed:lossless_only".to_string());+ }+// Group by type, tracking original indices.let mut groups: GroupBuckets = GroupBuckets::default();for (i, item) in items.iter().enumerate() {@@ -2073,4 +2080,73 @@ mod tests {"ccr_store grew under lossless_only — invariant violated");}++ #[test]+ fn lossless_only_keeps_every_mixed_array_item() {+ // The mixed-array crusher samples its string and number groups+ // and drops the rest with no marker (#3625).+ let items: Vec<Value> = (0..40)+ .map(|i| {+ if i % 2 == 0 {+ json!(format!("entry-{i}"))+ } else {+ json!(i)+ }+ })+ .collect();++ let (lossy, _) = crusher().crush_mixed_array(&items, "", 1.0);+ assert!(lossy.len() < items.len(), "default config should drop");++ let strict = SmartCrusher::new(SmartCrusherConfig {+ lossless_only: true,+ ..SmartCrusherConfig::default()+ });+ let (out, strategy) = strict.crush_mixed_array(&items, "", 1.0);+ assert_eq!(out, items, "lossless_only must keep every item");+ assert_eq!(strategy, "mixed:lossless_only");+ }++ #[test]+ fn lossless_only_crush_keeps_non_dict_arrays_and_object_keys() {+ // End-to-end through `crush()`, starting from the #3625 report:+ // an object whose value is a string array lost 38 of 53 items+ // with no marker even though lossless_only was set.+ let mut meta = serde_json::Map::new();+ for i in 0..40 {+ meta.insert(+ format!("k{i:02}"),+ json!(format!(+ "long description for entry {i}, above the small-value floor"+ )),+ );+ }+ let doc = json!({+ "slugs": (0..53).map(|i| format!("r{i}")).collect::<Vec<_>>(),+ "sizes": (1..=40).collect::<Vec<_>>(),+ "mixed": (0..40)+ .map(|i| if i % 2 == 0 { json!(format!("entry-{i}")) } else { json!(i) })+ .collect::<Vec<_>>(),+ "meta": meta,+ });+ let content = doc.to_string();++ let lossy: Value = serde_json::from_str(&crusher().crush(&content, "", 1.0).compressed)+ .expect("default output is JSON");+ assert_ne!(lossy, doc, "default config should drop items");++ let strict = SmartCrusher::new(SmartCrusherConfig {+ lossless_only: true,+ ..SmartCrusherConfig::default()+ });+ let result = strict.crush(&content, "", 1.0);+ assert!(+ !result.compressed.contains("<<ccr:"),+ "marker leaked under lossless_only: {}",+ result.compressed+ );+ let parsed: Value =+ serde_json::from_str(&result.compressed).expect("lossless_only output is JSON");+ assert_eq!(parsed, doc, "lossless_only output must decode to the input");+ }}diff --git a/crates/headroom-core/src/transforms/smart_crusher/crushers.rs b/crates/headroom-core/src/transforms/smart_crusher/crushers.rsindex 43c50498a..a6f3ecec2 100644--- a/crates/headroom-core/src/transforms/smart_crusher/crushers.rs+++ b/crates/headroom-core/src/transforms/smart_crusher/crushers.rs@@ -123,6 +123,15 @@ pub fn crush_string_array();}+ // Strict lossless mode: this crusher drops items without a CCR marker,+ // so nothing it removes would be recoverable. Keep the whole array.+ if config.lossless_only {+ return (+ items.iter().map(|s| (*s).to_string()).collect(),+ "string:lossless_only".to_string(),+ );+ }+// K split. Python serializes each item via json.dumps; for already-// string items that just wraps in quotes. We feed the raw &str refs// since adaptive_sizer's input is documented as "string repr in@@ -226,6 +235,11 @@ pub fn crush_number_array(return (items.to_vec(), "number:passthrough".to_string());}+ // Strict lossless mode: dropped numbers get no CCR marker either.+ if config.lossless_only {+ return (items.to_vec(), "number:lossless_only".to_string());+ }+// Filter to finite f64 only — Python: `isinstance(x, int|float) and math.isfinite(x)`.let finite: Vec<f64> = items.iter()@@ -399,6 +413,11 @@ pub fn crush_object(return (obj.clone(), "object:passthrough".to_string());}+ // Strict lossless mode: dropped keys get no CCR marker, so keep them all.+ if config.lossless_only {+ return (obj.clone(), "object:lossless_only".to_string());+ }+// Compute adaptive K on key-value string representations.let keys: Vec<&String> = obj.keys().collect();let kv_strings: Vec<String> = keys@@ -817,6 +836,65 @@ mod tests {);}+ // ---------- lossless_only (#3625) ----------+ //+ // These crushers drop items with no CCR marker at all, so strict+ // lossless mode must keep every item. Each test first confirms the+ // default config really drops on the same input, so the strict+ // assertion cannot pass vacuously.++ fn lossless_only_cfg() -> SmartCrusherConfig {+ SmartCrusherConfig {+ lossless_only: true,+ ..SmartCrusherConfig::default()+ }+ }++ #[test]+ fn string_array_lossless_only_keeps_every_item() {+ let owned: Vec<String> = (0..53).map(|i| format!("r{i}")).collect();+ let items: Vec<&str> = owned.iter().map(|s| s.as_str()).collect();++ let (lossy, _) = crush_string_array(&items, &cfg(), 1.0);+ assert!(lossy.len() < items.len(), "default config should drop");++ let (out, strat) = crush_string_array(&items, &lossless_only_cfg(), 1.0);+ assert_eq!(out, owned, "lossless_only must keep every string");+ assert_eq!(strat, "string:lossless_only");+ }++ #[test]+ fn number_array_lossless_only_keeps_every_item() {+ let items: Vec<Value> = (1..=40).map(|i| json!(i)).collect();++ let (lossy, _) = crush_number_array(&items, &cfg(), 1.0);+ assert!(lossy.len() < items.len(), "default config should drop");++ let (out, strat) = crush_number_array(&items, &lossless_only_cfg(), 1.0);+ assert_eq!(out, items, "lossless_only must keep every number");+ assert_eq!(strat, "number:lossless_only");+ }++ #[test]+ fn object_lossless_only_keeps_every_key() {+ let mut obj = Map::new();+ for i in 0..40 {+ obj.insert(+ format!("k{i:02}"),+ json!(format!(+ "long description for entry {i}, above the small-value floor"+ )),+ );+ }++ let (lossy, _) = crush_object(&obj, &cfg(), 1.0);+ assert!(lossy.len() < obj.len(), "default config should drop keys");++ let (out, strat) = crush_object(&obj, &lossless_only_cfg(), 1.0);+ assert_eq!(out, obj, "lossless_only must keep every key");+ assert_eq!(strat, "object:lossless_only");+ }+// ---------- BUG #1 documentation test ----------#[test]diff --git a/tests/test_transforms/test_smart_crusher_bugs.py b/tests/test_transforms/test_smart_crusher_bugs.pyindex 0981f2cba..23bf8fa2a 100644--- a/tests/test_transforms/test_smart_crusher_bugs.py+++ b/tests/test_transforms/test_smart_crusher_bugs.py@@ -162,6 +162,23 @@ class TestLosslessOnlyMode:assert "<<ccr:" not in out.compressedassert json.loads(out.compressed) == rows+ def test_lossless_only_keeps_non_dict_arrays_and_object_keys(self) -> None:+ # #3625: the string, number and mixed-array crushers and the+ # object-key crusher drop items with no marker, and they ignored+ # lossless_only, so strict mode silently truncated these shapes.+ doc = {+ "slugs": [f"r{i}" for i in range(53)],+ "sizes": list(range(1, 41)),+ "mixed": [f"entry-{i}" if i % 2 == 0 else i for i in range(40)],+ "meta": {+ f"k{i:02d}": f"long description for entry {i}, above the small-value floor"+ for i in range(40)+ },+ }+ out = SmartCrusher(config=SmartCrusherConfig(lossless_only=True)).crush(json.dumps(doc))+ assert "<<ccr:" not in out.compressed+ assert json.loads(out.compressed) == doc+def test_extract_context_survives_null_function_tool_call() -> None:# A tool_call with an explicit {"function": null} must not crash context