-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Expand file tree
/
Copy pathtest_proxy_byte_faithful_forwarding.py
More file actions
1610 lines (1369 loc) · 54.6 KB
/
Copy pathtest_proxy_byte_faithful_forwarding.py
File metadata and controls
1610 lines (1369 loc) · 54.6 KB
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Byte-faithful Python forwarder tests for PR-A3 (P0-2 fix).
The Python forwarder layer (server.py:_retry_request, streaming.py,
openai.py:_ws_http_fallback, batch.py) historically re-serialized every
request body via httpx's default JSON encoder, drifting separators (``, ``
vs ``,``) and ASCII-escaping non-ASCII text. Every such request collapsed
Anthropic prompt-cache hit-rate.
PR-A3 makes every forwarder byte-faithful:
* unmutated body → forward original ``await request.body()`` verbatim;
* mutated body → re-serialize once via ``serialize_body_canonical``
(compact separators, ``ensure_ascii=False``).
The legacy behavior is still reachable via
``HEADROOM_PROXY_PYTHON_FORWARDER_MODE=legacy_json_kwarg`` for emergency
rollback (operator opt-in, not a fallback).
"""
from __future__ import annotations
import gzip
import hashlib
import json
import logging
from types import SimpleNamespace
from unittest.mock import AsyncMock
import httpx
import pytest
from fastapi.testclient import TestClient
from headroom.pipeline import PipelineStage
from headroom.proxy.body_forwarding import (
BodyMutationTracker,
OutboundBody,
get_python_forwarder_mode,
outbound_body_is_client_bytes,
prepare_outbound_body_bytes,
select_outbound_body,
serialize_body_canonical,
)
from headroom.proxy.helpers import (
_reset_session_beta_tracker_for_test,
append_text_to_latest_user_chat_message,
get_session_beta_tracker,
log_outbound_request,
)
from headroom.proxy.server import ProxyConfig, create_app
pytest.importorskip("fastapi")
@pytest.fixture(autouse=True)
def _disable_output_shaper(monkeypatch: pytest.MonkeyPatch) -> None:
# Isolate this suite from the opt-in HEADROOM_OUTPUT_SHAPER a developer shell
# may export, which otherwise perturbs the byte-faithful assertions.
monkeypatch.delenv("HEADROOM_OUTPUT_SHAPER", raising=False)
# ---------------------------------------------------------------------------
# Unit tests for serializer + tracker
# ---------------------------------------------------------------------------
def test_serialize_canonical_compact_separators() -> None:
"""``serialize_body_canonical`` must use compact ``,``/``:`` (no spaces)."""
body = {"a": 1, "b": 2}
out = serialize_body_canonical(body)
assert out == b'{"a":1,"b":2}', repr(out)
def test_serialize_canonical_unicode_passthrough() -> None:
"""UTF-8 must survive — no ``\\uXXXX`` ASCII escaping."""
body = {"emoji": "🔥", "cjk": "日本語", "mixed": "hello → 世界"}
out = serialize_body_canonical(body)
# Each non-ASCII char appears as raw UTF-8 bytes, never as a \uXXXX literal.
assert b"\\u" not in out, repr(out)
parsed = json.loads(out.decode("utf-8"))
assert parsed == body
def test_serialize_canonical_preserves_dict_insertion_order() -> None:
"""Dict insertion order is preserved (Python 3.7+ guarantee)."""
body = {"z": 1, "a": 2, "m": 3}
out = serialize_body_canonical(body)
assert out.startswith(b'{"z":1,"a":2,"m":3'), repr(out)
def test_mutation_tracker_records_reason_memory_injection() -> None:
tracker = BodyMutationTracker()
assert tracker.mutated is False
assert tracker.reasons == []
tracker.mark_mutated("memory_injection")
assert tracker.mutated is True
assert tracker.reasons == ["memory_injection"]
def test_mutation_tracker_records_reason_compression() -> None:
tracker = BodyMutationTracker()
tracker.mark_mutated("compression_smart_crusher")
assert tracker.mutated is True
assert tracker.reasons == ["compression_smart_crusher"]
def test_mutation_tracker_dedupes_reasons() -> None:
tracker = BodyMutationTracker()
tracker.mark_mutated("memory_injection")
tracker.mark_mutated("memory_injection")
tracker.mark_mutated("compression")
assert tracker.reasons == ["memory_injection", "compression"]
def test_mutation_tracker_rejects_empty_reason() -> None:
tracker = BodyMutationTracker()
with pytest.raises(ValueError):
tracker.mark_mutated("")
def test_mutation_tracker_reasons_is_a_copy() -> None:
"""Caller-mutating the returned list must not affect the tracker."""
tracker = BodyMutationTracker()
tracker.mark_mutated("a")
out = tracker.reasons
out.append("b")
assert tracker.reasons == ["a"]
# ---------------------------------------------------------------------------
# prepare_outbound_body_bytes mode selection
# ---------------------------------------------------------------------------
def test_prepare_outbound_unmutated_returns_passthrough_bytes() -> None:
original = b'{"a":1,"b":"\xf0\x9f\x94\xa5"}'
out, source = prepare_outbound_body_bytes(
body={"a": 1, "b": "🔥"},
original_body_bytes=original,
body_mutated=False,
forwarder_mode="byte_faithful",
)
assert out == original
assert source == "passthrough"
def test_select_outbound_body_returns_value_object() -> None:
original = b'{"a":1}'
outbound = select_outbound_body(
body={"a": 1},
original_body_bytes=original,
body_mutated=False,
forwarder_mode="byte_faithful",
)
assert outbound == OutboundBody(content=original, source="passthrough")
def test_helpers_preserve_body_forwarding_compatibility_exports() -> None:
from headroom.proxy import helpers
assert helpers.BodyMutationTracker is BodyMutationTracker
assert helpers.get_python_forwarder_mode is get_python_forwarder_mode
assert helpers.prepare_outbound_body_bytes is prepare_outbound_body_bytes
assert helpers.serialize_body_canonical is serialize_body_canonical
def test_prepare_outbound_mutated_uses_canonical() -> None:
out, source = prepare_outbound_body_bytes(
body={"a": 1, "b": "🔥"},
original_body_bytes=b'{"a": 1, "b": "\xf0\x9f\x94\xa5"}', # spaces in original
body_mutated=True,
forwarder_mode="byte_faithful",
)
assert out == b'{"a":1,"b":"\xf0\x9f\x94\xa5"}'
assert source == "canonical"
@pytest.mark.parametrize("block_type", ["thinking", "redacted_thinking"])
def test_signed_thinking_history_with_original_bytes_uses_passthrough(
block_type: str,
) -> None:
body = {
"model": "claude-sonnet-4-5",
"messages": [
{"role": "user", "content": "Solve this"},
{
"role": "assistant",
"content": [
{
"type": block_type,
"thinking": "private reasoning",
"signature": "sig123",
},
{"type": "text", "text": "The answer is 42."},
],
},
{"role": "user", "content": "Continue"},
],
}
original = json.dumps(body, indent=2).encode("utf-8")
outbound = select_outbound_body(
body=body,
original_body_bytes=original,
body_mutated=True,
forwarder_mode="byte_faithful",
)
assert outbound.source == "passthrough"
assert outbound.content == original
def test_signed_thinking_history_without_original_bytes_uses_canonical() -> None:
body = {
"messages": [
{
"role": "assistant",
"content": [
{
"type": "thinking",
"thinking": "private reasoning",
"signature": "sig123",
}
],
}
]
}
outbound = select_outbound_body(
body=body,
original_body_bytes=None,
body_mutated=True,
forwarder_mode="byte_faithful",
)
assert outbound.source == "canonical"
assert outbound.content == serialize_body_canonical(body)
def test_signed_thinking_history_overrides_legacy_encoder() -> None:
body = {
"messages": [
{
"role": "assistant",
"content": [{"type": "thinking", "signature": "sig123"}],
}
]
}
original = json.dumps(body, indent=2).encode("utf-8")
outbound = select_outbound_body(
body=body,
original_body_bytes=original,
body_mutated=True,
forwarder_mode="legacy_json_kwarg",
)
assert outbound == OutboundBody(content=original, source="passthrough", dropped_mutations=True)
def test_signed_thinking_passthrough_reports_the_mutations_it_discarded() -> None:
"""Passthrough silently winning over a mutated body is what hid #2952."""
body = {
"stream": False,
"messages": [
{
"role": "assistant",
"content": [{"type": "thinking", "signature": "sig123"}],
}
],
}
original = json.dumps({**body, "stream": True}).encode("utf-8")
outbound = select_outbound_body(
body=body,
original_body_bytes=original,
body_mutated=True,
forwarder_mode="byte_faithful",
mutation_reasons=["ccr_streaming_retrieve_buffered_non_stream"],
)
assert outbound.source == "passthrough"
assert outbound.dropped_mutations is True
assert outbound.dropped_mutation_reasons == ("ccr_streaming_retrieve_buffered_non_stream",)
def test_original_signed_thinking_still_locks_when_mutation_removed_the_block() -> None:
original_body = {
"messages": [
{
"role": "assistant",
"content": [{"type": "thinking", "signature": "sig123"}],
}
]
}
mutated_body = {"messages": [{"role": "assistant", "content": "rewritten"}]}
original = json.dumps(original_body, indent=2).encode()
outbound = select_outbound_body(
body=mutated_body,
original_body_bytes=original,
body_mutated=True,
forwarder_mode="byte_faithful",
mutation_reasons=["compression"],
)
assert outbound.content == original
assert outbound.source == "passthrough"
assert outbound.dropped_mutation_reasons == ("compression",)
def test_signed_thinking_passthrough_reports_nothing_when_body_unmutated() -> None:
body = {
"messages": [
{
"role": "assistant",
"content": [{"type": "thinking", "signature": "sig123"}],
}
]
}
original = json.dumps(body).encode("utf-8")
outbound = select_outbound_body(
body=body,
original_body_bytes=original,
body_mutated=False,
forwarder_mode="byte_faithful",
mutation_reasons=["irrelevant"],
)
assert outbound.source == "passthrough"
assert outbound.dropped_mutations is False
assert outbound.dropped_mutation_reasons == ()
def test_canonical_path_reports_no_dropped_mutations() -> None:
body = {"messages": [{"role": "user", "content": "hi"}]}
outbound = select_outbound_body(
body=body,
original_body_bytes=b'{"messages": []}',
body_mutated=True,
forwarder_mode="byte_faithful",
mutation_reasons=["compression"],
)
assert outbound.source == "canonical"
assert outbound.dropped_mutations is False
assert outbound.dropped_mutation_reasons == ()
@pytest.mark.parametrize(
("original_body_bytes", "expected"),
[(b'{"messages": []}', True), (None, False)],
)
def test_outbound_body_is_client_bytes_matches_selection(
original_body_bytes: bytes | None, expected: bool
) -> None:
"""Handlers gate on this before mutating a body for their own upstream call."""
body = {
"messages": [
{
"role": "assistant",
"content": [{"type": "thinking", "signature": "sig123"}],
}
]
}
assert (
outbound_body_is_client_bytes(body=body, original_body_bytes=original_body_bytes)
is expected
)
outbound = select_outbound_body(
body=body,
original_body_bytes=original_body_bytes,
body_mutated=True,
forwarder_mode="byte_faithful",
)
assert (outbound.source == "passthrough") is expected
def test_outbound_body_is_client_bytes_false_without_thinking_blocks() -> None:
assert (
outbound_body_is_client_bytes(
body={"messages": [{"role": "user", "content": "hi"}]},
original_body_bytes=b'{"messages": []}',
)
is False
)
def test_prepare_outbound_no_original_bytes_uses_canonical() -> None:
out, source = prepare_outbound_body_bytes(
body={"a": 1},
original_body_bytes=None,
body_mutated=False,
forwarder_mode="byte_faithful",
)
assert out == b'{"a":1}'
assert source == "canonical"
def test_legacy_json_kwarg_mode_falls_back() -> None:
"""legacy_json_kwarg is an explicit operator opt-in — produces the historical bytes.
This is NOT a silent fallback (build constraint #4). It is reachable only
via env var and exists for emergency rollback validation.
"""
out, source = prepare_outbound_body_bytes(
body={"a": 1, "b": "🔥"},
original_body_bytes=b'{"a":1}',
body_mutated=False,
forwarder_mode="legacy_json_kwarg",
)
# Old httpx default: spaces after `,` and `:`, ascii escaping.
assert out == b'{"a": 1, "b": "\\ud83d\\udd25"}', repr(out)
assert source == "legacy"
def test_python_forwarder_mode_default_is_byte_faithful(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("HEADROOM_PROXY_PYTHON_FORWARDER_MODE", raising=False)
assert get_python_forwarder_mode() == "byte_faithful"
def test_python_forwarder_mode_invalid_raises(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("HEADROOM_PROXY_PYTHON_FORWARDER_MODE", "garbage")
with pytest.raises(ValueError, match="HEADROOM_PROXY_PYTHON_FORWARDER_MODE"):
get_python_forwarder_mode()
def test_python_forwarder_mode_legacy_value_accepted(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("HEADROOM_PROXY_PYTHON_FORWARDER_MODE", "legacy_json_kwarg")
assert get_python_forwarder_mode() == "legacy_json_kwarg"
# ---------------------------------------------------------------------------
# log_outbound_request structured log content
# ---------------------------------------------------------------------------
def test_log_outbound_request_emits_structured_fields() -> None:
"""Capture the structured log line via a temporary handler.
We attach a memory handler directly to the proxy logger so the test is
independent of whether ``_setup_file_logging`` has set ``propagate=False``
(which it does in the live proxy).
"""
import logging
proxy_logger = logging.getLogger("headroom.proxy")
records: list[logging.LogRecord] = []
class _ListHandler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
records.append(record)
handler = _ListHandler(level=logging.INFO)
prev_level = proxy_logger.level
proxy_logger.addHandler(handler)
proxy_logger.setLevel(logging.INFO)
try:
log_outbound_request(
forwarder="server",
method="POST",
path="/v1/messages",
body_bytes_count=42,
body_mutated=False,
mutation_reasons=[],
request_id="hr_test_1",
source="passthrough",
)
finally:
proxy_logger.removeHandler(handler)
proxy_logger.setLevel(prev_level)
matching = [r for r in records if "outbound_request" in r.getMessage()]
assert matching, f"no outbound_request log emitted; records={records!r}"
msg = matching[-1].getMessage()
assert "event=outbound_request" in msg
assert "forwarder=server" in msg
assert "path=/v1/messages" in msg
assert "body_bytes=42" in msg
assert "body_mutated=false" in msg
assert "source=passthrough" in msg
assert "request_id=hr_test_1" in msg
# Never log auth / body content.
assert "Authorization" not in msg
assert "x-api-key" not in msg.lower()
# ---------------------------------------------------------------------------
# httpx-mock end-to-end byte-faithful checks
# ---------------------------------------------------------------------------
class _CapturingTransport(httpx.AsyncBaseTransport):
"""An httpx transport that records the exact bytes received."""
def __init__(self) -> None:
self.captured_body: bytes | None = None
self.captured_headers: dict[str, str] | None = None
self.captured_url: str | None = None
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
# Eagerly read the request body so streaming bodies are captured too.
body = b""
async for chunk in request.stream:
body += chunk
self.captured_body = body
self.captured_headers = dict(request.headers.items())
self.captured_url = str(request.url)
return httpx.Response(
200,
json={
"id": "msg_1",
"type": "message",
"role": "assistant",
"content": [{"type": "text", "text": "ok"}],
"usage": {
"input_tokens": 10,
"output_tokens": 3,
"cache_read_input_tokens": 0,
"cache_creation_input_tokens": 0,
},
},
)
class _FakePrefixTracker:
def __init__(self, frozen_count: int = 0):
self._frozen_count = frozen_count
self._cached_token_count = 0
self._last_original_messages: list = []
self._last_forwarded_messages: list = []
def get_frozen_message_count(self) -> int:
return self._frozen_count
def get_last_original_messages(self): # noqa: ANN201
return list(self._last_original_messages)
def get_last_forwarded_messages(self): # noqa: ANN201
return list(self._last_forwarded_messages)
def update_from_response(self, **kwargs): # noqa: ANN003
self._last_original_messages = kwargs.get("original_messages", kwargs.get("messages", []))
self._last_forwarded_messages = kwargs.get("messages", [])
return None
class _SortedEmptyToolsPreSendExtension:
def on_pipeline_event(self, event): # noqa: ANN001
if event.stage is PipelineStage.PRE_SEND:
event.tools = []
return None
def _make_anthropic_app(*, optimize: bool) -> tuple[TestClient, _CapturingTransport]:
"""Boot an Anthropic proxy with a capturing transport."""
config = ProxyConfig(
optimize=optimize,
cache_enabled=False,
rate_limit_enabled=False,
cost_tracking_enabled=False,
log_requests=False,
ccr_inject_tool=False,
ccr_handle_responses=False,
ccr_context_tracking=False,
image_optimize=False,
)
app = create_app(config)
transport = _CapturingTransport()
proxy = app.state.proxy
proxy.http_client = httpx.AsyncClient(transport=transport)
# Pin a stable session tracker so the prefix walker doesn't re-read
# turn 0 on every run.
fake_tracker = _FakePrefixTracker(frozen_count=0)
proxy.session_tracker_store.compute_session_id = lambda request, model, messages: "s1"
proxy.session_tracker_store.get_or_create = lambda session_id, provider: fake_tracker
return TestClient(app), transport
def _make_no_optimize_app() -> tuple[TestClient, _CapturingTransport]:
"""Boot a proxy with all transforms disabled and a capturing transport."""
return _make_anthropic_app(optimize=False)
def test_signed_thinking_discarded_mutation_uses_wire_truth_for_all_accounting() -> None:
config = ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
cost_tracking_enabled=False,
log_requests=False,
ccr_inject_tool=False,
ccr_handle_responses=False,
ccr_context_tracking=False,
image_optimize=False,
)
app = create_app(config)
proxy = app.state.proxy
transport = _CapturingTransport()
proxy.http_client = httpx.AsyncClient(transport=transport)
proxy._record_request_outcome = AsyncMock(wraps=proxy._record_request_outcome)
tracker = _FakePrefixTracker(frozen_count=0)
proxy.session_tracker_store.compute_session_id = lambda request, model, messages: "signed"
proxy.session_tracker_store.get_or_create = lambda session_id, provider: tracker
inbound = {
"model": "claude-opus-5",
"max_tokens": 64,
"messages": [
{"role": "user", "content": "Solve this."},
{
"role": "assistant",
"content": [
{
"type": "thinking",
"thinking": "private",
"signature": "sig123",
},
{"type": "text", "text": "Working."},
],
},
{"role": "user", "content": "Continue."},
],
"tools": [
{
"name": "lookup",
"description": " Look up a value. ",
"input_schema": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {"key": {"type": "string"}},
},
}
],
}
inbound_bytes = json.dumps(inbound, indent=2).encode()
response = TestClient(app).post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
content=inbound_bytes,
)
assert response.status_code == 200
assert transport.captured_body == inbound_bytes
assert response.headers["x-headroom-tokens-saved"] == "0"
assert "x-headroom-transforms" not in response.headers
outcome = proxy._record_request_outcome.await_args.args[0]
assert outcome.tokens_saved == 0
assert outcome.optimized_tokens == outcome.original_tokens
assert outcome.transforms_applied == ()
assert outcome.tags["wire_mutations_discarded"] > 0
assert "anthropic:tool_schema_compaction" not in outcome.transforms_applied
assert "tool_search_deferred_tokens" not in outcome.tags
assert outcome.tags.get("_headroom_savings_attribution") == []
assert proxy.metrics.tokens_saved_total == 0
assert proxy.metrics.tool_search_saved_total == 0
assert tracker._last_forwarded_messages[: len(inbound["messages"])] == inbound["messages"]
def _openai_responses_body_bytes(*, stream: bool) -> bytes:
payload = {
"model": "gpt-5.5",
"input": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "hello 🔥 with spaces preserved",
}
],
}
],
"stream": stream,
}
return json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
def _openai_responses_codex_headers(content_encoding: str) -> dict[str, str]:
return {
"authorization": "Bearer test-token",
"chatgpt-account-id": "acct_test",
"originator": "Codex Desktop",
"content-type": "application/json",
"content-encoding": content_encoding,
"accept": "text/event-stream",
}
def _start_proxy_log_capture() -> tuple[
logging.Logger,
logging.Handler,
int,
list[logging.LogRecord],
]:
proxy_logger = logging.getLogger("headroom.proxy")
records: list[logging.LogRecord] = []
class _ListHandler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
records.append(record)
handler = _ListHandler(level=logging.INFO)
prev_level = proxy_logger.level
proxy_logger.addHandler(handler)
proxy_logger.setLevel(logging.INFO)
return proxy_logger, handler, prev_level, records
def _stop_proxy_log_capture(
proxy_logger: logging.Logger,
handler: logging.Handler,
prev_level: int,
) -> None:
proxy_logger.removeHandler(handler)
proxy_logger.setLevel(prev_level)
def _assert_openai_responses_encoded_passthrough(
transport: _CapturingTransport,
decoded_body: bytes,
) -> None:
assert transport.captured_body == decoded_body
assert transport.captured_headers is not None
captured_headers = {key.lower(): value for key, value in transport.captured_headers.items()}
assert "content-encoding" not in captured_headers
assert captured_headers.get("content-length") == str(len(decoded_body))
def _assert_outbound_passthrough_log(
records: list[logging.LogRecord],
*,
forwarder: str,
) -> None:
messages = [record.getMessage() for record in records]
assert any(
"event=outbound_request" in message
and f"forwarder={forwarder}" in message
and "body_mutated=false" in message
and "source=passthrough" in message
for message in messages
), messages
def test_passthrough_no_mutation_byte_equal_sha256() -> None:
"""No transform → upstream SHA-256 equals client-sent SHA-256."""
client, transport = _make_no_optimize_app()
# Compact JSON, simulating Claude Code / Codex CLI byte format.
inbound_dict = {
"model": "claude-sonnet-4-6",
"max_tokens": 64,
"messages": [{"role": "user", "content": "hello"}],
}
inbound_bytes = serialize_body_canonical(inbound_dict)
response = client.post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
content=inbound_bytes,
)
assert response.status_code == 200, response.text
assert transport.captured_body is not None
inbound_sha = hashlib.sha256(inbound_bytes).hexdigest()
upstream_sha = hashlib.sha256(transport.captured_body).hexdigest()
assert inbound_sha == upstream_sha, (
f"Byte-faithful invariant broken: inbound {inbound_sha} vs upstream "
f"{upstream_sha}; upstream body={transport.captured_body!r}"
)
def test_compression_off_unicode_preserved() -> None:
"""Emoji + CJK content survives forwarding without ``\\uXXXX`` escaping."""
client, transport = _make_no_optimize_app()
inbound_dict = {
"model": "claude-sonnet-4-6",
"max_tokens": 64,
"messages": [
{"role": "user", "content": "Hello 🔥 — 世界 — emoji is 🚀"},
],
}
inbound_bytes = serialize_body_canonical(inbound_dict)
response = client.post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
content=inbound_bytes,
)
assert response.status_code == 200
upstream = transport.captured_body or b""
assert upstream == inbound_bytes
assert b"\\u" not in upstream, repr(upstream)
assert "🔥".encode() in upstream
assert "世界".encode() in upstream
def test_compression_off_numeric_precision_preserved() -> None:
"""Floats with trailing zero stay floats; large ints preserve precision."""
client, transport = _make_no_optimize_app()
inbound_bytes = b'{"model":"claude-sonnet-4-6","max_tokens":64,"temperature":1.0,"seed":12345678901234567,"messages":[{"role":"user","content":"hi"}]}'
response = client.post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
content=inbound_bytes,
)
assert response.status_code == 200
upstream = transport.captured_body or b""
# Unmutated → byte-faithful: exact bytes preserved.
assert upstream == inbound_bytes
# Forward coverage only; the PRE_SEND case below is the base-fails proof for this fix.
def test_anthropic_tools_canonical_order_preserves_byte_faithful_request() -> None:
client, transport = _make_no_optimize_app()
inbound_dict = {
"model": "claude-sonnet-4-6",
"max_tokens": 64,
"messages": [{"role": "user", "content": "plan test"}],
"tools": [
{"name": "alpha"},
{"name": "zeta", "description": "later"},
],
}
inbound_bytes = serialize_body_canonical(inbound_dict)
response = client.post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
content=inbound_bytes,
)
assert response.status_code == 200, response.text
upstream = transport.captured_body or b""
assert upstream == inbound_bytes, (
f"Expected byte-faithful passthrough for canonical tools; upstream={upstream!r}"
)
def test_anthropic_tools_unsorted_order_preserves_byte_faithful_request() -> None:
client, transport = _make_no_optimize_app()
inbound_dict = {
"model": "claude-sonnet-4-6",
"max_tokens": 64,
"messages": [{"role": "user", "content": "plan test"}],
"tools": [
{"name": "zeta", "description": "later"},
{"name": "alpha"},
],
}
inbound_bytes = serialize_body_canonical(inbound_dict)
response = client.post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
content=inbound_bytes,
)
assert response.status_code == 200, response.text
upstream = transport.captured_body or b""
assert upstream == inbound_bytes
forwarded = json.loads(upstream.decode("utf-8"))
assert [tool["name"] for tool in forwarded["tools"]] == ["zeta", "alpha"]
def test_anthropic_tools_unsorted_reordered_and_canonicalized_when_optimized() -> None:
client, transport = _make_anthropic_app(optimize=True)
proxy = client.app.state.proxy
proxy.config.mode = "token"
def _fake_apply(**kwargs):
return SimpleNamespace(
messages=kwargs["messages"],
transforms_applied=[],
timing={},
tokens_before=100,
tokens_after=100,
waste_signals=None,
)
proxy.anthropic_pipeline.apply = _fake_apply
inbound_dict = {
"model": "claude-sonnet-4-6",
"max_tokens": 64,
"messages": [{"role": "user", "content": "plan test"}],
"tools": [
{"name": "zeta", "description": "later"},
{"name": "alpha"},
],
}
expected_dict = {
**inbound_dict,
"tools": [
inbound_dict["tools"][1],
inbound_dict["tools"][0],
],
}
inbound_bytes = serialize_body_canonical(inbound_dict)
expected_bytes = serialize_body_canonical(expected_dict)
response = client.post(
"/v1/messages",
headers={
"x-api-key": "test-key",
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
content=inbound_bytes,
)
assert response.status_code == 200, response.text
upstream = transport.captured_body or b""
assert upstream == expected_bytes
assert upstream != inbound_bytes
def test_anthropic_presend_sorted_empty_tools_keeps_body_unmutated() -> None:
inbound_dict = {
"model": "claude-sonnet-4-6",
"max_tokens": 64,
"messages": [{"role": "user", "content": "plan test"}],
}
inbound_bytes = serialize_body_canonical(inbound_dict)
config = ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
cost_tracking_enabled=False,
log_requests=False,
ccr_inject_tool=False,
ccr_handle_responses=False,
ccr_context_tracking=False,
image_optimize=False,
pipeline_extensions=[_SortedEmptyToolsPreSendExtension()],
discover_pipeline_extensions=False,
)
app = create_app(config)
client = TestClient(app)
captured: dict[str, object] = {}
async def _fake_retry(
method: str, # noqa: ARG001
url: str, # noqa: ARG001
headers: dict[str, str], # noqa: ARG001
body: dict[str, object], # noqa: ARG001
body_mutated: bool,
mutation_reasons: list[str],
**kwargs: object, # noqa: ANN003
) -> httpx.Response: # noqa: ANN201
captured["body_mutated"] = body_mutated
captured["mutation_reasons"] = mutation_reasons
captured["body"] = body
return httpx.Response(
200,
json={
"id": "msg_1",
"type": "message",
"role": "assistant",
"content": [{"type": "text", "text": "ok"}],
"usage": {
"input_tokens": 10,