fix(cache): exclude cold starts from TTL hit evidence (#4728)

## Description

`PrefixCacheTracker.classify_cache_miss()` deliberately returns
`is_miss=False, reason="cold_start"` when no prefix was cached on the
previous turn. The TTL estimator treated every falsey `is_miss` value as
a hit. Three cold starts and three later expiry misses could therefore
produce a learned TTL with zero actual hit observations. A long cold
start could also suppress a valid estimate by raising its supposed life
bound.

Count life evidence only for explicit `reason="hit", is_miss=False`
rows, and accept expiry evidence only with a boolean miss outcome. The
evidence floors, per-model grouping and conservative expiry rounding are
unchanged. This follows the recording and upper-bound fixes in #4711 and
#4710 by checking what the recorded outcomes actually prove.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- Distinguish cold starts from positive cache hits when collecting TTL
bounds.
- Ignore malformed/ambiguous hit outcomes instead of letting them
satisfy the sample floor.
- Cover actual tracker cold starts, mixed sample floors, long cold
starts alongside genuine hits, and non-hit/malformed controls.

## Testing

- [x] Relevant unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Formatting passes (`ruff format --check .`)
- [x] Type checking passes (original full-package mypy hook)
- [x] Regression tests added
- [x] Standalone runtime validation completed

### Test Output

```text
Owner test file with new regressions on original production code: 9 failed, 28 passed
pytest tests/test_cache tests/test_cold_prefix.py: 369 passed, 3 skipped
Original pre-commit and commit-msg hooks: passed
Whole-tree Ruff check and format --check: passed (1924 files)
Original pre-push make ci-precheck: passed
  Rust workspace: 1749 passed, 3 ignored
  Native extension: built, installed and import-verified
  Critical Python: 177 passed, 8 skipped
  commitlint: passed
```

The three cache skips require optional spaCy/embedding models.
Critical-suite skips require optional relevance models; the existing
token-count approximation warning remains in that log.

## Real Behavior Proof

- Environment: Windows 11, CPython 3.13.9, existing development venv;
clean baseline `1da8930ab47a2fc5339ded97e5a41bfe6fc419eb`, patch
`be03ab5a8ff74f18c5b90232f6d5874e1af8d9ec`. `HEADROOM_OFFLINE=1`,
`PYTHONPATH=.` for the selected checkout. Real local files, public APIs
and controlled idle inputs; no provider credentials.
- Exact command / steps: Run `python proof.py` from either checkout with
the following identical script. Both before and after runs were outside
pytest.

```python
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile

from headroom.cache.prefix_tracker import PrefixCacheTracker
from headroom.cache.ttl_observations import record_cache_observation

with tempfile.TemporaryDirectory() as directory:
    obs = Path(directory) / "observations.jsonl"
    out = Path(directory) / "learned.json"
    os.environ["HEADROOM_CACHE_TTL_LEARN"] = "1"
    os.environ["HEADROOM_STATELESS"] = "0"
    os.environ["HEADROOM_CACHE_TTL_OBS_PATH"] = str(obs)
    for idle in (120, 200, 240):
        tracker = PrefixCacheTracker("openai")
        attr = tracker.classify_cache_miss(0, [], idle_seconds=idle)
        record_cache_observation(provider="openai", model="fixture", attribution=attr)
    tracker = PrefixCacheTracker("openai")
    tracker.update_from_response(cache_read_tokens=0, cache_write_tokens=1000, messages=[])
    for idle in (600, 700, 800):
        attr = tracker.classify_cache_miss(0, [], idle_seconds=idle)
        record_cache_observation(provider="openai", model="fixture", attribution=attr)
    result = subprocess.run([sys.executable, "-m", "headroom.cache.ttl_estimator", "--obs", str(obs), "--out", str(out)], capture_output=True, text=True, check=True)
    rows = [json.loads(line) for line in obs.read_text(encoding="utf-8").splitlines()]
    print(json.dumps({"reasons": [r["reason"] for r in rows],
        "actual_hit_rows": sum(r["reason"] == "hit" for r in rows),
        "learned_file_written": out.exists(),
        "learned_table": json.loads(out.read_text()) if out.exists() else None,
        "cli_output": result.stdout.strip()}))
```

- Observed result: The real tracker and recorder produce three
`cold_start` and three `ttl_expiry` rows. Before the fix the CLI wrote a
600-second estimate claiming three hits; after it reports no estimable
keys and creates no learned file. This uses controlled idle inputs to
verify evidence classification.

```text
Before: {"reasons": ["cold_start", "cold_start", "cold_start", "ttl_expiry", "ttl_expiry", "ttl_expiry"], "actual_hit_rows": 0, "learned_file_written": true, "learned_table": {"openai/fixture": {"hits": 3, "max_hit_idle": 240, "ttl_expiry_misses": 3, "ttl_seconds": 600, "updated_at": 1794297956.945}}, "cli_output": "headroom-cache-ttl: wrote 1 estimate(s) (1 total) to C:\\Users\\ASUS\\AppData\\Local\\Temp\\tmp5ol13684\\learned.json"}
After:  {"reasons": ["cold_start", "cold_start", "cold_start", "ttl_expiry", "ttl_expiry", "ttl_expiry"], "actual_hit_rows": 0, "learned_file_written": false, "learned_table": null, "cli_output": "headroom-cache-ttl: no estimable keys in C:\\Users\\ASUS\\AppData\\Local\\Temp\\tmpnnetshza\\observations.jsonl (6 rows); nothing written"}
```

- Not tested: Live proxy/provider traffic, measured provider TTLs,
billing or model quality, and the complete Python suite. The runtime
proof verifies the local classification/file/CLI/decision behavior
above; hosted CI is tracked separately.

## Runtime Rollout Safety

- Rollout-managed feature(s): Existing optional TTL-learning/cold-prefix
behavior; no new flag.
- Minimum rollout channel: Normal release after maintainer review and CI
qualification.
- Stable/default behavior changed: Cold starts no longer create or
inflate a learned life bound. Valid explicit hit/expiry observations
retain their estimates; existing learned-table merge behavior is
unchanged.
- Kill switch / disable path: Do not run the optional estimator, or
remove the learned table to use the existing provider/config fallback.
- Unsafe override required: No.
- Qualification impact: Owner cache/cold-prefix tests and original local
gates passed; hosted checks provide remote qualification.
- Rollback path: Revert this commit. No dependency or storage-schema
change.

## 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 added tests that prove the fix
- [x] Relevant new and existing tests pass locally
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

Implementation and local validation were completed with Codex
assistance. The author reviewed the code and validation record.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4728"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
This commit is contained in:
Yuchuan He
2026-11-10 09:09:55 -06:00
committed by GitHub
parent 46a3d910c9
commit 93df7ae4f7
2 changed files with 48 additions and 3 deletions
+5 -3
View File
@@ -82,7 +82,7 @@ def estimate_ttls(
a cross-model aggregate is not a sound interval.
A key is emitted only when it has both enough life evidence (``min_hits``
hits with a positive, finite idle) and enough death evidence
explicit ``hit`` outcomes with a positive, finite idle) and enough death evidence
(``min_expiry_misses`` ``ttl_expiry`` misses), AND at least one death was
observed at an idle larger than every observed life — otherwise the
interval has no safe upper end and the static default is the better
@@ -109,10 +109,12 @@ def estimate_ttls(
# would abort the whole batch. Drop them with the other bad input.
if not math.isfinite(idle) or idle <= 0:
continue
if row.get("is_miss"):
if row.get("is_miss") is True:
if row.get("reason") == "ttl_expiry":
expiries[key].append(idle)
else:
elif row.get("is_miss") is False and row.get("reason") == "hit":
# cold_start also has is_miss=False, but no previous cached prefix
# existed: it supplies no evidence that a cache survived this idle.
hits[key].append(idle)
now = round(time.time(), 3)
+43
View File
@@ -54,6 +54,49 @@ def _legacy_aggregate(ttl: int) -> dict:
class TestEstimateTtls:
def test_cold_starts_do_not_supply_hit_evidence(self):
# The real tracker reports cold_start with is_miss=False: nothing was
# cached last turn, so this is neither a miss nor proof of a live cache.
from headroom.cache.prefix_tracker import PrefixCacheTracker
tracker = PrefixCacheTracker("openai")
rows = []
for idle in (120, 200, 240):
attribution = tracker.classify_cache_miss(0, [], idle_seconds=idle)
assert attribution.reason == "cold_start" and not attribution.is_miss
rows.append(_row(idle=idle, hit=not attribution.is_miss, reason=attribution.reason))
rows += _corpus([], [600, 700, 800])
assert estimate_ttls(rows) == {}
def test_cold_starts_cannot_top_up_the_hit_sample_floor(self):
rows = _corpus([120, 240], [600, 700, 800])
rows.append(_row(idle=180, hit=True, reason="cold_start"))
assert estimate_ttls(rows) == {}
def test_long_cold_start_does_not_invalidate_real_hit_bounds(self):
rows = _corpus([120, 200, 240], [600, 700, 800])
rows.append(_row(idle=3600, hit=True, reason="cold_start"))
estimate = estimate_ttls(rows)["openai/gpt-5.5"]
assert estimate["ttl_seconds"] == 600
assert estimate["hits"] == 3
assert estimate["max_hit_idle"] == 240
@pytest.mark.parametrize("reason", [None, "unknown", "prefix_change", "ttl_expiry"])
def test_non_hit_reason_is_not_life_evidence(self, reason):
rows = _corpus([120, 240], [600, 700, 800])
row = _row(idle=180, hit=True)
row["reason"] = reason
rows.append(row)
assert estimate_ttls(rows) == {}
@pytest.mark.parametrize("is_miss", [None, 0, "false"])
def test_malformed_outcome_is_not_life_evidence(self, is_miss):
rows = _corpus([120, 240], [600, 700, 800])
row = _row(idle=180, hit=True)
row["is_miss"] = is_miss
rows.append(row)
assert estimate_ttls(rows) == {}
@pytest.mark.parametrize(
("hit_idles", "expiry_idles", "expected"),
[