fix(memory): scope TrafficLearner's SQLite reads to its user_id (#4850)

## Description

`TrafficLearner` saves its rows under its configured `user_id`, but its
two direct SQLite reads ignored `user_id`:

- `_hydrate_persisted_state` (startup) loaded every user's
`traffic_learner` rows into the dedup maps, then applied `LIMIT
dedup_window`. Bob's learner could bind a pattern hash to Alice's row
and later bump *her* evidence instead of creating his own row. Other
users' rows also used up his window.
- `_load_persisted_patterns_from_sqlite` (used by
`_collect_all_patterns` when writing learned context files) returned
every user's patterns, so Alice's learned text ended up in Bob's files.

Both queries now filter on `user_id = ?`. In hydration the filter runs
before the `LIMIT`. Only matters when several user IDs share one memory
database; a single-user setup (`user_id="default"`) is unchanged.

## Type of Change

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

## Changes Made

- `headroom/memory/traffic_learner.py`: `WHERE user_id = ?` in both
reads. `_load_persisted_patterns_from_sqlite(db_path, user_id)` takes
the user explicitly (private helper; its only caller is updated).
- `tests/test_memory/test_traffic_learner.py`: new
`TestUserScopedPersistence`, which checks that hydration leaves another
user's row alone and collection excludes other users. Hand-built test
schemas gain the `user_id` column that the real `memories` table has,
and direct helper calls pass `"default"`.

