File size: 15,671 Bytes
305de0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6002247
 
305de0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6002247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305de0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6002247
305de0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95cb372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305de0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95cb372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""Per-strategy compression observability tests.

These guard the forcing function: when any compressor runs in
production, a `CompressionObserver` notification fires once per real
compression event, and `PrometheusMetrics` accumulates per-strategy
counters that the test suite asserts on directly.

The TOIN→SmartCrusher silent disconnect (caught three weeks late by
manual audit) was invisible because no signal distinguished by
strategy. These tests exist so the next regression of that shape
fails the suite the day it lands instead of waiting on an audit.

The counters live ONLY as in-process state on the metrics instance;
they are deliberately NOT exported through the Prometheus scrape or
OTel surface, because the metric→Supabase pipeline treats each
metric name as a column and we cannot add new columns. CI-level
observability via these tests is enough to catch silent regressions;
production export waits on a non-column-adding pipeline.

Coverage:

1. `ContentRouter.compress(...)` calls observer once per RoutingDecision.
2. `SmartCrusher.apply(...)` calls observer once per crushed message.
3. Both transforms tolerate an observer that raises (compression must
   still succeed).
4. `PrometheusMetrics` correctly satisfies the `CompressionObserver`
   protocol β€” `record_compression` increments per-strategy counters
   and `tokens_saved_by_strategy` accumulates only positive savings.
5. The Prometheus scrape output (`export()`) does NOT emit any new
   metric names β€” the per-strategy state stays internal.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any

import pytest

from headroom.transforms.content_detector import ContentType
from headroom.transforms.content_router import (
    CompressionStrategy,
    ContentRouter,
    ContentRouterConfig,
    RouterCompressionResult,
    RoutingDecision,
)
from headroom.transforms.observability import CompressionObserver
from headroom.transforms.smart_crusher import SmartCrusher, SmartCrusherConfig

# ─── Test doubles ──────────────────────────────────────────────────────


@dataclass
class SpyObserver:
    """Captures every `record_compression` call for assertion."""

    calls: list[tuple[str, int, int]] = field(default_factory=list)

    def record_compression(
        self,
        strategy: str,
        original_tokens: int,
        compressed_tokens: int,
    ) -> None:
        self.calls.append((strategy, original_tokens, compressed_tokens))


@dataclass
class ExplodingObserver:
    """Raises on every call. Used to assert observer failures don't
    propagate out and break compression."""

    raised: int = 0

    def record_compression(self, *_a: Any, **_kw: Any) -> None:
        self.raised += 1
        raise RuntimeError("simulated observer outage")


# ─── Protocol conformance ──────────────────────────────────────────────


def test_spy_satisfies_observer_protocol():
    spy = SpyObserver()
    # `runtime_checkable` Protocol β€” isinstance check works.
    assert isinstance(spy, CompressionObserver)


def test_prometheus_metrics_satisfies_observer_protocol():
    from headroom.proxy.prometheus_metrics import PrometheusMetrics

    m = PrometheusMetrics()
    assert isinstance(m, CompressionObserver)


# ─── ContentRouter wiring ──────────────────────────────────────────────


def test_content_router_records_observer_call_per_routing_decision():
    spy = SpyObserver()
    router = ContentRouter(ContentRouterConfig(), observer=spy)

    # Forge a routing log directly via the result object β€” the observer
    # call site walks `result.routing_log`, so we assert the contract
    # without depending on which compressor would actually fire.
    result = RouterCompressionResult(
        compressed="x",
        original="x",
        strategy_used=CompressionStrategy.SMART_CRUSHER,
        routing_log=[
            RoutingDecision(
                content_type=ContentType.JSON_ARRAY,
                strategy=CompressionStrategy.SMART_CRUSHER,
                original_tokens=200,
                compressed_tokens=50,
            ),
            RoutingDecision(
                content_type=ContentType.SOURCE_CODE,
                strategy=CompressionStrategy.CODE_AWARE,
                original_tokens=300,
                compressed_tokens=300,  # passthrough β€” still recorded
            ),
        ],
    )
    router._observe(result)

    assert spy.calls == [
        ("smart_crusher", 200, 50),
        ("code_aware", 300, 300),
    ]


def test_content_router_with_no_observer_is_silent():
    router = ContentRouter(ContentRouterConfig())  # observer defaults None
    result = RouterCompressionResult(
        compressed="x",
        original="x",
        strategy_used=CompressionStrategy.PASSTHROUGH,
        routing_log=[
            RoutingDecision(
                content_type=ContentType.PLAIN_TEXT,
                strategy=CompressionStrategy.TEXT,
                original_tokens=10,
                compressed_tokens=5,
            )
        ],
    )
    # Should not raise.
    router._observe(result)


