Repository navigation
fix(memory): reject duplicate fact ids in imports regardless of entry order - #8153
Conversation
… order A backup containing two entries for the same fact id was accepted or rejected depending only on their order. The duplicate check in _commit_changes_locked consulted the map of prepared writes, but an entry whose normalized content matches the stored fact is skipped from that map - so an unchanged entry followed by an edited duplicate passed the check while the reverse order raised, and the saved snapshot ended up with whichever entry came last. Track every incoming id in a seen-set for duplicate detection, before the unchanged-entry skip. The saved snapshot now survives the rejection in both orders. Fixes bytedance#8150
There was a problem hiding this comment.
🟡 Changes recommended
Capacity trimming can hide duplicate fact IDs during import, allowing invalid backups to save different content depending on entry order rather than being rejected without changing storage.
1 open issue
What changed in this PR
This PR addresses order-dependent duplicate fact ID handling in DeerMem imports by separating duplicate detection from pending writes.
Changes:
- Track every incoming fact ID, including unchanged entries skipped from writes.
- Add a file-backed regression test covering unchanged-first and edited-first imports.
| File | Description |
|---|---|
backend/tests/test_memory_updater.py |
Adds duplicate-import rejection coverage for both entry orders. |
backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/storage.py |
Uses a dedicated ID set to detect duplicates before skipping unchanged facts. |
Review effort: Balanced
| if fact_id in seen_ids: | ||
| raise ValueError(f"Duplicate fact id {fact_id!r} in upserts") | ||
| seen_ids.add(fact_id) |
Copilot review follow-up on bytedance#8153: the storage-level duplicate guard runs after _select_for_capacity, and the capacity policy can drop one of two same-id entries (e.g. lower-confidence copies trimmed to max_facts) - the duplicate then never reaches the guard and the import outcome still depends on entry order. Validate all normalized incoming ids in import_memory_data before capacity selection. The storage-level guard stays as defense in depth. Regression test with max_facts=10 and 9 distinct high-confidence facts plus two same-id copies.
|
Valid catch — fixed in b17d005. |
willem-bd
left a comment
There was a problem hiding this comment.
Twin-PR note: #8151 (head 42a96b0) fixes the same #8150 defect. Comparison at the current heads:
- This PR is the only one that repairs the genuinely broken storage-layer guard in
_commit_changes_locked(unchanged entries were skipped fromprepared, making the check order-dependent). #8151 leaves that latent order-dependence in place for non-import change-set callers. b17d005 also adds the pre-capacity import check that addresses the Copilot review here. - #8151 validates before capacity selection too, but at the updater boundary ahead of both import paths, adds a dedicated
MemoryDuplicateFactIdErrorwith a router mapping to 400 "fact IDs must be unique.", parametrizes manager- and router-level tests over the default and named buckets with store-untouched assertions, and updates CHANGELOG + docs/guide/memory.md. - This PR surfaces the duplicate as a bare
ValueError, which the router maps to the misleading 400 detail "facts must be a list of objects with non-empty content."; its tests cover only the named bucket and never assert store-untouched state; no CHANGELOG/docs entry.
Recommendation: land #8151 as the import-boundary fix, then rebase this PR to keep the storage-layer _commit_changes_locked repair (its unique value) and adopt the same duplicate error type and router mapping — or fold both into one change. Posting inline findings on the current head regardless.
| incoming_ids_seen: set[str] = set() | ||
| for fact in incoming_facts: | ||
| if fact["id"] in incoming_ids_seen: | ||
| raise ValueError(f"Duplicate fact id {fact['id']!r} in import") |
There was a problem hiding this comment.
[P2] Error surface: this bare ValueError falls through to the router's generic catch (memory.py imports except ValueError -> 400), so POST /api/memory/import answers "Invalid memory import: facts must be a list of objects with non-empty content." even though every fact has non-empty content, and the duplicated id is never named. The memory settings page displays that detail verbatim. The twin PR (#8151) received the same P2 in review and fixed it with a dedicated MemoryDuplicateFactIdError mapped to "Invalid memory import: fact IDs must be unique." plus a router test asserting the exact detail and the preserved snapshot. Suggest mirroring that here (or reusing its exception type if both PRs land).
| # on entry order (Copilot review on #8153). | ||
| incoming_ids_seen: set[str] = set() | ||
| for fact in incoming_facts: | ||
| if fact["id"] in incoming_ids_seen: |
There was a problem hiding this comment.
[P3] Coverage: this check lives inside the apply_changes-override branch, so an import whose storage uses the base MemoryStorage save() path with a named agent bypasses both guards and silently persists duplicated ids. #8151's boundary check (right after normalize_memory_data, before the branch split) covers that path and matches the existing validate-before-capacity posture (test_import_validates_revisions_before_capacity_selection). Acceptable for DeerMem-only deployments, but moving the check before the branch split (or noting the limitation) would make the guard complete.
| edited = _fact("Use SQLite instead", "fact_dup") | ||
| facts = [unchanged, edited] if order == "unchanged-first" else [edited, unchanged] | ||
|
|
||
| with pytest.raises(ValueError, match="Duplicate fact id"): |
There was a problem hiding this comment.
[P3] Both new tests run agent_name="researcher" only and stop at pytest.raises, so the store-untouched guarantee claimed in the description ("The saved snapshot survives the rejection in both orders") is never asserted, and the default bucket (agent_name=None; DeerMem.import_memory resolves it to DEFAULT_AGENT_BUCKET, the bucket /api/memory/import uses without an agent param) is unexercised. Suggest parametrizing over [None, "researcher"] the way test_memory_import.py does and asserting the reloaded snapshot still equals the seeded one after rejection.
…x/deermem-import-duplicate-ids
willem-bd review on bytedance#8153, three follow-ups: 1. P2: the bare ValueError fell through to the router's generic catch, so POST /api/memory/import answered with the facts-array message even when every fact had non-empty content. Add MemoryDuplicateFactIdError (same type as bytedance#8151) at the manager boundary and map it to its own 400 detail that names the duplicated id; router test asserts the exact detail. 2. P3: the duplicate check lived inside the apply_changes-override branch, so the base MemoryStorage save() path bypassed both guards. Move it before the branch split, right after normalize_memory_data, matching bytedance#8151's validate-before-capacity posture. 3. P3: parametrize the order-dependence regression over the default bucket (agent_name=None) and "researcher", and assert the seeded snapshot survives the rejection in both orders.
|
All three follow-ups addressed in 6ae556a:
188 tests pass across the router and updater suites. |
willem-bd
left a comment
There was a problem hiding this comment.
Follow-up review of 6ae556a (head moved from b17d005 mostly via a main merge; one functional commit). All three prior findings are addressed: the P2 is fixed with a dedicated MemoryDuplicateFactIdError mapped to its own 400 detail naming the duplicated id (router test pins the exact detail); the P3 branch-coverage gap is fixed by moving the gate before the apply_changes/save() branch split; the P3 test gap is narrowed by parametrizing over [None, "researcher"] and both orders. The storage-layer seen_ids hardening is retained and now order-independent for all change-set callers, and the changelog/docs entries were dropped so #8151 carries the import-fix entry — no duplication. Verified by execution: tests/test_memory_updater.py + tests/test_memory_router.py fully green (188 passed) against a scratch archive of this head with PYTHONPATH pinned to it.
Twin-PR status vs the prior verdict: diverged from the storage-only split — this head now carries a strengthened import gate (pre-capacity, both buckets, both storage paths) in addition to the storage hardening, and #8151 (still unmerged, head 61d0db1) carries its own gate. The MemoryDuplicateFactIdError definitions land at the same manager.py anchor with identical bytes (clean merge), but the two PRs add different gate code at the same updater.py anchor and map the error to different router details ("fact IDs must be unique." vs the verbatim duplicate-id message), so whichever lands second needs conflict resolution and one router-detail test rewritten. This head's gate is the broader of the two (it also explicitly covers the default bucket, which #8151 leaves to the storage guard), so converging on this gate and letting #8151 keep changelog/docs/export would be the simplest landing order. Two new P3s below.
| updater.import_memory_data(_make_memory(facts=facts), agent_name=agent_name) | ||
|
|
||
| # The rejection must not have touched the seeded snapshot. | ||
| snapshot_after_seed = updater.get_memory_data(agent_name=agent_name) |
There was a problem hiding this comment.
[P3] This assertion cannot fail: MemoryUpdater.get_memory_data is literally return self._storage.load(...) (updater.py:908-910), and both reads happen after the rejected import, so the next line compares storage.load against itself. A regression that partially applied the duplicate before rejecting would leave both reads equally mutated and pass. The docstring's (and the reply thread's) "seeded snapshot must survive the rejection" property is never actually pinned. Capture the expectation right after seeding — expected = storage.load(agent_name=agent_name) before the pytest.raises block, then assert storage.load(agent_name=agent_name) == expected after it — which matches the shape of #8151's test in test_memory_import.py.
| # normalized candidate) is skipped from `prepared`, so a duplicate | ||
| # after it would otherwise pass and the import outcome would depend | ||
| # on the order of the two entries. | ||
| if fact_id in seen_ids: |
There was a problem hiding this comment.
[P3] This hardening is this PR's unique contribution vs #8151, but nothing pins it anymore: the updater's pre-gate now rejects import duplicates before storage is touched, so the order test exercises only the gate, and no test drives _commit_changes_locked/apply_changes with an unchanged duplicate first — reverting this hunk would keep the suite green. A direct storage-level regression test (change_set with [unchanged, edited] on the same id, asserting rejection and an untouched store) would anchor it. Also consider raising MemoryDuplicateFactIdError here via a function-local import (as import_memory_data does) instead of bare ValueError: non-import change-set callers currently get only the generic ValueError mapping, though the subclass relationship keeps existing catches working.
…tion willem-bd review follow-ups on bytedance#8153: 1. The snapshot-survival assertion compared storage.load against get_memory_data, which is itself storage.load - both reads happened after the rejected import, so a regression that partially applied the duplicate would pass. Capture the seeded snapshot before the rejected import and compare against it. 2. The updater gate rejects import duplicates before storage is touched, so nothing exercised the storage-level guard in _commit_changes_locked with an unchanged duplicate first - reverting it would keep the suite green. Add a direct apply_changes regression test; verified it fails with the guard removed.
|
Both P3s addressed in 83dc5bc:
|
willem-bd
left a comment
There was a problem hiding this comment.
Re-review of new head 83dc5bc (one commit over the previously reviewed 6ae556a: "test(memory): pin the storage duplicate guard and fix the no-op assertion"). All six prior findings are addressed on this head: the Copilot capacity-trimming hole is closed by the pre-capacity updater gate plus an over-capacity regression test; the duplicate now surfaces as MemoryDuplicateFactIdError mapped to its own 400 detail (router test pins the exact message); the gate precedes the apply_changes/save() branch split, covering the base save() path; tests parametrize [None, "researcher"] over both orders; the snapshot assertion is no longer tautological (pre-import capture); and the storage-layer seen_ids hardening is pinned directly. Verified by execution against a scratch archive of this head with PYTHONPATH pinned to it: tests/test_memory_updater.py + tests/test_memory_router.py fully green (189 passed), and reverting the storage hunk fails test_storage_apply_changes_rejects_unchanged_duplicate_first while the import-order test still passes (the updater gate covers imports), confirming the storage test pins this PR's unique contribution. Keeping bare ValueError in _commit_changes_locked is fine - non-import change-set callers keep the generic mapping and the ValueError subclass preserves existing catches. Two new minor findings below. Twin-PR standing note unchanged: #8151 defines the identical MemoryDuplicateFactIdError at the same manager.py anchor with a different router detail, so whichever lands second resolves the conflict.
| from app.gateway.persistent_writes import run_drained_write | ||
| from app.gateway.secret_masking import mask_secret_values, normalize_config_key | ||
| from deerflow.agents.memory import MemoryConflictError, MemoryCorruptionError, MemoryManager, get_memory_manager | ||
| from deerflow.agents.memory.manager import MemoryDuplicateFactIdError |
There was a problem hiding this comment.
nit (convention): this deep import diverges from line 14's package-facade import and from the established manager-error surface - MemoryManagerError, MemoryReadError, MemoryConflictError, and MemoryCorruptionError are all re-exported from deerflow/agents/memory/init.py, but the new MemoryDuplicateFactIdError is not. Adding it to that re-export list (and folding this into line 14's import) keeps the public error contract in one place; the deep imports in the two new tests could then use the facade too.
|
|
||
| unchanged = _fact("Keep PostgreSQL", "fact_dup", revision=1) | ||
| edited = _fact("Use SQLite instead", "fact_dup", revision=1) | ||
| with pytest.raises(ValueError, match="Duplicate fact id"): |
There was a problem hiding this comment.
Residual from the earlier storage-guard thread: this test pins rejection but not the untouched-store half that was requested alongside it, so a future regression that partially applies the first entry before raising would still pass. Capturing the snapshot right after seeding (expected = storage.load(agent_name="researcher")) and asserting storage.load(agent_name="researcher") == expected after this block - the same shape test_import_duplicate_id_rejected_regardless_of_entry_order uses - would close it; today nothing is written before the loop-level raise, so the assertion should hold.
…x/deermem-import-duplicate-ids # Conflicts: # backend/app/gateway/routers/memory.py # backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/updater.py
|
Merged latest main (#8151 landed while this branch was in flight) and reconciled the two implementations:
193 tests pass across the router and updater suites. The remaining delta vs #8151 is this PR's unique surface: the order-dependence regression (both orders), the over-capacity pre-capacity validation test, and the storage-guard pin. |
… import willem-bd review follow-ups on bytedance#8153: 1. The storage-guard regression test pinned rejection but not the untouched-store half: capture the seeded snapshot right after seeding and assert storage.load still equals it after the rejection, so a regression that partially applies the first entry before raising fails. 2. The router regression test imported MemoryDuplicateFactIdError from the manager module directly; use the package-facade import consistent with the other manager-error usage (the symbol is already re-exported from deerflow.agents.memory since bytedance#8151).
|
Both follow-ups addressed in 8cde4a5:
193 tests pass. |
| """A MemoryDuplicateFactIdError surfaces its own detail verbatim, not the | ||
| generic facts-array message (Copilot P2 on #8153).""" | ||
|
|
||
|
|
There was a problem hiding this comment.
[P2] The extra blank line after the docstring makes ruff format --check fail on this head with the repo-pinned Ruff 0.15.12, so lint-backend will fail. I'd drop this mock test altogether. The merged #8151 already drives the real import route with duplicate IDs and asserts the same 400 response plus an unchanged snapshot. This test's name and docstring also imply the response includes the duplicated ID, while the assertion checks the generic uniqueness message. The direct apply_changes() regression is worth keeping. I verified it fails on the PR base and passes here.
ShenAC-SAC review on bytedance#8153: bytedance#8151 already drives the real import route with duplicate IDs and asserts the same 400 response plus an unchanged snapshot, and the mock test's docstring implied a detail the assertion did not check. The direct apply_changes() regression is kept. Also removes the blank line after the docstring that tripped ruff format --check on the repo-pinned Ruff version.
|
Addressed in 7a6a5a3: dropped the mock router test per your P2 (#8151 already drives the real import route and asserts the same 400 response plus the unchanged snapshot, and the docstring implied a detail the assertion did not check). The direct apply_changes() regression is kept. The blank line after the docstring is also gone, so ruff format --check passes on the repo-pinned Ruff version. 192 tests pass across the router and updater suites. |
| app = make_authed_test_app() | ||
| app.include_router(memory.router) | ||
| mock_mgr = MagicMock() | ||
| mock_mgr.import_memory.side_effect = MemoryDuplicateFactIdError("Duplicate fact id 'fact_dup' in memory import") | ||
| with patch("app.gateway.routers.memory.get_memory_manager", return_value=mock_mgr): | ||
| with TestClient(app) as client: | ||
| response = client.post( | ||
| "/api/memory/import", | ||
| json={"facts": [{"id": "fact_dup", "content": "x", "category": "context", "confidence": 0.9, "createdAt": "2026-03-20T00:00:00Z", "source": "manual"}]}, | ||
| ) | ||
| assert response.status_code == 400 | ||
| assert response.json()["detail"] == "Invalid memory import: fact IDs must be unique." |
There was a problem hiding this comment.
[P3] The mock import test body still runs inside test_clear_route_keeps_working_for_windows_reserved_agent_name after the function definition and docstring were removed. Please delete this entire block and remove MemoryDuplicateFactIdError from the imports in this file. #8151 already covers the duplicate-ID response through the real import route.
ShenAC-SAC review: my earlier deletion removed the function definition and docstring but left the test body running inside test_clear_route_keeps_working_for_windows_reserved_agent_name. Remove the whole block and the now-unused MemoryDuplicateFactIdError import; bytedance#8151 already covers the duplicate-ID response through the real import route.
|
Fixed in dc4721d — my earlier deletion removed the function definition and docstring but left the test body orphaned inside test_clear_route_keeps_working_for_windows_reserved_agent_name, exactly as you flagged. The whole block and the now-unused MemoryDuplicateFactIdError import are removed. 192 tests pass across the router and updater suites. |

Fixes #8150
Problem
A backup containing two entries for the same fact id was accepted or rejected depending only on their order:
The duplicate check in
_commit_changes_lockedconsulted the map of prepared writes (prepared), but an entry whose normalized content matches the stored fact is skipped from that map — so an unchanged entry followed by an edited duplicate passed the check while the reverse order raised. The saved snapshot ended up with whichever entry came last.Fix
Track every incoming id in a
seen_idsset for duplicate detection, before the unchanged-entry skip. The saved snapshot survives the rejection in both orders.Tests
test_import_duplicate_id_rejected_regardless_of_entry_order(tmp-pathFileMemoryStorage, both orders): fails onmain(unchanged-first accepted), passes with the fix. Fulltests/test_memory_updater.py: 103 passed.ruff check+ruff format --checkclean.