## 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
# new tests against origin/main (c21b0813)
$ pytest tests/test_memory/test_traffic_learner.py -k TestUserScopedPersistence
E   assert ['Alice-only ...ge workflow."] == ["Bob's package workflow."]
FAILED ...::TestUserScopedPersistence::test_hydration_ignores_other_users_rows
FAILED ...::TestUserScopedPersistence::test_collected_patterns_exclude_other_users
====================== 2 failed, 236 deselected in 2.76s =======================

# this branch
$ pytest tests/test_memory/test_traffic_learner.py
============================= 238 passed in 18.28s =============================
$ pytest tests/test_openai_responses_traffic_learner.py tests/test_learn/test_worktree_merge.py tests/test_learn/test_section_lifecycle.py tests/test_memory/test_learn_flag.py
============================== 47 passed in 4.81s ==============================
$ ruff check / ruff format --check (0.17.3): All checks passed!
$ mypy headroom/memory/traffic_learner.py --ignore-missing-imports
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: macOS, Python 3.12. One SQLite `memory.db` holding a
`traffic_learner` row for `alice` and one for `bob`.
- Exact command / steps: `TrafficLearner(backend=<backend pointing at
that db>, user_id="bob")._collect_all_patterns()`.
- Observed result:
```text
origin/main:  bob collects: ['Alice-only procedure.', "Bob's preference."]
this branch:  bob collects: ["Bob's preference."]
```
- Not tested: a full proxy run with `--learn --memory` and several
users.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: see Description
- Kill switch / disable path: none needed
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR

## 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

Rows written before this change already carry the correct `user_id` (the
save path always set it), so no migration is needed.

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

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4850"
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 -->

Reported by @JoaoMarcos44. Thank you for your contribution! 🩵

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-15 01:52:47 +05:30
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent 491afe98b1
commit 9321a415a6
2 changed files with 92 additions and 17 deletions
+8 -6
View File
@@ -743,7 +743,7 @@ class TrafficLearner:
db_path = _resolve_backend_db_path(self._backend)
if db_path is not None and db_path.exists():
try:
persisted = _load_persisted_patterns_from_sqlite(db_path)
persisted = _load_persisted_patterns_from_sqlite(db_path, self._user_id)
except Exception as e:
logger.debug("Reading persisted traffic patterns failed: %s", e)
persisted = []
@@ -1473,7 +1473,8 @@ class TrafficLearner:
try:
rows = conn.execute(
"SELECT id, content, metadata FROM memories "
"WHERE json_extract(metadata, '$.source') = 'traffic_learner' "
"WHERE user_id = ? "
"AND json_extract(metadata, '$.source') = 'traffic_learner' "
# Hydrate at most dedup_window rows so a large persisted
# history does not start the in-memory dedup maps oversized
# (they are trimmed to dedup_window in steady state). Keep the
@@ -1482,7 +1483,7 @@ class TrafficLearner:
# as a deterministic tie-break.
"ORDER BY json_extract(metadata, '$.last_seen_at') DESC, id DESC "
"LIMIT ?",
(self._dedup_window,),
(self._user_id, self._dedup_window),
).fetchall()
except sqlite3.DatabaseError as e:
logger.warning("Traffic learner hydrate: failed to read %s: %s", db_path, e)
@@ -1909,8 +1910,8 @@ def _resolve_backend_db_path(backend: Any) -> Path | None:
return Path(db_path)
def _load_persisted_patterns_from_sqlite(db_path: Path) -> list[ExtractedPattern]:
"""Read traffic_learner rows from memory.db, dedupe, return patterns.
def _load_persisted_patterns_from_sqlite(db_path: Path, user_id: str) -> list[ExtractedPattern]:
"""Read ``user_id``'s traffic_learner rows from memory.db, dedupe, return patterns.
Uses a direct read-only SQLite connection — we don't go through the
backend's vector search because we want all rows, not semantically
@@ -1928,7 +1929,8 @@ def _load_persisted_patterns_from_sqlite(db_path: Path) -> list[ExtractedPattern
rows = conn.execute(
"SELECT content, metadata, entity_refs, importance, created_at "
"FROM memories "
"WHERE json_extract(metadata, '$.source') = 'traffic_learner'"
"WHERE user_id = ? AND json_extract(metadata, '$.source') = 'traffic_learner'",
(user_id,),
).fetchall()
except sqlite3.DatabaseError as e:
logger.warning("Traffic learner: failed to read persisted patterns %s: %s", db_path, e)
+84 -11
View File
@@ -771,6 +771,7 @@ class TestLoadPersistedPatterns:
conn.execute(
"CREATE TABLE memories ("
"id TEXT PRIMARY KEY, content TEXT NOT NULL, "
"user_id TEXT NOT NULL DEFAULT 'default', "
"metadata TEXT NOT NULL DEFAULT '{}', "
"entity_refs TEXT NOT NULL DEFAULT '[]', "
"importance REAL NOT NULL DEFAULT 0.5, "
@@ -816,7 +817,7 @@ class TestLoadPersistedPatterns:
},
],
)
patterns = _load_persisted_patterns_from_sqlite(db)
patterns = _load_persisted_patterns_from_sqlite(db, "default")
assert len(patterns) == 1
assert patterns[0].evidence_count == 5
assert patterns[0].category == PatternCategory.ERROR_RECOVERY
@@ -838,7 +839,7 @@ class TestLoadPersistedPatterns:
},
],
)
patterns = _load_persisted_patterns_from_sqlite(db)
patterns = _load_persisted_patterns_from_sqlite(db, "default")
assert len(patterns) == 1
assert patterns[0].content == "From traffic"
@@ -856,7 +857,7 @@ class TestLoadPersistedPatterns:
},
],
)
patterns = _load_persisted_patterns_from_sqlite(db)
patterns = _load_persisted_patterns_from_sqlite(db, "default")
assert len(patterns) == 1
assert patterns[0].importance == 0.85
@@ -870,7 +871,7 @@ class TestLoadPersistedPatterns:
},
],
)
assert _load_persisted_patterns_from_sqlite(db) == []
assert _load_persisted_patterns_from_sqlite(db, "default") == []
# =============================================================================
@@ -1567,6 +1568,74 @@ class TestSaveRecovery:
assert rows[0][2]["evidence_count"] == 6
class TestUserScopedPersistence:
"""Learners sharing one memory.db only read their own user's rows."""
@pytest.mark.asyncio
async def test_hydration_ignores_other_users_rows(self, tmp_path, monkeypatch):
import json
import sqlite3
monkeypatch.setenv("HOME", str(tmp_path / "home"))
(tmp_path / "home").mkdir()
db = tmp_path / "memory.db"
_init_db(db)
backend = _FakeBackend(db)
content = "Use uv for Python packages."
await backend.save_memory(
content=content,
user_id="alice",
importance=0.7,
metadata={
"source": "traffic_learner",
"category": "preference",
"evidence_count": 3,
"last_seen_at": "2026-02-01T00:00:00+00:00",
},
)
learner = TrafficLearner(backend=backend, user_id="bob", min_evidence=3, dedup_window=1)
await learner.start()
try:
for _ in range(3):
await learner._accumulate(
ExtractedPattern(
category=PatternCategory.PREFERENCE, content=content, importance=0.7
)
)
await _wait_for_saved(learner, 2, db)
finally:
await learner.stop()
with sqlite3.connect(db) as conn:
rows = conn.execute("SELECT user_id, metadata FROM memories").fetchall()
evidence = {user_id: json.loads(meta)["evidence_count"] for user_id, meta in rows}
assert evidence == {"alice": 3, "bob": 3}
@pytest.mark.asyncio
async def test_collected_patterns_exclude_other_users(self, tmp_path):
db = tmp_path / "memory.db"
_init_db(db)
backend = _FakeBackend(db)
for user_id, content in (
("alice", "Alice-only deployment procedure."),
("bob", "Bob's package workflow."),
):
await backend.save_memory(
content=content,
user_id=user_id,
importance=0.7,
metadata={
"source": "traffic_learner",
"category": "preference",
"evidence_count": 5,
},
)
learner = TrafficLearner(backend=backend, user_id="bob")
contents = [p.content for p in learner._collect_all_patterns()]
assert contents == ["Bob's package workflow."]
class TestEvidencePersistence:
@pytest.mark.asyncio
@pytest.mark.parametrize("min_evidence", [1, 2, 5])
@@ -2023,7 +2092,7 @@ class TestCollectAllPatterns:
},
)
learner = TrafficLearner(backend=backend, min_evidence=1)
learner = TrafficLearner(backend=backend, user_id="t", min_evidence=1)
# Same content in accumulator with count=2; hash matches.
p = ExtractedPattern(
category=PatternCategory.ENVIRONMENT,
@@ -2596,6 +2665,7 @@ class TestLoadPersistedPatternsTimestamps:
conn.execute(
"CREATE TABLE memories ("
"id TEXT PRIMARY KEY, content TEXT NOT NULL, "
"user_id TEXT NOT NULL DEFAULT 'default', "
"metadata TEXT NOT NULL DEFAULT '{}', "
"entity_refs TEXT NOT NULL DEFAULT '[]', "
"importance REAL NOT NULL DEFAULT 0.5, "
@@ -2635,7 +2705,7 @@ class TestLoadPersistedPatternsTimestamps:
}
],
)
patterns = _load_persisted_patterns_from_sqlite(db)
patterns = _load_persisted_patterns_from_sqlite(db, "default")
assert len(patterns) == 1
p = patterns[0]
assert p.first_seen_at is not None
@@ -2659,7 +2729,7 @@ class TestLoadPersistedPatternsTimestamps:
}
],
)
patterns = _load_persisted_patterns_from_sqlite(db)
patterns = _load_persisted_patterns_from_sqlite(db, "default")
assert len(patterns) == 1
assert patterns[0].first_seen_at is not None
assert patterns[0].first_seen_at.month == 3
@@ -2695,7 +2765,7 @@ class TestLoadPersistedPatternsTimestamps:
},
],
)
patterns = _load_persisted_patterns_from_sqlite(db)
patterns = _load_persisted_patterns_from_sqlite(db, "default")
assert len(patterns) == 1
p = patterns[0]
assert p.evidence_count == 5
@@ -2714,6 +2784,7 @@ class TestLoadPersistedPatternsTimestamps:
conn.execute(
"CREATE TABLE memories ("
"id TEXT PRIMARY KEY, content TEXT NOT NULL, "
"user_id TEXT NOT NULL DEFAULT 'default', "
"metadata TEXT NOT NULL DEFAULT '{}', "
"entity_refs TEXT NOT NULL DEFAULT '[]', "
"importance TEXT, "
@@ -2736,7 +2807,7 @@ class TestLoadPersistedPatternsTimestamps:
)
conn.commit()
conn.close()
patterns = _load_persisted_patterns_from_sqlite(db)
patterns = _load_persisted_patterns_from_sqlite(db, "default")
assert len(patterns) == 1
assert patterns[0].importance == 0.5
@@ -2749,6 +2820,7 @@ class TestLoadPersistedPatternsTimestamps:
conn.execute(
"CREATE TABLE memories ("
"id TEXT PRIMARY KEY, content TEXT NOT NULL, "
"user_id TEXT NOT NULL DEFAULT 'default', "
"metadata TEXT NOT NULL DEFAULT '{}', "
"entity_refs TEXT NOT NULL DEFAULT '[]', "
"importance REAL NOT NULL DEFAULT 0.5, "
@@ -2756,13 +2828,14 @@ class TestLoadPersistedPatternsTimestamps:
)
# Invalid JSON in metadata
conn.execute(
"INSERT INTO memories VALUES (?,?,?,?,?,?)",
"INSERT INTO memories (id, content, metadata, entity_refs, importance, created_at) "
"VALUES (?,?,?,?,?,?)",
("0", "bullet", "{not json", "[]", 0.5, None),
)
conn.commit()
conn.close()
# Should not raise — the row is simply skipped (no recognizable category).
patterns = _load_persisted_patterns_from_sqlite(db)
patterns = _load_persisted_patterns_from_sqlite(db, "default")
assert patterns == []