def test_content_router_swallows_observer_failures():
    boom = ExplodingObserver()
    router = ContentRouter(ContentRouterConfig(), observer=boom)
    result = RouterCompressionResult(
        compressed="x",
        original="x",
        strategy_used=CompressionStrategy.TEXT,
        routing_log=[
            RoutingDecision(
                content_type=ContentType.PLAIN_TEXT,
                strategy=CompressionStrategy.TEXT,
                original_tokens=10,
                compressed_tokens=5,
            )
        ],
    )
    # Must not raise β€” observability failures are not compression failures.
    router._observe(result)
    assert boom.raised == 1


# ─── SmartCrusher wiring (legacy direct-pipeline path) ─────────────────


def _bigger_array(n: int = 60) -> str:
    import json as _json

    items = [{"status": "ok", "tag": "x", "n": i} for i in range(n)]
    return _json.dumps(items)


@pytest.fixture
def isolated_toin(tmp_path, monkeypatch):
    """Point TOIN at a tempdir for the duration of the test.

    SmartCrusher.apply() feeds the global TOIN learning store via
    `record_compression`. Its default storage path is
    `~/.headroom/toin.json`, which persists across pytest invocations.
    On Python 3.11 CI runs the suite twice (regular + coverage); a
    pattern written in run #1 changes which rows the lossy sampler
    keeps in run #2 and breaks `test_first_last_items_always_preserved`
    in `test_evals.py`.

    Isolating the TOIN file per test contains the side effect.
    """
    from pathlib import Path

    from headroom.telemetry.toin import TOIN_PATH_ENV_VAR, reset_toin

    storage = str(Path(tmp_path) / "toin.json")
    monkeypatch.setenv(TOIN_PATH_ENV_VAR, storage)
    reset_toin()
    yield
    reset_toin()


def test_smart_crusher_apply_records_observer_per_crushed_message(isolated_toin):
    """End-to-end: SmartCrusher.apply() walks messages, crushes the
    big tool_result, fires the observer with strategy='smart_crusher'."""
    from headroom.providers.openai import OpenAITokenCounter
    from headroom.tokenizer import Tokenizer

    spy = SpyObserver()
    crusher = SmartCrusher(SmartCrusherConfig(), observer=spy)
    tok = Tokenizer(OpenAITokenCounter("gpt-4o-mini"), model="gpt-4o-mini")

    messages = [
        {"role": "user", "content": "what's in the data?"},
        {"role": "tool", "content": _bigger_array(60)},
    ]
    result = crusher.apply(messages, tok)
    # If the analyzer chose passthrough this run, the observer wasn't
    # fired; that's fine for the wiring test β€” we only assert it WAS
    # fired in the case it crushed.
    if "smart_crush:" in ",".join(result.transforms_applied):
        assert spy.calls, "smart_crusher crushed but observer wasn't notified"
        for strategy, original, compressed in spy.calls:
            assert strategy == "smart_crusher"
            assert original > 0
            assert compressed >= 0


def test_smart_crusher_apply_swallows_observer_failures(isolated_toin):
    """Observer raises β†’ compression still completes, returns valid
    TransformResult, count of raises matches the crushed_count."""
    from headroom.providers.openai import OpenAITokenCounter
    from headroom.tokenizer import Tokenizer

    boom = ExplodingObserver()
    crusher = SmartCrusher(SmartCrusherConfig(), observer=boom)
    tok = Tokenizer(OpenAITokenCounter("gpt-4o-mini"), model="gpt-4o-mini")
    messages = [{"role": "tool", "content": _bigger_array(60)}]
    result = crusher.apply(messages, tok)
    # Either the analyzer didn't crush (boom.raised == 0) or it did
    # (boom.raised >= 1) β€” but in both cases compression returned a
    # valid TransformResult. No exception escaped.
    assert result.messages is not None


# ─── PrometheusMetrics implementation ──────────────────────────────────


def test_prometheus_metrics_accumulates_per_strategy_counters():
    from headroom.proxy.prometheus_metrics import PrometheusMetrics

    m = PrometheusMetrics()

    m.record_compression("smart_crusher", original_tokens=200, compressed_tokens=50)
    m.record_compression("smart_crusher", original_tokens=100, compressed_tokens=40)
    m.record_compression("diff", original_tokens=80, compressed_tokens=80)  # no savings
    m.record_compression("code_aware", original_tokens=50, compressed_tokens=70)  # negative savings

    assert m.compressions_by_strategy == {
        "smart_crusher": 2,
        "diff": 1,
        "code_aware": 1,
    }
    # Tokens saved is `max(0, original - compressed)` per strategy.
    # smart_crusher: 150 + 60 = 210; diff: 0 (no savings, dict entry omitted);
    # code_aware: 0 (negative).
    assert m.tokens_saved_by_strategy == {"smart_crusher": 210}
    # Original tokens are tracked regardless of whether savings occurred,
    # so `/stats` can still compute a ratio for no-op strategies.
    assert m.tokens_original_by_strategy == {
        "smart_crusher": 300,
        "diff": 80,
        "code_aware": 50,
    }


