Skip to content

fix(memory): reject duplicate fact IDs during import - #8151

Merged
WillemJiang merged 6 commits into
bytedance:mainfrom
Wang-Zephyr:fix/memory-import-duplicate-facts
Nov 12, 2026
Merged

WillemJiang merged 6 commits into
bytedance:mainfrom
Wang-Zephyr:fix/memory-import-duplicate-facts

Conversation

@Wang-Zephyr

@Wang-Zephyr Wang-Zephyr commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #8150

Why

A backup with two records for the same fact ID can be accepted when the first record matches saved memory. That record schedules no write, so the second can pass the storage duplicate check and overwrite the fact. Reversing the same records rejects the backup.

What changed

Check normalized fact IDs at the import boundary, before loading the destination snapshot or applying the capacity policy. A backup with duplicate IDs is rejected in either order and leaves the saved snapshot intact.

Surface area

  • Default behavior change — DeerMem replacement imports reject duplicate IDs

Bug fix verification

backend/tests/test_memory_import.py::test_import_rejects_duplicate_fact_ids_without_replacing_memory covers both orders in the default and named-agent buckets. The two unchanged-first cases failed on d9b2cb4b. All four pass with the fix, including checks that the saved snapshot is preserved.

Validation

  • Memory import and router suites: 136 passed.
  • Ruff lint, format, and git diff --check passed.

AI assistance

Tool(s) used: OpenAI Codex.

How you used it: Investigated and reproduced the import behavior, implemented the validation and regression tests, and drafted the issue and PR.

  • I've read and understand every line of this change and take responsibility for it — it's not unreviewed AI output.

@Wang-Zephyr
Wang-Zephyr marked this pull request as ready for review November 11, 2026 09:49
@github-actions github-actions Bot added area:agents Agents, subagents, graph wiring, prompts, langgraph.json area:docs Documentation and Markdown only 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:11

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 remain for the change rejecting duplicate fact IDs during memory imports.

No open issues 🎉

What changed in this PR

This PR addresses #8150 by rejecting duplicate fact IDs during DeerMem backup imports, preventing order-dependent overwrites of saved memory.

Changes:

  • Validates normalized fact IDs before loading the destination snapshot or applying capacity selection.
  • Adds regression coverage for both entry orders in default and named-agent buckets, checking that rejected imports preserve saved memory.
  • Documents duplicate-ID rejection in the memory guide and changelog.
File Description
docs/​guide/​memory.md Documents duplicate-ID rejection during imports.
CHANGELOG.md Records the import fix and links to #8150.
backend/​tests/​test_memory_import.py Tests entry-order independence and snapshot preservation across both bucket types.
backend/​packages/​harness/​deerflow/​agents/​memory/​backends/​deermem/​deermem/​core/​updater.py Adds duplicate-ID validation before snapshot loading and capacity selection.

Review effort: Balanced

for fact in memory_data["facts"]:
fact_id = fact["id"]
if fact_id in seen_ids:
raise ValueError(f"Duplicate fact id {fact_id!r} in memory import")

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] Report duplicate fact IDs in the import response

POST /api/memory/import maps this ValueError to Invalid memory import: facts must be a list of objects with non-empty content., which the memory settings page displays verbatim. I verified with the Gateway route and real DeerMem storage that both entry orders now return that message even when every fact has non-empty content. The unchanged-first case previously returned 200 and now gives the user no indication that they need to remove a duplicate ID.

Could the Gateway map this validation error to an HTTP 400 detail that identifies duplicate fact IDs? A router regression test can assert that detail and that the saved snapshot stays intact.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching the misleading error. Fixed in 42a96b0. The Gateway now maps the duplicate-ID validation error to HTTP 400 with Invalid memory import: fact IDs must be unique. The router regression uses real DeerMem storage and verifies the response and the preserved snapshot for both entry orders in the default and named-agent buckets. The memory router, import, and manager interface suites passed (168 tests).

@github-actions github-actions Bot added the area:backend Gateway / runtime / core backend under backend/ label 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.

