Skip to content

Commit 7c9a032

Browse files
authored
refactor(proxy): extract ccr golden replay policy (#2006)
## Description Extracts CCR golden tool replay and fresh-definition canonicalization from `headroom.proxy.helpers.apply_session_sticky_ccr_tool` into a focused policy module. This keeps sticky CCR orchestration in helpers while making the byte replay/regeneration behavior independently testable. Closes # ## Type of Change - [ ] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [x] Code refactoring (no functional changes) ## Changes Made - Added `headroom.proxy.ccr_golden_policy` for replaying stored CCR golden bytes and creating canonical fresh CCR tool definitions. - Updated `apply_session_sticky_ccr_tool` to delegate CCR golden replay/fresh definition policy while preserving tracker coordination and logging decisions. - Added direct tests for golden-byte replay, invalid/corrupt bytes, non-UTF-8 bytes, and fresh canonical definition generation. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text python -m pytest tests/test_ccr_golden_policy.py tests/test_ccr_tool_always_on.py tests/test_corrupt_golden_bytes_recovery.py tests/test_proxy/test_ccr_frozen_prefix_coupling.py 30 passed in 0.34s python -m ruff check . All checks passed! python -m ruff format --check . 1069 files already formatted python -m mypy headroom --ignore-missing-imports Success: no issues found in 410 source files gitleaks protect --staged --no-banner --redact no leaks found ``` ## Real Behavior Proof - Environment: Windows, Python 3.13.13, clean worktree from `headroomlabs/main` at `d2170b19`. - Exact command / steps: Ran targeted CCR golden replay/sticky injection/corrupt-byte regression tests plus ruff, ruff-format, mypy, and staged gitleaks scan. - Observed result: All targeted tests and local gates passed; staged secret scan found no leaks. - Not tested: Full Docker/native wrapper CI locally; covered by repository CI. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) N/A. ## Additional Notes Documentation and changelog updates are not applicable for this internal refactor. The push reported existing default-branch Dependabot vulnerabilities; this PR's staged gitleaks scan passed and CI security checks are expected to validate the branch.
1 parent d1c484b commit 7c9a032

3 files changed

Lines changed: 109 additions & 18 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""Policy helpers for replaying CCR golden tool definitions."""
2+
3+
from __future__ import annotations
4+
5+
import json
6+
from dataclasses import dataclass
7+
from typing import Any, Literal, cast
8+
9+
from headroom.ccr.tool_injection import create_ccr_tool_definition
10+
11+
12+
@dataclass(frozen=True)
13+
class CcrToolDefinitionReplay:
14+
"""CCR tool definition selected for sticky replay or fresh injection."""
15+
16+
tool_definition: dict[str, Any]
17+
canonical_bytes: bytes
18+
used_golden_bytes: bool
19+
20+
21+
def serialize_ccr_tool_definition_canonical(tool_definition: dict[str, Any]) -> bytes:
22+
"""Return stable canonical bytes for a CCR tool definition."""
23+
24+
return json.dumps(
25+
tool_definition,
26+
ensure_ascii=False,
27+
separators=(",", ":"),
28+
).encode("utf-8")
29+
30+
31+
def replay_golden_ccr_tool_definition(golden_tool_bytes: bytes) -> CcrToolDefinitionReplay:
32+
"""Decode a stored CCR tool definition and preserve its original bytes."""
33+
34+
tool_definition = json.loads(golden_tool_bytes.decode("utf-8"))
35+
return CcrToolDefinitionReplay(
36+
tool_definition=cast(dict[str, Any], tool_definition),
37+
canonical_bytes=golden_tool_bytes,
38+
used_golden_bytes=True,
39+
)
40+
41+
42+
def create_fresh_ccr_tool_definition(
43+
provider: Literal["anthropic", "openai", "google"],
44+
) -> CcrToolDefinitionReplay:
45+
"""Create and canonicalize a fresh CCR tool definition for ``provider``."""
46+
47+
tool_definition = create_ccr_tool_definition(provider)
48+
return CcrToolDefinitionReplay(
49+
tool_definition=tool_definition,
50+
canonical_bytes=serialize_ccr_tool_definition_canonical(tool_definition),
51+
used_golden_bytes=False,
52+
)

headroom/proxy/helpers.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@
3838
prepare_outbound_body_bytes as prepare_outbound_body_bytes, # noqa: F401 - compatibility export
3939
)
4040
from headroom.proxy.body_forwarding import serialize_body_canonical
41+
from headroom.proxy.ccr_golden_policy import (
42+
create_fresh_ccr_tool_definition,
43+
replay_golden_ccr_tool_definition,
44+
)
4145
from headroom.proxy.ccr_session_tracker import SessionCcrTracker as _SessionCcrTracker
4246
from headroom.proxy.internal_header_policy import (
4347
INTERNAL_HEADER_PREFIX,
@@ -2303,7 +2307,7 @@ def apply_session_sticky_ccr_tool(
23032307
Returns ``(updated_tools, was_injected)``. ``updated_tools`` is a
23042308
fresh list (caller-safe).
23052309
"""
2306-
from headroom.ccr.tool_injection import CCR_TOOL_NAME, create_ccr_tool_definition
2310+
from headroom.ccr.tool_injection import CCR_TOOL_NAME
23072311

23082312
if provider not in ("anthropic", "openai", "google"):
23092313
raise ValueError(f"unsupported provider: {provider!r}")
@@ -2337,14 +2341,13 @@ def apply_session_sticky_ccr_tool(
23372341
request_id=request_id,
23382342
)
23392343
return tools_out, False
2340-
tool_def = create_ccr_tool_definition(provider)
2341-
canonical = serialize_tool_definition_canonical(tool_def)
2342-
tools_out.append(tool_def)
2344+
replay = create_fresh_ccr_tool_definition(provider)
2345+
tools_out.append(replay.tool_definition)
23432346
log_tool_injection_decision(
23442347
provider=provider,
23452348
session_id=None,
23462349
decision="inject_first_time",
2347-
tool_definition_bytes_count=len(canonical),
2350+
tool_definition_bytes_count=len(replay.canonical_bytes),
23482351
request_id=request_id,
23492352
)
23502353
return tools_out, True
@@ -2361,13 +2364,13 @@ def apply_session_sticky_ccr_tool(
23612364
golden = tracker.get_golden_tool_bytes(provider, session_id)
23622365
if golden is not None:
23632366
try:
2364-
tool_def = json.loads(golden.decode("utf-8"))
2365-
tools_out.append(tool_def)
2367+
replay = replay_golden_ccr_tool_definition(golden)
2368+
tools_out.append(replay.tool_definition)
23662369
log_tool_injection_decision(
23672370
provider=provider,
23682371
session_id=session_id,
23692372
decision="inject_sticky_replay",
2370-
tool_definition_bytes_count=len(golden),
2373+
tool_definition_bytes_count=len(replay.canonical_bytes),
23712374
request_id=request_id,
23722375
)
23732376
return tools_out, True
@@ -2381,15 +2384,14 @@ def apply_session_sticky_ccr_tool(
23812384
# Fall through to fresh creation below
23822385
# Tracker says "done CCR" but has no golden bytes (or they were corrupt). Pin
23832386
# them now so future turns are stable.
2384-
tool_def = create_ccr_tool_definition(provider)
2385-
canonical = serialize_tool_definition_canonical(tool_def)
2386-
tracker.record_ccr_done(provider, session_id, canonical)
2387-
tools_out.append(tool_def)
2387+
replay = create_fresh_ccr_tool_definition(provider)
2388+
tracker.record_ccr_done(provider, session_id, replay.canonical_bytes)
2389+
tools_out.append(replay.tool_definition)
23882390
log_tool_injection_decision(
23892391
provider=provider,
23902392
session_id=session_id,
23912393
decision="inject_sticky_replay",
2392-
tool_definition_bytes_count=len(canonical),
2394+
tool_definition_bytes_count=len(replay.canonical_bytes),
23932395
request_id=request_id,
23942396
)
23952397
return tools_out, True
@@ -2405,15 +2407,14 @@ def apply_session_sticky_ccr_tool(
24052407
)
24062408
return tools_out, False
24072409

2408-
tool_def = create_ccr_tool_definition(provider)
2409-
canonical = serialize_tool_definition_canonical(tool_def)
2410-
tracker.record_ccr_done(provider, session_id, canonical)
2411-
tools_out.append(tool_def)
2410+
replay = create_fresh_ccr_tool_definition(provider)
2411+
tracker.record_ccr_done(provider, session_id, replay.canonical_bytes)
2412+
tools_out.append(replay.tool_definition)
24122413
log_tool_injection_decision(
24132414
provider=provider,
24142415
session_id=session_id,
24152416
decision="inject_first_time",
2416-
tool_definition_bytes_count=len(canonical),
2417+
tool_definition_bytes_count=len(replay.canonical_bytes),
24172418
request_id=request_id,
24182419
)
24192420
return tools_out, True

tests/test_ccr_golden_policy.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from __future__ import annotations
2+
3+
import pytest
4+
5+
from headroom.ccr.tool_injection import CCR_TOOL_NAME, create_ccr_tool_definition
6+
from headroom.proxy.ccr_golden_policy import (
7+
create_fresh_ccr_tool_definition,
8+
replay_golden_ccr_tool_definition,
9+
serialize_ccr_tool_definition_canonical,
10+
)
11+
12+
13+
def test_replays_golden_definition_without_reserializing() -> None:
14+
golden = b'{ "name" : "headroom_retrieve" , "description" : "client bytes" }'
15+
16+
replay = replay_golden_ccr_tool_definition(golden)
17+
18+
assert replay.tool_definition["name"] == CCR_TOOL_NAME
19+
assert replay.canonical_bytes == golden
20+
assert replay.used_golden_bytes is True
21+
22+
23+
def test_rejects_invalid_golden_json() -> None:
24+
with pytest.raises(ValueError):
25+
replay_golden_ccr_tool_definition(b"not-json")
26+
27+
28+
def test_rejects_non_utf8_golden_bytes() -> None:
29+
with pytest.raises(UnicodeDecodeError):
30+
replay_golden_ccr_tool_definition(b"\x80\x81")
31+
32+
33+
def test_fresh_definition_uses_canonical_bytes() -> None:
34+
replay = create_fresh_ccr_tool_definition("anthropic")
35+
36+
assert replay.tool_definition == create_ccr_tool_definition("anthropic")
37+
assert replay.canonical_bytes == serialize_ccr_tool_definition_canonical(replay.tool_definition)
38+
assert replay.used_golden_bytes is False

0 commit comments

Comments
 (0)