mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-25 12:11:49 +08:00
## Description
`HEADROOM_TOIN_BACKEND=none` documents itself as "Explicit
in-memory-only (e.g. `--stateless` mode)" but still writes `toin.json`.
`_create_default_toin_backend` communicates only through its return
value, and it returns `None` for two different situations:
```python
backend_type = (os.environ.get(TOIN_BACKEND_ENV_VAR) or "").strip().lower()
if not backend_type or backend_type == "filesystem":
return None
if backend_type == "none":
return None # Explicit in-memory-only (e.g. --stateless mode)
```
`ToolIntelligenceNetwork.__init__` reads `None` as "no explicit backend"
and falls through to the storage path, which is never empty by default:
```python
if backend is not None:
self._backend = backend
elif self._config.storage_path: # <- default ~/.headroom/toin.json
self._backend = FileSystemTOINBackend(self._config.storage_path)
else:
self._backend = None
```
So `none` is a no-op. The mechanism that actually works is a different
one — `storage_path=""` — which is what `_apply_stateless_persistence`
and `tests/test_stateless_toin.py` use.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring
## Why it matters
Operators reaching for the documented env var to stop TOIN persistence
silently keep it. On one long-lived proxy this left a 14.5 GB
`toin.json` holding 278,767 patterns; `FileSystemTOINBackend.save`
re-runs `json.dumps(data, indent=2)` over the whole store on every
autosave, so the process peaked at a 42 GB physical footprint and filled
swap. `HEADROOM_TOIN_BACKEND=none` looked like the supported way out and
did nothing.
## Changes Made
- Add `toin_backend_disabled()` to distinguish explicit in-memory-only
mode from an unspecified backend.
- Make `HEADROOM_TOIN_BACKEND=none` win over a configured storage path
while preserving explicit backend injection.
- Add seven regression and control tests.
Decide it where the backend choice is actually made, so a non-empty
`storage_path` can no longer defeat it. A new `toin_backend_disabled()`
predicate reads the env directly, which keeps the "explicitly disabled"
case distinguishable from "nothing configured".
The explicit `backend=` argument still wins, so dependency injection is
unaffected.
## Real Behavior Proof
- Environment: macOS 27.0 arm64, Python 3.14, current PR head.
- Exact command / steps: reproduced with HEADROOM_TOIN_BACKEND=none and
a non-empty storage path; ran tests/test_toin_backend_none.py and the
adjacent TOIN/telemetry/stateless selection.
- Observed result: before the fix a FileSystemTOINBackend wrote to disk;
after the fix persistence is disabled while in-memory learning remains
available, with 7 focused tests passing.
- Not tested: long-running production memory behavior and the separate
unbounded-store/file-serialization concerns noted below.
Environment: macOS 27.0 arm64, Python 3.14, headroom @ `main` (2f2950a),
`pip install -e ".[dev,proxy]"`.
Reproduction (before the fix) — `_backend` is a `FileSystemTOINBackend`
even though the env asks for none:
```
$ HEADROOM_TOIN_BACKEND=none python -c "
from headroom.telemetry.toin import TOINConfig, ToolIntelligenceNetwork
t = ToolIntelligenceNetwork(TOINConfig(storage_path='/tmp/probe/toin.json'))
print(type(t._backend).__name__)
t.save()
import os; print('file written:', os.path.exists('/tmp/probe/toin.json'))
"
FileSystemTOINBackend
file written: True
```
Before-fix test run. Reverting only the `__init__` branch (keeping the
new helper so the import resolves) gives a behavioral failure, not a
collection error:
```
FAILED tests/test_toin_backend_none.py::test_backend_none_keeps_toin_in_memory
- assert <FileSystemTOINBackend object> is None
FAILED tests/test_toin_backend_none.py::test_backend_none_is_case_and_whitespace_insensitive
- assert <FileSystemTOINBackend object> is None
2 failed, 5 passed in 0.17s
```
After-fix test run:
```
$ python -m pytest tests/test_toin_backend_none.py -q
7 passed in 0.12s
```
No regressions across the TOIN/telemetry/stateless suites:
```
$ python -m pytest tests/ -q -k "toin or telemetry or stateless" --ignore=tests/test_memory_eval.py
302 passed, 30 skipped, 10703 deselected, 3 warnings in 16.50s
```
`ruff check` and `ruff format --check` clean on both changed files.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check`)
- [x] New regression tests added
### Test Output
```text
7 passed in 0.12s
302 passed, 30 skipped, 10703 deselected
ruff check and ruff format --check passed
```
`tests/test_toin_backend_none.py`:
- `none` yields no backend and writes nothing, despite a non-empty
`storage_path` (the regression)
- value normalization matches every other backend name (`" NONE "`)
- `none` disables persistence but not in-memory learning
- controls: unset and `filesystem` still persist
- an explicitly injected backend still wins over `none`
- the `toin_backend_disabled()` predicate itself
## Notes
Related but deliberately out of scope, happy to file separately:
`FileSystemTOINBackend.save` builds the entire store as one
`json.dumps(..., indent=2)` string in memory, and `_patterns` has no
eviction (the inner fields are bounded, the dict is not). That is what
let a single store reach 14.5 GB.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
134 lines
4.1 KiB
Python
134 lines
4.1 KiB
Python
"""HEADROOM_TOIN_BACKEND=none must mean in-memory-only, not "use the default".
|
|
|
|
`_create_default_toin_backend` reports its decision only through a return value,
|
|
and it returned `None` both for "nothing configured" and for the explicit
|
|
`none` setting. `ToolIntelligenceNetwork.__init__` reads `None` as "no explicit
|
|
backend" and falls back to `FileSystemTOINBackend(config.storage_path)`, and the
|
|
default storage_path is never empty -- so `none` kept writing toin.json.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
from headroom.telemetry.toin import (
|
|
TOIN_BACKEND_ENV_VAR,
|
|
TOINConfig,
|
|
ToolIntelligenceNetwork,
|
|
toin_backend_disabled,
|
|
)
|
|
|
|
|
|
def _network(tmp_path, name: str = "toin.json") -> tuple[ToolIntelligenceNetwork, object]:
|
|
path = tmp_path / name
|
|
return ToolIntelligenceNetwork(TOINConfig(storage_path=str(path))), path
|
|
|
|
|
|
def test_backend_none_keeps_toin_in_memory(tmp_path, monkeypatch):
|
|
"""The regression: a non-empty storage_path must not defeat `none`."""
|
|
monkeypatch.setenv(TOIN_BACKEND_ENV_VAR, "none")
|
|
|
|
toin, path = _network(tmp_path)
|
|
|
|
assert toin._backend is None
|
|
toin.save()
|
|
assert not path.exists()
|
|
assert not list(tmp_path.rglob("*.json"))
|
|
|
|
|
|
def test_backend_none_is_case_and_whitespace_insensitive(tmp_path, monkeypatch):
|
|
"""Matches how the value is normalized for every other backend name."""
|
|
monkeypatch.setenv(TOIN_BACKEND_ENV_VAR, " NONE ")
|
|
|
|
toin, path = _network(tmp_path)
|
|
|
|
assert toin._backend is None
|
|
toin.save()
|
|
assert not path.exists()
|
|
|
|
|
|
def test_backend_none_still_records_patterns_in_memory(tmp_path, monkeypatch):
|
|
"""In-memory-only disables persistence, not learning."""
|
|
monkeypatch.setenv(TOIN_BACKEND_ENV_VAR, "none")
|
|
from headroom.telemetry.models import ToolSignature
|
|
|
|
toin, path = _network(tmp_path)
|
|
toin.record_compression(
|
|
tool_signature=ToolSignature(
|
|
structure_hash="abc123",
|
|
field_count=2,
|
|
has_nested_objects=False,
|
|
has_arrays=True,
|
|
max_depth=1,
|
|
string_field_count=1,
|
|
has_error_like_field=False,
|
|
has_message_like_field=True,
|
|
),
|
|
original_count=100,
|
|
compressed_count=10,
|
|
original_tokens=1000,
|
|
compressed_tokens=100,
|
|
strategy="test",
|
|
)
|
|
|
|
assert toin.get_stats()["patterns_tracked"] == 1
|
|
assert not path.exists()
|
|
|
|
|
|
def test_unset_backend_still_persists(tmp_path, monkeypatch):
|
|
"""Control: the default path must keep writing, or the fix broke persistence."""
|
|
monkeypatch.delenv(TOIN_BACKEND_ENV_VAR, raising=False)
|
|
|
|
toin, path = _network(tmp_path)
|
|
|
|
assert toin._backend is not None
|
|
toin.save()
|
|
assert path.exists()
|
|
assert json.loads(path.read_text())["version"] == "2.0"
|
|
|
|
|
|
def test_filesystem_backend_still_persists(tmp_path, monkeypatch):
|
|
"""Control: the explicit filesystem name is unaffected."""
|
|
monkeypatch.setenv(TOIN_BACKEND_ENV_VAR, "filesystem")
|
|
|
|
toin, path = _network(tmp_path)
|
|
|
|
assert toin._backend is not None
|
|
toin.save()
|
|
assert path.exists()
|
|
|
|
|
|
def test_explicit_backend_argument_beats_the_env(tmp_path, monkeypatch):
|
|
"""A caller-supplied backend still wins -- `none` must not veto injection."""
|
|
monkeypatch.setenv(TOIN_BACKEND_ENV_VAR, "none")
|
|
|
|
saved: list[dict] = []
|
|
|
|
class _RecordingBackend:
|
|
def load(self) -> dict:
|
|
return {}
|
|
|
|
def save(self, data: dict) -> None:
|
|
saved.append(data)
|
|
|
|
path = tmp_path / "toin.json"
|
|
toin = ToolIntelligenceNetwork(TOINConfig(storage_path=str(path)), backend=_RecordingBackend())
|
|
|
|
toin.save()
|
|
assert len(saved) == 1
|
|
assert not path.exists()
|
|
|
|
|
|
def test_toin_backend_disabled_predicate(monkeypatch):
|
|
monkeypatch.delenv(TOIN_BACKEND_ENV_VAR, raising=False)
|
|
assert toin_backend_disabled() is False
|
|
|
|
monkeypatch.setenv(TOIN_BACKEND_ENV_VAR, "none")
|
|
assert toin_backend_disabled() is True
|
|
|
|
monkeypatch.setenv(TOIN_BACKEND_ENV_VAR, "filesystem")
|
|
assert toin_backend_disabled() is False
|
|
|
|
monkeypatch.setenv(TOIN_BACKEND_ENV_VAR, "redis")
|
|
assert toin_backend_disabled() is False
|