Verified against head 42a96b0a: reproduced the PR's claim on base d9b2cb4b (both unchanged-first manager cases accept the duplicate; changed-first already rejected), and at head tests/test_memory_import.py + tests/test_memory_router.py pass (140 tests), including both orders for the default and named-agent buckets with export-equality checks that the store is untouched.

The detection point is right per the #8131 pattern: the gate runs in import_memory_data after normalize_memory_data and before the destination snapshot load and _select_for_capacity, so rejection never touches storage and over-capacity trimming cannot hide a duplicate. It is set-based, hence order-independent; _normalize_legacy_import_fact guarantees every normalized fact a non-empty stripped string id, so the fact["id"] access is safe (missing/blank ids get generated uuids and cannot collide); and skipping the gate when agent_name is None is correct because that path discards facts entirely. The MemoryDuplicateFactIdError clause is correctly ordered before the generic ValueError mapping, and the facade always resolves a non-None bucket name, so every import_memory call is covered.

Twin comparison with #8153 (storage-layer seen_ids fix in _commit_changes_locked): both make rejection order-independent for imports, but this PR detects earlier (pre-capacity, pre-snapshot-load), so it additionally closes the over-capacity trim hole and covers the base-MemoryStorage save path that has no storage-layer check; it also gives the Gateway a distinct 400 detail with router regression tests plus docs/changelog, where #8153 leaves duplicates surfacing as the misleading generic facts must be a list of objects... message and Copilot's capacity-trim finding open. Recommending this PR lands; #8153's storage-layer hardening is still worth keeping as defense-in-depth for non-import apply_changes callers (update flows) and can rebase on top of this.

