Skip to content

fix(memory): reject duplicate fact ids in imports regardless of entry order - #8153

Merged
WillemJiang merged 10 commits into
bytedance:mainfrom
Luckyou-d:fix/deermem-import-duplicate-ids
Nov 12, 2026
Merged

WillemJiang merged 10 commits into
bytedance:mainfrom
Luckyou-d:fix/deermem-import-duplicate-ids

Conversation

@Luckyou-d

Copy link
Copy Markdown
Contributor

Fixes #8150

Problem

A backup containing two entries for the same fact id was accepted or rejected depending only on their order:

order result saved content
unchanged, edited accepted Use SQLite instead
edited, unchanged Duplicate fact id Keep PostgreSQL

The duplicate check in _commit_changes_locked consulted 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_ids set 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-path FileMemoryStorage, both orders): fails on main (unchanged-first accepted), passes with the fix. Full tests/test_memory_updater.py: 103 passed.

ruff check + ruff format --check clean.

… 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
@github-actions github-actions Bot added area:agents Agents, subagents, graph wiring, prompts, langgraph.json needs-validation Touches front/back contract surface; needs real-path validation risk:high High risk: backend API, agents, sandbox, auth, deps, CI size/S PR changes 20-100 lines labels Nov 11, 2026
@ShenAC-SAC
ShenAC-SAC requested a balanced review from Copilot November 11, 2026 10:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment on lines +1362 to +1364
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.
@Luckyou-d

Copy link
Copy Markdown
Contributor Author

Valid catch — fixed in b17d005. import_memory_data now validates all normalized incoming ids before _select_for_capacity, so an over-capacity backup can no longer have one of two same-id entries trimmed away and slip the duplicate past the storage guard. The storage-level guard stays as defense in depth. Regression test added: max_facts=10 with 9 distinct high-confidence facts plus two same-id copies — fails on 6ed664e, passes with the fix. 104 tests in the suite pass.

@willem-bd willem-bd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 from prepared, 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 MemoryDuplicateFactIdError with 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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread backend/tests/test_memory_updater.py Outdated
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"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

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.
@Luckyou-d

Copy link
Copy Markdown
Contributor Author

All three follow-ups addressed in 6ae556a:

  1. P2 (error surface) — MemoryDuplicateFactIdError added at the manager boundary (same type as fix(memory): reject duplicate fact IDs during import #8151, so both PRs converge) and mapped in the router to its own 400 detail naming the duplicated id. Router test asserts the exact detail: Invalid memory import: Duplicate fact id 'fact_dup' in memory import.
  2. P3 (coverage) — the duplicate check moved before the branch split (right after normalize_memory_data), so the base MemoryStorage save() path is covered too, matching the validate-before-capacity posture of test_import_validates_revisions_before_capacity_selection.
  3. P3 (test parametrization) — the order-dependence regression is now parametrized over [None, "researcher"] and asserts the reloaded snapshot still equals the post-seed state after rejection in both orders.

188 tests pass across the router and updater suites.

@github-actions github-actions Bot added area:backend Gateway / runtime / core backend under backend/ size/M PR changes 100-300 lines and removed size/S PR changes 20-100 lines labels Nov 11, 2026

@willem-bd willem-bd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread backend/tests/test_memory_updater.py Outdated
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.
@Luckyou-d

Copy link
Copy Markdown
Contributor Author

Both P3s addressed in 83dc5bc:

  1. No-op assertion — the seeded snapshot is now captured before the rejected import and compared after, so a partially-applied duplicate regression fails instead of comparing storage.load against itself.
  2. Storage guard unpinned — added test_storage_apply_changes_rejects_unchanged_duplicate_first, a direct apply_changes call with the unchanged duplicate first; verified it fails when the seen_ids guard is removed from _commit_changes_locked.

@willem-bd willem-bd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread backend/app/gateway/routers/memory.py Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@github-actions github-actions Bot removed the area:backend Gateway / runtime / core backend under backend/ label Nov 12, 2026
@Luckyou-d

Copy link
Copy Markdown
Contributor Author

Merged latest main (#8151 landed while this branch was in flight) and reconciled the two implementations:

  • Kept this PR's pre-branch-split check (covers the base MemoryStorage save() path per the earlier P3) and the storage-level guard + both regression tests (the two P3s from 00:27).
  • Adopted fix(memory): reject duplicate fact IDs during import #8151's conventions now that they are canonical: the updater raises its local DuplicateFactIdError and deer_mem._call_backend translates it into the manager-boundary MemoryDuplicateFactIdError, which the router maps to "Invalid memory import: fact IDs must be unique." The router test now asserts that exact detail.
  • Removed the dead DuplicateFactIdError-vs-MemoryDuplicateFactIdError duplication by keeping the local raise path intact.

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).
@Luckyou-d

Copy link
Copy Markdown
Contributor Author

Both follow-ups addressed in 8cde4a5:

  1. Untouched-store assertion — the storage-guard test now captures the seeded snapshot right after seeding (expected = storage.load(...)) and asserts storage.load(...) == expected after the rejection, matching the shape of test_import_duplicate_id_rejected_regardless_of_entry_order.
  2. Facade import — the router regression test now imports MemoryDuplicateFactIdError from deerflow.agents.memory (already re-exported since fix(memory): reject duplicate fact IDs during import #8151), consistent with the other manager-error usage.

193 tests pass.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues block the duplicate fact ID import fix.

1 open issue

Review effort: Balanced

Comment thread backend/tests/test_memory_router.py Outdated
"""A MemoryDuplicateFactIdError surfaces its own detail verbatim, not the
generic facts-array message (Copilot P2 on #8153)."""


Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.
@Luckyou-d

Copy link
Copy Markdown
Contributor Author

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.

Comment thread backend/tests/test_memory_router.py Outdated
Comment on lines +1204 to +1215
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."

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 ShenAC-SAC added the reviewing A maintainer is reviewing this PR label Nov 12, 2026
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.
@Luckyou-d

Copy link
Copy Markdown
Contributor Author

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.

@WillemJiang
WillemJiang merged commit eb97327 into bytedance:main Nov 12, 2026
22 checks passed
@WillemJiang WillemJiang added this to the 2.3.0 milestone Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agents Agents, subagents, graph wiring, prompts, langgraph.json needs-validation Touches front/back contract surface; needs real-path validation reviewing A maintainer is reviewing this PR risk:high High risk: backend API, agents, sandbox, auth, deps, CI size/M PR changes 100-300 lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] DeerMem backup import can accept duplicate fact IDs depending on their order

5 participants