fix(toin): skip a malformed pattern instead of aborting the store load

import_patterns parsed every stored pattern in one loop with no
per-entry handling, so a single entry that ToolPattern.from_dict or the
load sanitizer rejects (a missing tool_signature_hash, a bad
field_semantics or query_pattern_frequency value, a non-object entry)
aborted the whole load. _load_from_backend only logged toin_load_failed,
the patterns after the bad one were never read, and the next save wrote
the partial set over the file.

Parse each entry on its own: an entry that raises AttributeError,
TypeError or ValueError is skipped, the rest load, and one
toin_import_skipped warning reports how many were skipped and the first
error. The over-limit store in the same issue needs a maintainer
decision and is not changed here.

Refs #4476
This commit is contained in:
Ayushraj06-bit
2026-10-26 02:16:48 +05:30
parent 3fef15d376
commit c472de22b9
2 changed files with 101 additions and 3 deletions
+24 -3
View File
@@ -1397,11 +1397,20 @@ class ToolIntelligenceNetwork:
patterns_data = data.get("patterns", {})
source_instance = data.get("instance_id", "unknown")
skipped = 0
first_error: Exception | None = None
with self._lock:
for serialized_key, pattern_dict in patterns_data.items():
key = _deserialize_pattern_key(serialized_key)
imported = ToolPattern.from_dict(pattern_dict)
self._sanitize_loaded_pattern(imported)
try:
key = _deserialize_pattern_key(serialized_key)
imported = ToolPattern.from_dict(pattern_dict)
self._sanitize_loaded_pattern(imported)
except (AttributeError, TypeError, ValueError) as e:
# One unreadable entry must not abort the rest: the store
# that did load would be saved over the whole file.
skipped += 1
first_error = first_error or e
continue
# Make sure dataclass fields agree with the dict key — pre-F3
# dumps don't carry tenant_key on the pattern, and pre-B5
# dumps don't carry auth_mode/model_family either; promote
@@ -1431,6 +1440,18 @@ class ToolIntelligenceNetwork:
self._prune_patterns_locked()
self._dirty = True
if first_error is not None:
logger.warning(
"TOIN skipped malformed patterns on import",
extra={
"event": "toin_import_skipped",
"skipped": skipped,
"imported": len(patterns_data) - skipped,
"error_type": type(first_error).__name__,
"error": str(first_error),
},
)
def _merge_patterns(self, existing: ToolPattern, imported: ToolPattern) -> None:
"""Merge imported pattern into existing."""
total = existing.sample_size + imported.sample_size
+77
View File
@@ -3,6 +3,9 @@
from __future__ import annotations
import json
import logging
import pytest
from headroom.telemetry.backends.filesystem import FileSystemTOINBackend
from headroom.telemetry.models import ToolSignature
@@ -83,6 +86,80 @@ def test_legacy_raw_query_keys_are_removed_on_load(tmp_path) -> None:
assert pattern.common_query_patterns == ["status:* user:*"]
def _record(toin: ToolIntelligenceNetwork, index: int) -> None:
toin.record_compression(
tool_signature=_signature(index),
original_count=10,
compressed_count=5,
original_tokens=100,
compressed_tokens=50,
strategy="test",
)
def _saved_store(path, count: int) -> dict:
toin = ToolIntelligenceNetwork(TOINConfig(storage_path=str(path), auto_save_interval=0))
for index in range(count):
_record(toin, index)
toin.save()
return json.loads(path.read_text(encoding="utf-8"))
def _skip_warnings(caplog) -> list[logging.LogRecord]:
return [r for r in caplog.records if getattr(r, "event", None) == "toin_import_skipped"]
@pytest.mark.parametrize(
"corrupt",
[
lambda entry: {k: v for k, v in entry.items() if k != "tool_signature_hash"},
lambda entry: {**entry, "field_semantics": {"field_1": "not a dict"}},
lambda entry: {**entry, "query_pattern_frequency": "not a dict"},
lambda entry: {**entry, "query_pattern_frequency": {"status:*": "many"}},
lambda entry: "not a pattern",
],
ids=[
"missing_signature_hash",
"bad_field_semantics",
"bad_query_frequencies",
"bad_query_count",
"not_a_dict",
],
)
def test_malformed_pattern_does_not_drop_the_rest_of_the_store(tmp_path, caplog, corrupt) -> None:
path = tmp_path / "toin.json"
data = _saved_store(path, 5)
keys = list(data["patterns"])
data["patterns"][keys[1]] = corrupt(data["patterns"][keys[1]])
path.write_text(json.dumps(data), encoding="utf-8")
with caplog.at_level(logging.WARNING, logger="headroom.telemetry.toin"):
toin = ToolIntelligenceNetwork(TOINConfig(storage_path=str(path), auto_save_interval=0))
assert len(toin._patterns) == 4
[warning] = _skip_warnings(caplog)
assert warning.skipped == 1
assert warning.imported == 4
# The next save used to write only the patterns read before the bad one.
_record(toin, 99)
toin.save()
saved = json.loads(path.read_text(encoding="utf-8"))["patterns"]
assert set(keys) - {keys[1]} <= set(saved)
assert len(saved) == 5
def test_valid_store_loads_without_a_skip_warning(tmp_path, caplog) -> None:
path = tmp_path / "toin.json"
_saved_store(path, 5)
with caplog.at_level(logging.WARNING, logger="headroom.telemetry.toin"):
toin = ToolIntelligenceNetwork(TOINConfig(storage_path=str(path), auto_save_interval=0))
assert len(toin._patterns) == 5
assert _skip_warnings(caplog) == []
def test_filesystem_backend_writes_compact_json(tmp_path) -> None:
path = tmp_path / "toin.json"
FileSystemTOINBackend(str(path)).save({"patterns": {"a": {"value": 1}}})