def test_get_compression_segments_returns_per_strategy_breakdown():
    """`get_compression_segments()` is the `/stats` surface for the
    per-segment routing breakdown. It returns ratio + savings_pct per
    strategy tag, and omits strategies that never observed tokens."""
    from headroom.proxy.prometheus_metrics import PrometheusMetrics

    m = PrometheusMetrics()
    m.record_compression("smart_crusher", original_tokens=200, compressed_tokens=50)
    m.record_compression("smart_crusher", original_tokens=100, compressed_tokens=40)
    m.record_compression("code_aware", original_tokens=80, compressed_tokens=80)
    m.record_compression("diff", original_tokens=50, compressed_tokens=70)  # negative savings

    segments = m.get_compression_segments()

    # smart_crusher: 300 original, 90 saved β†’ 210 compressed, 30% ratio, 30% savings
    assert segments["smart_crusher"] == {
        "count": 2,
        "original_tokens": 300,
        "saved_tokens": 210,
        "compressed_tokens": 90,
        "savings_pct": 70.0,
        "compression_ratio": 0.3,
    }
    # code_aware: 80 original, 0 saved β†’ 80 compressed, 100% ratio, 0% savings
    assert segments["code_aware"] == {
        "count": 1,
        "original_tokens": 80,
        "saved_tokens": 0,
        "compressed_tokens": 80,
        "savings_pct": 0.0,
        "compression_ratio": 1.0,
    }
    # diff: 50 original, negative savings clamped to 0 β†’ ratio 1.0
    assert segments["diff"] == {
        "count": 1,
        "original_tokens": 50,
        "saved_tokens": 0,
        "compressed_tokens": 50,
        "savings_pct": 0.0,
        "compression_ratio": 1.0,
    }


def test_get_compression_segments_empty_when_no_observed_data():
    from headroom.proxy.prometheus_metrics import PrometheusMetrics

    assert PrometheusMetrics().get_compression_segments() == {}


def test_prometheus_export_does_not_leak_per_strategy_metrics():
    """Per-strategy state is tracked in-process only. The Prometheus
    scrape output deliberately must NOT emit new metric names β€” the
    metric→Supabase pipeline treats each metric name as a column, and
    we cannot add new columns. This test guards that constraint: if a
    future change adds the metric to the scrape, this fails and forces
    a conscious decision."""
    import asyncio

    from headroom.proxy.prometheus_metrics import PrometheusMetrics

    m = PrometheusMetrics()
    m.record_compression("smart_crusher", original_tokens=200, compressed_tokens=50)
    m.record_compression("diff", original_tokens=120, compressed_tokens=70)

    output = asyncio.run(m.export())

    assert "headroom_compressions_total" not in output
    assert "headroom_tokens_saved_by_strategy_total" not in output


# ─── End-to-end smoke (router + metrics together) ──────────────────────


def test_router_with_prometheus_observer_increments_counters():
    """Plumbing test: a router wired to a real PrometheusMetrics
    instance lights up the per-strategy counters as routing decisions
    accumulate. This is the production wiring shape from
    `headroom/proxy/server.py`."""
    from headroom.proxy.prometheus_metrics import PrometheusMetrics

    m = PrometheusMetrics()
    router = ContentRouter(ContentRouterConfig(), observer=m)

    fake_result = RouterCompressionResult(
        compressed="x",
        original="x",
        strategy_used=CompressionStrategy.MIXED,
        routing_log=[
            RoutingDecision(
                content_type=ContentType.JSON_ARRAY,
                strategy=CompressionStrategy.SMART_CRUSHER,
                original_tokens=300,
                compressed_tokens=80,
            ),
            RoutingDecision(
                content_type=ContentType.SOURCE_CODE,
                strategy=CompressionStrategy.CODE_AWARE,
                original_tokens=200,
                compressed_tokens=120,
            ),
            RoutingDecision(
                content_type=ContentType.JSON_ARRAY,
                strategy=CompressionStrategy.SMART_CRUSHER,
                original_tokens=100,
                compressed_tokens=40,
            ),
        ],
    )
    router._observe(fake_result)

    assert m.compressions_by_strategy == {"smart_crusher": 2, "code_aware": 1}
    assert m.tokens_saved_by_strategy == {
        "smart_crusher": (300 - 80) + (100 - 40),  # 280
        "code_aware": (200 - 120),  # 80
    }
    assert m.tokens_original_by_strategy == {
        "smart_crusher": 400,
        "code_aware": 200,
    }
    # Segments surface wires through to /stats:
    assert m.get_compression_segments() == {
        "smart_crusher": {
            "count": 2,
            "original_tokens": 400,
            "saved_tokens": 280,
            "compressed_tokens": 120,
            "savings_pct": 70.0,
            "compression_ratio": 0.3,
        },
        "code_aware": {
            "count": 1,
            "original_tokens": 200,
            "saved_tokens": 80,
            "compressed_tokens": 120,
            "savings_pct": 40.0,
            "compression_ratio": 0.6,
        },
    }