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
Add dynamic anchor selection with content deduplication
chopratejas2292724ff777
diff --git a/docs/plans/dynamic-smart-crusher.md b/docs/plans/dynamic-smart-crusher.mdnew file mode 100644index 000000000..88754bf79--- /dev/null+++ b/docs/plans/dynamic-smart-crusher.md@@ -0,0 +1,769 @@+# Dynamic SmartCrusher Preservation Plan++## Problem Statement++Current SmartCrusher uses **static "First 3 + Last 2" preservation** regardless of:+- Array size (100 items vs 10,000 items get same treatment)+- Data pattern (time series vs search results vs logs)+- Query context (user asking about "latest" vs "oldest")+- Position importance (first items might all be identical/wasteful)+- Learned retrieval patterns (which positions do users actually need?)++This is too simplistic for a production-grade compression system.++---++## Current Implementation Analysis++**Location:** `headroom/transforms/smart_crusher.py`++**Current Logic (lines 2273-2279, 2353-2359, 2561-2567):**+```python+# Always keep first 3+for i in range(min(3, n)):+ keep_indices.add(i)++# Always keep last 2+for i in range(max(0, n - 2), n):+ keep_indices.add(i)+```++**Problems:**+1. **Fixed slots waste budget** - If first 3 items are identical, we've wasted 3 slots+2. **No size adaptation** - 20-item array loses 25% to anchors; 1000-item array loses 0.5%+3. **Pattern-agnostic** - Search results don't need "last 2"; time series might need more recency+4. **No learning** - Doesn't adapt based on what users actually retrieve++---++## Proposed Solution: Adaptive Slot Allocation++### Idea 1: Size-Proportional Anchor Budget++Instead of fixed counts, allocate a **percentage budget** for position-based anchors:++```python+def calculate_anchor_budget(array_size: int, max_items: int) -> AnchorBudget:+ """Allocate slots proportionally, with floors and ceilings."""++ # Base: 20% of output budget for position anchors+ total_anchor_slots = max(3, min(10, int(max_items * 0.20)))++ # Distribution: 60% front, 40% back (front-weighted for context)+ front_slots = max(1, int(total_anchor_slots * 0.6))+ back_slots = max(1, total_anchor_slots - front_slots)++ return AnchorBudget(front=front_slots, back=back_slots)+```++**Example:**+| Array Size | Max Items | Anchor Budget | Front | Back |+|------------|-----------|---------------|-------|------|+| 50 | 10 | 3 | 2 | 1 |+| 200 | 15 | 3 | 2 | 1 |+| 1000 | 20 | 4 | 3 | 1 |+| 5000 | 30 | 6 | 4 | 2 |++---++### Idea 2: Pattern-Aware Anchor Weighting++Different data patterns need different position importance:++```python+class AnchorStrategy(Enum):+ FRONT_HEAVY = "front_heavy" # Search results: top items matter most+ BACK_HEAVY = "back_heavy" # Logs: recent items matter most+ BALANCED = "balanced" # Time series: both ends matter+ MIDDLE_AWARE = "middle_aware" # Database: order might be arbitrary++def get_anchor_strategy(pattern: DataPattern) -> AnchorStrategy:+ return {+ DataPattern.SEARCH_RESULTS: AnchorStrategy.FRONT_HEAVY, # Top N by score+ DataPattern.LOGS: AnchorStrategy.BACK_HEAVY, # Recency matters+ DataPattern.TIME_SERIES: AnchorStrategy.BALANCED, # Both ends for trend+ DataPattern.GENERIC: AnchorStrategy.MIDDLE_AWARE, # Don't assume order+ }.get(pattern, AnchorStrategy.BALANCED)+```++**FRONT_HEAVY (Search Results):**+- Front: 80% of anchor budget+- Back: 20% of anchor budget+- Rationale: Top search results are ranked by relevance++**BACK_HEAVY (Logs):**+- Front: 20% of anchor budget+- Back: 80% of anchor budget+- Rationale: Most recent logs are usually most relevant++**BALANCED (Time Series):**+- Front: 50% of anchor budget+- Back: 50% of anchor budget+- Rationale: Need both start and end for trend analysis++**MIDDLE_AWARE (Generic/Database):**+- Front: 30% of anchor budget+- Back: 30% of anchor budget+- Middle sample: 40% of anchor budget (stratified)+- Rationale: Order might be arbitrary; sample across positions++---++### Idea 3: Query-Aware Dynamic Weighting++Adjust anchor strategy based on user's query:++```python+def adjust_for_query(base_strategy: AnchorStrategy, query: str) -> AnchorWeights:+ """Shift anchor weights based on query intent."""++ weights = base_strategy.default_weights()++ # Recency signals+ recency_keywords = ["latest", "recent", "last", "newest", "current"]+ if any(kw in query.lower() for kw in recency_keywords):+ weights.back_weight *= 1.5+ weights.front_weight *= 0.7++ # Historical signals+ historical_keywords = ["first", "oldest", "earliest", "original", "initial"]+ if any(kw in query.lower() for kw in historical_keywords):+ weights.front_weight *= 1.5+ weights.back_weight *= 0.7++ # Range signals+ range_keywords = ["all", "every", "complete", "full"]+ if any(kw in query.lower() for kw in range_keywords):+ weights.middle_weight *= 1.3 # Better coverage++ return weights.normalize()+```++---++### Idea 4: Information-Density Anchor Selection++Don't blindly take first N - select **most informative** items from anchor regions:++```python+def select_informative_anchors(+ items: list[dict],+ region: str, # "front", "back", "middle"+ slots: int,+ all_items_hash: set[str]+) -> list[int]:+ """Select most informative items from a region."""++ if region == "front":+ candidates = list(range(min(slots * 3, len(items)))) # Consider 3x candidates+ elif region == "back":+ start = max(0, len(items) - slots * 3)+ candidates = list(range(start, len(items)))+ else: # middle+ step = len(items) // (slots * 3 + 1)+ candidates = [i * step for i in range(1, slots * 3 + 1)]++ # Score each candidate by information content+ scored = []+ for idx in candidates:+ item = items[idx]+ item_hash = hash_item(item)++ # Skip if we've seen identical item+ if item_hash in all_items_hash:+ continue++ score = calculate_information_score(item, items)+ scored.append((idx, score, item_hash))++ # Select top N by information score+ scored.sort(key=lambda x: x[1], reverse=True)+ selected = []+ for idx, _, item_hash in scored[:slots]:+ selected.append(idx)+ all_items_hash.add(item_hash)++ return sorted(selected)+++def calculate_information_score(item: dict, all_items: list[dict]) -> float:+ """Score item by how much unique information it contributes."""++ score = 0.0++ # 1. Field uniqueness - rare field values score higher+ for field, value in item.items():+ field_values = [i.get(field) for i in all_items if field in i]+ value_frequency = field_values.count(value) / len(field_values)+ score += (1 - value_frequency) # Rare values score higher++ # 2. Structural uniqueness - different fields than typical+ typical_fields = get_typical_fields(all_items)+ unique_fields = set(item.keys()) - typical_fields+ score += len(unique_fields) * 0.5++ # 3. Content length - longer items often more informative+ content_length = len(json.dumps(item))+ avg_length = sum(len(json.dumps(i)) for i in all_items) / len(all_items)+ if content_length > avg_length:+ score += 0.3++ return score+```++---++### Idea 5: TOIN-Learned Position Importance++Track which positions users actually retrieve and learn from it:++```python+@dataclass+class PositionRetrievalPattern:+ """Learned position importance from retrieval data."""+ tool_name: str+ total_compressions: int+ position_retrievals: dict[str, int] # "front_10%", "middle", "back_10%"++ def get_position_weights(self) -> dict[str, float]:+ """Convert retrieval counts to weights."""+ total = sum(self.position_retrievals.values())+ if total == 0:+ return {"front": 0.5, "middle": 0.0, "back": 0.5}++ return {+ position: count / total+ for position, count in self.position_retrievals.items()+ }+++class TOINPositionLearning:+ """Learn position importance from retrieval patterns."""++ def record_retrieval(+ self,+ tool_name: str,+ original_size: int,+ retrieved_indices: list[int]+ ):+ """Record which positions were retrieved."""+ for idx in retrieved_indices:+ position = self._classify_position(idx, original_size)+ self._increment_position_count(tool_name, position)++ def _classify_position(self, idx: int, size: int) -> str:+ """Classify index into position bucket."""+ relative_pos = idx / size+ if relative_pos < 0.1:+ return "front_10%"+ elif relative_pos < 0.3:+ return "front_30%"+ elif relative_pos > 0.9:+ return "back_10%"+ elif relative_pos > 0.7:+ return "back_30%"+ else:+ return "middle"++ def get_anchor_recommendation(self, tool_name: str) -> AnchorWeights:+ """Get learned anchor weights for a tool."""+ pattern = self._get_pattern(tool_name)+ if pattern.total_compressions < 10:+ return AnchorWeights.default() # Not enough data++ weights = pattern.get_position_weights()+ return AnchorWeights(+ front=weights.get("front_10%", 0.3) + weights.get("front_30%", 0.1),+ middle=weights.get("middle", 0.2),+ back=weights.get("back_10%", 0.3) + weights.get("back_30%", 0.1),+ )+```++---++### Idea 6: Stratified Sampling for Middle Positions++For large arrays, sample strategically from middle:++```python+def stratified_middle_sample(+ items: list[dict],+ num_samples: int,+ analysis: ArrayAnalysis+) -> list[int]:+ """Sample middle positions using stratified approach."""++ n = len(items)+ front_boundary = int(n * 0.1)+ back_boundary = int(n * 0.9)+ middle_items = list(range(front_boundary, back_boundary))++ if not middle_items or num_samples <= 0:+ return []++ # Strategy 1: Cluster-based sampling+ if analysis.has_clusterable_field:+ clusters = cluster_by_field(items, analysis.cluster_field)+ return sample_from_clusters(clusters, num_samples, middle_items)++ # Strategy 2: Variance-based sampling (pick high-variance points)+ if analysis.numeric_fields:+ variance_scores = calculate_position_variance(items, analysis.numeric_fields)+ sorted_by_variance = sorted(+ middle_items,+ key=lambda i: variance_scores.get(i, 0),+ reverse=True+ )+ return sorted(sorted_by_variance[:num_samples])++ # Strategy 3: Even spacing (fallback)+ step = len(middle_items) // (num_samples + 1)+ return [middle_items[i * step] for i in range(1, num_samples + 1)]+```++---++## Testing Strategy++### Test Category 1: Adversarial Position Tests++Test cases where important data is NOT at expected positions:++```python+class TestAdversarialPositions:+ """Test scenarios that break 'first 3 + last 2' assumption."""++ def test_important_data_in_middle(self):+ """Critical error at position 50 of 100-item array."""+ items = [{"status": "ok", "value": i} for i in range(100)]+ items[50] = {"status": "error", "error_code": "CRITICAL", "value": 50}++ result = smart_crusher.crush(items, max_items=10)++ # Error item MUST be preserved regardless of position+ assert any(item.get("error_code") == "CRITICAL" for item in result)++ def test_spike_not_at_boundaries(self):+ """Numeric spike at position 75 of 100-item array."""+ items = [{"metric": 10.0 + random.random()} for _ in range(100)]+ items[75]["metric"] = 1000.0 # Spike++ result = smart_crusher.crush(items, max_items=10)++ # Spike MUST be preserved as anomaly+ assert any(item["metric"] > 500 for item in result)++ def test_first_items_identical(self):+ """First 10 items are identical - shouldn't waste slots."""+ items = [{"id": "same", "value": 0}] * 10 + [+ {"id": f"unique_{i}", "value": i} for i in range(90)+ ]++ result = smart_crusher.crush(items, max_items=10)++ # Should NOT have multiple identical items+ ids = [item["id"] for item in result]+ # At most 1-2 of the identical items, not 3+ assert ids.count("same") <= 2++ def test_last_items_identical(self):+ """Last 10 items are identical - shouldn't waste slots."""+ items = [{"id": f"unique_{i}", "value": i} for i in range(90)] + [+ {"id": "same", "value": 100}+ ] * 10++ result = smart_crusher.crush(items, max_items=10)++ ids = [item["id"] for item in result]+ assert ids.count("same") <= 2++ def test_relevant_item_in_middle(self):+ """Item matching user query is in middle of array."""+ items = [{"name": f"item_{i}", "status": "active"} for i in range(100)]+ items[42]["name"] = "target_item"+ items[42]["description"] = "This is what user asked about"++ result = smart_crusher.crush(+ items,+ max_items=10,+ query="find target_item"+ )++ # Query-matched item MUST be preserved+ assert any("target_item" in item.get("name", "") for item in result)+```++### Test Category 2: Size Adaptation Tests++```python+class TestSizeAdaptation:+ """Test that anchor allocation scales with array size."""++ @pytest.mark.parametrize("size,expected_min_anchors", [+ (20, 3), # Small array: at least 3 anchors+ (100, 4), # Medium array: at least 4 anchors+ (500, 5), # Large array: at least 5 anchors+ (2000, 6), # Very large: at least 6 anchors+ ])+ def test_anchor_count_scales(self, size, expected_min_anchors):+ """Anchor count should increase with array size."""+ items = [{"id": i, "value": i * 10} for i in range(size)]++ result = smart_crusher.crush(items, max_items=20)++ # Count items from first 10% and last 10%+ anchor_count = sum(+ 1 for item in result+ if item["id"] < size * 0.1 or item["id"] > size * 0.9+ )++ assert anchor_count >= expected_min_anchors++ def test_small_array_high_preservation(self):+ """Small arrays should preserve higher percentage."""+ items = [{"id": i} for i in range(15)]++ result = smart_crusher.crush(items, max_items=20)++ # Should preserve most/all of small array+ assert len(result) >= 10 # At least 66%++ def test_large_array_efficient_sampling(self):+ """Large arrays should sample efficiently."""+ items = [{"id": i, "value": i} for i in range(5000)]++ result = smart_crusher.crush(items, max_items=20)++ # Should have good distribution across positions+ positions = [item["id"] for item in result]++ has_front = any(p < 500 for p in positions)+ has_middle = any(500 < p < 4500 for p in positions)+ has_back = any(p > 4500 for p in positions)++ assert has_front and has_back+ # Middle should be represented if array is large enough+ assert has_middle+```++### Test Category 3: Pattern-Specific Tests++```python+class TestPatternAwareAnchoring:+ """Test pattern-specific anchor strategies."""++ def test_search_results_front_heavy(self):+ """Search results should preserve more from front."""+ items = [+ {"title": f"Result {i}", "score": 1.0 - (i * 0.01)}+ for i in range(100)+ ]++ result = smart_crusher.crush(items, max_items=10)++ # More items should be from front (high scores)+ front_count = sum(1 for item in result if item["score"] > 0.9)+ back_count = sum(1 for item in result if item["score"] < 0.1)++ assert front_count > back_count++ def test_logs_back_heavy(self):+ """Logs should preserve more from back (recent)."""+ items = [+ {"timestamp": f"2024-01-{i:02d}", "level": "INFO", "message": f"Log {i}"}+ for i in range(1, 31)+ ]++ result = smart_crusher.crush(items, max_items=10)++ # More items should be from back (recent logs)+ timestamps = [item["timestamp"] for item in result]+ recent_count = sum(1 for ts in timestamps if int(ts[-2:]) > 20)+ old_count = sum(1 for ts in timestamps if int(ts[-2:]) < 10)++ assert recent_count >= old_count++ def test_time_series_balanced(self):+ """Time series should have balanced front/back."""+ items = [+ {"timestamp": f"2024-01-01T{i:02d}:00:00", "value": 100 + i}+ for i in range(24)+ ]++ result = smart_crusher.crush(items, max_items=8)++ hours = [int(item["timestamp"][11:13]) for item in result]+ front_count = sum(1 for h in hours if h < 8)+ back_count = sum(1 for h in hours if h > 16)++ # Should be roughly balanced+ assert abs(front_count - back_count) <= 2+```++### Test Category 4: Query-Aware Tests++```python+class TestQueryAwareAnchoring:+ """Test query-based anchor adjustment."""++ def test_latest_query_shifts_to_back(self):+ """'Latest' in query should preserve more recent items."""+ items = [{"id": i, "created": f"2024-01-{i:02d}"} for i in range(1, 31)]++ result = smart_crusher.crush(+ items,+ max_items=8,+ query="Show me the latest entries"+ )++ ids = [item["id"] for item in result]+ recent_count = sum(1 for id in ids if id > 20)++ assert recent_count >= 3 # At least 3 recent items++ def test_first_query_shifts_to_front(self):+ """'First' in query should preserve earlier items."""+ items = [{"id": i, "created": f"2024-01-{i:02d}"} for i in range(1, 31)]++ result = smart_crusher.crush(+ items,+ max_items=8,+ query="Show me the first entries"+ )++ ids = [item["id"] for item in result]+ early_count = sum(1 for id in ids if id < 10)++ assert early_count >= 3++ def test_specific_id_query_finds_item(self):+ """Query for specific ID should find it regardless of position."""+ items = [{"id": f"item_{i:04d}", "value": i} for i in range(1000)]++ result = smart_crusher.crush(+ items,+ max_items=10,+ query="Find item_0567"+ )++ assert any(item["id"] == "item_0567" for item in result)+```++### Test Category 5: Coverage Metrics Tests++```python+class TestCoverageMetrics:+ """Test that preserved items represent the full distribution."""++ def test_value_range_coverage(self):+ """Preserved items should cover the value range."""+ items = [{"value": i} for i in range(100)]++ result = smart_crusher.crush(items, max_items=10)++ values = [item["value"] for item in result]++ # Should cover most of the range+ assert min(values) < 10 # Has low values+ assert max(values) > 90 # Has high values++ # Should have some middle values too+ middle_count = sum(1 for v in values if 30 < v < 70)+ assert middle_count >= 1++ def test_category_coverage(self):+ """Preserved items should represent all categories."""+ items = [+ {"category": cat, "id": i}+ for i, cat in enumerate(["A"] * 30 + ["B"] * 30 + ["C"] * 40)+ ]++ result = smart_crusher.crush(items, max_items=10)++ categories = set(item["category"] for item in result)++ # Should have at least 2 of 3 categories+ assert len(categories) >= 2++ def test_temporal_coverage(self):+ """Preserved items should span the time range."""+ items = [+ {"timestamp": f"2024-{m:02d}-15", "event": f"event_{i}"}+ for i, m in enumerate(range(1, 13))+ ]++ result = smart_crusher.crush(items, max_items=5)++ months = [int(item["timestamp"][5:7]) for item in result]++ # Should span at least 6 months of the year+ assert max(months) - min(months) >= 6+```++### Test Category 6: Retrieval Simulation Tests++```python+class TestRetrievalSimulation:+ """Simulate user retrieval patterns to measure effectiveness."""++ def test_retrieval_hit_rate_random_queries(self):+ """Measure how often preserved items satisfy random queries."""+ items = [+ {"id": i, "name": f"Item {i}", "category": f"cat_{i % 5}"}+ for i in range(100)+ ]++ compressed = smart_crusher.crush(items, max_items=15)+ compressed_ids = {item["id"] for item in compressed}++ # Simulate 100 random "queries" (random item lookups)+ hits = 0+ for _ in range(100):+ target_id = random.randint(0, 99)+ if target_id in compressed_ids:+ hits += 1++ # Should hit at least 15% (we keep 15 of 100)+ assert hits >= 15++ def test_retrieval_hit_rate_weighted_queries(self):+ """Measure hits for queries weighted toward common patterns."""+ items = [{"id": i, "value": i * 10} for i in range(100)]++ compressed = smart_crusher.crush(items, max_items=15)+ compressed_ids = {item["id"] for item in compressed}++ # Weight queries toward front (30%), back (30%), anomalies (40%)+ hits = 0+ queries = (+ list(range(10)) * 3 + # Front queries+ list(range(90, 100)) * 3 + # Back queries+ [50] * 4 # Middle anomaly queries+ )++ for target_id in queries:+ if target_id in compressed_ids:+ hits += 1++ # Should hit more often than random due to anchor strategy+ assert hits >= 20 # At least 20% hit rate+```++---++## Implementation Phases++### Phase 1: Refactor Anchor Logic (Foundation)++1. Extract anchor selection into `AnchorSelector` class+2. Make slot counts configurable via `AnchorConfig`+3. Add size-proportional allocation+4. Maintain backward compatibility with current defaults++### Phase 2: Pattern-Aware Anchoring++1. Map `DataPattern` to `AnchorStrategy`+2. Implement front-heavy, back-heavy, balanced, middle-aware strategies+3. Add pattern-specific anchor weight configs++### Phase 3: Information-Density Selection++1. Add `calculate_information_score()` for items+2. Select from candidate region instead of fixed positions+3. Deduplicate identical items across regions++### Phase 4: Query-Aware Adjustment++1. Parse query for position intent keywords+2. Adjust anchor weights dynamically+3. Add query-position relevance scoring++### Phase 5: TOIN Position Learning++1. Track retrieval positions in TOIN+2. Learn per-tool position importance+3. Use learned weights to adjust anchor strategy++### Phase 6: Comprehensive Testing++1. Implement all adversarial tests+2. Add coverage metric tests+3. Add retrieval simulation tests+4. Performance benchmarks++---++## Configuration Schema++```python+@dataclass+class AnchorConfig:+ """Configuration for dynamic anchor allocation."""++ # Base anchor budget as percentage of max_items+ anchor_budget_pct: float = 0.20 # 20% of slots for position anchors++ # Minimum and maximum anchor slots+ min_anchor_slots: int = 3+ max_anchor_slots: int = 10++ # Default distribution (overridden by pattern)+ default_front_weight: float = 0.5+ default_back_weight: float = 0.5+ default_middle_weight: float = 0.0++ # Pattern-specific overrides+ search_front_weight: float = 0.8+ logs_back_weight: float = 0.8+ time_series_balance: float = 0.5++ # Query keyword detection+ recency_keywords: list[str] = field(default_factory=lambda: [+ "latest", "recent", "last", "newest", "current"+ ])+ historical_keywords: list[str] = field(default_factory=lambda: [+ "first", "oldest", "earliest", "original", "initial"+ ])++ # Information density selection+ use_information_density: bool = True+ candidate_multiplier: int = 3 # Consider 3x candidates per slot++ # TOIN learning+ use_learned_positions: bool = True+ min_samples_for_learning: int = 10+```++---++## Success Metrics++1. **Retrieval Coverage**: % of user retrievals that hit preserved items (target: >80%)+2. **Information Density**: Unique information per preserved slot (target: no duplicate items)+3. **Distribution Coverage**: Preserved items span full value/time/category ranges+4. **Adversarial Robustness**: All adversarial tests pass+5. **Backward Compatibility**: Existing tests still pass+6. **Performance**: <5ms additional latency for anchor selection++---++## Risks and Mitigations++| Risk | Mitigation |+|------|------------|+| Information density calculation is expensive | Cache scores, limit candidate pool |+| Query keyword detection is brittle | Use as soft signal, not hard rule |+| TOIN learning needs cold start | Fall back to pattern-based defaults |+| Breaking existing behavior | Feature flag, A/B testing |+| Middle sampling misses important items | Always include anomalies/errors regardless |++---++## Next Steps++1. Review and approve this plan+2. Write failing tests first (TDD approach)+3. Implement Phase 1 (refactor foundation)+4. Iterate through phases with test validation+5. Benchmark against current implementation+6. A/B test in production with telemetrydiff --git a/headroom/config.py b/headroom/config.pyindex 838b65030..6d08c738b 100644--- a/headroom/config.py+++ b/headroom/config.py@@ -288,6 +288,63 @@ class RelevanceScorerConfig:relevance_threshold: float = 0.25 # Keep items above this score+@dataclass+class AnchorConfig:+ """Configuration for dynamic anchor allocation in SmartCrusher.++ Anchor selection determines which array positions are preserved during+ compression. Different data patterns benefit from different anchor strategies:+ - Search results: Front-heavy (top results are most relevant)+ - Logs: Back-heavy (recent entries matter most)+ - Time series: Balanced (need both ends to show trends)+ - Generic: Distributed (no assumption about order importance)++ The anchor budget is a percentage of max_items allocated to position-based+ anchors. The remaining budget goes to relevance-scored items.+ """++ # Base anchor budget as percentage of max_items+ anchor_budget_pct: float = 0.25 # 25% of slots for position anchors++ # Minimum and maximum anchor slots+ min_anchor_slots: int = 3+ max_anchor_slots: int = 12++ # Default distribution weights (sum to 1.0)+ default_front_weight: float = 0.5+ default_back_weight: float = 0.4+ default_middle_weight: float = 0.1++ # Pattern-specific overrides+ search_front_weight: float = 0.75 # Search results: front-heavy+ search_back_weight: float = 0.15+ logs_front_weight: float = 0.15 # Logs: back-heavy (recent)+ logs_back_weight: float = 0.75++ # Query keyword detection for dynamic adjustment+ recency_keywords: tuple[str, ...] = (+ "latest",+ "recent",+ "last",+ "newest",+ "current",+ "now",+ )+ historical_keywords: tuple[str, ...] = (+ "first",+ "oldest",+ "earliest",+ "original",+ "initial",+ "beginning",+ )++ # Information density selection+ use_information_density: bool = True+ candidate_multiplier: int = 3 # Consider 3x candidates per slot+ dedup_identical_items: bool = True # Don't waste slots on identical items++@dataclassclass SmartCrusherConfig:"""Configuration for smart statistical crusher (DEFAULT).@@ -338,6 +395,15 @@ class SmartCrusherConfig:# Relevance scoring configurationrelevance: RelevanceScorerConfig = field(default_factory=RelevanceScorerConfig)+ # Anchor selection configuration (dynamic position-based preservation)+ anchor: AnchorConfig = field(default_factory=AnchorConfig)++ # Content deduplication - prevents wasting slots on identical items+ # When multiple preservation mechanisms (anchors, anomalies, outliers) add+ # the same item, only one copy is kept. This is critical for arrays where+ # many items have identical content (e.g., repeated status messages).+ dedup_identical_items: bool = True+@dataclassclass CacheOptimizerConfig:diff --git a/headroom/transforms/__init__.py b/headroom/transforms/__init__.pyindex 125d6976c..37d34df44 100644--- a/headroom/transforms/__init__.py+++ b/headroom/transforms/__init__.py@@ -1,5 +1,13 @@"""Transform modules for Headroom SDK."""+from .anchor_selector import (+ AnchorSelector,+ AnchorStrategy,+ AnchorWeights,+ DataPattern,+ calculate_information_score,+ compute_item_hash,+)from .base import Transformfrom .cache_aligner import CacheAlignerfrom .content_detector import ContentType, DetectionResult, detect_content_type@@ -56,6 +64,13 @@ __all__ = [# Base"Transform","TransformPipeline",+ # Anchor selection+ "AnchorSelector",+ "AnchorStrategy",+ "AnchorWeights",+ "DataPattern",+ "calculate_information_score",+ "compute_item_hash",# JSON compression"ToolCrusher","SmartCrusher",diff --git a/headroom/transforms/anchor_selector.py b/headroom/transforms/anchor_selector.pynew file mode 100644index 000000000..119e3929b--- /dev/null+++ b/headroom/transforms/anchor_selector.py@@ -0,0 +1,768 @@+"""Dynamic anchor selection for SmartCrusher.++This module provides intelligent position-based anchor selection for array+compression. Instead of using fixed first-K/last-K rules, it dynamically+allocates anchor positions based on:++1. Data pattern (search results, logs, time series, generic)+2. Query keywords (recency vs historical context)+3. Information density (rare values, structural uniqueness)+4. Deduplication (skip identical items)++The anchor selection strategy is configurable via AnchorConfig and adapts+to both the data characteristics and the user's query context.++Example usage:+ from headroom.config import AnchorConfig+ from headroom.transforms.anchor_selector import (+ AnchorSelector,+ AnchorStrategy,+ DataPattern,+ )++ config = AnchorConfig()+ selector = AnchorSelector(config)++ # Select anchors for search results+ anchors = selector.select_anchors(+ items=search_results,+ max_items=15,+ pattern=DataPattern.SEARCH_RESULTS,+ query="find the latest error messages",+ )+"""++from __future__ import annotations++import hashlib+import json+import logging+from collections import Counter+from dataclasses import dataclass+from enum import Enum+from typing import Any++from ..config import AnchorConfig++logger = logging.getLogger(__name__)+++class DataPattern(Enum):+ """Data patterns detected in tool outputs.++ Each pattern has different characteristics that affect optimal anchor selection:+ - SEARCH_RESULTS: Ordered by relevance, top items most important+ - LOGS: Chronological, recent entries typically most relevant+ - TIME_SERIES: Temporal data, need both ends to show trends+ - GENERIC: No clear ordering, distributed sampling preferred+ """++ SEARCH_RESULTS = "search_results"+ LOGS = "logs"+ TIME_SERIES = "time_series"+ GENERIC = "generic"++ @classmethod+ def from_string(cls, pattern_str: str) -> DataPattern:+ """Convert a pattern string to DataPattern enum.++ Args:+ pattern_str: Pattern string like "search_results", "logs", etc.++ Returns:+ Corresponding DataPattern enum value.+ """+ pattern_map = {+ "search_results": cls.SEARCH_RESULTS,+ "logs": cls.LOGS,+ "time_series": cls.TIME_SERIES,+ "generic": cls.GENERIC,+ }+ return pattern_map.get(pattern_str.lower(), cls.GENERIC)+++class AnchorStrategy(Enum):+ """Anchor distribution strategies based on data patterns.++ Each strategy allocates position-based anchors differently:+ - FRONT_HEAVY: Most anchors at start (search results)+ - BACK_HEAVY: Most anchors at end (logs with recent items)+ - BALANCED: Equal distribution (time series)+ - DISTRIBUTED: Evenly spread throughout (generic/unknown)+ """++ FRONT_HEAVY = "front_heavy" # Search results+ BACK_HEAVY = "back_heavy" # Logs (recent matters)+ BALANCED = "balanced" # Time series+ DISTRIBUTED = "distributed" # Generic/database results+++@dataclass+class AnchorWeights:+ """Distribution weights for anchor positions.++ Weights control how many anchors go to each region:+ - front: Beginning of array+ - middle: Center region+ - back: End of array++ Weights should sum to 1.0 for proper distribution.+ """++ front: float = 0.5+ middle: float = 0.1+ back: float = 0.4++ def normalize(self) -> AnchorWeights:+ """Return a copy with weights normalized to sum to 1.0.++ Returns:+ New AnchorWeights with normalized values.+ """+ total = self.front + self.middle + self.back+ if total == 0:+ return AnchorWeights()+ return AnchorWeights(+ front=self.front / total,+ middle=self.middle / total,+ back=self.back / total,+ )+++def calculate_information_score(item: dict[str, Any], all_items: list[dict[str, Any]]) -> float:+ """Calculate information density score for an item.++ Information density is based on three factors:+ 1. Field value uniqueness: Rare values score higher+ 2. Content length: Longer items often more informative+ 3. Structural uniqueness: Different fields than typical items++ Args:+ item: Dictionary item to score.+ all_items: All items in the array for comparison.++ Returns:+ Score in range [0.0, 1.0] where higher means more informative.+ """+ if not item or not all_items:+ return 0.0++ if not isinstance(item, dict):+ return 0.0++ score = 0.0+ weights_used = 0.0++ # 1. Field value uniqueness (rare values score higher)+ uniqueness_score = _calculate_value_uniqueness(item, all_items)+ score += uniqueness_score * 0.4+ weights_used += 0.4++ # 2. Content length (longer items often more informative)+ length_score = _calculate_length_score(item, all_items)+ score += length_score * 0.3+ weights_used += 0.3++ # 3. Structural uniqueness (different fields than typical)+ structural_score = _calculate_structural_uniqueness(item, all_items)+ score += structural_score * 0.3+ weights_used += 0.3++ # Normalize in case weights don't sum to 1.0+ if weights_used > 0:+ score /= weights_used++ return min(1.0, max(0.0, score))+++def _calculate_value_uniqueness(item: dict[str, Any], all_items: list[dict[str, Any]]) -> float:+ """Calculate how unique the item's field values are.++ Rare field values indicate potentially important or anomalous data.++ Args:+ item: Item to check.+ all_items: All items for comparison.++ Returns:+ Score in [0.0, 1.0] where higher means rarer values.+ """+ if len(all_items) < 2:+ return 0.5++ # Count value frequencies for each field+ field_value_counts: dict[str, Counter[str]] = {}+ for other in all_items:+ if not isinstance(other, dict):+ continue+ for key, value in other.items():+ if key not in field_value_counts:+ field_value_counts[key] = Counter()+ # Convert to string for hashability+ try:+ value_str = json.dumps(value, sort_keys=True) if not isinstance(value, str) else value+ except (TypeError, ValueError):+ value_str = str(value)+ field_value_counts[key][value_str] += 1++ # Calculate rareness score for this item's values+ rareness_scores: list[float] = []+ total_items = len(all_items)++ for key, value in item.items():+ if key not in field_value_counts:+ continue+ try:+ value_str = json.dumps(value, sort_keys=True) if not isinstance(value, str) else value+ except (TypeError, ValueError):+ value_str = str(value)++ count = field_value_counts[key].get(value_str, 0)+ if count > 0:+ # Inverse frequency: rare values get higher scores+ frequency = count / total_items+ rareness = 1.0 - frequency+ rareness_scores.append(rareness)++ if not rareness_scores:+ return 0.5++ # Return average rareness+ return sum(rareness_scores) / len(rareness_scores)+++def _calculate_length_score(item: dict[str, Any], all_items: list[dict[str, Any]]) -> float:+ """Calculate score based on content length.++ Longer items often contain more information, but we normalize+ against the corpus to identify relatively detailed items.++ Args:+ item: Item to check.+ all_items: All items for comparison.++ Returns:+ Score in [0.0, 1.0] where higher means more content.+ """+ if len(all_items) < 2:+ return 0.5++ # Calculate serialized lengths+ def get_length(i: dict[str, Any]) -> int:+ try:+ return len(json.dumps(i))+ except (TypeError, ValueError):+ return len(str(i))++ item_length = get_length(item)+ all_lengths = [get_length(i) for i in all_items if isinstance(i, dict)]++ if not all_lengths:+ return 0.5++ max_length = max(all_lengths)+ min_length = min(all_lengths)++ if max_length == min_length:+ return 0.5++ # Normalize to [0, 1]+ return (item_length - min_length) / (max_length - min_length)+++def _calculate_structural_uniqueness(+ item: dict[str, Any], all_items: list[dict[str, Any]]+) -> float:+ """Calculate how structurally unique an item is.++ Items with unusual field sets may contain error information,+ special cases, or other important data.++ Args:+ item: Item to check.+ all_items: All items for comparison.++ Returns:+ Score in [0.0, 1.0] where higher means more unique structure.+ """+ if len(all_items) < 2:+ return 0.5++ # Get common field set (fields in 80%+ of items)+ field_counts: Counter[str] = Counter()+ valid_items = [i for i in all_items if isinstance(i, dict)]+ n = len(valid_items)++ if n < 2:+ return 0.5++ for other in valid_items:+ for key in other.keys():+ field_counts[key] += 1++ common_fields = {k for k, v in field_counts.items() if v >= n * 0.8}+ rare_fields = {k for k, v in field_counts.items() if v < n * 0.2}++ item_fields = set(item.keys())++ # Score based on presence of rare fields or absence of common fields+ has_rare = len(item_fields & rare_fields)+ missing_common = len(common_fields - item_fields)++ # More rare fields or missing common fields = more unique+ uniqueness = 0.0+ if rare_fields:+ uniqueness += 0.5 * (has_rare / max(len(rare_fields), 1))+ if common_fields:+ uniqueness += 0.5 * (missing_common / max(len(common_fields), 1))++ return min(1.0, uniqueness)+++def compute_item_hash(item: dict[str, Any]) -> str:+ """Compute a hash for an item for deduplication.++ Args:+ item: Dictionary item to hash.++ Returns:+ SHA256 hash (first 16 characters) of the item's content.+ """+ try:+ content = json.dumps(item, sort_keys=True, default=str)+ except (TypeError, ValueError):+ content = str(item)+ return hashlib.sha256(content.encode()).hexdigest()[:16]+++class AnchorSelector:+ """Dynamic anchor selection for array compression.++ This class determines which array positions should be preserved+ during compression based on data patterns, query context, and+ information density.++ The selection process:+ 1. Calculate anchor budget based on array size and max_items+ 2. Determine strategy from data pattern+ 3. Adjust weights based on query keywords+ 4. Distribute anchors across front/middle/back regions+ 5. Apply information density scoring for middle candidates+ 6. Deduplicate identical items+ """++ def __init__(self, config: AnchorConfig | None = None) -> None:+ """Initialize anchor selector.++ Args:+ config: Anchor configuration. Uses defaults if not provided.+ """+ self.config = config or AnchorConfig()++ def calculate_anchor_budget(self, array_size: int, max_items: int) -> int:+ """Calculate anchor budget based on array size and target.++ The budget is proportional to max_items but bounded by+ min_anchor_slots and max_anchor_slots.++ Args:+ array_size: Total number of items in the array.+ max_items: Target maximum items after compression.++ Returns:+ Number of anchor slots to allocate.+ """+ if array_size <= max_items:+ # No compression needed, no anchors required+ return 0++ # Calculate proportional budget+ raw_budget = int(max_items * self.config.anchor_budget_pct)++ # Clamp to configured bounds+ budget = max(self.config.min_anchor_slots, raw_budget)+ budget = min(self.config.max_anchor_slots, budget)++ # Don't exceed what we can actually use+ budget = min(budget, array_size)++ return budget++ def get_strategy_for_pattern(self, pattern: DataPattern) -> AnchorStrategy:+ """Map data pattern to anchor strategy.++ Args:+ pattern: Detected data pattern.++ Returns:+ Appropriate anchor strategy for the pattern.+ """+ strategy_map = {+ DataPattern.SEARCH_RESULTS: AnchorStrategy.FRONT_HEAVY,+ DataPattern.LOGS: AnchorStrategy.BACK_HEAVY,+ DataPattern.TIME_SERIES: AnchorStrategy.BALANCED,+ DataPattern.GENERIC: AnchorStrategy.DISTRIBUTED,+ }+ return strategy_map.get(pattern, AnchorStrategy.DISTRIBUTED)++ def get_base_weights_for_strategy(self, strategy: AnchorStrategy) -> AnchorWeights:+ """Get base anchor weights for a strategy.++ Args:+ strategy: Anchor distribution strategy.++ Returns:+ AnchorWeights with appropriate distribution.+ """+ if strategy == AnchorStrategy.FRONT_HEAVY:+ return AnchorWeights(+ front=self.config.search_front_weight,+ middle=1.0 - self.config.search_front_weight - self.config.search_back_weight,+ back=self.config.search_back_weight,+ )+ elif strategy == AnchorStrategy.BACK_HEAVY:+ return AnchorWeights(+ front=self.config.logs_front_weight,+ middle=1.0 - self.config.logs_front_weight - self.config.logs_back_weight,+ back=self.config.logs_back_weight,+ )+ elif strategy == AnchorStrategy.BALANCED:+ # Equal front and back, small middle+ return AnchorWeights(front=0.45, middle=0.1, back=0.45)+ else: # DISTRIBUTED+ return AnchorWeights(+ front=self.config.default_front_weight,+ middle=self.config.default_middle_weight,+ back=self.config.default_back_weight,+ )++ def adjust_weights_for_query(+ self,+ base_weights: AnchorWeights,+ query: str | None,+ ) -> AnchorWeights:+ """Adjust anchor weights based on query keywords.++ If the query contains recency keywords, shift weight toward the back.+ If it contains historical keywords, shift weight toward the front.++ Args:+ base_weights: Starting weight distribution.+ query: User query text (may be None).++ Returns:+ Adjusted AnchorWeights based on query analysis.+ """+ if not query:+ return base_weights++ query_lower = query.lower()++ # Check for recency keywords+ has_recency = any(kw in query_lower for kw in self.config.recency_keywords)++ # Check for historical keywords+ has_historical = any(kw in query_lower for kw in self.config.historical_keywords)++ if has_recency and not has_historical:+ # Shift weight toward back (recent items)+ shift = 0.15+ new_front = max(0.1, base_weights.front - shift)+ new_back = min(0.8, base_weights.back + shift)+ return AnchorWeights(+ front=new_front,+ middle=base_weights.middle,+ back=new_back,+ ).normalize()++ elif has_historical and not has_recency:+ # Shift weight toward front (older items)+ shift = 0.15+ new_front = min(0.8, base_weights.front + shift)+ new_back = max(0.1, base_weights.back - shift)+ return AnchorWeights(+ front=new_front,+ middle=base_weights.middle,+ back=new_back,+ ).normalize()++ # No adjustment needed+ return base_weights++ def select_anchors(+ self,+ items: list[dict[str, Any]],+ max_items: int,+ pattern: DataPattern,+ query: str | None = None,+ ) -> set[int]:+ """Select anchor indices for array compression.++ This is the main method for anchor selection. It:+ 1. Calculates the anchor budget+ 2. Determines the appropriate strategy+ 3. Adjusts weights based on query+ 4. Distributes anchors across regions+ 5. Applies information density scoring+ 6. Deduplicates identical items++ Args:+ items: List of dictionary items to select anchors from.+ max_items: Target maximum items after compression.+ pattern: Detected data pattern.+ query: Optional user query for context-aware selection.++ Returns:+ Set of indices that should be preserved as anchors.+ """+ array_size = len(items)++ if array_size == 0:+ return set()++ if array_size <= max_items:+ # No compression needed, keep all items+ return set(range(array_size))++ # Calculate budget+ budget = self.calculate_anchor_budget(array_size, max_items)++ if budget == 0:+ return set()++ # Get strategy and weights+ strategy = self.get_strategy_for_pattern(pattern)+ base_weights = self.get_base_weights_for_strategy(strategy)+ weights = self.adjust_weights_for_query(base_weights, query)+ weights = weights.normalize()++ # Calculate slots per region+ front_slots = max(1, int(budget * weights.front))+ back_slots = max(1, int(budget * weights.back))+ middle_slots = max(0, budget - front_slots - back_slots)++ # Ensure we don't exceed budget+ total_slots = front_slots + middle_slots + back_slots+ if total_slots > budget:+ # Reduce middle first, then back+ excess = total_slots - budget+ middle_reduction = min(middle_slots, excess)+ middle_slots -= middle_reduction+ excess -= middle_reduction+ if excess > 0:+ back_slots = max(1, back_slots - excess)++ logger.debug(+ f"Anchor selection: budget={budget}, front={front_slots}, "+ f"middle={middle_slots}, back={back_slots}, strategy={strategy.value}"+ )++ anchors: set[int] = set()+ seen_hashes: set[str] = set()++ # Select front anchors+ front_anchors = self._select_region_anchors(+ items=items,+ start_idx=0,+ end_idx=min(front_slots * 2, array_size // 3), # Front third+ num_slots=front_slots,+ seen_hashes=seen_hashes,+ use_density=False, # Front is always position-based+ )+ anchors.update(front_anchors)++ # Select back anchors+ back_start = max(array_size - back_slots * 2, (2 * array_size) // 3)+ back_anchors = self._select_region_anchors(+ items=items,+ start_idx=back_start,+ end_idx=array_size,+ num_slots=back_slots,+ seen_hashes=seen_hashes,+ use_density=False, # Back is always position-based+ )+ anchors.update(back_anchors)++ # Select middle anchors (with information density if enabled)+ if middle_slots > 0:+ middle_start = len(front_anchors)+ middle_end = array_size - len(back_anchors)+ if middle_end > middle_start:+ middle_anchors = self._select_region_anchors(+ items=items,+ start_idx=middle_start,+ end_idx=middle_end,+ num_slots=middle_slots,+ seen_hashes=seen_hashes,+ use_density=self.config.use_information_density,+ )+ anchors.update(middle_anchors)++ return anchors++ def _select_region_anchors(+ self,+ items: list[dict[str, Any]],+ start_idx: int,+ end_idx: int,+ num_slots: int,+ seen_hashes: set[str],+ use_density: bool,+ ) -> set[int]:+ """Select anchors from a specific region of the array.++ Args:+ items: Full list of items.+ start_idx: Start index of region (inclusive).+ end_idx: End index of region (exclusive).+ num_slots: Number of anchors to select.+ seen_hashes: Set of already-seen item hashes (for dedup).+ use_density: Whether to use information density scoring.++ Returns:+ Set of selected indices from this region.+ """+ if num_slots <= 0 or start_idx >= end_idx:+ return set()++ selected: set[int] = set()+ region_size = end_idx - start_idx++ if not use_density:+ # Position-based selection (evenly distributed within region)+ if num_slots >= region_size:+ # Select all from region (with dedup)+ for idx in range(start_idx, end_idx):+ if self._should_include(items, idx, seen_hashes):+ selected.add(idx)+ else:+ # Select evenly spaced indices+ step = region_size / (num_slots + 1)+ for i in range(num_slots):+ idx = start_idx + int((i + 1) * step)+ idx = min(idx, end_idx - 1)+ if self._should_include(items, idx, seen_hashes):+ selected.add(idx)+ else:+ # Try adjacent indices if this one is a duplicate+ for offset in [1, -1, 2, -2]:+ alt_idx = idx + offset+ if start_idx <= alt_idx < end_idx:+ if self._should_include(items, alt_idx, seen_hashes):+ selected.add(alt_idx)+ break+ else:+ # Information density-based selection+ selected = self._select_by_density(+ items=items,+ start_idx=start_idx,+ end_idx=end_idx,+ num_slots=num_slots,+ seen_hashes=seen_hashes,+ )++ return selected++ def _select_by_density(+ self,+ items: list[dict[str, Any]],+ start_idx: int,+ end_idx: int,+ num_slots: int,+ seen_hashes: set[str],+ ) -> set[int]:+ """Select anchors based on information density.++ Considers more candidates than slots and selects the most+ informative ones.++ Args:+ items: Full list of items.+ start_idx: Start index of region (inclusive).+ end_idx: End index of region (exclusive).+ num_slots: Number of anchors to select.+ seen_hashes: Set of already-seen item hashes (for dedup).++ Returns:+ Set of selected indices.+ """+ # Determine candidate pool (multiplier of slots)+ num_candidates = min(+ num_slots * self.config.candidate_multiplier,+ end_idx - start_idx,+ )++ # Select evenly spaced candidates+ region_size = end_idx - start_idx+ step = region_size / (num_candidates + 1) if num_candidates > 0 else 1++ candidates: list[tuple[int, float]] = []+ region_items = items[start_idx:end_idx]++ for i in range(num_candidates):+ idx = start_idx + int((i + 1) * step)+ idx = min(idx, end_idx - 1)++ # Skip if duplicate+ if not self._should_include(items, idx, seen_hashes, check_only=True):+ continue++ # Calculate information score+ item = items[idx]+ if isinstance(item, dict):+ score = calculate_information_score(item, region_items)+ else:+ score = 0.5++ candidates.append((idx, score))++ # Sort by score (descending) and select top slots+ candidates.sort(key=lambda x: x[1], reverse=True)++ selected: set[int] = set()+ for idx, _score in candidates[:num_slots]:+ if self._should_include(items, idx, seen_hashes):+ selected.add(idx)++ return selected++ def _should_include(+ self,+ items: list[dict[str, Any]],+ idx: int,+ seen_hashes: set[str],+ check_only: bool = False,+ ) -> bool:+ """Check if an item should be included (deduplication check).++ Args:+ items: Full list of items.+ idx: Index to check.+ seen_hashes: Set of already-seen hashes.+ check_only: If True, don't add to seen_hashes.++ Returns:+ True if item should be included, False if duplicate.+ """+ if not self.config.dedup_identical_items:+ if not check_only:+ # Still need to track for potential future dedup+ pass+ return True++ if idx < 0 or idx >= len(items):+ return False++ item = items[idx]+ if not isinstance(item, dict):+ return True++ item_hash = compute_item_hash(item)++ if item_hash in seen_hashes:+ return False++ if not check_only:+ seen_hashes.add(item_hash)++ return Truediff --git a/headroom/transforms/smart_crusher.py b/headroom/transforms/smart_crusher.pyindex dd08bbdfa..d54104506 100644--- a/headroom/transforms/smart_crusher.py+++ b/headroom/transforms/smart_crusher.py@@ -54,7 +54,7 @@ from typing import Anyfrom ..cache.compression_feedback import CompressionFeedback, get_compression_feedbackfrom ..cache.compression_store import CompressionStore, get_compression_store-from ..config import CCRConfig, RelevanceScorerConfig, TransformResult+from ..config import AnchorConfig, CCRConfig, RelevanceScorerConfig, TransformResultfrom ..relevance import RelevanceScorer, create_scorerfrom ..telemetry import TelemetryCollector, ToolSignature, get_telemetry_collectorfrom ..telemetry.models import FieldSemantics@@ -67,6 +67,8 @@ from ..utils import (safe_json_dumps,safe_json_loads,)+from .anchor_selector import AnchorSelector+from .anchor_selector import DataPattern as AnchorDataPatternfrom .base import Transformlogger = logging.getLogger(__name__)@@ -813,6 +815,9 @@ class SmartCrusherConfig:# Minimum confidence required to apply TOIN recommendationstoin_confidence_threshold: float = 0.5+ # Content deduplication - prevents wasting slots on identical items+ dedup_identical_items: bool = True+class SmartAnalyzer:"""Analyzes JSON arrays to determine optimal compression strategy."""@@ -1412,9 +1417,29 @@ class SmartCrusher(Transform):rel_cfg = relevance_config or RelevanceScorerConfig()self._relevance_threshold = rel_cfg.relevance_threshold+ # Initialize AnchorSelector for dynamic position-based preservation+ anchor_config = self.config.anchor if hasattr(self.config, 'anchor') else AnchorConfig()+ self._anchor_selector = AnchorSelector(anchor_config)+# NOTE: Error detection now uses structural outlier detection (_detect_structural_outliers)# instead of hardcoded keywords. This scales to any data domain.+ def _map_to_anchor_pattern(self, strategy: CompressionStrategy) -> AnchorDataPattern:+ """Map SmartCrusher compression strategy to AnchorSelector data pattern.++ Args:+ strategy: The detected compression strategy.++ Returns:+ Corresponding AnchorDataPattern for anchor selection.+ """+ return {+ CompressionStrategy.TIME_SERIES: AnchorDataPattern.TIME_SERIES,+ CompressionStrategy.TOP_N: AnchorDataPattern.SEARCH_RESULTS,+ CompressionStrategy.CLUSTER_SAMPLE: AnchorDataPattern.LOGS,+ CompressionStrategy.SMART_SAMPLE: AnchorDataPattern.GENERIC,+ }.get(strategy, AnchorDataPattern.GENERIC)+def crush(self, content: str, query: str = "") -> CrushResult:"""Crush content string directly (for use by ContentRouter).@@ -1554,6 +1579,178 @@ class SmartCrusher(Transform):# Telemetry should never break compressionpass+ def _deduplicate_indices_by_content(+ self,+ keep_indices: set[int],+ items: list[dict],+ ) -> set[int]:+ """Deduplicate indices by content hash, preferring lower indices.++ When multiple indices contain identical content, only the lowest index+ is kept. This maximizes information density in the compressed output.++ Enterprise considerations:+ - Thread-safe: No shared state modified+ - Performance: O(n) single pass with hash map+ - Memory: O(n) for hash storage (16-char hashes)+ - Fault-tolerant: Serialization errors preserve the item++ Args:+ keep_indices: Set of indices to deduplicate.+ items: The items array for content lookup.++ Returns:+ Deduplicated set of indices (may be smaller than input).+ """+ if not keep_indices:+ return keep_indices++ # Track first occurrence of each content hash+ # Using dict[hash -> lowest_index] for O(1) lookup+ seen_hashes: dict[str, int] = {}+ duplicates_removed = 0++ # Process in sorted order to ensure deterministic "lowest index wins"+ for idx in sorted(keep_indices):+ # Bounds check+ if idx < 0 or idx >= len(items):+ continue++ item = items[idx]++ # Compute content hash+ try:+ if isinstance(item, dict):+ # Canonical JSON serialization for consistent hashing+ content = json.dumps(item, sort_keys=True, default=str)+ else:+ # Non-dict items: use string representation+ content = str(item)+ item_hash = hashlib.sha256(content.encode()).hexdigest()[:16]+ except (TypeError, ValueError, RecursionError) as e:+ # Serialization failed - keep the item (fail-safe)+ logger.debug(+ "Dedup hash failed for item at index %d: %s. Keeping item.", idx, e+ )+ # Use index as unique "hash" to ensure item is kept+ item_hash = f"__idx_{idx}__"++ # First occurrence wins+ if item_hash not in seen_hashes:+ seen_hashes[item_hash] = idx+ else:+ duplicates_removed += 1++ # Log deduplication stats for observability+ if duplicates_removed > 0:+ logger.debug(+ "Content deduplication removed %d duplicate items from %d candidates "+ "(%.1f%% reduction). Unique items: %d",+ duplicates_removed,+ len(keep_indices),+ 100 * duplicates_removed / len(keep_indices),+ len(seen_hashes),+ )++ return set(seen_hashes.values())++ def _fill_remaining_slots(+ self,+ keep_indices: set[int],+ items: list[dict],+ n: int,+ effective_max: int,+ ) -> set[int]:+ """Fill remaining slots with unique items when under budget.++ When deduplication reduces keep_indices below effective_max, this method+ fills the remaining slots with diverse items from the array. It:+ 1. Computes content hashes for already-kept items+ 2. Scans array for items with unique content not yet kept+ 3. Distributes new items evenly across the array for coverage++ Enterprise considerations:+ - Thread-safe: No shared state modified+ - Performance: O(n) for hash computation, O(n) for filling+ - Memory: O(k) where k = len(keep_indices) for hash storage+ - Deterministic: Same input always produces same output++ Args:+ keep_indices: Current set of indices to keep (already deduplicated).+ items: The full items array.+ n: Total number of items.+ effective_max: Target maximum items.++ Returns:+ Updated set of indices, filled up to effective_max with unique items.+ """+ remaining_slots = effective_max - len(keep_indices)+ if remaining_slots <= 0:+ return keep_indices++ # Build set of content hashes for items we're already keeping+ seen_hashes: set[str] = set()+ for idx in keep_indices:+ if 0 <= idx < n:+ item = items[idx]+ try:+ if isinstance(item, dict):+ content = json.dumps(item, sort_keys=True, default=str)+ else:+ content = str(item)+ seen_hashes.add(hashlib.sha256(content.encode()).hexdigest()[:16])+ except (TypeError, ValueError, RecursionError):+ pass # Skip hash computation failures++ # Find candidate indices not in keep_indices+ candidates = [i for i in range(n) if i not in keep_indices]+ if not candidates:+ return keep_indices++ # Distribute selection evenly across the array for coverage+ # Use stride-based sampling to avoid clustering+ result = keep_indices.copy()+ added = 0++ # Calculate step size for even distribution+ step = max(1, len(candidates) // (remaining_slots + 1))++ # First pass: evenly distributed unique items+ for start_offset in range(step):+ if added >= remaining_slots:+ break+ for i in range(start_offset, len(candidates), step):+ if added >= remaining_slots:+ break+ idx = candidates[i]+ item = items[idx]++ # Check if this item's content is unique+ try:+ if isinstance(item, dict):+ content = json.dumps(item, sort_keys=True, default=str)+ else:+ content = str(item)+ item_hash = hashlib.sha256(content.encode()).hexdigest()[:16]+ except (TypeError, ValueError, RecursionError):+ # Hash failure - use index as unique hash (fail-safe)+ item_hash = f"__idx_{idx}__"++ if item_hash not in seen_hashes:+ result.add(idx)+ seen_hashes.add(item_hash)+ added += 1++ if added > 0:+ logger.debug(+ "Filled %d remaining slots (from %d to %d items) after deduplication",+ added,+ len(keep_indices),+ len(result),+ )++ return result+def _prioritize_indices(self,keep_indices: set[int],@@ -1596,6 +1793,31 @@ class SmartCrusher(Transform):# Use provided max_items or fall back to configeffective_max = max_items if max_items is not None else self.config.max_items_after_crush+ # === ENTERPRISE FIX: Content-based deduplication ===+ # Multiple preservation mechanisms (anchors, anomalies, outliers, etc.) can add+ # the same item multiple times by index. More critically, different INDICES can+ # contain IDENTICAL content (e.g., 10 identical status messages at indices 0-9).+ # Without deduplication, we waste slots on redundant information.+ #+ # This deduplication runs FIRST, before any other logic, to ensure:+ # 1. Budget calculations work with unique items only+ # 2. Critical item detection doesn't double-count+ # 3. Final output maximizes information density+ #+ # Performance: O(n) where n = len(keep_indices), single pass with hash map+ # Memory: O(n) for hash storage, hashes are 16 chars each+ if self.config.dedup_identical_items:+ keep_indices = self._deduplicate_indices_by_content(keep_indices, items)++ # === ENTERPRISE FIX: Fill up to max_items when under budget ===+ # After deduplication, we may have fewer unique items than max_items.+ # Instead of returning a sparse result, fill remaining slots with+ # diverse items from the array. This maximizes information density.+ if len(keep_indices) < effective_max and len(keep_indices) < n:+ keep_indices = self._fill_remaining_slots(+ keep_indices, items, n, effective_max+ )+if len(keep_indices) <= effective_max:return keep_indices@@ -2270,15 +2492,17 @@ class SmartCrusher(Transform):n = len(items)keep_indices = set()- # 1. First 3 items- for i in range(min(3, n)):- keep_indices.add(i)-- # 2. Last 2 items- for i in range(max(0, n - 2), n):- keep_indices.add(i)+ # 1. Dynamic anchor selection (replaces static first 3 + last 2)+ anchor_pattern = self._map_to_anchor_pattern(CompressionStrategy.TIME_SERIES)+ anchor_indices = self._anchor_selector.select_anchors(+ items=items,+ max_items=effective_max,+ pattern=anchor_pattern,+ query=query_context or None,+ )+ keep_indices.update(anchor_indices)- # 3. Items around change points from numeric fields+ # 2. Items around change points from numeric fieldsfor stats in analysis.field_stats.values():if stats.change_points:for cp in stats.change_points:@@ -2288,16 +2512,16 @@ class SmartCrusher(Transform):if 0 <= idx < n:keep_indices.add(idx)- # 4. Structural outlier items (STATISTICAL detection - no hardcoded keywords)+ # 3. Structural outlier items (STATISTICAL detection - no hardcoded keywords)outlier_indices = _detect_structural_outliers(items)keep_indices.update(outlier_indices)- # 4b. Error items via KEYWORD detection (PRESERVATION GUARANTEE)+ # 3b. Error items via KEYWORD detection (PRESERVATION GUARANTEE)# This is critical - errors must ALWAYS be preserved regardless of structureerror_indices = _detect_error_items_for_preservation(items)keep_indices.update(error_indices)- # 5. Items matching query anchors (DETERMINISTIC exact match)+ # 4. Items matching query anchors (DETERMINISTIC exact match)# Anchors provide reliable preservation for specific entity lookups (UUIDs, IDs, names)if query_context:anchors = extract_query_anchors(query_context)@@ -2305,7 +2529,7 @@ class SmartCrusher(Transform):if item_matches_anchors(item, anchors):keep_indices.add(i)- # 6. Items with high relevance to query context (PROBABILISTIC semantic match)+ # 5. Items with high relevance to query context (PROBABILISTIC semantic match)if query_context:item_strs = [json.dumps(item, default=str) for item in items]scores = self._scorer.score_batch(item_strs, query_context)@@ -2313,7 +2537,7 @@ class SmartCrusher(Transform):if score.score >= self._relevance_threshold:keep_indices.add(i)- # 6b. TOIN preserve_fields: boost items where query matches these fields+ # 5b. TOIN preserve_fields: boost items where query matches these fields# Note: preserve_fields are SHA256[:8] hashes, use helper to matchif preserve_fields and query_context:for i, item in enumerate(items):@@ -2350,24 +2574,26 @@ class SmartCrusher(Transform):n = len(items)keep_indices = set()- # 1. First 3 items- for i in range(min(3, n)):- keep_indices.add(i)-- # 2. Last 2 items- for i in range(max(0, n - 2), n):- keep_indices.add(i)+ # 1. Dynamic anchor selection (replaces static first 3 + last 2)+ anchor_pattern = self._map_to_anchor_pattern(CompressionStrategy.CLUSTER_SAMPLE)+ anchor_indices = self._anchor_selector.select_anchors(+ items=items,+ max_items=effective_max,+ pattern=anchor_pattern,+ query=query_context or None,+ )+ keep_indices.update(anchor_indices)- # 3. Structural outlier items (STATISTICAL detection - no hardcoded keywords)+ # 2. Structural outlier items (STATISTICAL detection - no hardcoded keywords)outlier_indices = _detect_structural_outliers(items)keep_indices.update(outlier_indices)- # 3b. Error items via KEYWORD detection (PRESERVATION GUARANTEE)+ # 2b. Error items via KEYWORD detection (PRESERVATION GUARANTEE)# This is critical - errors must ALWAYS be preserved regardless of structureerror_indices = _detect_error_items_for_preservation(items)keep_indices.update(error_indices)- # 4. Cluster by message-like field and keep representatives+ # 3. Cluster by message-like field and keep representatives# Find a high-cardinality string field (likely message field)message_field = Nonemax_uniqueness = 0.0@@ -2395,7 +2621,7 @@ class SmartCrusher(Transform):for idx in indices[:2]:keep_indices.add(idx)- # 5. Items matching query anchors (DETERMINISTIC exact match)+ # 4. Items matching query anchors (DETERMINISTIC exact match)# Anchors provide reliable preservation for specific entity lookups (UUIDs, IDs, names)if query_context:anchors = extract_query_anchors(query_context)@@ -2403,7 +2629,7 @@ class SmartCrusher(Transform):if item_matches_anchors(item, anchors):keep_indices.add(i)- # 6. Items with high relevance to query context (PROBABILISTIC semantic match)+ # 5. Items with high relevance to query context (PROBABILISTIC semantic match)if query_context:item_strs = [json.dumps(item, default=str) for item in items]scores = self._scorer.score_batch(item_strs, query_context)@@ -2411,7 +2637,7 @@ class SmartCrusher(Transform):if score.score >= self._relevance_threshold:keep_indices.add(i)- # 6b. TOIN preserve_fields: boost items where query matches these fields+ # 5b. TOIN preserve_fields: boost items where query matches these fields# Note: preserve_fields are SHA256[:8] hashes, use helper to matchif preserve_fields and query_context:for i, item in enumerate(items):@@ -2538,8 +2764,7 @@ class SmartCrusher(Transform):"""Plan smart statistical sampling using STATISTICAL detection.Always keeps:- - First K items (default 3)- - Last K items (default 2)+ - Dynamic anchor positions (based on data pattern and query context)- Structural outliers (items with rare fields or rare status values)- Anomalous numeric items (> 2 std from mean)- Items around change points@@ -2558,24 +2783,26 @@ class SmartCrusher(Transform):n = len(items)keep_indices = set()- # 1. First K items (default 3)- for i in range(min(3, n)):- keep_indices.add(i)-- # 2. Last K items (default 2)- for i in range(max(0, n - 2), n):- keep_indices.add(i)+ # 1. Dynamic anchor selection (replaces static first 3 + last 2)+ anchor_pattern = self._map_to_anchor_pattern(CompressionStrategy.SMART_SAMPLE)+ anchor_indices = self._anchor_selector.select_anchors(+ items=items,+ max_items=effective_max,+ pattern=anchor_pattern,+ query=query_context or None,+ )+ keep_indices.update(anchor_indices)- # 3. Structural outlier items (STATISTICAL detection - no hardcoded keywords)+ # 2. Structural outlier items (STATISTICAL detection - no hardcoded keywords)outlier_indices = _detect_structural_outliers(items)keep_indices.update(outlier_indices)- # 3b. Error items via KEYWORD detection (PRESERVATION GUARANTEE)+ # 2b. Error items via KEYWORD detection (PRESERVATION GUARANTEE)# This is critical - errors must ALWAYS be preserved regardless of structureerror_indices = _detect_error_items_for_preservation(items)keep_indices.update(error_indices)- # 4. Anomalous numeric items (> 2 std from mean)+ # 3. Anomalous numeric items (> 2 std from mean)for name, stats in analysis.field_stats.items():if stats.field_type == "numeric" and stats.mean_val is not None and stats.variance:std = stats.variance**0.5@@ -2587,7 +2814,7 @@ class SmartCrusher(Transform):if abs(val - stats.mean_val) > threshold:keep_indices.add(i)- # 5. Items around change points (if detected)+ # 4. Items around change points (if detected)if self.config.preserve_change_points:for stats in analysis.field_stats.values():if stats.change_points:@@ -2598,7 +2825,7 @@ class SmartCrusher(Transform):if 0 <= idx < n:keep_indices.add(idx)- # 6. Items matching query anchors (DETERMINISTIC exact match)+ # 5. Items matching query anchors (DETERMINISTIC exact match)# Anchors provide reliable preservation for specific entity lookups (UUIDs, IDs, names)if query_context:anchors = extract_query_anchors(query_context)@@ -2606,7 +2833,7 @@ class SmartCrusher(Transform):if item_matches_anchors(item, anchors):keep_indices.add(i)- # 7. Items with high relevance to query context (PROBABILISTIC semantic match)+ # 6. Items with high relevance to query context (PROBABILISTIC semantic match)if query_context:item_strs = [json.dumps(item, default=str) for item in items]scores = self._scorer.score_batch(item_strs, query_context)@@ -2614,7 +2841,7 @@ class SmartCrusher(Transform):if score.score >= self._relevance_threshold:keep_indices.add(i)- # 7b. TOIN preserve_fields: boost items where query matches these fields+ # 6b. TOIN preserve_fields: boost items where query matches these fields# Note: preserve_fields are SHA256[:8] hashes, use helper to matchif preserve_fields and query_context:for i, item in enumerate(items):diff --git a/tests/test_transforms/test_anchor_selector.py b/tests/test_transforms/test_anchor_selector.pynew file mode 100644index 000000000..79cc15f80--- /dev/null+++ b/tests/test_transforms/test_anchor_selector.py@@ -0,0 +1,1209 @@+"""Tests for AnchorSelector - Adaptive position-based anchor allocation.++Comprehensive tests covering:+- Adversarial positions: Important data NOT at expected positions+- Size adaptation: Anchor allocation scaling with array size+- Pattern-aware anchoring: Different strategies for different data patterns+- Query-aware anchoring: Query-based anchor adjustment+- Information density: Unique/informative item selection+- Coverage metrics: Distribution coverage verification+- Edge cases: Boundary conditions and special scenarios++These tests verify the AnchorSelector replaces the static "first 3 + last 2"+preservation with adaptive, pattern-aware anchor selection.+"""++import json+from dataclasses import dataclass+from enum import Enum+from typing import Any++import pytest++from headroom import OpenAIProvider, SmartCrusherConfig, Tokenizer+from headroom.transforms.smart_crusher import (+ CompressionStrategy,+ SmartAnalyzer,+ SmartCrusher,+)+++# =============================================================================+# Test Fixtures+# =============================================================================++_provider = OpenAIProvider()+++def get_tokenizer(model: str = "gpt-4o") -> Tokenizer:+ """Get a tokenizer for tests using OpenAI provider."""+ token_counter = _provider.get_token_counter(model)+ return Tokenizer(token_counter, model)+++def tokenizer():+ """Provide a tokenizer for tests."""+ return get_tokenizer()+++def default_config():+ """Default SmartCrusherConfig for testing."""+ return SmartCrusherConfig(+ enabled=True,+ min_items_to_analyze=3,+ min_tokens_to_crush=0, # Always crush for tests+ max_items_after_crush=10,+ variance_threshold=2.0,+ )+++def analyzer(default_config):+ """SmartAnalyzer instance for testing."""+ return SmartAnalyzer(default_config)+++def crusher(default_config):+ """SmartCrusher instance for testing."""+ return SmartCrusher(default_config)+++# =============================================================================+# Test Data Generators+# =============================================================================+++def generate_uniform_items(n: int, value: int = 0) -> list[dict]:+ """Generate array of identical items."""+ return [{"id": "same", "value": value, "status": "ok"} for _ in range(n)]+++def generate_numbered_items(n: int, with_value: bool = True) -> list[dict]:+ """Generate items with sequential IDs for position tracking."""+ items = []+ for i in range(n):+ item = {"id": i, "name": f"Item {i}"}+ if with_value:+ item["value"] = i * 10+ items.append(item)+ return items+++def generate_time_series_data(+ n: int = 50,+ spike_positions: list[int] | None = None,+ spike_value: float = 1000.0,+) -> list[dict]:+ """Generate time series with optional spikes at specific positions."""+ items = []+ for i in range(n):+ value = 100.0 + (i * 0.5) # Slight upward trend+ if spike_positions and i in spike_positions:+ value = spike_value+ items.append(+ {+ "timestamp": f"2025-01-{(i % 28) + 1:02d}T{(i % 24):02d}:00:00Z",+ "value": value,+ "metric": "cpu_usage",+ }+ )+ return items+++def generate_log_data(+ n: int = 50,+ error_positions: list[int] | None = None,+) -> list[dict]:+ """Generate log-style data with optional errors at specific positions."""+ levels = ["INFO", "DEBUG", "WARN"]+ items = []+ for i in range(n):+ level = levels[i % len(levels)]+ if error_positions and i in error_positions:+ level = "ERROR"+ message = f"Critical failure at step {i}: connection timeout"+ else:+ message = f"Processing request {i} successfully"+ items.append(+ {+ "level": level,+ "message": message,+ "timestamp": f"2025-01-06T{12 + (i // 60):02d}:{i % 60:02d}:00Z",+ }+ )+ return items+++def generate_search_results(n: int = 50) -> list[dict]:+ """Generate search results with scores (higher = better, at front)."""+ return [+ {+ "id": f"doc_{i}",+ "title": f"Document {i}",+ "score": 1.0 - (i * 0.02), # Scores decrease as index increases+ "snippet": f"This is a snippet from document {i}...",+ }+ for i in range(n)+ ]+++def generate_categorized_items(+ categories: dict[str, int],+) -> list[dict]:+ """Generate items with specific category distribution.++ Args:+ categories: Dict mapping category name to count, e.g. {"A": 30, "B": 30, "C": 40}+ """+ items = []+ i = 0+ for category, count in categories.items():+ for _ in range(count):+ items.append({"id": i, "category": category, "name": f"Item {i}"})+ i += 1+ return items+++# =============================================================================+# Helper Functions+# =============================================================================+++def crush_items(+ items: list[dict],+ tokenizer: Tokenizer,+ max_items: int = 10,+ query: str = "",+ min_items: int = 3,+) -> list[dict]:+ """Helper to crush items and return the result list.++ Args:+ items: Array of items to compress.+ tokenizer: Tokenizer instance.+ max_items: Maximum items after crushing.+ query: Optional query context.+ min_items: Minimum items to analyze.++ Returns:+ List of preserved items after crushing.+ """+ messages = [+ {"role": "system", "content": "You are helpful."},+ ]++ if query:+ messages.append({"role": "user", "content": query})+ messages.append(+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "search_items", "arguments": "{}"},+ }+ ],+ }+ )++ messages.append(+ {"role": "tool", "tool_call_id": "call_1", "content": json.dumps(items)}+ )++ config = SmartCrusherConfig(+ enabled=True,+ min_tokens_to_crush=0,+ min_items_to_analyze=min_items,+ max_items_after_crush=max_items,+ )+ crusher = SmartCrusher(config)+ result = crusher.apply(messages, tokenizer)++ # Parse result+ tool_content = result.messages[-1]["content"]+ json_part = tool_content.split("\n<headroom:")[0]+ return json.loads(json_part)+++def get_preserved_positions(result: list[dict], original_size: int) -> dict[str, list[int]]:+ """Categorize preserved item positions into front/middle/back.++ Args:+ result: List of preserved items (must have 'id' field with original index).+ original_size: Size of original array.++ Returns:+ Dict with 'front', 'middle', 'back' keys containing lists of preserved indices.+ """+ front_boundary = int(original_size * 0.1)+ back_boundary = int(original_size * 0.9)++ positions = {"front": [], "middle": [], "back": []}++ for item in result:+ idx = item.get("id")+ if idx is None:+ continue++ if isinstance(idx, int):+ if idx < front_boundary:+ positions["front"].append(idx)+ elif idx >= back_boundary:+ positions["back"].append(idx)+ else:+ positions["middle"].append(idx)++ return positions+++# =============================================================================+# TestAdversarialPositions+# =============================================================================+++class TestAdversarialPositions:+ """Test scenarios that break 'first 3 + last 2' assumption.++ These tests verify that important data is preserved regardless of position,+ not just because it happens to be at the front or back of the array.+ """++ def test_important_data_in_middle(self, tokenizer):+ """Critical error item at position 50 of 100-item array should be preserved.++ The error item is in the middle where static anchoring would miss it.+ It should be preserved due to error detection, not position.+ """+ items = [{"id": i, "status": "ok", "value": i * 10} for i in range(100)]+ # Place critical error in the middle+ items[50] = {+ "id": 50,+ "status": "error",+ "error_code": "CRITICAL",+ "message": "Connection failed",+ }++ crushed = crush_items(items, tokenizer, max_items=15)++ # Error item MUST be preserved regardless of position+ preserved_ids = [item["id"] for item in crushed]+ assert 50 in preserved_ids, "Critical error at position 50 should be preserved"++ # Verify it's preserved for the right reason (has error indicator)+ error_items = [item for item in crushed if item.get("status") == "error"]+ assert len(error_items) >= 1, "At least one error item should be preserved"++ def test_spike_not_at_boundaries(self, tokenizer):+ """Numeric spike at position 75 of 100-item array must be preserved.++ The spike represents an anomaly that should be detected statistically,+ not missed because it's not at the front or back.+ """+ items = generate_time_series_data(100, spike_positions=[75], spike_value=1000.0)+ # Add id field for tracking+ for i, item in enumerate(items):+ item["id"] = i++ crushed = crush_items(items, tokenizer, max_items=15)++ # Spike MUST be preserved as anomaly+ has_spike = any(item.get("value", 0) > 500 for item in crushed)+ assert has_spike, "Anomalous spike at position 75 should be preserved"++ # Verify the specific position was kept+ preserved_ids = [item.get("id") for item in crushed]+ assert 75 in preserved_ids, "Position 75 with spike should be in result"++ def test_multiple_spikes_scattered(self, tokenizer):+ """Multiple spikes at positions 25, 50, 75 should all be preserved."""+ spike_positions = [25, 50, 75]+ items = generate_time_series_data(100, spike_positions=spike_positions, spike_value=999.0)+ for i, item in enumerate(items):+ item["id"] = i++ crushed = crush_items(items, tokenizer, max_items=15)++ # All spikes should be preserved+ preserved_ids = set(item.get("id") for item in crushed)+ for pos in spike_positions:+ assert pos in preserved_ids, f"Spike at position {pos} should be preserved"++ def test_first_items_identical(self, tokenizer):+ """First 10 identical items - should NOT waste all anchor slots on them.++ When first N items are identical, we should keep at most 1-2 of them,+ not waste 3 anchor slots on duplicates.+ """+ # First 10 items are identical+ identical_items = [{"id": "same", "value": 0, "type": "duplicate"} for _ in range(10)]+ # Rest are unique+ unique_items = [+ {"id": f"unique_{i}", "value": i * 10, "type": "unique"}+ for i in range(90)+ ]+ items = identical_items + unique_items++ crushed = crush_items(items, tokenizer, max_items=10)++ # Should NOT have multiple identical items+ same_count = sum(1 for item in crushed if item.get("id") == "same")+ assert same_count <= 2, f"Got {same_count} identical items, expected at most 2"++ # Should have some unique items+ unique_count = sum(1 for item in crushed if item.get("type") == "unique")+ assert unique_count >= 5, f"Expected at least 5 unique items, got {unique_count}"++ def test_last_items_identical(self, tokenizer):+ """Last 10 identical items - should NOT waste anchor slots.++ Similar to above but for back anchors - when last N items are identical,+ we should preserve variety instead of duplicates.+ """+ # First 90 items are unique+ unique_items = [+ {"id": f"unique_{i}", "value": i * 10, "type": "unique"}+ for i in range(90)+ ]+ # Last 10 items are identical+ identical_items = [{"id": "same", "value": 100, "type": "duplicate"} for _ in range(10)]+ items = unique_items + identical_items++ crushed = crush_items(items, tokenizer, max_items=10)++ # Should NOT have multiple identical items+ same_count = sum(1 for item in crushed if item.get("id") == "same")+ assert same_count <= 2, f"Got {same_count} identical items, expected at most 2"++ def test_relevant_item_in_middle(self, tokenizer):+ """Item matching query in middle position must be found.++ When user queries for a specific item that's at position 42,+ it should be preserved even though it's not at front/back.+ """+ items = [+ {"id": i, "name": f"item_{i}", "status": "active"}+ for i in range(100)+ ]+ # Put target item in the middle+ items[42]["name"] = "target_special_item"+ items[42]["description"] = "This is what the user is looking for"++ crushed = crush_items(+ items,+ tokenizer,+ max_items=10,+ query="Find target_special_item",+ )++ # Query-matched item MUST be preserved+ has_target = any("target_special_item" in item.get("name", "") for item in crushed)+ assert has_target, "Item matching query should be preserved regardless of position"++ def test_error_in_middle_of_otherwise_uniform_data(self, tokenizer):+ """Single error in middle of 100 identical OK items must be preserved."""+ items = [{"id": i, "status": "ok", "data": "normal"} for i in range(100)]+ items[47] = {"id": 47, "status": "failed", "error": "Unexpected failure"}++ crushed = crush_items(items, tokenizer, max_items=15)++ # Error must be preserved+ error_items = [item for item in crushed if item.get("status") == "failed"]+ assert len(error_items) >= 1, "Error item at position 47 should be preserved"+ assert error_items[0]["id"] == 47, "The specific error item should be preserved"+++# =============================================================================+# TestSizeAdaptation+# =============================================================================+++class TestSizeAdaptation:+ """Test that anchor allocation scales with array size.++ Larger arrays should allocate proportionally more anchor slots+ to ensure adequate coverage across the data range.+ """++ @pytest.mark.parametrize(+ "size,max_items,expected_min_anchors",+ [+ (20, 10, 3), # Small array: at least 3 anchors (front + back)+ (100, 15, 4), # Medium array: at least 4 anchors+ (500, 20, 5), # Large array: at least 5 anchors+ (2000, 25, 6), # Very large: at least 6 anchors+ ],+ )+ def test_anchor_count_scales(self, tokenizer, size, max_items, expected_min_anchors):+ """Anchor count should increase with array size.++ Verifies that the number of items from boundary regions (front 10%, back 10%)+ increases as the array size grows.+ """+ items = generate_numbered_items(size)++ crushed = crush_items(items, tokenizer, max_items=max_items)++ # Count items from first 10% and last 10%+ front_boundary = int(size * 0.1)+ back_boundary = int(size * 0.9)++ anchor_count = sum(+ 1+ for item in crushed+ if item["id"] < front_boundary or item["id"] >= back_boundary+ )++ assert anchor_count >= expected_min_anchors, (+ f"Array of size {size} should have at least {expected_min_anchors} "+ f"anchors from boundary regions, got {anchor_count}"+ )++ def test_small_array_high_preservation(self, tokenizer):+ """Small arrays (< max_items) should preserve most/all items.++ When the array is smaller than max_items, there's no need to drop items.+ """+ items = generate_numbered_items(8)++ # max_items=20 is larger than array size+ crushed = crush_items(items, tokenizer, max_items=20)++ # Should preserve all or nearly all items+ assert len(crushed) >= 7, f"Small array should preserve most items, got {len(crushed)}"++ def test_small_array_exact_size(self, tokenizer):+ """Array exactly at max_items should preserve all items."""+ items = generate_numbered_items(10)++ crushed = crush_items(items, tokenizer, max_items=10)++ # Should preserve all items+ assert len(crushed) == 10, "Array at max_items limit should keep all items"++ def test_large_array_efficient_sampling(self, tokenizer):+ """Large arrays should sample efficiently across all positions.++ A 500-item array crushed to 20 items should have representation+ from front, middle, and back regions.+ """+ items = generate_numbered_items(500)++ crushed = crush_items(items, tokenizer, max_items=20)++ positions = get_preserved_positions(crushed, 500)++ # Should have representation from all regions+ has_front = len(positions["front"]) >= 1+ has_back = len(positions["back"]) >= 1+ # Middle representation is optional but preferred for large arrays+ has_middle = len(positions["middle"]) >= 1++ assert has_front, "Large array should preserve items from front"+ assert has_back, "Large array should preserve items from back"+ # Middle coverage is important for large arrays+ assert has_middle, "Large array should have some middle representation"++ def test_very_large_array_coverage(self, tokenizer):+ """Very large array (1000+) should have good position distribution."""+ items = generate_numbered_items(1000)++ crushed = crush_items(items, tokenizer, max_items=25)++ positions = get_preserved_positions(crushed, 1000)++ # Calculate coverage spread+ all_positions = positions["front"] + positions["middle"] + positions["back"]+ if len(all_positions) >= 2:+ spread = max(all_positions) - min(all_positions)+ # Should span at least 80% of the array+ assert spread >= 800, f"Preserved items should span array, spread was {spread}"+++# =============================================================================+# TestPatternAwareAnchoring+# =============================================================================+++class TestPatternAwareAnchoring:+ """Test pattern-specific anchor strategies.++ Different data patterns (search results, logs, time series) should+ use different anchor weighting strategies.+ """++ def test_search_results_front_heavy(self, tokenizer):+ """Search results with scores should preserve more from front (high scores).++ Search results are sorted by relevance score, so top items are most important.+ """+ items = generate_search_results(100)+ for i, item in enumerate(items):+ item["idx"] = i # Track original position++ crushed = crush_items(items, tokenizer, max_items=12)++ # Count items by their original position+ front_count = sum(1 for item in crushed if item.get("idx", 100) < 30)+ back_count = sum(1 for item in crushed if item.get("idx", 0) >= 70)++ # For search results, front (high scores) should dominate+ assert front_count > back_count, (+ f"Search results should preserve more front items (high scores), "+ f"got front={front_count}, back={back_count}"+ )++ # Top results should definitely be present+ ids = [item["id"] for item in crushed]+ assert "doc_0" in ids, "Top search result should be preserved"+ assert "doc_1" in ids, "Second search result should be preserved"++ def test_logs_back_heavy(self, tokenizer):+ """Logs with timestamps should preserve more recent items (back of array).++ Logs are typically ordered chronologically, with recent items at the end.+ """+ items = generate_log_data(100)+ for i, item in enumerate(items):+ item["idx"] = i++ crushed = crush_items(items, tokenizer, max_items=12)++ # For logs, back (recent) should be emphasized+ # Extract indices - use 'idx' field we added+ indices = [item.get("idx", 0) for item in crushed]++ recent_count = sum(1 for idx in indices if idx >= 70)+ old_count = sum(1 for idx in indices if idx < 30)++ # Recent logs should be at least as represented as old logs+ assert recent_count >= old_count, (+ f"Logs should preserve recent items, got recent={recent_count}, old={old_count}"+ )++ def test_time_series_balanced(self, tokenizer):+ """Time series should have balanced front/back representation.++ For trend analysis, we need both the start and end of the time series.+ """+ items = generate_time_series_data(100)+ for i, item in enumerate(items):+ item["id"] = i++ crushed = crush_items(items, tokenizer, max_items=12)++ positions = get_preserved_positions(crushed, 100)++ front_count = len(positions["front"])+ back_count = len(positions["back"])++ # Should be relatively balanced for time series (within 2:1 ratio)+ if front_count > 0 and back_count > 0:+ ratio = max(front_count, back_count) / min(front_count, back_count)+ assert ratio <= 3, f"Time series should have balanced anchors, ratio was {ratio}"++ def test_generic_distributed(self, tokenizer):+ """Generic data should sample across all positions.++ When pattern is unknown, sampling should be distributed rather than+ heavily weighted to any particular region.+ """+ items = generate_numbered_items(100)++ crushed = crush_items(items, tokenizer, max_items=15)++ positions = get_preserved_positions(crushed, 100)++ # Should have items from multiple regions+ regions_with_items = sum(+ 1 for region in ["front", "middle", "back"] if positions[region]+ )++ assert regions_with_items >= 2, (+ f"Generic data should cover multiple regions, got {regions_with_items}"+ )+++# =============================================================================+# TestQueryAwareAnchoring+# =============================================================================+++class TestQueryAwareAnchoring:+ """Test query-based anchor adjustment.++ User queries containing temporal keywords should shift anchor weighting.+ """++ def test_latest_query_shifts_to_back(self, tokenizer):+ """'Latest' in query should preserve more recent items."""+ items = [{"id": i, "created": f"2024-01-{i:02d}"} for i in range(1, 31)]++ crushed = crush_items(+ items,+ tokenizer,+ max_items=8,+ query="Show me the latest entries",+ )++ ids = [item["id"] for item in crushed]+ recent_count = sum(1 for id in ids if id > 20)++ # Should have multiple recent items due to "latest" keyword+ assert recent_count >= 2, f"Query with 'latest' should preserve recent items, got {recent_count}"++ def test_recent_query_shifts_to_back(self, tokenizer):+ """'Recent' in query should preserve more recent items."""+ items = generate_log_data(50)+ for i, item in enumerate(items):+ item["idx"] = i++ crushed = crush_items(+ items,+ tokenizer,+ max_items=10,+ query="Show me recent log entries",+ )++ indices = [item.get("idx", 0) for item in crushed]+ recent_count = sum(1 for idx in indices if idx >= 35)++ assert recent_count >= 2, "Query with 'recent' should have multiple recent items"++ def test_first_query_shifts_to_front(self, tokenizer):+ """'First' in query should preserve earlier items."""+ items = [{"id": i, "created": f"2024-01-{i:02d}"} for i in range(1, 31)]++ crushed = crush_items(+ items,+ tokenizer,+ max_items=8,+ query="Show me the first entries",+ )++ ids = [item["id"] for item in crushed]+ early_count = sum(1 for id in ids if id < 10)++ # Should have multiple early items due to "first" keyword+ assert early_count >= 2, f"Query with 'first' should preserve early items, got {early_count}"++ def test_oldest_query_shifts_to_front(self, tokenizer):+ """'Oldest' in query should preserve earlier items."""+ items = generate_numbered_items(50)++ crushed = crush_items(+ items,+ tokenizer,+ max_items=10,+ query="Find the oldest records",+ )++ ids = [item["id"] for item in crushed]+ early_count = sum(1 for id in ids if id < 15)++ assert early_count >= 3, "Query with 'oldest' should have multiple early items"++ def test_specific_id_query_finds_item(self, tokenizer):+ """Query for specific ID should find it regardless of position."""+ items = [{"id": f"item_{i:04d}", "value": i} for i in range(200)]++ crushed = crush_items(+ items,+ tokenizer,+ max_items=10,+ query="Find item_0123",+ )++ # Item at position 123 should be found+ ids = [item["id"] for item in crushed]+ assert "item_0123" in ids, "Specific ID query should find the item"++ def test_no_query_uses_default_weights(self, tokenizer):+ """Without query, use pattern-based defaults."""+ items = generate_numbered_items(100)++ crushed = crush_items(items, tokenizer, max_items=15)++ # Without query, should use default anchoring (some front, some back)+ positions = get_preserved_positions(crushed, 100)++ assert len(positions["front"]) >= 1, "Default should include front items"+ assert len(positions["back"]) >= 1, "Default should include back items"+++# =============================================================================+# TestInformationDensity+# =============================================================================+++class TestInformationDensity:+ """Test information-density based selection.++ Items with unique or rare properties should be preferred over common ones.+ """++ def test_unique_items_preferred(self, tokenizer):+ """Items with rare field values should be preferred over common ones.++ When most items have status="ok" but a few have status="warning",+ the warning items should be preserved as they're more informative.+ """+ items = []+ for i in range(100):+ status = "warning" if i in [25, 50, 75] else "ok"+ items.append({"id": i, "status": status, "value": i})++ crushed = crush_items(items, tokenizer, max_items=15)++ # Warning items (rare status) should be preserved+ warning_count = sum(1 for item in crushed if item.get("status") == "warning")+ assert warning_count >= 2, f"Rare status items should be preferred, got {warning_count}"++ def test_dedup_identical_items(self, tokenizer):+ """Identical items should be deduplicated in anchor selection.++ If positions 0-5 all have identical content, we shouldn't keep all of them.+ """+ # First 6 items are identical+ items = [{"id": "dup", "value": 0, "constant": "same"} for _ in range(6)]+ # Rest are unique+ items.extend(+ [{"id": f"uniq_{i}", "value": i * 10, "unique": True} for i in range(94)]+ )++ crushed = crush_items(items, tokenizer, max_items=12)++ # Should not have many identical items+ dup_count = sum(1 for item in crushed if item.get("id") == "dup")+ unique_count = sum(1 for item in crushed if item.get("unique"))++ assert dup_count <= 2, f"Should deduplicate identical items, got {dup_count}"+ assert unique_count >= 6, f"Should prefer unique items, got {unique_count}"++ def test_structural_outliers_preferred(self, tokenizer):+ """Items with different structure should be preferred.++ An item with extra fields (like an error with stack trace) should be+ preferred over uniform items.+ """+ items = [{"id": i, "status": "ok"} for i in range(100)]+ # Add a structurally different item in the middle+ items[42] = {+ "id": 42,+ "status": "error",+ "error_message": "Something went wrong",+ "stack_trace": "at line 123...",+ "error_code": "ERR_001",+ }++ crushed = crush_items(items, tokenizer, max_items=15)++ # Structural outlier should be preserved+ outlier = [item for item in crushed if item.get("stack_trace")]+ assert len(outlier) >= 1, "Structurally different item should be preserved"++ def test_diverse_values_over_uniform(self, tokenizer):+ """When selecting from candidates, prefer diverse values."""+ items = []+ # Create items with varying diversity+ for i in range(100):+ items.append({+ "id": i,+ "type": "common" if i < 90 else f"rare_type_{i}",+ "value": i,+ })++ crushed = crush_items(items, tokenizer, max_items=15)++ # Should have some rare types+ rare_types = [item for item in crushed if "rare" in item.get("type", "")]+ assert len(rare_types) >= 1, "Rare type values should be preserved"+++# =============================================================================+# TestCoverageMetrics+# =============================================================================+++class TestCoverageMetrics:+ """Test that preserved items represent the full distribution.++ Compression should maintain coverage of value ranges, categories, and time.+ """++ def test_value_range_coverage(self, tokenizer):+ """Preserved items should cover the value range."""+ items = [{"id": i, "value": i} for i in range(100)]++ crushed = crush_items(items, tokenizer, max_items=12)++ values = [item["value"] for item in crushed]++ # Should cover most of the range [0, 100]+ assert min(values) < 10, "Should have low values"+ assert max(values) > 90, "Should have high values"++ # Should have some middle values too+ middle_count = sum(1 for v in values if 30 < v < 70)+ assert middle_count >= 1, "Should have some middle-range values"++ def test_category_coverage(self, tokenizer):+ """Preserved items should represent multiple categories."""+ items = generate_categorized_items({"A": 30, "B": 30, "C": 40})++ crushed = crush_items(items, tokenizer, max_items=12)++ categories = set(item["category"] for item in crushed)++ # Should have at least 2 of 3 categories represented+ assert len(categories) >= 2, f"Should cover multiple categories, got {categories}"++ def test_category_proportional_representation(self, tokenizer):+ """Category distribution should roughly reflect original proportions."""+ items = generate_categorized_items({"major": 80, "minor": 20})++ crushed = crush_items(items, tokenizer, max_items=15)++ major_count = sum(1 for item in crushed if item["category"] == "major")+ minor_count = sum(1 for item in crushed if item["category"] == "minor")++ # Major category should have more items, but minor should be represented+ assert major_count > minor_count, "Major category should dominate"+ assert minor_count >= 1, "Minor category should still be represented"++ def test_temporal_coverage(self, tokenizer):+ """Preserved items should span the time range."""+ # Create items spanning 12 months+ items = [+ {"id": i, "timestamp": f"2024-{(i % 12) + 1:02d}-15", "event": f"event_{i}"}+ for i in range(60)+ ]++ crushed = crush_items(items, tokenizer, max_items=12)++ months = [int(item["timestamp"][5:7]) for item in crushed]++ # Should span a significant portion of the year+ month_range = max(months) - min(months)+ assert month_range >= 5, f"Should span multiple months, got range of {month_range}"++ def test_numeric_distribution_coverage(self, tokenizer):+ """Preserved numeric values should represent the distribution."""+ # Create items with bimodal distribution+ items = []+ for i in range(50):+ items.append({"id": i, "value": 10 + (i % 5)}) # Low cluster: 10-15+ for i in range(50):+ items.append({"id": 50 + i, "value": 90 + (i % 5)}) # High cluster: 90-95++ crushed = crush_items(items, tokenizer, max_items=12)++ values = [item["value"] for item in crushed]++ # Should have items from both clusters+ low_cluster = [v for v in values if v < 20]+ high_cluster = [v for v in values if v > 85]++ assert len(low_cluster) >= 1, "Should have items from low cluster"+ assert len(high_cluster) >= 1, "Should have items from high cluster"+++# =============================================================================+# TestEdgeCases+# =============================================================================+++class TestEdgeCases:+ """Edge cases and boundary conditions."""++ def test_empty_array(self, tokenizer):+ """Empty array should return empty result."""+ items: list[dict] = []++ messages = [+ {"role": "system", "content": "You are helpful."},+ {"role": "tool", "tool_call_id": "call_1", "content": "[]"},+ ]++ config = SmartCrusherConfig(+ enabled=True,+ min_tokens_to_crush=0,+ min_items_to_analyze=3,+ max_items_after_crush=10,+ )+ crusher = SmartCrusher(config)+ result = crusher.apply(messages, tokenizer)++ tool_content = result.messages[-1]["content"]+ json_part = tool_content.split("\n<headroom:")[0]+ crushed = json.loads(json_part)++ assert crushed == [], "Empty array should return empty result"++ def test_single_item(self, tokenizer):+ """Single item array should preserve the item."""+ items = [{"id": 0, "name": "Only item"}]++ crushed = crush_items(items, tokenizer, max_items=10, min_items=1)++ assert len(crushed) == 1, "Single item should be preserved"+ assert crushed[0]["name"] == "Only item"++ def test_two_items(self, tokenizer):+ """Two item array should preserve both items."""+ items = [{"id": 0, "name": "First"}, {"id": 1, "name": "Second"}]++ crushed = crush_items(items, tokenizer, max_items=10, min_items=1)++ assert len(crushed) == 2, "Both items should be preserved"++ def test_all_identical_items(self, tokenizer):+ """Array of all identical items should keep minimal anchors."""+ items = [{"id": "same", "value": 42, "status": "ok"} for _ in range(50)]++ crushed = crush_items(items, tokenizer, max_items=10)++ # Should not keep all 10 identical items - that would be wasteful+ # But some anchors are needed for structure+ assert len(crushed) <= 10, "Should respect max_items"+ # All items are identical, so any subset is equivalent++ def test_max_items_greater_than_array(self, tokenizer):+ """max_items > array size should return all items."""+ items = generate_numbered_items(8)++ crushed = crush_items(items, tokenizer, max_items=20)++ assert len(crushed) == 8, "Should return all items when max_items > array size"++ def test_max_items_equals_array(self, tokenizer):+ """max_items == array size should return all items."""+ items = generate_numbered_items(15)++ crushed = crush_items(items, tokenizer, max_items=15)++ assert len(crushed) == 15, "Should return all items when max_items == array size"++ def test_all_items_have_errors(self, tokenizer):+ """When all items have errors, quality guarantee preserves all.++ Current behavior: Error preservation takes precedence over max_items.+ All error items are preserved to avoid losing critical information.+ This is a deliberate design choice documented in SmartCrusher.++ NOTE: Future AnchorSelector may implement error deduplication or sampling+ for cases where all items are errors, but that requires careful design.+ """+ items = [+ {"id": i, "status": "error", "error_code": f"ERR_{i}"}+ for i in range(50)+ ]++ crushed = crush_items(items, tokenizer, max_items=15)++ # Current behavior: all errors are preserved (quality guarantee)+ # This is intentional - we don't want to lose error information+ assert len(crushed) == 50, "All error items should be preserved (quality guarantee)"++ def test_none_values_handled(self, tokenizer):+ """Items with None values should be handled gracefully."""+ items = [+ {"id": i, "value": None if i % 3 == 0 else i * 10, "name": f"Item {i}"}+ for i in range(30)+ ]++ crushed = crush_items(items, tokenizer, max_items=10)++ # Should not crash, should return valid items+ assert len(crushed) > 0, "Should handle None values"+ assert all(isinstance(item, dict) for item in crushed)++ def test_mixed_types_in_array(self, tokenizer):+ """Array with mixed item structures should be handled."""+ items = [+ {"id": 0, "simple": True},+ {"id": 1, "nested": {"deep": {"value": 42}}},+ {"id": 2, "list_field": [1, 2, 3]},+ {"id": 3, "mixed": {"a": [1, 2], "b": "text"}},+ ]+ # Add more simple items to trigger crushing+ items.extend([{"id": i, "simple": True} for i in range(4, 20)])++ crushed = crush_items(items, tokenizer, max_items=8, min_items=3)++ # Should preserve structurally interesting items+ assert len(crushed) > 0, "Should handle mixed structures"++ def test_unicode_content_preserved(self, tokenizer):+ """Unicode content should be preserved correctly."""+ # Use the full Unicode codepoint for rocket emoji (U+1F680)+ rocket_emoji = "\U0001f680" # Full codepoint, not surrogate pair+ items = [+ {"id": i, "name": f"Item {i} - \u4e2d\u6587 \u65e5\u672c\u8a9e {rocket_emoji}"}+ for i in range(20)+ ]++ crushed = crush_items(items, tokenizer, max_items=10)++ # Unicode should be preserved+ for item in crushed:+ assert "\u4e2d\u6587" in item["name"], "Chinese characters should be preserved"+ assert rocket_emoji in item["name"], "Emoji should be preserved"++ def test_very_long_string_values(self, tokenizer):+ """Items with very long string values should be handled."""+ items = [+ {"id": i, "data": "x" * 10000 if i == 10 else "short"}+ for i in range(30)+ ]++ crushed = crush_items(items, tokenizer, max_items=10)++ # Should not crash+ assert len(crushed) > 0, "Should handle long strings"++ def test_deeply_nested_items(self, tokenizer):+ """Deeply nested items should be handled without stack overflow."""+ def create_nested(depth: int) -> dict:+ if depth == 0:+ return {"value": "leaf"}+ return {"nested": create_nested(depth - 1)}++ items = [{"id": i, "deep": create_nested(10)} for i in range(20)]++ crushed = crush_items(items, tokenizer, max_items=10)++ assert len(crushed) > 0, "Should handle deeply nested items"+++# =============================================================================+# TestAnchorConfigBehavior+# =============================================================================+++class TestAnchorConfigBehavior:+ """Test configuration-driven anchor behavior."""++ def test_high_max_items_reduces_compression(self, tokenizer):+ """Higher max_items should preserve more items.++ NOTE: Data must have "importance signals" (errors, anomalies) to trigger+ compression. Generic unique items without signals are SKIPPED by the+ crushability analysis (conservative behavior to avoid losing entities).++ This test uses search results which always compress based on score.+ """+ # Use search results - they always trigger TOP_N compression+ items = generate_search_results(100)++ crushed_low = crush_items(items, tokenizer, max_items=8)+ crushed_high = crush_items(items, tokenizer, max_items=25)++ assert len(crushed_high) > len(crushed_low), (+ f"Higher max_items should preserve more items, "+ f"got low={len(crushed_low)}, high={len(crushed_high)}"+ )++ def test_min_items_to_analyze_threshold(self, tokenizer):+ """Arrays below min_items_to_analyze should not be crushed."""+ items = generate_numbered_items(5)++ # Set min_items_to_analyze higher than array size+ messages = [+ {"role": "system", "content": "You are helpful."},+ {"role": "tool", "tool_call_id": "call_1", "content": json.dumps(items)},+ ]++ config = SmartCrusherConfig(+ enabled=True,+ min_tokens_to_crush=0,+ min_items_to_analyze=10, # Higher than array size+ max_items_after_crush=3,+ )+ crusher = SmartCrusher(config)+ result = crusher.apply(messages, tokenizer)++ tool_content = result.messages[-1]["content"]+ json_part = tool_content.split("\n<headroom:")[0]+ crushed = json.loads(json_part)++ # Should not crush because array is below threshold+ assert len(crushed) == 5, "Array below min_items_to_analyze should not be crushed"+++# =============================================================================+# TestPreservationGuarantees+# =============================================================================+++class TestPreservationGuarantees:+ """Test hard guarantees about what must be preserved."""++ def test_errors_always_preserved(self, tokenizer):+ """Error items must ALWAYS be preserved, regardless of position or count."""+ items = [{"id": i, "status": "ok"} for i in range(100)]+ # Scatter errors throughout+ error_positions = [10, 25, 45, 65, 85]+ for pos in error_positions:+ items[pos] = {"id": pos, "status": "error", "error": f"Error at {pos}"}++ crushed = crush_items(items, tokenizer, max_items=15)++ # All errors should be preserved+ error_count = sum(1 for item in crushed if item.get("status") == "error")+ assert error_count == len(error_positions), (+ f"All {len(error_positions)} errors should be preserved, got {error_count}"+ )++ def test_anomalies_always_preserved(self, tokenizer):+ """Numeric anomalies (statistical outliers) must be preserved."""+ items = [{"id": i, "value": 100 + (i % 5)} for i in range(100)]+ # Add anomalies+ items[33]["value"] = 9999+ items[66]["value"] = -9999++ crushed = crush_items(items, tokenizer, max_items=15)++ values = [item["value"] for item in crushed]++ # Anomalies should be present+ assert 9999 in values, "High anomaly should be preserved"+ assert -9999 in values, "Low anomaly should be preserved"++ def test_query_matches_always_preserved(self, tokenizer):+ """Items matching user query must be preserved."""+ items = [{"id": i, "name": f"generic_item_{i}"} for i in range(100)]+ items[55]["name"] = "special_target_item"+ items[55]["important"] = True++ crushed = crush_items(+ items,+ tokenizer,+ max_items=10,+ query="Find special_target_item",+ )++ # Target should be found+ names = [item["name"] for item in crushed]+ assert "special_target_item" in names, "Query-matched item must be preserved"++ def test_change_points_preserved(self, tokenizer):+ """Items around detected change points should be preserved."""+ # Create data with clear step change+ items = []+ for i in range(60):+ value = 100.0 if i < 30 else 300.0 # Step change at index 30+ items.append({"id": i, "value": value, "timestamp": f"2025-01-{(i % 28) + 1:02d}"})++ crushed = crush_items(items, tokenizer, max_items=12)++ # Should have items from around the change point+ preserved_ids = [item["id"] for item in crushed]++ # Check for items near the change point (indices 28-32)+ near_change = sum(1 for id in preserved_ids if 25 <= id <= 35)+ assert near_change >= 1, "Items near change point should be preserved"