mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(cache): carry CCR entries and seed every token path across a restart
Review of the prefix-state snapshot found four gaps: - The snapshot kept the forwarded messages and read-maturation markers but not the CompressionStore entries behind them. With the in-process CCR backend a restart emptied the store, so a marker the restored tracker replayed (hash=cc146b21... in the read-maturation scenario) no longer resolved. save_state now writes, per tracker, every live CCR entry its messages reference (hash= markers and <<ccr:...>>), counted in the 64 MB cap, and load_state re-stores them with their original expiry before any tracker goes live. An entry a persistent backend still holds is left alone. - Only the Anthropic token path seeded its CompressionCache from a restored tracker. The OpenAI chat token path and the session-aware /v1/compress path froze nothing on their first request, recompressed the history, and beyond the provider-confirmed floor the overlay declined the larger previous form, so the prefix changed. One shared seed_restored_compression_cache now runs on all three. - save_state unlinked the old snapshot before writing, so a failed write (ENOSPC) lost it. It now tightens the existing file to 0600 in place and lets the atomic replace keep the old file on failure. - A stateless start still loaded the snapshot, and loading deletes it. load_state now uses the same persistence_allowed gate as save_state. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -401,7 +401,7 @@ headroom proxy --learn --min-evidence 3
|
||||
| `HEADROOM_THINKING_COMPACT` | Compact plain-text reasoning that models re-send every turn (Kimi/GLM/DeepSeek `reasoning_content` / inline `<think>`): Kompress it on warm turns, drop it on cold turns. No-op for Claude/Codex/OpenAI (encrypted reasoning). See [Cold-prefix hook](#cold-prefix-hook--reasoning-compaction). | `off` |
|
||||
| `HEADROOM_THINKING_COMPACT_KEEP_LAST` | Most-recent assistant turns whose reasoning is left intact (the active reasoning the model still uses). Only applies with `HEADROOM_THINKING_COMPACT`. | `1` |
|
||||
| `HEADROOM_COLD_RECOMPACT` | On a confirmed-cold turn (idle past the real cache TTL), recompact the whole prefix — cross-turn dedupe + superseded-read drop + lossless folds — instead of forwarding a byte-identical prefix to a dead cache. Warm turns unchanged. Pair with `HEADROOM_DEDUPE`. See [Cold-prefix hook](#cold-prefix-hook--reasoning-compaction). | `off` |
|
||||
| `HEADROOM_PREFIX_STATE_FILE` | Path where the proxy saves its prefix-cache trackers on a graceful shutdown and restores them on the next start (then deletes the file), so warm conversations replay the exact prefix the provider cached instead of re-writing it. The file holds conversation content: it is written `0600`, capped at the 256 newest conversations and 64 MB, and only trackers still inside their cache lifetime are restored. Not supported with multiple workers; ignored in stateless mode. | -- |
|
||||
| `HEADROOM_PREFIX_STATE_FILE` | Path where the proxy saves its prefix-cache trackers on a graceful shutdown and restores them on the next start (then deletes the file), so warm conversations replay the exact prefix the provider cached instead of re-writing it. The file holds conversation content: it is written `0600`, capped at the 256 newest conversations and 64 MB, and only trackers still inside their cache lifetime are restored, with the retrieval (CCR) entries their markers point at, so those markers resolve even with `HEADROOM_CCR_BACKEND=memory`. Not supported with multiple workers; ignored in stateless mode (neither read nor written). | -- |
|
||||
| `HEADROOM_DEDUPE` | Whole-conversation verbatim cross-turn dedup in the router (cache-safe, information-preserving via retrieval markers). Superseded-read drop + lossless folds run without it; this adds verbatim dedup. | `off` |
|
||||
| `HEADROOM_CACHE_TTL_LEARN` | Append per-turn cache-outcome observations (provider, model, idle, hit/miss) to `cache_ttl_observations.jsonl` for the offline `headroom-cache-ttl` learner. Observation-only (no request-behavior change); respects `HEADROOM_STATELESS`; the log is size-bounded. | `off` |
|
||||
| `HEADROOM_KOMPRESS_ENDPOINT` / `HEADROOM_KOMPRESS_ENDPOINT_TOKEN` | Offload ML compression (Kompress) to a remote endpoint instead of the local ONNX model — used by reasoning compaction and the router when set. | -- |
|
||||
|
||||
Vendored
+43
-1
@@ -40,7 +40,7 @@ import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass, field, replace
|
||||
from dataclasses import asdict, dataclass, field, replace
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from ..log_safety import describe_exception, safe_id
|
||||
@@ -737,6 +737,48 @@ class CompressionStore:
|
||||
|
||||
return list(reversed(events_copy[-limit:]))
|
||||
|
||||
def export_entries(self, hashes: list[str]) -> list[dict[str, Any]]:
|
||||
"""The live entries for ``hashes`` as JSON-safe dicts, without counting
|
||||
a retrieval. ``SessionTrackerStore.save_state`` carries them across a
|
||||
restart so the markers it replays still resolve (:meth:`import_entries`)."""
|
||||
with self._lock:
|
||||
found = [self._backend.get(hash_key) for hash_key in hashes]
|
||||
return [asdict(e) for e in found if e is not None and not e.is_expired()]
|
||||
|
||||
def import_entries(self, entries: list[CompressionEntry]) -> int:
|
||||
"""Re-store :meth:`export_entries` output, each with its original expiry.
|
||||
|
||||
An entry the backend still holds (a persistent backend kept it) is left
|
||||
as it is. Raises on a malformed entry. Returns the entries stored.
|
||||
"""
|
||||
now = time.time()
|
||||
stored = 0
|
||||
for e in entries:
|
||||
if not all(
|
||||
isinstance(v, str) for v in (e.hash, e.original_content, e.compressed_content)
|
||||
):
|
||||
raise ValueError(f"malformed CCR entry {e.hash!r}")
|
||||
ttl = int(e.created_at + e.ttl - now)
|
||||
if ttl <= 0 or self.exists(e.hash):
|
||||
continue
|
||||
self.store(
|
||||
e.original_content,
|
||||
e.compressed_content,
|
||||
original_tokens=e.original_tokens,
|
||||
compressed_tokens=e.compressed_tokens,
|
||||
original_item_count=e.original_item_count,
|
||||
compressed_item_count=e.compressed_item_count,
|
||||
tool_name=e.tool_name,
|
||||
tool_call_id=e.tool_call_id,
|
||||
query_context=e.query_context,
|
||||
tool_signature_hash=e.tool_signature_hash,
|
||||
compression_strategy=e.compression_strategy,
|
||||
ttl=ttl,
|
||||
explicit_hash=e.hash,
|
||||
)
|
||||
stored += 1
|
||||
return stored
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear all entries. Mainly for testing."""
|
||||
with self._lock:
|
||||
|
||||
Vendored
+56
-8
@@ -16,12 +16,14 @@ pipeline skips them entirely.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import copy
|
||||
import hashlib
|
||||
import itertools
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from collections import OrderedDict, deque
|
||||
from contextvars import ContextVar
|
||||
@@ -79,6 +81,9 @@ _PREFIX_STATE_VERSION = 1
|
||||
# Newest trackers first; whatever does not fit starts cold, as all did before.
|
||||
_PREFIX_STATE_MAX_TRACKERS = 256
|
||||
_PREFIX_STATE_MAX_BYTES = 64 * 1024 * 1024
|
||||
# Any CCR reference in saved messages: ``hash=<hex>`` markers (Retrieve
|
||||
# more/original, compressed-item counts) and SmartCrusher's ``<<ccr:<hex>``.
|
||||
_CCR_HASH_RE = re.compile(r"(?:hash=|<<ccr:)([0-9a-f]{12,24})")
|
||||
|
||||
|
||||
def prefix_state_file() -> str | None:
|
||||
@@ -1649,6 +1654,23 @@ def _decode_turn_state(table: list[Any], state: list[Any]) -> tuple[Any, ...]:
|
||||
)
|
||||
|
||||
|
||||
def seed_restored_compression_cache(tracker: Any, comp_cache: Any) -> None:
|
||||
"""Seed a token-mode CompressionCache on a tracker's first request after
|
||||
:meth:`SessionTrackerStore.load_state`.
|
||||
|
||||
The new process has no cache entries behind the restored prefix, so the
|
||||
freeze computed from that cache freezes nothing: the pipeline recompresses
|
||||
(and read maturation rewrites) messages the provider cached, and beyond the
|
||||
provider-confirmed floor the overlay declines a larger replay. Seeding with
|
||||
what was forwarded gives the freeze the pre-restart count.
|
||||
"""
|
||||
if getattr(tracker, "restored_from_disk", False):
|
||||
tracker.restored_from_disk = False
|
||||
comp_cache.update_from_result(
|
||||
tracker.get_last_original_messages(), tracker.get_last_forwarded_messages()
|
||||
)
|
||||
|
||||
|
||||
class SessionTrackerStore:
|
||||
"""Manages PrefixCacheTracker instances across sessions.
|
||||
|
||||
@@ -2057,9 +2079,12 @@ class SessionTrackerStore:
|
||||
from the prefix the provider cached, and the cache is re-written from
|
||||
the first changed message. Newest trackers first, capped at
|
||||
``_PREFIX_STATE_MAX_TRACKERS`` and ``_PREFIX_STATE_MAX_BYTES``; a
|
||||
tracker whose messages are not JSON is skipped. Never raises; returns
|
||||
the number of trackers written.
|
||||
tracker whose messages are not JSON is skipped. Each tracker carries
|
||||
the CCR entries its messages reference, so its replayed markers still
|
||||
resolve when the CCR backend does not survive the restart (memory).
|
||||
Never raises; returns the number of trackers written.
|
||||
"""
|
||||
from headroom.cache.compression_store import get_compression_store
|
||||
from headroom.fsutil import write_text
|
||||
from headroom.paths import persistence_allowed
|
||||
|
||||
@@ -2072,23 +2097,33 @@ class SessionTrackerStore:
|
||||
reverse=True,
|
||||
)
|
||||
entries: list[str] = []
|
||||
ccr: dict[str, str] = {}
|
||||
size = 0
|
||||
for key, tracker in live[:_PREFIX_STATE_MAX_TRACKERS]:
|
||||
try:
|
||||
entry = self._encode_tracker(key, tracker, sessions.get(key))
|
||||
except (TypeError, ValueError):
|
||||
refs = [h for h in dict.fromkeys(_CCR_HASH_RE.findall(entry)) if h not in ccr]
|
||||
records = get_compression_store().export_entries(refs) if refs else []
|
||||
payloads = {r["hash"]: json.dumps(r) for r in records}
|
||||
except Exception: # an unsaveable tracker starts cold, as all did before
|
||||
continue
|
||||
if size + len(entry) > _PREFIX_STATE_MAX_BYTES:
|
||||
grow = len(entry) + sum(len(p) + 1 for p in payloads.values())
|
||||
if size + grow > _PREFIX_STATE_MAX_BYTES:
|
||||
continue
|
||||
size += len(entry) + 1
|
||||
size += grow + 1
|
||||
entries.append(entry)
|
||||
ccr.update(payloads)
|
||||
try:
|
||||
target = Path(path)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
# write_text keeps an existing file's mode; a fresh one is 0600.
|
||||
target.unlink(missing_ok=True)
|
||||
# write_text keeps the target's mode, so tighten it in place rather
|
||||
# than unlinking: a failed write must leave the last snapshot.
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
target.chmod(0o600)
|
||||
write_text(
|
||||
target, f'{{"version":{_PREFIX_STATE_VERSION},"trackers":[{",".join(entries)}]}}'
|
||||
target,
|
||||
f'{{"version":{_PREFIX_STATE_VERSION},"trackers":[{",".join(entries)}],'
|
||||
f'"ccr":[{",".join(ccr.values())}]}}',
|
||||
)
|
||||
except OSError as exc:
|
||||
logger.warning("SessionTrackerStore: prefix state not saved to %s: %s", path, exc)
|
||||
@@ -2147,6 +2182,11 @@ class SessionTrackerStore:
|
||||
lost. A missing file is normal; an unreadable or invalid one is logged
|
||||
and leaves the store empty. Never raises; returns trackers restored.
|
||||
"""
|
||||
from headroom.paths import persistence_allowed
|
||||
|
||||
# Loading deletes the file, so stateless mode leaves it for a later run.
|
||||
if not persistence_allowed("prefix-cache tracker state"):
|
||||
return 0
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
@@ -2175,8 +2215,11 @@ class SessionTrackerStore:
|
||||
|
||||
def _decode_state(self, data: Any) -> int:
|
||||
"""Validate the whole file first, then install it; a bad file installs nothing."""
|
||||
from headroom.cache.compression_store import CompressionEntry, get_compression_store
|
||||
|
||||
if data.get("version") != _PREFIX_STATE_VERSION:
|
||||
raise ValueError(f"unsupported version {data.get('version')!r}")
|
||||
ccr = [CompressionEntry(**record) for record in data["ccr"]]
|
||||
trackers: dict[str, PrefixCacheTracker] = {}
|
||||
families: dict[str, OrderedDict[str, list[Any]]] = {}
|
||||
affinities: dict[str, str | None] = {}
|
||||
@@ -2220,6 +2263,11 @@ class SessionTrackerStore:
|
||||
affinity = meta["affinity"]
|
||||
affinities[key] = None if affinity is None else str(affinity)
|
||||
|
||||
if ccr and trackers:
|
||||
# First, so a marker a restored tracker replays resolves from its
|
||||
# first request; a failure here still installs no tracker.
|
||||
get_compression_store().import_entries(ccr)
|
||||
|
||||
# New turns and lineages must not reuse a restored id.
|
||||
turns = [t for h in histories.values() for _, t in h]
|
||||
turns += [t for tracker in trackers.values() for t in tracker._turn_states]
|
||||
|
||||
@@ -2029,15 +2029,15 @@ class AnthropicHandlerMixin:
|
||||
compression_policy = resolve_policy(getattr(request.state, "auth_mode", None))
|
||||
if is_token_mode(self.config.mode):
|
||||
comp_cache = self._get_compression_cache(session_id)
|
||||
if getattr(prefix_tracker, "restored_from_disk", False):
|
||||
# Resumed after a restart (HEADROOM_PREFIX_STATE_FILE):
|
||||
# seed the empty cache with what was forwarded, or the
|
||||
# clamp below freezes nothing and read maturation
|
||||
# rewrites Reads inside the cached prefix.
|
||||
prefix_tracker.restored_from_disk = False
|
||||
comp_cache.update_from_result(
|
||||
previous_original_messages, previous_forwarded_messages
|
||||
)
|
||||
from headroom.cache.prefix_tracker import (
|
||||
seed_restored_compression_cache,
|
||||
)
|
||||
|
||||
# Seeds the empty cache after a restart
|
||||
# (HEADROOM_PREFIX_STATE_FILE); without it the clamp below
|
||||
# freezes nothing and read maturation rewrites Reads
|
||||
# inside the cached prefix.
|
||||
seed_restored_compression_cache(prefix_tracker, comp_cache)
|
||||
|
||||
# Freeze + stable marking + Zone-1 swap now live in the
|
||||
# shared session engine (PROXY policy: clamp by BOTH the
|
||||
|
||||
@@ -3821,6 +3821,12 @@ class OpenAIHandlerMixin:
|
||||
|
||||
if is_token_mode(self.config.mode):
|
||||
comp_cache = self._get_compression_cache(openai_session_id)
|
||||
from headroom.cache.prefix_tracker import seed_restored_compression_cache
|
||||
|
||||
# Seeds the empty cache after a restart
|
||||
# (HEADROOM_PREFIX_STATE_FILE); without it the freeze below
|
||||
# freezes nothing.
|
||||
seed_restored_compression_cache(openai_prefix_tracker, comp_cache)
|
||||
|
||||
if not is_cache_mode(self.config.mode):
|
||||
# Token mode: shared engine, REPLAYABLE policy — its
|
||||
@@ -10695,6 +10701,9 @@ class OpenAIHandlerMixin:
|
||||
session_tracker = self.session_tracker_store.get_or_create(
|
||||
_session_key, _tracker_provider
|
||||
)
|
||||
from headroom.cache.prefix_tracker import seed_restored_compression_cache
|
||||
|
||||
seed_restored_compression_cache(session_tracker, comp_cache)
|
||||
|
||||
# A claimed turn prepares its executor-side work here (tokenizer,
|
||||
# hooks, scope binding) — CPU-bound parts run inside the closures
|
||||
|
||||
@@ -16,19 +16,27 @@ replays the exact prefix the provider cached.
|
||||
from __future__ import annotations
|
||||
|
||||
import contextvars
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("fastapi")
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from headroom.cache import prefix_tracker
|
||||
from headroom.cache.compression_store import reset_compression_store
|
||||
from headroom.cache.compression_store import get_compression_store, reset_compression_store
|
||||
from headroom.cache.prefix_tracker import PREFIX_STATE_FILE_ENV, SessionTrackerStore
|
||||
from headroom.ccr.tool_injection import CCRToolInjector
|
||||
from headroom.config import TransformResult
|
||||
from headroom.proxy.server import ProxyConfig, create_app
|
||||
from headroom.transforms.pipeline import TransformPipeline
|
||||
from tests.test_anthropic_fork_lineage_cache import (
|
||||
_drive,
|
||||
@@ -45,6 +53,11 @@ def _wire(messages: list[dict[str, Any]]) -> str:
|
||||
return json.dumps(_strip(messages))
|
||||
|
||||
|
||||
def _ccr_hashes(messages: list[dict[str, Any]]) -> set[str]:
|
||||
"""Retrieval references the model sees, found the way the proxy finds them."""
|
||||
return set(CCRToolInjector().scan_for_markers(messages))
|
||||
|
||||
|
||||
def _with_fake_kompress(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""A deterministic stand-in for the Kompress ML stage (off in this suite).
|
||||
|
||||
@@ -125,10 +138,11 @@ _SCENARIOS = {
|
||||
|
||||
def _restart_between_turns(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, scenario: str
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], int]:
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], int, dict[str, str]]:
|
||||
"""Some turns in one proxy, the next turn in a fresh one, one warm
|
||||
provider cache. Returns (last forwarded before, first forwarded after,
|
||||
its read hit)."""
|
||||
its read hit, the original behind each retrieval reference forwarded
|
||||
before the restart)."""
|
||||
build, turns, config, kompress = _SCENARIOS[scenario]
|
||||
monkeypatch.setenv("HEADROOM_CCR_BACKEND", "memory")
|
||||
# As the desktop app runs it: a cold start forwards the fast pass.
|
||||
@@ -140,9 +154,11 @@ def _restart_between_turns(
|
||||
cache = _PromptCache()
|
||||
reset_compression_store()
|
||||
before = _drive([build(n) for n in range(1, turns + 1)], cache, **config)
|
||||
store = get_compression_store()
|
||||
originals = {h: store.retrieve(h).original_content for h in _ccr_hashes(before[-1][0])} # type: ignore[union-attr]
|
||||
reset_compression_store() # nothing in process memory survives a restart
|
||||
(after,) = _drive([build(turns + 1)], cache, **config)
|
||||
return before[-1][0], after[0], after[1]
|
||||
return before[-1][0], after[0], after[1], originals
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scenario", list(_SCENARIOS))
|
||||
@@ -152,12 +168,34 @@ def test_first_request_after_a_restart_replays_the_cached_prefix(
|
||||
state = tmp_path / "prefix-state.json"
|
||||
monkeypatch.setenv(PREFIX_STATE_FILE_ENV, str(state))
|
||||
|
||||
previous, current, hit = _restart_between_turns(monkeypatch, tmp_path, scenario)
|
||||
previous, current, hit, _ = _restart_between_turns(monkeypatch, tmp_path, scenario)
|
||||
|
||||
assert _wire(current[: len(previous)]) == _wire(previous)
|
||||
assert hit >= len(previous) - 1, f"read only {hit + 1}/{len(previous)} cached messages"
|
||||
|
||||
|
||||
def test_restored_retrieval_references_resolve_to_their_originals(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""Review of #4299: matching bytes are not enough. With the in-process CCR
|
||||
backend a restart emptied the store, so a matured Read the restored
|
||||
tracker kept replaying pointed at a hash that no longer resolved."""
|
||||
monkeypatch.setenv(PREFIX_STATE_FILE_ENV, str(tmp_path / "prefix-state.json"))
|
||||
|
||||
previous, current, _, originals = _restart_between_turns(
|
||||
monkeypatch, tmp_path, "read-maturation"
|
||||
)
|
||||
|
||||
emitted = _ccr_hashes(current)
|
||||
assert emitted & originals.keys(), "no pre-restart reference was replayed"
|
||||
store = get_compression_store()
|
||||
for h in emitted:
|
||||
entry = store.retrieve(h)
|
||||
assert entry is not None, f"hash={h} does not resolve after the restart"
|
||||
if h in originals:
|
||||
assert entry.original_content == originals[h]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scenario", list(_SCENARIOS))
|
||||
def test_without_the_state_file_a_restart_rewrites_the_prefix(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, scenario: str
|
||||
@@ -166,7 +204,7 @@ def test_without_the_state_file_a_restart_rewrites_the_prefix(
|
||||
the test above is not vacuous."""
|
||||
monkeypatch.delenv(PREFIX_STATE_FILE_ENV, raising=False)
|
||||
|
||||
previous, current, hit = _restart_between_turns(monkeypatch, tmp_path, scenario)
|
||||
previous, current, hit, _ = _restart_between_turns(monkeypatch, tmp_path, scenario)
|
||||
|
||||
assert _wire(current[: len(previous)]) != _wire(previous)
|
||||
assert hit < len(previous) - 1
|
||||
@@ -286,6 +324,184 @@ def test_stateless_mode_writes_nothing(monkeypatch: pytest.MonkeyPatch, tmp_path
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def test_a_stateless_proxy_leaves_a_saved_snapshot_alone(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""Loading deletes the file, so a stateless start must not load it: the
|
||||
next normal start resumes those conversations."""
|
||||
path = tmp_path / "state.json"
|
||||
assert _two_conversations().save_state(str(path)) == 2
|
||||
saved = path.read_text()
|
||||
monkeypatch.setenv(PREFIX_STATE_FILE_ENV, str(path))
|
||||
monkeypatch.setenv("HEADROOM_STATELESS", "1")
|
||||
|
||||
_drive([]) # one stateless proxy start and graceful shutdown
|
||||
|
||||
assert path.read_text() == saved
|
||||
monkeypatch.delenv("HEADROOM_STATELESS")
|
||||
assert SessionTrackerStore().load_state(str(path)) == 2
|
||||
|
||||
|
||||
def test_a_failed_save_keeps_the_previous_snapshot(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
path = tmp_path / "state.json"
|
||||
assert _two_conversations().save_state(str(path)) == 2
|
||||
saved = path.read_text()
|
||||
|
||||
def disk_full(*args: Any, **kwargs: Any) -> None:
|
||||
raise OSError(errno.ENOSPC, "No space left on device")
|
||||
|
||||
monkeypatch.setattr("headroom.fsutil.write_text", disk_full)
|
||||
assert _two_conversations().save_state(str(path)) == 0
|
||||
|
||||
assert path.read_text() == saved
|
||||
|
||||
|
||||
def test_saved_ccr_entries_resolve_after_a_restart(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""Store level, compressor markers in the replayed prefix: both hash
|
||||
formats resolve to the same original with the same expiry after the
|
||||
in-process CCR store is emptied, and an entry that expired does not."""
|
||||
monkeypatch.setenv("HEADROOM_CCR_BACKEND", "memory")
|
||||
reset_compression_store()
|
||||
ccr = get_compression_store()
|
||||
rows = ccr.store(json.dumps(list(range(400))), "[0, 1]", ttl=900)
|
||||
blob = ccr.store("x" * 5000, "", ttl=900, explicit_hash="abcdef123456")
|
||||
gone = ccr.store("expired original", "", ttl=900)
|
||||
ccr._backend.get(gone).created_at -= 1000 # type: ignore[union-attr]
|
||||
expires = {h: ccr.get_entry_status(h)["expires_at"] for h in (rows, blob)}
|
||||
text = (
|
||||
f"[400 items compressed to 2. Retrieve more: hash={rows}] "
|
||||
f"<<ccr:{blob},base64,4.9KB>> [stale. Retrieve original: hash={gone}]"
|
||||
)
|
||||
store = SessionTrackerStore()
|
||||
contextvars.Context().run(_send, store, [{"role": "user", "content": text}])
|
||||
path = str(tmp_path / "state.json")
|
||||
assert store.save_state(path) == 1
|
||||
reset_compression_store()
|
||||
|
||||
assert SessionTrackerStore().load_state(path) == 1
|
||||
|
||||
ccr = get_compression_store()
|
||||
assert ccr.retrieve(rows).original_content == json.dumps(list(range(400))) # type: ignore[union-attr]
|
||||
assert ccr.retrieve(blob).original_content == "x" * 5000 # type: ignore[union-attr]
|
||||
assert ccr.retrieve(gone) is None
|
||||
for h, at in expires.items():
|
||||
assert abs(ccr.get_entry_status(h)["expires_at"] - at) < 2
|
||||
reset_compression_store()
|
||||
|
||||
|
||||
def _chat_turns(n: int) -> list[dict[str, Any]]:
|
||||
"""An OpenAI chat agent: one big tool result, then ``n - 1`` follow-ups."""
|
||||
messages: list[dict[str, Any]] = [
|
||||
{"role": "user", "content": "run the build and show me the log"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "call_1",
|
||||
"type": "function",
|
||||
"function": {"name": "bash", "arguments": "{}"},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "call_1", "content": "build log line OK\n" * 200},
|
||||
]
|
||||
for i in range(1, n):
|
||||
messages += [
|
||||
{"role": "assistant", "content": f"answer {i}"},
|
||||
{"role": "user", "content": "and now?"},
|
||||
]
|
||||
return messages
|
||||
|
||||
|
||||
def _relevance_pipeline(**kwargs: Any) -> TransformResult:
|
||||
"""Query-dependent compression, like SmartCrusher's relevance scoring: the
|
||||
same tool result compresses differently under a different user query."""
|
||||
frozen = kwargs.get("frozen_message_count") or 0
|
||||
query = next(m["content"] for m in reversed(kwargs["messages"]) if m["role"] == "user")
|
||||
messages = [
|
||||
{**m, "content": f"[log: kept lines relevant to {query!r}]"}
|
||||
if i >= frozen and m.get("role") == "tool"
|
||||
else m
|
||||
for i, m in enumerate(kwargs["messages"])
|
||||
]
|
||||
return TransformResult(
|
||||
messages=messages, tokens_before=2000, tokens_after=40, transforms_applied=["relevance"]
|
||||
)
|
||||
|
||||
|
||||
def _drive_openai_chat(requests: list[list[dict[str, Any]]]) -> list[list[dict[str, Any]]]:
|
||||
"""Each history through the real OpenAI chat handler in token mode; one
|
||||
app per call, so a second call is a proxy restart."""
|
||||
app = create_app(
|
||||
ProxyConfig(
|
||||
optimize=True,
|
||||
mode="token",
|
||||
disable_kompress=True,
|
||||
rate_limit_enabled=False,
|
||||
cost_tracking_enabled=False,
|
||||
log_requests=False,
|
||||
)
|
||||
)
|
||||
forwarded: list[list[dict[str, Any]]] = []
|
||||
with TestClient(app) as client:
|
||||
proxy = client.app.state.proxy
|
||||
proxy.openai_pipeline.apply = _relevance_pipeline
|
||||
|
||||
async def _upstream(method, url, headers, body, stream=False, **kwargs): # noqa: ANN001, ANN003
|
||||
forwarded.append(json.loads(json.dumps(body["messages"])))
|
||||
# Automatic prefix caching reports nothing cached on a
|
||||
# conversation's first request, so there is no confirmed floor.
|
||||
usage = {"prompt_tokens": 600, "completion_tokens": 3, "total_tokens": 603}
|
||||
usage["prompt_tokens_details"] = {"cached_tokens": 0}
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"id": "chatcmpl_x",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {"role": "assistant", "content": "ok"},
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
],
|
||||
"usage": usage,
|
||||
},
|
||||
)
|
||||
|
||||
proxy._retry_request = _upstream
|
||||
for messages in requests:
|
||||
response = client.post(
|
||||
"/v1/chat/completions",
|
||||
headers={"authorization": "Bearer test-key"},
|
||||
json={"model": "gpt-4o-mini", "messages": messages},
|
||||
)
|
||||
assert response.status_code == 200, response.text[:300]
|
||||
return forwarded
|
||||
|
||||
|
||||
def test_openai_token_mode_replays_its_prefix_after_a_restart(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""Review of #4299: only the Anthropic handler seeded its CompressionCache
|
||||
from a restored tracker. The OpenAI token path froze nothing, recompressed
|
||||
the tool result under the new query, and with no provider-confirmed floor
|
||||
the overlay declined the larger previous form, so the prefix changed."""
|
||||
monkeypatch.setenv("HEADROOM_CCR_BACKEND", "memory")
|
||||
monkeypatch.setenv(PREFIX_STATE_FILE_ENV, str(tmp_path / "prefix-state.json"))
|
||||
reset_compression_store()
|
||||
|
||||
(previous,) = _drive_openai_chat([_chat_turns(1)])
|
||||
(current,) = _drive_openai_chat([_chat_turns(2)])
|
||||
|
||||
assert previous[2]["content"] != _chat_turns(1)[2]["content"], "nothing was compressed"
|
||||
assert current[: len(previous)] == previous
|
||||
|
||||
|
||||
def test_read_maturation_state_survives_a_restart(tmp_path: Path) -> None:
|
||||
"""Matured Reads stay booked once: without this a restart books their
|
||||
removal again on every later request of the conversation."""
|
||||
@@ -313,3 +529,26 @@ def test_read_maturation_state_survives_a_restart(tmp_path: Path) -> None:
|
||||
assert adopted._matured == manager._matured
|
||||
assert adopted._booked == manager._booked
|
||||
assert adopted._replay_token_deltas == manager._replay_token_deltas
|
||||
|
||||
|
||||
def test_compress_sidecar_session_replays_its_prefix_after_a_restart(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""The same seed on the session-aware /v1/compress path (sidecar gateways),
|
||||
which replays with the size bound alone (no provider-confirmed floor)."""
|
||||
from tests.test_compress_session_mode import _compress, _make_client
|
||||
|
||||
monkeypatch.setenv("HEADROOM_CCR_BACKEND", "memory")
|
||||
monkeypatch.setenv(PREFIX_STATE_FILE_ENV, str(tmp_path / "prefix-state.json"))
|
||||
reset_compression_store()
|
||||
forwarded = []
|
||||
for history in (_chat_turns(1), _chat_turns(2)): # one proxy each: a restart between
|
||||
with _make_client() as client:
|
||||
client.app.state.proxy._no_ccr_pipeline = lambda: SimpleNamespace(
|
||||
apply=_relevance_pipeline
|
||||
)
|
||||
forwarded.append(_compress(client, history, session_id="conv-r")["messages"])
|
||||
previous, current = forwarded
|
||||
|
||||
assert previous[2]["content"] != _chat_turns(1)[2]["content"], "nothing was compressed"
|
||||
assert current[: len(previous)] == previous
|
||||
|
||||
Reference in New Issue
Block a user