Files
headroom/tests/test_ccr_sqlite_backend.py
T
4e6e955cad fix(memory): log storage and SQLite failures that currently make retrieval miss silently (#4111)
## Description

Several storage paths turn a real failure into a quiet miss. They either
log nothing, or log a line that does not say which operation or file
failed. When CCR or memory retrieval misses, an operator cannot tell
corruption or a broken plugin from a genuine "not found". This PR adds
the missing log lines. Return values and control flow do not change.

Refs #4136

## Type of Change

- [x] 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

- `headroom/storage/__init__.py` (`create_storage`):
- A `headroom.storage_backend` plugin that raised on load was swallowed
by `except Exception: pass`. So was a scheme with no plugin. Both then
fell back to `SQLiteStorage(store_url)`, which opens a SQLite file named
after the URL.
- Both cases now log a warning that names the scheme. The URL itself is
not logged, because it can carry credentials.
- A plugin that raises is logged with the exception type only, because
its text can echo the URL. A separate DEBUG line gives
`log_safety.describe_exception` (exception types and code locations,
never the message), so no level carries the URL or its password.
  - The module gets a `logger`.
- `headroom/cache/backends/sqlite.py` (CCR store):
- `_entry_from_json` returned `None` with no log for a row that fails to
decode or rebuild. So `get()` reported a plain miss for an entry that
exists but is unreadable.
- It now logs a warning with the hash, the db path and the exception
type. `items()` decodes every row on each eviction pass, so the warning
fires once per hash.
- The once-per-hash guard is `log_safety.WarnOnce`. Within a one-hour
window it warns for at most 1,000 hashes, then logs one overflow
warning, and later rows log at DEBUG only, so repeated eviction scans
over many bad rows cannot flood the log. When the window ends, a row
that is still broken warns again, about once an hour. A hash is used up
only while WARNING is enabled.
- CCR keys come from model-issued retrieve calls, so they are logged
through `log_safety.safe_id`: a repr (newlines escaped) capped at 80
characters.
- Failed `delete`/`exists`/`clear`/`count`/`keys`/`items`/`get_stats`
all logged as `"op"`. Each now logs its real name, with the key for
`get`/`set`/`delete`/`exists`.
  - The transient-error warning now includes the db path.
- `headroom/memory/traffic_learner.py`: the two read-only SQLite reads
returned `[]` on `OperationalError`/`DatabaseError` with no log: the
hydrate path and `_load_persisted_patterns_from_sqlite`. Both now warn
with the db path. Also:
- dropped a redundant `conn.close()` in an `except` whose `finally`
already closes;
- the two best-effort `conn.close()` calls now catch `sqlite3.Error` and
log at debug, instead of `except Exception: pass`.
- `headroom/memory/backends/direct_mem0.py`:
`get_memory`/`delete_memory` turned any Qdrant/Neo4j exception into "not
found". They now warn with the memory id and the exception type first.
- The exception text is not logged at any level, because backend errors
can carry stored memory or connection details. A DEBUG line gives
`describe_exception`.
- Memory ids come from the model, so they are logged through
`log_safety.safe_id`, which escapes newlines and caps the length.
- mem0 2.x `Memory.delete` raises exactly `ValueError(f"Memory with id
{memory_id} not found")` for an unknown id. Only that message, for the
requested id, logs at DEBUG; the delete is model-driven, so it is
expected. Any other `ValueError`, such as a missing collection, still
warns.
- When a corrupt CCR store is recreated, the unreadable-row guard starts
fresh, because the new file has no rows.
- `headroom/learn/registry.py`: a built-in learn plugin that fails to
import was logged at debug, so `headroom learn --agent <name>` only said
"Unknown agent". It is now a warning with the traceback. Built-in
plugins use only the stdlib, so this never fires on a healthy install.
- `headroom/cache/compression_store.py`: the "Failed to load CCR
backend" warning now says it falls back to the in-process store, and
what that costs. This matches the SQLite branch next to it. It logs the
exception type only, because the backend's text can echo
`HEADROOM_REDIS_URL`. DEBUG gets `describe_exception`.

## 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
$ pytest -q -p no:cacheprovider tests/test_storage_backends.py tests/test_storage tests/test_ccr_sqlite_backend.py tests/test_compression_store.py tests/test_learn/test_registry.py tests/test_memory/test_traffic_learner.py tests/test_memory/test_direct_mem0.py tests/test_private_state_files.py tests/test_adapter_hooks.py tests/test_cache/test_backends.py tests/test_learn/test_opencode_scanner.py tests/test_openai_responses_traffic_learner.py tests/test_learn/test_section_lifecycle.py tests/test_learn/test_worktree_merge.py tests/test_memory_handler_native_ops.py
================= 537 passed, 1 skipped, 5 warnings in 34.37s ==================
# The three new tests against origin/main (product code reverted):
FAILED tests/test_storage_backends.py::test_create_storage_warns_when_a_backend_plugin_fails_to_load
FAILED tests/test_ccr_sqlite_backend.py::TestSQLiteBackend::test_unreadable_row_is_logged_once_and_healthy_rows_are_not
FAILED tests/test_learn/test_registry.py::TestBuiltinLoadFailure::test_broken_builtin_plugin_is_logged_as_a_warning
$ uvx ruff@0.16.8 check <changed files>
All checks passed!
# Added in review: the hydration-failure warning; mem0 delete/get paths (only mem0's exact missing-memory message is quiet; a missing collection warns); newline and 100,000-char model ids; two scans over more bad rows than the cap; and storage-plugin, CCR-backend and mem0 failures whose records are rendered with logging.Formatter at DEBUG and WARNING and checked for credential and content canaries.
# Those tests against the previous head 6c1ad49c, in a scratch worktree:
FAILED tests/test_ccr_sqlite_backend.py::TestSQLiteBackend::test_repeated_scans_over_the_cap_stay_bounded
FAILED tests/test_storage_backends.py::test_create_storage_warns_when_a_backend_plugin_fails_to_load
FAILED tests/test_memory/test_direct_mem0.py::test_backend_failures_warn_without_exception_text[delete_memory-exc1-True]
FAILED tests/test_memory/test_direct_mem0.py::test_backend_failures_warn_without_exception_text[delete_memory-exc4-True]
FAILED tests/test_memory/test_direct_mem0.py::test_backend_failures_warn_without_exception_text[get_memory-exc5-True]
FAILED tests/test_adapter_hooks.py::TestCCREntryPointLoading::test_failing_backend_plugin_logs_no_credentials_at_any_level
$ mypy <6 changed product files> --ignore-missing-imports
Success: no issues found in 6 source files
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13, repo .venv, branch checkout at
72a166cb (base a9815bbb plus main and #4138 merged in), temp HOME /
HEADROOM_WORKSPACE_DIR / CODEX_HOME, offline.
- Exact command / steps: two runs from this checkout, listed below.
- Ran the shared smoke harness, which starts a real proxy from this
checkout against a local fake upstream and sends one Anthropic and one
OpenAI request with a compressible tool result.
- Ran a direct, unmocked script at DEBUG. A storage plugin raises an
error that quotes its `pg://user:CRED_CANARY@...` URL. Then 5 unreadable
rows are written into a real CCR SQLite store (the cap is lowered to 3
for the run), and `items()` scans it twice.
- Observed result: as listed below. The raw output is in the blocks
after this list.
- Both proxy requests return HTTP 200 with savings, and the proxy log
has no new warnings.
- The storage fallback logs the scheme and exception type at WARNING,
and only types and code locations at DEBUG. `CRED_CANARY` appears
nowhere in the output.
- The CCR store warns for 3 rows, then once for the overflow, and the
second scan (inside the same hour) adds nothing. All 5 rows are kept,
and reads miss as before.
- Not tested: the two paths listed below.
- A live Qdrant/Neo4j outage on the DirectMem0 path. Unit tests with a
raising client cover it.
  - A real third-party storage or CCR plugin.

```text
$ bash smoke.sh <worktree>
branch: cleanup/memory-cache-storage-logging @ 72a166cb
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines:
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you 
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.

$ HOME=$TMP/home HEADROOM_WORKSPACE_DIR=$TMP/ws CODEX_HOME=$TMP/codex python -u run.py   # logging at DEBUG
INFO headroom._ort - Pinned ORT_DYLIB_PATH to bundled ONNX Runtime: /Users/tejas/headroom/.venv/lib/python3.12/site-packages/onnxruntime/capi/libonnxruntime.1.26.0.dylib
WARNING headroom.storage - Failed to load storage backend for scheme 'pg' (<ValueError>); falling back to SQLite storage
DEBUG headroom.storage - Storage backend 'pg' load failure: ValueError at run.py:11 in factory <- headroom/storage/__init__.py:70 in create_storage
WARNING headroom.cache.backends.sqlite - CCR SQLite entry 'bad0' in $TMP/ws/ccr_store.db is unreadable (JSONDecodeError); treating as a miss
WARNING headroom.cache.backends.sqlite - CCR SQLite entry 'bad1' in $TMP/ws/ccr_store.db is unreadable (JSONDecodeError); treating as a miss
WARNING headroom.cache.backends.sqlite - CCR SQLite entry 'bad2' in $TMP/ws/ccr_store.db is unreadable (JSONDecodeError); treating as a miss
WARNING headroom.cache.backends.sqlite - More than 3 distinct unreadable CCR SQLite entries; further ones are logged at debug only
scan 1 -> []
scan 2 -> []
rows kept: 5
```

Update 2026-10-15 (head `4e78ca73`). Plugin-load warnings now name the
exception through `safe_id`, which renders `<ValueError>`, or `<object>`
for a class whose name is not a plain identifier. The learn-plugin
failures no longer put a traceback in the WARNING. This is a direct,
unmocked run at DEBUG with `HEADROOM_DEBUG_DUMP` unset. A storage plugin
and an external learn plugin raise errors quoting
`pg://user:CRED_CANARY@db`, one of them through a class named
`PRIVATE_CREDENTIAL_CANARY\nFORGED_LOG_ENTRY`. `grep -c 'CANARY|FORGED'`
on the output gives 0.

```text
WARNING headroom.storage - Failed to load storage backend for scheme 'pg' (<ValueError>); falling back to SQLite storage
DEBUG headroom.storage - Storage backend 'pg' load failure: ValueError at headroom/storage/__init__.py:70 in create_storage
WARNING headroom.storage - Failed to load storage backend for scheme 'pg' (<object>); falling back to SQLite storage
DEBUG headroom.storage - Storage backend 'pg' load failure: <exception> at headroom/storage/__init__.py:70 in create_storage
WARNING headroom.learn.registry - Failed to load external learn plugin 'broken' (<object>)
DEBUG headroom.learn.registry - External learn plugin 'broken' failure: <exception> at headroom/learn/registry.py:52 in _discover
learn plugins: ['claude', 'codex', 'gemini', 'grok', 'opencode']
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A; logging only.
- Stable/default behavior changed: No. Only log output changes. All
return values and fallbacks are as before.
- Kill switch / disable path: Standard logging level configuration for
the `headroom.*` loggers.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [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

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

- Documentation: N/A, because no user-facing option changes.
- On the DirectMem0 path, deleting an unknown id stays quiet at the
default level. Only real backend failures warn.
- Depends on #4138; its two files show in this diff until it merges.
- The `describe_exception` calls run only when
`logger.isEnabledFor(logging.DEBUG)`, so a failure path does no
formatting work at INFO. That PR also touches
`headroom/proxy/handlers/_debug_dump.py`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-16 14:30:34 -07:00

534 lines
21 KiB
Python

"""Tests for the SQLite CCR backend and session-scale TTL defaults.
The SQLite backend is the default for `get_compression_store()` because the
30-minute TTL assumes entries survive proxy restarts and are visible across
worker processes — neither holds for the in-memory dict.
"""
from __future__ import annotations
import logging
import os
import sqlite3
import time
import pytest
from headroom.cache.backends.sqlite import SQLiteBackend
from headroom.cache.compression_store import CompressionEntry, CompressionStore
def make_entry(hash_key: str = "h1", content: str = "x" * 600, ttl: int = 1800) -> CompressionEntry:
return CompressionEntry(
hash=hash_key,
original_content=content,
compressed_content="c",
original_tokens=100,
compressed_tokens=10,
original_item_count=50,
compressed_item_count=5,
tool_name="Read",
tool_call_id="t1",
query_context=None,
created_at=time.time(),
ttl=ttl,
)
@pytest.fixture
def db_path(tmp_path):
return tmp_path / "ccr_test.db"
class TestSQLiteBackend:
def test_crud_roundtrip(self, db_path):
b = SQLiteBackend(db_path)
entry = make_entry()
b.set("h1", entry)
got = b.get("h1")
assert got is not None
assert got.original_content == entry.original_content
assert got.tool_name == "Read"
assert got.ttl == 1800
assert b.exists("h1")
assert b.count() == 1
assert b.keys() == ["h1"]
assert b.delete("h1")
assert not b.exists("h1")
assert not b.delete("h1")
@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits only")
def test_db_file_is_private_under_permissive_umask(self, db_path):
"""The CCR db (sensitive tool output) must be 0o600 under any umask.
``_ensure_private`` creates the db with an explicit ``0o600`` mode
(``O_CREAT | O_EXCL``) before ``sqlite3.connect`` opens it, so it is
private from birth. Forcing ``umask(0o022)`` — which would make sqlite
create it 0o644 — confirms the mode is umask-independent.
"""
old_umask = os.umask(0o022)
try:
SQLiteBackend(db_path) # fresh open, private from birth
finally:
os.umask(old_umask)
assert db_path.exists()
assert (db_path.stat().st_mode & 0o777) == 0o600
@pytest.mark.skipif(os.name == "nt", reason="POSIX chmod semantics")
def test_open_fails_closed_when_db_cannot_be_made_private(self, db_path, monkeypatch):
"""If an existing db cannot be narrowed, opening must abort (fail closed).
A store of raw tool output must not be opened world-readable, so
``_ensure_private`` raises rather than silently proceeding to
``sqlite3.connect`` on a db it could not make private.
"""
import headroom.cache.backends.sqlite as sqlite_mod
db_path.write_text("") # pre-existing regular db file
def boom(fd, mode):
raise PermissionError("cannot fchmod")
# The existing-file path narrows through the descriptor (fchmod), so a
# narrowing failure there must still abort the open.
monkeypatch.setattr(sqlite_mod.os, "fchmod", boom)
with pytest.raises(PermissionError):
SQLiteBackend(db_path)
@pytest.mark.skipif(os.name == "nt", reason="POSIX symlink semantics")
def test_open_fails_closed_on_symlinked_db_path(self, tmp_path):
"""A symlinked db path must be refused without following it.
If the db path is a symlink an attacker planted, ``_ensure_private``
must fail closed (O_NOFOLLOW) rather than chmod-ing and handing the
attacker-chosen target to ``sqlite3.connect``. The target must be left
untouched: neither narrowed nor opened/rewritten.
"""
target = tmp_path / "attacker_target"
# Create the target with a deliberately wider mode via umask (not an
# explicit permissive chmod) so a chmod-follow regression would show up
# as a mode change, without the test itself performing a world-readable
# chmod that the security scanner flags as overly permissive.
old_umask = os.umask(0o022)
try:
target.write_text("SECRET-ORIGINAL") # lands 0o644 under this umask
finally:
os.umask(old_umask)
before_mode = target.stat().st_mode & 0o777
assert before_mode != 0o600 # precondition: a narrow would be visible
link = tmp_path / "ccr_store.db"
link.symlink_to(target)
with pytest.raises(PermissionError):
SQLiteBackend(link)
# Target was neither narrowed (mode unchanged) nor opened/rewritten by
# sqlite (contents intact, no WAL/journal siblings created).
assert (target.stat().st_mode & 0o777) == before_mode
assert target.read_text() == "SECRET-ORIGINAL"
assert link.is_symlink()
def test_survives_reopen(self, db_path):
"""The restart-survival property the default flip exists for."""
SQLiteBackend(db_path).set("h1", make_entry())
reopened = SQLiteBackend(db_path)
got = reopened.get("h1")
assert got is not None
assert got.original_content == "x" * 600
def test_two_connections_share_data(self, db_path):
"""Multi-worker property: a second live connection sees writes."""
writer = SQLiteBackend(db_path)
reader = SQLiteBackend(db_path)
writer.set("h1", make_entry())
assert reader.get("h1") is not None
def test_items_and_stats(self, db_path):
b = SQLiteBackend(db_path)
b.set("h1", make_entry("h1"))
b.set("h2", make_entry("h2"))
items = dict(b.items())
assert set(items) == {"h1", "h2"}
stats = b.get_stats()
assert stats["backend_type"] == "sqlite"
assert stats["entry_count"] == 2
assert stats["bytes_used"] > 0
def test_opening_a_db_with_the_old_index_drops_it_and_keeps_the_rows(self, db_path):
# Databases written before idx_ccr_expiry_deadline still carry the
# superseded idx_ccr_expiry; opening them must migrate, not fail.
seeded = SQLiteBackend(db_path)
seeded.set("h1", make_entry("h1"))
seeded._conn.execute(
"CREATE INDEX IF NOT EXISTS idx_ccr_expiry ON ccr_entries (created_at)"
)
seeded._conn.commit()
seeded._conn.close()
b = SQLiteBackend(db_path)
indexes = {
row[0]
for row in b._conn.execute(
"SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'idx_%'"
)
}
assert indexes == {"idx_ccr_expiry_deadline"}
entry = b.get("h1")
assert entry is not None
assert entry.original_content == make_entry("h1").original_content
def test_purge_expired_deletes_by_deadline_and_keeps_the_boundary_row(self, db_path):
b = SQLiteBackend(db_path)
now = time.time()
expired = make_entry("expired", ttl=10)
expired.created_at = now - 11
boundary = make_entry("boundary", ttl=10)
boundary.created_at = now - 10
live = make_entry("live", ttl=60)
live.created_at = now - 11
# Keep backend.set() from performing its opportunistic purge first.
b._last_purge = now
for entry in (expired, boundary, live):
b.set(entry.hash, entry)
assert b.purge_expired(now) == 1
assert set(b.keys()) == {"boundary", "live"}
def test_new_insert_purges_expired_sqlite_entry_without_decoding_live_payloads(
self, db_path, monkeypatch
):
backend = SQLiteBackend(db_path)
store = CompressionStore(max_entries=4, backend=backend, enable_feedback=False)
expired_hash = store.store("expired original", "expired compact", ttl=10)
live_hash = store.store("live original", "live compact", ttl=60)
other_live_hash = store.store("other live original", "other live compact", ttl=60)
expired = backend.get(expired_hash)
assert expired is not None
expired.created_at = time.time() - 11
backend.set(expired_hash, expired)
# The setup stores above intentionally exercised the periodic purge and
# advanced its 60-second throttle. Make the insertion under test eligible
# to purge the row we only just backdated.
backend._last_purge = 0.0
monkeypatch.setattr(
backend,
"_entry_from_json",
lambda *_args: pytest.fail("new insertion decoded existing CCR payloads"),
)
new_hash = store.store("new original", "new compact", ttl=60)
assert not backend.exists(expired_hash)
assert backend.exists(live_hash)
assert backend.exists(other_live_hash)
assert backend.exists(new_hash)
def test_clear(self, db_path):
b = SQLiteBackend(db_path)
b.set("h1", make_entry())
b.clear()
assert b.count() == 0
def test_unknown_json_fields_tolerated(self, db_path):
"""Forward-compat: entries written by a newer headroom version
(extra fields) must still load."""
b = SQLiteBackend(db_path)
b.set("h1", make_entry())
with b._lock:
row = b._conn.execute("SELECT entry_json FROM ccr_entries WHERE hash='h1'").fetchone()
doctored = row[0][:-1] + ', "field_from_the_future": 7}'
b._conn.execute("UPDATE ccr_entries SET entry_json=? WHERE hash='h1'", (doctored,))
b._conn.commit()
got = b.get("h1")
assert got is not None
assert got.original_content == "x" * 600
def test_missing_required_field_degrades_to_miss(self, db_path):
"""A row that parses as JSON but is missing a required CompressionEntry
field (schema drift across an upgrade, a partially written row) must
degrade to a miss, not raise. Otherwise it crashes get() and — via
items(), which _clean_expired runs on every store's eviction — breaks
all reads, evictions, and stores for one poison row."""
b = SQLiteBackend(db_path)
b.set("good", make_entry("good"))
# Insert a valid-JSON blob missing required fields, plus a non-dict blob.
with b._lock:
for hash_key, blob in (
("poison", '{"hash": "poison", "original_content": "x"}'),
("nulljson", "null"),
):
b._conn.execute(
"INSERT OR REPLACE INTO ccr_entries "
"(hash, entry_json, created_at, ttl) VALUES (?, ?, ?, ?)",
(hash_key, blob, time.time(), 1800),
)
b._conn.commit()
assert b.get("poison") is None # no TypeError
assert b.get("nulljson") is None
# items() skips the bad rows instead of raising; the good row survives.
items = dict(b.items())
assert set(items) == {"good"}
# A store cycle (which evicts via items()) still works with poison present.
store = CompressionStore(backend=b, max_entries=1000)
store.store(original="fresh original", compressed="c", original_item_count=1)
assert b.get("good") is not None
def test_unreadable_row_is_logged_once_and_healthy_rows_are_not(self, db_path):
"""An unreadable row must say so in the log (once per hash), so an
operator can tell corruption from a genuine retrieval miss."""
records: list[logging.LogRecord] = []
class _Collect(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
records.append(record)
handler = _Collect(level=logging.DEBUG)
logger = logging.getLogger("headroom.cache.backends.sqlite")
logger.addHandler(handler)
try:
b = SQLiteBackend(db_path)
b.set("good", make_entry("good"))
assert b.get("good") is not None
assert [r for r in records if "unreadable" in r.getMessage()] == []
with b._lock:
b._conn.execute(
"INSERT OR REPLACE INTO ccr_entries "
"(hash, entry_json, created_at, ttl) VALUES (?, ?, ?, ?)",
("broken", "{not json", time.time(), 1800),
)
b._conn.commit()
assert b.get("broken") is None
b.items()
b.items()
unreadable = [r for r in records if "unreadable" in r.getMessage()]
assert len(unreadable) == 1
assert unreadable[0].levelno == logging.WARNING
assert "broken" in unreadable[0].getMessage()
assert "good" not in unreadable[0].getMessage()
finally:
logger.removeHandler(handler)
def test_repeated_scans_over_the_cap_stay_bounded(self, db_path, monkeypatch):
"""More bad rows than the cap, scanned twice: at most cap row warnings plus
one overflow warning in total, and the rows stay in place and still miss."""
import headroom.cache.backends.sqlite as sqlite_mod
monkeypatch.setattr(sqlite_mod, "_MAX_REPORTED_UNREADABLE", 2)
records: list[logging.LogRecord] = []
class _Collect(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
records.append(record)
handler = _Collect(level=logging.DEBUG)
logger = logging.getLogger("headroom.cache.backends.sqlite")
logger.addHandler(handler)
keys = [f"bad{i}" for i in range(5)]
try:
b = SQLiteBackend(db_path)
with b._lock:
for key in keys:
b._conn.execute(
"INSERT OR REPLACE INTO ccr_entries "
"(hash, entry_json, created_at, ttl) VALUES (?, ?, ?, ?)",
(key, "{not json", time.time(), 1800),
)
b._conn.commit()
assert b.items() == []
assert b.items() == []
assert b.get("bad4") is None
assert b.count() == len(keys)
finally:
logger.removeHandler(handler)
warnings = [r.getMessage() for r in records if r.levelno == logging.WARNING]
row_warnings = [m for m in warnings if "is unreadable" in m]
assert len(row_warnings) == 2
assert all("JSONDecodeError" in m for m in row_warnings)
assert len([m for m in warnings if "More than 2 warnings about" in m]) == 1
assert len(warnings) == 3
def test_store_ttl_enforcement_via_compression_store(self, db_path):
"""TTL checks stay in CompressionStore; expired entries miss."""
store = CompressionStore(backend=SQLiteBackend(db_path))
expired = make_entry(ttl=1)
expired.created_at = time.time() - 10
store._backend.set("h1", expired)
assert store.retrieve("h1") is None
def test_retrieval_count_persists(self, db_path):
"""record_access mutations are re-persisted (store re-sets the
entry after mutating), so feedback counts survive reopen."""
store = CompressionStore(backend=SQLiteBackend(db_path))
store._backend.set("h1", make_entry())
store.retrieve("h1", query="foo")
reopened = SQLiteBackend(db_path)
got = reopened.get("h1")
assert got is not None
assert got.retrieval_count == 1
class TestMultiWorkerSafety:
def test_busy_error_does_not_delete_database(self, db_path):
"""SQLITE_BUSY (OperationalError, a DatabaseError subclass) under
multi-worker write contention must be treated as transient — NOT
as corruption that deletes every stored original."""
b = SQLiteBackend(db_path)
b.set("h1", make_entry())
class BusyOnceConn:
"""Delegating wrapper; first SELECT raises 'database is locked'."""
def __init__(self, real):
self._real = real
self.raised = False
def execute(self, *args, **kwargs):
if not self.raised and args and "SELECT" in args[0]:
self.raised = True
raise sqlite3.OperationalError("database is locked")
return self._real.execute(*args, **kwargs)
def __getattr__(self, name):
return getattr(self._real, name)
real = b._conn
b._conn = BusyOnceConn(real) # type: ignore[assignment]
assert b.get("h1") is None # transient miss, not a crash
b._conn = real
# The data and the database file both survived.
assert db_path.exists()
assert b.get("h1") is not None
def test_corruption_message_triggers_reset(self, db_path):
b = SQLiteBackend(db_path)
b.set("h1", make_entry())
b._handle_db_error(sqlite3.DatabaseError("database disk image is malformed"), "get")
# Database recreated: empty but functional.
assert b.count() == 0
b.set("h2", make_entry("h2"))
assert b.exists("h2")
def test_busy_timeout_configured(self, db_path):
b = SQLiteBackend(db_path)
timeout = b._conn.execute("PRAGMA busy_timeout").fetchone()[0]
assert timeout >= 5000
def test_expired_rows_purged_on_open(self, db_path):
b = SQLiteBackend(db_path)
expired = make_entry(ttl=1)
expired.created_at = time.time() - 10
b.set("old", expired)
b.set("fresh", make_entry("fresh"))
reopened = SQLiteBackend(db_path)
assert not reopened.exists("old") # swept at open
assert reopened.exists("fresh")
@pytest.mark.skipif(os.name != "posix", reason="POSIX permissions")
def test_database_file_is_private(self, db_path):
SQLiteBackend(db_path)
mode = db_path.stat().st_mode & 0o777
assert mode == 0o600
class TestDefaults:
def test_session_scale_ttl_lockstep(self):
"""CCRConfig, CompressionEntry, and CompressionStore must agree."""
from headroom.config import CCRConfig
assert CCRConfig().store_ttl_seconds == 1800
assert CompressionEntry.__dataclass_fields__["ttl"].default == 1800
assert CompressionStore()._default_ttl == 1800
def test_default_backend_is_sqlite(self, monkeypatch, tmp_path):
from headroom.cache.compression_store import _create_default_ccr_backend
monkeypatch.delenv("HEADROOM_CCR_BACKEND", raising=False)
monkeypatch.setenv("HEADROOM_CCR_SQLITE_PATH", str(tmp_path / "d.db"))
backend = _create_default_ccr_backend()
assert backend is not None
assert backend.get_stats()["backend_type"] == "sqlite"
def test_workspace_dir(self, monkeypatch, tmp_path):
from headroom.cache.compression_store import _create_default_ccr_backend
workspace = tmp_path / "workspace"
fake_home = tmp_path / "fake_home"
monkeypatch.delenv("HEADROOM_CCR_BACKEND", raising=False)
monkeypatch.delenv("HEADROOM_CCR_SQLITE_PATH", raising=False)
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(workspace))
monkeypatch.setenv("HOME", str(fake_home))
monkeypatch.setenv("USERPROFILE", str(fake_home))
backend = _create_default_ccr_backend()
assert backend is not None
assert str(backend._path) == str(workspace / "ccr_store.db")
def test_sqlite_path_env_wins(self, monkeypatch, tmp_path):
from headroom.cache.compression_store import _create_default_ccr_backend
workspace = tmp_path / "workspace"
sqlite_path = tmp_path / "sqlite_override.db"
monkeypatch.delenv("HEADROOM_CCR_BACKEND", raising=False)
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(workspace))
monkeypatch.setenv("HEADROOM_CCR_SQLITE_PATH", str(sqlite_path))
backend = _create_default_ccr_backend()
assert backend is not None
assert str(backend._path) == str(sqlite_path)
def test_home_fallback(self, monkeypatch, tmp_path):
from headroom.cache.compression_store import _create_default_ccr_backend
fake_home = tmp_path / "fake_home"
monkeypatch.delenv("HEADROOM_CCR_BACKEND", raising=False)
monkeypatch.delenv("HEADROOM_CCR_SQLITE_PATH", raising=False)
monkeypatch.delenv("HEADROOM_WORKSPACE_DIR", raising=False)
monkeypatch.setenv("HOME", str(fake_home))
monkeypatch.setenv("USERPROFILE", str(fake_home))
backend = _create_default_ccr_backend()
assert backend is not None
assert str(backend._path) == str(fake_home / ".headroom" / "ccr_store.db")
def test_explicit_db_path(self, tmp_path):
explicit = tmp_path / "explicit.db"
backend = SQLiteBackend(explicit)
assert backend._path == explicit
def test_memory_opt_out(self, monkeypatch):
from headroom.cache.compression_store import _create_default_ccr_backend
monkeypatch.setenv("HEADROOM_CCR_BACKEND", "memory")
assert _create_default_ccr_backend() is None
def test_miss_message_is_actionable(self):
from headroom.cache.compression_store import CCR_MISS_MESSAGE
assert "re-read" in CCR_MISS_MESSAGE
assert "re-run" in CCR_MISS_MESSAGE
if __name__ == "__main__":
pytest.main([__file__, "-v"])