Comment thread CHANGELOG.md Outdated
each group. ([#7794])

- **memory:** DeerMem rejects backups with duplicate fact IDs before replacing
saved memory, regardless of entry order. ([#8150](https://github.com/bytedance/deer-flow/issues/8150))

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: this is the only Unreleased entry using an inline URL, and it links the issue rather than the PR. Every sibling entry uses reference-style PR links (e.g. ([#8131]) with a [#8131]: https://github.com/bytedance/deer-flow/pull/8131 definition at the bottom of the file). Suggest ([#8151]) plus a matching [#8151] definition for consistency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated the Unreleased entry to use ([#8151]) and added the matching PR link definition in 0018723. git diff --check passed.

from datetime import UTC, datetime, timedelta
from typing import Any

from deerflow.agents.memory.manager import MemoryDuplicateFactIdError

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.

[P1] Keep the DeerMem core independent of the host package

This import adds a second DeerFlow dependency inside the vendorable backend. The portability contract requires consumers to copy the backend and repoint only the manager import in deer_mem.py. A consumer without DeerFlow installed will still hit this import when loading the copied backend. CI shard 1 fails test_portability_only_abc_contract_imports_deerflow (2 == 1), and I reproduced it locally on 61d0db1.

Please raise a DeerMem-local duplicate-ID exception here and translate it to MemoryDuplicateFactIdError in deer_mem.py, alongside the existing exception translations. Keep the host import confined to that adapter, update the vendored manager fixture for the new contract symbol, and rerun the portability and memory import/router tests.

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.

One targeted regression check for the same fix: after repointing the adapter import in test_portability_vendor_to_other_agent, import a backup with duplicate IDs and assert that it raises otheragent.manager.MemoryDuplicateFactIdError and leaves the saved snapshot unchanged. The existing successful round-trip runs with DeerFlow available, so it does not exercise the new error translation against the vendored host contract.

Luckyou-d added a commit to Luckyou-d/deer-flow that referenced this pull request Nov 11, 2026
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.

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

Reconciling follow-up now that both heads moved (#8151 -> 61d0db1, #8153 -> 6ae556a); everything below verified by execution against scratch archives of both heads.

Changed ground truth, acknowledged: (1) the changelog-link nit from my earlier review is fixed at 61d0db1 (([#8151]) reference + link definition); the memory code is otherwise byte-identical to 42a96b0 and the memory suites are green here (140 passed). (2) #8153's rebase diverged from the storage-only split its earlier verdict assumed: its head now carries an unconditional pre-capacity import gate (same post-normalize_memory_data anchor) plus the kept storage-layer seen_ids hardening, defines the same MemoryDuplicateFactIdError (manager.py definitions are byte-identical across the two PRs - clean merge), and maps it to a 400 detail naming the duplicated id with a pinned router test. 188 memory tests green there (reproduced independently).

Default-bucket ruling (the open semantic question), probed at both heads: there is no Gateway-level divergence - the facade resolves agent_name=None to DEFAULT_AGENT_BUCKET, so both gates fire for default-bucket imports through manager.import_memory. The only uncovered path is the raw MemoryUpdater.import_memory_data(..., agent_name=None) internal call, which wipes the facts array; there a duplicate payload is provably harmless (the accepted import leaves surviving facts []), so #8151's skip is not a correctness hole. #8153's unconditional gate is still the better final contract: one bucket-independent "duplicate ids are malformed input" rule in the strict-import posture of #8131, no latent asymmetry for direct updater callers, and it stays correct if the wipe semantics ever change.

Recommendation (this reverses my earlier land-#8151 verdict, which was correct against #8153's old storage-only head): converge on #8153's head - it functionally subsumes this PR's core (pre-capacity gate, dedicated error type, 400 mapping, both buckets) and uniquely keeps the storage-layer hardening - while #8151 rebases (or closes after porting) to carry its unique low-conflict assets onto that gate: the CHANGELOG entry + [#8151] definition, the docs/guide/memory.md line, the deerflow.agents.memory __init__ export of MemoryDuplicateFactIdError (#8153 lacks it), and the manager-level facade tests in test_memory_import.py (real DeerMem storage, export-equality store-untouched, both buckets and orders - #8153's router test is mock-based and its store-untouched assertion compares two reads of the same unwritten store). Whichever lands second resolves three things: the updater.py gate anchor (adopt the unconditional gate), the router except-clause anchor (adopt the verbatim-id detail), and this PR's router-detail test, pinned to the old static message, rewritten to the verbatim-id form.

@WillemJiang

Copy link
Copy Markdown
Collaborator

@Wang-Zephyr, please check out the unit test error fix.

Copy link
Copy Markdown
Contributor Author

Thanks, @WillemJiang. I addressed the unit-test failure in 0e2e14f. Duplicate-ID validation now raises a DeerMem-local exception, and the adapter translates it to the public manager error. This keeps the host import at the adapter boundary. I reran the portability, memory import, router, and manager interface suites locally: 213 passed, including the previously failing portability test. The new GitHub Actions run is awaiting approval.

@WillemJiang WillemJiang added this to the 2.3.0 milestone Nov 12, 2026
@WillemJiang
WillemJiang merged commit b80191f into bytedance:main Nov 12, 2026
17 checks passed
Luckyou-d added a commit to Luckyou-d/deer-flow that referenced this pull request Nov 12, 2026
Luckyou-d added a commit to Luckyou-d/deer-flow that referenced this pull request Nov 12, 2026
… 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 added a commit to Luckyou-d/deer-flow that referenced this pull request Nov 12, 2026
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 added a commit to Luckyou-d/deer-flow that referenced this pull request 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.
WillemJiang pushed a commit that referenced this pull request Nov 12, 2026
… order (#8153)

* fix(memory): reject duplicate fact ids in imports regardless of entry 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 #8150

* fix(memory): validate duplicate import ids before capacity selection

Copilot review follow-up on #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.

* fix(memory): surface duplicate fact id errors with their own detail

willem-bd review on #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 #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 #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.

* test(memory): pin the storage duplicate guard and fix the no-op assertion

willem-bd review follow-ups on #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.

* style(memory): apply ruff fixes after #8151 merge resolution

* test(memory): assert untouched store in the storage-guard pin; facade import

willem-bd review follow-ups on #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 #8151).

* test(memory): drop the mock router duplicate-id test

ShenAC-SAC review on #8153: #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.

* test(memory): remove the orphaned mock-router test body

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;
#8151 already covers the duplicate-ID response through the real import
route.
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 area:backend Gateway / runtime / core backend under backend/ area:docs Documentation and Markdown only 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

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