headroom/tests/test_cross_turn_dedup.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

475 lines
20 KiB
Python
Raw Permalink Normal View History

feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
"""Cross-turn dedup: cache-safety (prefix-monotonicity) + accuracy (info-preserving)."""
import re
from headroom.transforms.cross_turn_dedup import (
DedupBlock,
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
_num_and_key,
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
dedup_blocks,
is_prefix_monotonic,
)
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
# Compact fold pointer: ``[↑<N>L same as msg <ref>[ <±delta>L]: '<anchor>']`` —
# span length + referenced msg + optional line-number offset + a truncated
# first-line anchor (no explicit line range; recovery locates the span by anchor).
_FOLD_RE = re.compile(r"\[↑(\d+)L same as msg (\d+)(?: ([+-]\d+)L)?: '([^']*)'\]")
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
def _blk(text, turn, protected=False):
return DedupBlock(text=text, turn=turn, protected=protected)
def _code(prefix, n):
# A realistic, non-trivial multi-line source span.
return "\n".join(
f"{prefix} result_{i} = compute_overdraft(business_id={i}, amount={i * 100})"
for i in range(n)
)
def _reconstruct(orig_blocks, out_blocks):
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
"""Replace each fold pointer with the referenced msg's original lines and assert
it reproduces the original block proves references are faithful & in-context.
The compact pointer names the ref msg + span length + a first-line anchor (not
an explicit line range), so recovery locates the span by its anchor in the
referenced message and takes ``<N>`` lines. (All test spans are unnumbered, so
delta is always absent; a non-zero delta would renumber on the way out.)"""
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
by_turn = {b.turn: b.text.split("\n") for b in orig_blocks}
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
def _content(line):
return _num_and_key(line)[2].strip()
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
for orig, out in zip(orig_blocks, out_blocks):
if orig.protected:
assert out.text == orig.text
continue
rebuilt = []
for line in out.text.split("\n"):
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
m = _FOLD_RE.search(line)
if m and line.lstrip().startswith("[↑"):
assert m.group(3) is None, "unexpected delta for an unnumbered span"
n, ref, anchor = int(m.group(1)), int(m.group(2)), m.group(4)
assert ref < orig.turn, "reference must point to an EARLIER msg"
core = anchor[:-3] if anchor.endswith("...") else anchor
ref_lines = by_turn[ref]
idx = next(i for i, rl in enumerate(ref_lines) if _content(rl).startswith(core))
rebuilt.extend(ref_lines[idx : idx + n])
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
else:
rebuilt.append(line)
assert "\n".join(rebuilt) == orig.text, f"turn {orig.turn} not faithfully reconstructable"
def test_verbatim_reread_is_folded_keep_earliest():
span = _code("", 8)
blocks = [_blk(f"cat merge.py\n{span}\ntail", 1), _blk(f"sed run\n{span}\nmore", 5)]
out, stats = dedup_blocks(blocks)
assert out[0].text == blocks[0].text # earliest untouched
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
assert "[↑" in out[1].text # later occurrence folded
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
assert stats["spans_folded"] == 1
_reconstruct(blocks, out)
def test_cache_safety_prefix_monotonic():
span = _code("x", 10)
blocks = [
_blk("intro line one\nintro line two\n" + span, 1),
_blk("unrelated diff output\n@@ -1 +1 @@\n-a\n+b", 2),
_blk("here again:\n" + span, 3),
_blk("and once more\n" + span + "\ntrailer", 4),
]
assert is_prefix_monotonic(blocks) is True
def test_below_min_lines_not_folded():
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
span = _code("", 2) # below min_lines (3)
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
blocks = [_blk(span, 1), _blk(span, 2)]
out, stats = dedup_blocks(blocks)
assert stats["spans_folded"] == 0
assert out[1].text == blocks[1].text
def test_trivial_repeated_lines_not_folded():
junk = "\n".join(["}"] * 20) # trivial lines only
blocks = [_blk(junk, 1), _blk(junk, 2)]
out, stats = dedup_blocks(blocks)
assert stats["spans_folded"] == 0
def test_deterministic():
span = _code("z", 9)
blocks = [_blk(span, 1), _blk("mid\n" + span, 2), _blk(span, 3)]
a, _ = dedup_blocks(blocks)
b, _ = dedup_blocks(blocks)
assert [x.text for x in a] == [x.text for x in b]
def test_protected_block_not_rewritten_but_is_reference_target():
span = _code("", 8)
blocks = [
_blk(span, 1, protected=True), # cache_control block — never rewritten
_blk("later:\n" + span, 2), # should still fold against the protected one
]
out, stats = dedup_blocks(blocks)
assert out[0].text == blocks[0].text
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
assert "[↑" in out[1].text
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
_reconstruct(blocks, out)
def test_info_preserving_reconstruction_multiref():
s1 = _code("a", 7)
s2 = _code("b", 8)
blocks = [
_blk("h1\n" + s1, 1),
_blk("h2\n" + s2, 2),
_blk("mix\n" + s1 + "\n---\n" + s2, 3), # two folds in one block
]
out, stats = dedup_blocks(blocks)
assert stats["spans_folded"] == 2
_reconstruct(blocks, out)
fix(transforms/cross-turn-dedup): don't renumber-fold zero-padded line prefixes (#2369) ## Description On an HTTP tool-output re-read, `cross_turn_dedup` folds a contiguous span that already appeared in an earlier block into a compact pointer, and when the line numbers shifted by a constant it carries the offset as a `delta` so the original bytes recover as `int(number) + delta`. The module states this renumber path is "strictly lossless" for UNPADDED numbers only. `_LINENO_RE = ^(\d+)(:|\t)(.*)$` does not enforce the "unpadded" restriction: `\d+` also matches a LEADING-ZERO prefix. A timestamped log row such as `08:00:01 ...` is read as line number `8`, not as data, so a re-read shifted by a constant (a later window of the same hourly log) folds under a uniform delta. Recovery then renders `str(int("08") + 1)` = `"9"`, not `"09"`: the round-trip is not byte-exact. This is a lossy (false-positive) fold in a module whose stated posture is to prefer false negatives (`CONTRIBUTING.md:129`, `cross_turn_dedup.py:45-50`). ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `headroom/transforms/cross_turn_dedup.py`: restrict `_LINENO_RE` to `[1-9]\d*` so a leading-zero run stays non-numbered and can fold only on an EXACT match (delta 0), never under a lossy renumber. Real `grep -n` / `sed -n` / `rg -n` numbers never carry a leading zero, so the intended renumber-fold feature is unchanged. Added a comment stating why the character class is load-bearing. - `tests/test_cross_turn_dedup.py`: added a delta-aware reconstruction helper and three regression tests (the existing `_reconstruct` asserts delta is absent, so it never exercised the numbered path this bug lives on). ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed Three named scenarios, one test each: 1. `test_zero_padded_prefix_not_folded_lossily`: a padded shifted re-read is left verbatim (`spans_folded == 0`). This fails on `main` (it folds under a delta). 2. `test_unpadded_renumber_still_folds_and_recovers_exactly`: an unpadded `grep -n` read renumbered by `+5` still folds and reconstructs byte-exact (feature guard). 3. `test_padded_content_exact_redisplay_still_folds`: the same padded rows re-displayed verbatim still fold with delta 0 (surgical-scope guard). ### Test Output ```text --- ruff check --- All checks passed! --- ruff format --check --- 2 files already formatted --- mypy --- Success: no issues found in 1 source file --- pytest: 3 new tests on the branch (fixed) --- 3 passed, 14 deselected --- pytest: revert regex to \d+ (simulate main): the regression test must FAIL --- 1 failed ``` ## Real Behavior Proof - Environment: clean `python:3.12-slim` Docker, `PYTHONPATH` at the source tree, core deps installed by name (tiktoken, pydantic, litellm, click, rich, opentelemetry-api, pyyaml, tomlkit), `ruff==0.15.17`, `mypy==1.20.2`. - Exact command / steps: import the module and print provenance, then run ruff, ruff format, mypy on the two changed files, then `pytest` the three new tests on the branch, then revert only the regex to `\d+` and re-run the regression test. - Observed result: module `cross_turn_dedup.py` (sha256 7ff204b65f40617d505895841aa1cfc1ee54bf63ffe6520198f0aa05a850aa8d), regex now `^([1-9]\d*)(:|\t)(.*)$`; ruff, ruff format, mypy all green; branch `3 passed`, reverted-regex main `1 failed`. Breakdown: - `module: /src/headroom/transforms/cross_turn_dedup.py` - `sha256: 7ff204b65f40617d505895841aa1cfc1ee54bf63ffe6520198f0aa05a850aa8d` - `regex : ^([1-9]\d*)(:|\t)(.*)$` - ruff, ruff format, mypy: all green (output above). - Branch: `3 passed`. Reverted-regex main: the regression test `1 failed`. - Not tested: the router-level and Rust-backed integration tests in this file (`test_apply_*`, `test_dedup_*`) need the compiled `headroom._core` extension, which is not built in this lightweight container; they are `ModuleNotFoundError` on both `main` and this branch here, so they were not exercised. The change is a pure-stdlib regex in a pure-stdlib function; the unit-level `dedup_blocks` tests above cover it directly. I also did not measure how often real-world tool output hits the leading-zero shifted shape; the argument is the module's own strictly-lossless contract, not observed field frequency. ## 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 (N/A: no doc surface) - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` ## Additional Notes Per `CONTRIBUTING.md` ("Bug or small fix -> Open a PR with repro + test"), this goes straight to a PR rather than an issue. One concern only; no dependency or generated-file changes.
2026-07-21 03:47:56 +03:00
# --------------------------------------------------------------------------
# Numbered (renumber-fold) path: a leading line-number lets the same content
# fold across a uniform shift, with the offset carried in the pointer so the
# original bytes recover as ``str(int(number) + delta)``. That recovery is
# byte-exact ONLY for UNPADDED numbers: a leading-zero prefix (a timestamped
# log row, ``08:00:01``) loses its pad on renumber (``int("08") + 1`` -> ``"9"``,
# not ``"09"``), so it must not fold under a delta. The helper below renumbers
# exactly as the module documents, so the round-trip assertion is faithful.
# --------------------------------------------------------------------------
def _reconstruct_numbered(orig_blocks, out_blocks):
"""Like ``_reconstruct`` but honours a non-zero delta: recover each folded
span from the referenced msg, renumbering leading line numbers by the stated
offset (``str(int(number) + delta) + key``), then assert byte-exact bytes."""
by_turn = {b.turn: b.text.split("\n") for b in orig_blocks}
def _content(line):
return _num_and_key(line)[2].strip()
for orig, out in zip(orig_blocks, out_blocks):
if orig.protected:
assert out.text == orig.text
continue
rebuilt = []
for line in out.text.split("\n"):
m = _FOLD_RE.search(line)
if m and line.lstrip().startswith("[↑"):
n, ref = int(m.group(1)), int(m.group(2))
delta = int(m.group(3)) if m.group(3) else 0
anchor = m.group(4)
assert ref < orig.turn, "reference must point to an EARLIER msg"
core = anchor[:-3] if anchor.endswith("...") else anchor
ref_lines = by_turn[ref]
idx = next(i for i, rl in enumerate(ref_lines) if _content(rl).startswith(core))
for rl in ref_lines[idx : idx + n]:
num, key, _c = _num_and_key(rl) # key keeps the separator
rebuilt.append(f"{num + delta}{key}" if (num is not None and delta) else rl)
else:
rebuilt.append(line)
assert "\n".join(rebuilt) == orig.text, f"turn {orig.turn} not faithfully reconstructable"
def _log(prefixes):
# Timestamped probe rows: identical content, distinct LEADING-ZERO hour.
return "\n".join(f"{p}:00:01 probe ok latency=12ms region=us-east-1" for p in prefixes)
def test_zero_padded_prefix_not_folded_lossily():
# A leading-zero numeric prefix shifted by a uniform +1 looks like a renumber
# (keys match, delta is uniform), but recovery via int(number)+delta drops the
# pad, so the fold would NOT round-trip. It must be left verbatim instead.
blocks = [
_blk("probe window A\n" + _log(["06", "07", "08"]) + "\ndone A", 1),
_blk("probe window B\n" + _log(["07", "08", "09"]) + "\ndone B", 5),
]
out, stats = dedup_blocks(blocks)
assert stats["spans_folded"] == 0
assert out[1].text == blocks[1].text and "[↑" not in out[1].text
_reconstruct_numbered(blocks, out) # trivially exact: nothing folded
def test_unpadded_renumber_still_folds_and_recovers_exactly():
# The intended feature: an UNPADDED grep -n / sed -n read re-displayed after an
# edit shifted every line number by a constant still folds, and the pointer's
# delta recovers the exact numbered bytes. The fix must not regress this.
span = [
" result_0 = compute_overdraft(business_id=0, amount=0)",
" result_1 = compute_overdraft(business_id=1, amount=100)",
" result_2 = compute_overdraft(business_id=2, amount=200)",
]
b1 = "read A\n" + "\n".join(f"{10 + i}:{s}" for i, s in enumerate(span)) + "\nend A"
b2 = "read B\n" + "\n".join(f"{15 + i}:{s}" for i, s in enumerate(span)) + "\nend B"
blocks = [_blk(b1, 1), _blk(b2, 3)]
out, stats = dedup_blocks(blocks)
assert stats["spans_folded"] == 1
assert "+5L" in out[1].text # uniform +5 shift carried in the pointer
_reconstruct_numbered(blocks, out)
def test_padded_content_exact_redisplay_still_folds():
# Surgical-scope guard: the fix only blocks the LOSSY renumbered fold. The same
# zero-padded rows re-displayed VERBATIM (delta 0) are still a byte-identical
# fold and must continue to compress.
log = _log(["06", "07", "08"])
blocks = [
_blk("probe window A\n" + log + "\ndone A", 1),
_blk("re-check\n" + log + "\ntail", 4),
]
out, stats = dedup_blocks(blocks)
assert stats["spans_folded"] == 1
m = _FOLD_RE.search(out[1].text)
assert m is not None and m.group(3) is None # folded, delta-free (byte-identical)
_reconstruct_numbered(blocks, out)
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
# --------------------------------------------------------------------------
# Integration: full router.apply() path (content-block tool_result format)
# --------------------------------------------------------------------------
def _mk_tok():
from headroom.providers import OpenAIProvider
from headroom.tokenizer import Tokenizer
return Tokenizer(OpenAIProvider().get_token_counter("gpt-4o"), "gpt-4o")
def _toolmsg(text, tid):
return {
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": tid, "content": text}],
}
def _apply_fresh(messages):
# Fresh router per call: tests the pure-function (prefix-monotonic) property,
# not cross-call cache state.
import copy
from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
r = ContentRouter(ContentRouterConfig(lossless=True, enable_cross_turn_dedup=True))
return r.apply(copy.deepcopy(messages), _mk_tok()).messages
def test_apply_dedups_reread_and_keeps_prefix_stable():
span = "\n".join(
f" result_{i} = compute_overdraft(business_id={i}, amount={i * 100})" for i in range(12)
)
m1 = [
{"role": "user", "content": "fix the overdraft bug"},
{"role": "assistant", "content": "cat merge.py"},
_toolmsg(f"$ cat merge.py\n{span}\n# end", "t1"),
]
m2 = m1 + [
{"role": "assistant", "content": "sed -n range"},
_toolmsg(f"$ sed -n 1,20p merge.py\n{span}\n# more", "t2"),
]
out1 = _apply_fresh(m1)
out2 = _apply_fresh(m2)
# Dedup fired on the later re-read (turn t2), earliest (t1) untouched.
later = out2[-1]["content"][0]["content"]
earlier = out2[2]["content"][0]["content"]
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
assert "[↑" in later
assert "[↑" not in earlier and span in earlier
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
# CACHE-SAFETY at the router level: appending turn t2 did NOT change any
# earlier message's emitted bytes → the prompt-cache prefix is stable.
def _tool_texts(msgs):
return [
b["content"]
for m in msgs
if isinstance(m.get("content"), list)
for b in m["content"]
if isinstance(b, dict) and b.get("type") == "tool_result"
]
assert _tool_texts(out2)[:1] == _tool_texts(out1) # t1 block byte-identical
def test_apply_no_dedup_when_flag_off():
span = "\n".join(f" v_{i} = f({i})" for i in range(12))
import copy
from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
msgs = [
_toolmsg(f"a\n{span}", "t1"),
_toolmsg(f"b\n{span}", "t2"),
]
r = ContentRouter(ContentRouterConfig(lossless=True, enable_cross_turn_dedup=False))
out = r.apply(copy.deepcopy(msgs), _mk_tok()).messages
joined = "".join(b["content"] for m in out for b in m["content"] if isinstance(b, dict))
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
assert "[↑" not in joined
feat(content-router): lossless-first dispatch, cross-turn dedup, and A7 lossy-after-fold (#1818) ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:32:06 -07:00
def test_apply_dedup_runs_in_ccr_mode_too():
# Dedup is no longer gated to lossless mode: with lossless=False (CCR) and
# the flag on, an exact re-read still folds to an in-context pointer.
span = "\n".join(f" total_{i} = reconcile(entry_id={i}, ledger=book_{i})" for i in range(12))
import copy
from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
msgs = [
_toolmsg(f"$ cat ledger.py\n{span}\n# eof", "t1"),
{"role": "assistant", "content": "re-check"},
_toolmsg(f"$ cat ledger.py\n{span}\n# eof", "t2"), # exact re-run
]
r = ContentRouter(ContentRouterConfig(lossless=False, enable_cross_turn_dedup=True))
out = r.apply(copy.deepcopy(msgs), _mk_tok()).messages
joined = "".join(
b["content"]
for m in out
if isinstance(m.get("content"), list)
for b in m["content"]
if isinstance(b, dict)
)
fix(dedup): shorter fold pointer + MIN_LINES=3, dedup Anthropic list-… (#1932) …content tool_results, line-number reanchoring cross_turn_dedup: - Compact the fold pointer (~35c vs ~100c) and lower MIN_LINES=3 / MIN_CHARS=40 so the abundant short (2-4 line) re-read repeats pay off (~4.3% -> ~6% lossless observation-byte reduction on Opus SWE-bench, measured on 73 real trajectories). - Add uniform-offset line-number reanchoring: a re-read whose line numbers all shifted by a constant after an edit now still folds. Matching keys on the number-stripped content; the offset is carried in the pointer so recovery of the original numbered bytes stays exact (unpadded grep/sed/rg -n form only). Cache-safe (prefix-monotonic) and information-preserving (earliest copy kept verbatim). Small real-data gain, but closes the renumbering blind spot. content_router: - Dedup Anthropic list-content tool_result blocks (the single {"type":"text"} sub-block), which the string-only extraction path previously skipped entirely, so cross-turn dedup never fired on Anthropic-native tool results. ## Description <!-- Briefly explain the change and why it is needed. --> 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 - [ ] Code refactoring (no functional changes) ## Changes Made - ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [ ] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # Paste relevant command output or artifact links here ``` ## Real Behavior Proof - Environment: - Exact command / steps: - Observed result: - Not tested: ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) Add screenshots to help explain your changes. ## Additional Notes <!-- Mention any N/A checklist items, tradeoffs, follow-ups, or maintainer context. --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 11:38:08 -04:00
assert "[↑" in joined # dedup fired despite lossless=False
# --------------------------------------------------------------------------
# No dangling reference: dedup folds only against content present in the array
# it processes (it runs last, over the final sent messages). If compaction
# already removed the original, there is nothing earlier to reference → verbatim.
# --------------------------------------------------------------------------
def test_no_fold_when_original_absent_fallback():
span = _code("", 8)
# Only the LATER read survives; its original was compacted out of the array.
blocks = [_blk("unrelated log\n" + _code("z", 8), 1), _blk(f"sed\n{span}\nmore", 5)]
out, stats = dedup_blocks(blocks)
assert stats["spans_folded"] == 0
assert out[1].text == blocks[1].text and "[↑" not in out[1].text
# --------------------------------------------------------------------------
# Shape-agnostic CODE-READ coverage: a file read gets deduped wherever it lands
# — role:tool, role:function, or a text-harness role:user string — keyed off the
# read OUTCOME, never ordinary user prose.
# --------------------------------------------------------------------------
def _dedup_only(messages):
"""Run ONLY the cross-turn dedup pass (no per-block compression) on a raw
message array, isolating extraction + fold across message shapes."""
from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
r = ContentRouter(ContentRouterConfig(lossless=True, enable_cross_turn_dedup=True))
return r._cross_turn_dedup_messages(messages, 0, [], None)
def _readspan():
return "\n".join(f" result_{i} = compute_overdraft(business_id={i})" for i in range(10))
def test_dedup_folds_user_string_read_observation():
# Text-harness shape: the read output arrives as a role:user STRING after an
# assistant fenced `cat`. The later identical read folds; earliest stays intact.
span = _readspan()
asst = {"role": "assistant", "content": "```bash\ncat report.py\n```"}
msgs = [
asst,
{"role": "user", "content": span}, # read #1 (reference target)
asst,
{"role": "user", "content": span}, # read #2 (duplicate) -> folds
]
out = _dedup_only(msgs)
assert "[↑" in out[3]["content"]
assert out[1]["content"] == span
def test_dedup_does_not_fold_plain_user_prose():
# A duplicated ORDINARY user message (no preceding read command) must stay
# verbatim — user intent is never folded.
prose = "\n".join(f"please also make sure case {i} is handled carefully" for i in range(10))
msgs = [
{"role": "user", "content": prose},
{"role": "assistant", "content": "understood"},
{"role": "user", "content": prose}, # duplicate prose -> must NOT fold
]
out = _dedup_only(msgs)
assert "[↑" not in out[2]["content"] and out[2]["content"] == prose
def test_dedup_folds_role_function_output():
# Legacy OpenAI role:function tool output — same operation, different label.
span = _readspan()
msgs = [
{"role": "function", "name": "read_file", "content": span},
{"role": "assistant", "content": "let me re-check"},
{"role": "function", "name": "read_file", "content": span}, # dup -> folds
]
out = _dedup_only(msgs)
assert "[↑" in out[2]["content"]
fix: skip cross-turn dedup pointers on OpenAI chat streaming (#3191) ## Description Cross-turn dedup (`HEADROOM_DEDUPE` / `enable_cross_turn_dedup`, plus the cold-prefix recompaction router) folds a repeated tool-output span into a one-line in-context pointer, `[↑NL same as msg M: 'anchor']`. That pointer is only recoverable where the model can resolve the reference. On the OpenAI chat-completions STREAMING path (what `headroom wrap copilot` serves) it cannot, for two independent reasons: 1. The proxy itself logs `CCR: skipping retrieval-tool injection for OpenAI chat streaming; this path cannot intercept tool calls`, so no `headroom_retrieve` tool exists on this path and nothing can mechanically resolve a fold. 2. The pointer names its source as `msg M`, Headroom's internal message index. OpenAI-compatible chat clients never show the model numbered messages, so the reference is unresolvable even though the original bytes are technically still earlier in the same request. Observed with Kimi k2.7-code / k3 via `wrap copilot`: the model treats the pointer as deleted output, reports "the renderer is deduplicating/compressing", and retry-loops near-identical reads (one session burned ~200 turns; a folded conflicted-files listing hid 4 of 5 conflicted files and the agent committed unresolved `<<<<<<<` markers). The router already keeps unrecoverable LOSSY output verbatim (`lossy_unrecoverable_skipped`). Dedup folds are lossless in theory but unrecoverable in practice on this path; this PR gives them the same recoverability gate. Closes #3190 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `headroom/transforms/content_router.py`: `ContentRouter.apply()` accepts a per-request `cross_turn_dedup_recoverable` kwarg (default `True`, so every existing caller is byte-identical). When `False`, the cross-turn dedup pass is skipped and repeated spans stay verbatim, mirroring the recoverability posture of the lossy `lossy_unrecoverable_skipped` guard. Config comment on `enable_cross_turn_dedup` documents the gate. - `headroom/proxy/handlers/openai.py`: `handle_openai_chat` computes the gate from the same predicate that already gates CCR retrieval-tool injection, `_should_inject_openai_chat_ccr_tool(ccr_inject_tool, stream)`, and threads it into both `openai_pipeline.apply(...)` call sites (token-mode and non-token-mode branches). Streaming chat requests skip the fold; buffered (non-streaming) chat, which can inject and redeem the retrieval tool, keeps folding. - `headroom/transforms/cold_prefix.py`: `cold_recompact_messages` no longer hardcodes pointer emission; new keyword-only `cross_turn_dedup_recoverable: bool = True` is forwarded to the router gate. The only caller (Anthropic cache-mode cold turn) keeps the default and is unchanged. - `tests/test_cross_turn_dedup.py`: router-gate regression tests (unrecoverable path keeps verbatim bytes for both the OpenAI `role:tool` string shape and the Anthropic `tool_result` block shape; default/explicit-`True` still folds). - `tests/test_cold_prefix.py` (new): recompaction folds by default (Anthropic path unchanged) and keeps verbatim bytes with `cross_turn_dedup_recoverable=False`. - `tests/test_openai_chat_dedup_recoverability.py` (new): end-to-end through the real `/v1/chat/completions` handler with `HEADROOM_DEDUPE=1`, capturing the exact upstream request body: `stream=True` keeps both copies byte-verbatim with no `[↑` pointer; `stream=False` still folds; `stream=False` under `--lossless` (which forces `ccr_inject_tool=False`) also keeps verbatim bytes, locking the intended coupling of "no retrieval tool" to "no bare pointer". ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text # BEFORE (branch base, fix reverted): the streaming regression test fails, # the upstream body carries the unresolvable pointer and drops the bytes. $ git stash push headroom/ && uv run pytest -q \ tests/test_openai_chat_dedup_recoverability.py::test_streaming_chat_keeps_verbatim_bytes_no_dedup_pointer E assert '[↑' not in "fix the ove...t merge.py']" E '[↑' is contained here: E [↑14L same as msg 2: '$ cat merge.py'] FAILED tests/test_openai_chat_dedup_recoverability.py::test_streaming_chat_keeps_verbatim_bytes_no_dedup_pointer (same run: test_cold_recompact_unrecoverable_path_keeps_verbatim_bytes also fails pre-fix; both recoverable-path legs pass before and after) # AFTER (full diff applied): $ uv run pytest tests/test_cross_turn_dedup.py tests/test_cold_prefix.py \ tests/test_openai_chat_dedup_recoverability.py \ tests/test_proxy/test_openai_chat_ccr_injection.py tests/test_no_ccr_lossy.py \ tests/test_openai_chat_turn_hooks.py tests/test_openai_chat_tool_desc_compaction.py \ tests/test_responses_cross_turn_dedup.py -q 45 passed, 2 warnings in 8.75s $ uv run pytest tests/test_proxy/ tests/test_openai_codex_routing.py \ tests/test_openai_chat_turn_hooks.py tests/test_openai_chat_tool_desc_compaction.py \ tests/test_openai_beta_session_sticky.py tests/test_openai_max_completion_tokens.py \ tests/test_no_ccr_lossy.py tests/test_netcost_gate.py tests/test_agent_savings.py \ tests/test_cross_turn_dedup.py tests/test_cold_prefix.py \ tests/test_openai_chat_dedup_recoverability.py -q 424 passed, 2 warnings in 73.52s $ uv run ruff format --check <touched files> && uv run ruff check <touched files> All checks passed! $ uv run mypy headroom/transforms/cold_prefix.py headroom/transforms/content_router.py headroom/proxy/handlers/openai.py Success: no issues found in 3 source files $ cargo fmt --all -- --check # FMT_OK $ cargo clippy --all-targets # 2 pre-existing warnings in untouched lib-test code, no errors $ cargo test # all targets green; see Additional Notes for the one environmental exception ``` ## Real Behavior Proof - Environment: macOS (Darwin), Python 3.13, repo tip `upstream/main` 5e0ce242 (v0.36.2). No secrets, no external network: the proof drives the real proxy handler in-process via FastAPI `TestClient` with the upstream send stubbed, capturing the exact request body the provider would receive. - Exact command / steps (copy-pasteable, self-contained): next lines ```sh # 1. The bug, on the branch base (pointer emitted on the streaming path): git stash push headroom/ # or check out upstream/main uv run pytest -q tests/test_openai_chat_dedup_recoverability.py # streaming leg FAILS git stash pop # 2. The fix: uv run pytest -q tests/test_openai_chat_dedup_recoverability.py # both legs pass ``` The test posts a chat-completions request whose history contains two identical multi-line tool outputs (the shape that folds), with `HEADROOM_DEDUPE=1`, and asserts on the captured upstream body: - `stream=True` (the `wrap copilot` shape): both copies forwarded byte-verbatim, no `[↑NL same as msg M]` pointer anywhere. - `stream=False` (buffered, retrieval tool injectable): the repeated span still folds to a pointer; the earliest copy stays verbatim as the in-context original. - Observed result: BEFORE, the streaming leg fails with the pointer present in the upstream body (same `transforms=router:cross_turn_dedup:N` evidence seen in proxy.log when the bug bit). AFTER, streaming keeps verbatim bytes and buffered keeps folding; the full touched-module suite (423 tests) is green. - Not tested: a live `wrap copilot` session against the real Copilot API (needs a subscription token; the in-process test captures the identical upstream body the handler produces). The Responses API path (`_dedup_responses_output_items`, Codex) is intentionally untouched: Responses streaming has a separate buffered-CCR path that can intercept tool calls. `/v1/compress` derived pipelines keep the default (recoverable) behavior. Separately worth verifying in a follow-up: whether `headroom_retrieve` resolves `msg M` dedup pointers on the paths that keep folding, or only CCR `hash=` content markers (the Anthropic-path fold is retained per the issue's scope, where it has not been observed to cause retry loops). ## Runtime Rollout Safety - Rollout-managed feature(s): none - Minimum rollout channel: N/A - Stable/default behavior changed: only the OpenAI chat-completions request path, and only when cross-turn dedup is active (opt-in `HEADROOM_DEDUPE=1`, or cold-prefix recompaction): streaming chat now keeps repeated tool-output bytes verbatim instead of emitting `[↑NL same as msg M]` pointers, and (because `--lossless` forces `ccr_inject_tool=False`) buffered chat in lossless mode does the same. Buffered chat with CCR on, Anthropic, Responses, and `/v1/compress` are byte-identical to before (default `cross_turn_dedup_recoverable=True`; the Responses fold is covered by the untouched, still-green `tests/test_responses_cross_turn_dedup.py`). - Kill switch / disable path: dedup remains opt-in via `HEADROOM_DEDUPE`; the gate itself can be overridden per request by passing `cross_turn_dedup_recoverable=True`. - Unsafe override required: no - Qualification impact: none - Rollback path: revert the single commit; no state, schema, or config migration involved. ## 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 - [x] I have made corresponding changes to the documentation (docstrings + config comments) - [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 - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Screenshots (if applicable) N/A ## Additional Notes - Mirrors the existing recoverability precedent: the lossy path already refuses to emit unrecoverable output (`lossy_unrecoverable_skipped`, issue #1307); this extends the same posture to cross-turn dedup folds. - The gate reuses `_should_inject_openai_chat_ccr_tool`, the predicate that already decides whether the chat path can redeem an injected retrieval tool, so the two can never drift apart. - Prefer-false-negatives posture: a skipped fold only ever means bytes stay verbatim; no content is dropped, reordered, or lossy-transformed by this change. - Secondary operational bug noticed while diagnosing (NOT fixed here, separate issue candidate): all concurrent proxy processes write the same `~/.headroom/logs/proxy.log` with independent rotating handlers, so rotation stomps history across `wrap` instances on different ports. - Local environment note: `cargo test` on this machine hangs inside `crates/headroom-core/tests/kompress_parity.rs` (both tests stall in `ort` ONNX-runtime environment init, reproducible on the untouched branch base; this PR changes no Rust). With those two tests skipped, the full Rust suite is green (all targets `ok`, 0 failed). `cargo clippy --all-targets` and `cargo fmt --all -- --check` pass as-is.
2026-08-22 00:51:05 +02:00
# --------------------------------------------------------------------------
# Recoverability gate (unresolvable-pointer paths). The fold rewrites a
# repeated span to a bare `[↑NL same as msg M]` pointer naming Headroom's
# internal message index. On the OpenAI chat-completions streaming path
# (wrap copilot) no CCR retrieval tool can be injected and the client never
# shows the model numbered messages, so the pointer is unresolvable: the
# model reads it as deleted content and retry-loops. `apply()` therefore
# accepts `cross_turn_dedup_recoverable=False` — the same recoverability
# posture as the lossy `lossy_unrecoverable_skipped` guard — and keeps the
# repeated bytes verbatim. Default True preserves every other path.
# --------------------------------------------------------------------------
def _apply_with_recoverable(messages, recoverable):
import copy
from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
r = ContentRouter(ContentRouterConfig(lossless=True, enable_cross_turn_dedup=True))
return r.apply(
copy.deepcopy(messages), _mk_tok(), cross_turn_dedup_recoverable=recoverable
).messages
def test_apply_unrecoverable_path_keeps_verbatim_bytes():
# The OpenAI chat streaming shape (role:tool strings): with dedup ENABLED
# but the path flagged unrecoverable, the re-read must NOT fold — the
# request keeps the verbatim bytes, no bare pointer.
span = _readspan()
msgs = [
{"role": "tool", "tool_call_id": "c1", "content": f"$ cat f.py\n{span}"},
{"role": "assistant", "content": "again"},
{"role": "tool", "tool_call_id": "c2", "content": f"$ cat f.py\n{span}"},
]
out = _apply_with_recoverable(msgs, recoverable=False)
assert out[2]["content"] == f"$ cat f.py\n{span}" # verbatim, no pointer
assert "[↑" not in out[2]["content"]
def test_apply_unrecoverable_gate_also_covers_tool_result_blocks():
# Anthropic tool_result block shape, same gate: nothing folds when the
# caller reports the pointer is unresolvable on this path.
span = _readspan()
msgs = [_toolmsg(f"a\n{span}", "t1"), _toolmsg(f"b\n{span}", "t2")]
out = _apply_with_recoverable(msgs, recoverable=False)
joined = "".join(b["content"] for m in out for b in m["content"] if isinstance(b, dict))
assert "[↑" not in joined
assert out[-1]["content"][0]["content"] == f"b\n{span}" # verbatim bytes kept
def test_apply_recoverable_default_and_true_still_fold():
# The recoverable paths (Anthropic, buffered/non-streaming chat — anywhere
# the reference resolves) keep folding: default kwarg-absent behavior is
# unchanged, and an explicit True folds too.
span = _readspan()
msgs = [
{"role": "tool", "tool_call_id": "c1", "content": f"$ cat f.py\n{span}"},
{"role": "assistant", "content": "again"},
{"role": "tool", "tool_call_id": "c2", "content": f"$ cat f.py\n{span}"},
]
import copy
from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
default_out = (
ContentRouter(ContentRouterConfig(lossless=True, enable_cross_turn_dedup=True))
.apply(copy.deepcopy(msgs), _mk_tok())
.messages
)
assert "[↑" in default_out[2]["content"] # no kwarg -> still folds
true_out = _apply_with_recoverable(msgs, recoverable=True)
assert "[↑" in true_out[2]["content"] # explicit recoverable -> folds