Repository navigation
fix(backend): resolve duplicate memory adds to the existing identical row - #12524
Conversation
… row POST /v3/memories 500s at over a thousand requests per day since the #12084 deploy (2026-08-28): canonical write failed: ApplyStatus.invalid_patch (add patch new_memory_id already exists), raised from create_memory through write_canonical_extraction_memory. Manual/API memory ids derive deterministically from content, but operation identity folds the observed head commit into the operation id, so a duplicate submission is replay-idempotent only while the account head has not moved. Any other canonical write in between makes the duplicate propose a fresh operation whose add collides with the existing row id — and a client re-sending the same memory (retry, sync replay, re-import) gets a 500 for a write that is already complete. Resolve the collision at the write boundary: when the add's target row exists with identical content and is still active, report the write complete with the existing id and leave the row untouched. A collision with different content (a client-supplied id reused for new text) or against a non-active row keeps failing, so a resurrected id can never masquerade as a fresh create; the privacy-deleted receipt branch is unchanged and still refuses. Failure-Class: new Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
2 issues found across 3 files
Confidence score: 3/5
backend/utils/memory/canonical_memory_adapter.pycan resolve a duplicate to an ID after the row is no longer active, or convert a valid replay into a 500 when deletion or updates race the collision check; make the second read atomic with the collision check.backend/tests/unit/test_ws_j_delete_privacy.pydoes not cover the stated invariant for identical content when the existing row is non-active, leaving the race-sensitive behavior under-tested; add that scenario before relying on the fix.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/tests/unit/test_ws_j_delete_privacy.py">
<violation number="1" location="backend/tests/unit/test_ws_j_delete_privacy.py:977">
P3: The two new tests cover the idempotent-replay case (identical content, active row, resolves to existing id) and the different-content collision case, but the fix's third stated invariant — identical content on a non-active row must keep failing — has no regression test. `_existing_identical_add_row` explicitly returns None when `item.status != MemoryItemStatus.active`, and the PR lists "identical content but non-active rows … remain failing as before" as a key edge case reviewers should confirm. Add a test that writes a row, marks it non-active (e.g. `hidden`/`superseded`), then resubmits identical content and asserts it still raises "already exists" and leaves the row untouched, mirroring `test_reusing_a_row_id_for_different_content_still_fails`.</violation>
</file>
<file name="backend/utils/memory/canonical_memory_adapter.py">
<violation number="1" location="backend/utils/memory/canonical_memory_adapter.py:1430">
P2: When a privacy deletion or row update races a duplicate submission, this second read is not atomic with the collision check: it can return an ID after the row is no longer active, or turn a valid replay into a 500. Carry the authoritative row validation through the apply transaction or revalidate under a concurrency fence before returning.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| """ | ||
| if result.status != ApplyStatus.invalid_patch or result.reason != _DUPLICATE_ADD_ROW_REASON: | ||
| return None | ||
| snapshot = db_client.document(f"{MemoryCollections(uid=uid).memory_items}/{memory_id}").get() |
There was a problem hiding this comment.
P2: When a privacy deletion or row update races a duplicate submission, this second read is not atomic with the collision check: it can return an ID after the row is no longer active, or turn a valid replay into a 500. Carry the authoritative row validation through the apply transaction or revalidate under a concurrency fence before returning.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/canonical_memory_adapter.py, line 1430:
<comment>When a privacy deletion or row update races a duplicate submission, this second read is not atomic with the collision check: it can return an ID after the row is no longer active, or turn a valid replay into a 500. Carry the authoritative row validation through the apply transaction or revalidate under a concurrency fence before returning.</comment>
<file context>
@@ -1401,6 +1402,42 @@ def _canonical_extraction_apply_write(
+ """
+ if result.status != ApplyStatus.invalid_patch or result.reason != _DUPLICATE_ADD_ROW_REASON:
+ return None
+ snapshot = db_client.document(f"{MemoryCollections(uid=uid).memory_items}/{memory_id}").get()
+ if not getattr(snapshot, "exists", False):
+ return None
</file context>
| assert retired_evidence == [] | ||
|
|
||
|
|
||
| def test_resubmitting_an_identical_manual_memory_resolves_to_the_existing_row(monkeypatch, canonical_db): |
There was a problem hiding this comment.
P3: The two new tests cover the idempotent-replay case (identical content, active row, resolves to existing id) and the different-content collision case, but the fix's third stated invariant — identical content on a non-active row must keep failing — has no regression test. _existing_identical_add_row explicitly returns None when item.status != MemoryItemStatus.active, and the PR lists "identical content but non-active rows … remain failing as before" as a key edge case reviewers should confirm. Add a test that writes a row, marks it non-active (e.g. hidden/superseded), then resubmits identical content and asserts it still raises "already exists" and leaves the row untouched, mirroring test_reusing_a_row_id_for_different_content_still_fails.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_ws_j_delete_privacy.py, line 977:
<comment>The two new tests cover the idempotent-replay case (identical content, active row, resolves to existing id) and the different-content collision case, but the fix's third stated invariant — identical content on a non-active row must keep failing — has no regression test. `_existing_identical_add_row` explicitly returns None when `item.status != MemoryItemStatus.active`, and the PR lists "identical content but non-active rows … remain failing as before" as a key edge case reviewers should confirm. Add a test that writes a row, marks it non-active (e.g. `hidden`/`superseded`), then resubmits identical content and asserts it still raises "already exists" and leaves the row untouched, mirroring `test_reusing_a_row_id_for_different_content_still_fails`.</comment>
<file context>
@@ -973,6 +974,63 @@ def test_readding_a_deleted_manual_memory_lands_on_a_fresh_evidence_identity(mon
assert retired_evidence == []
+def test_resubmitting_an_identical_manual_memory_resolves_to_the_existing_row(monkeypatch, canonical_db):
+ """Prod regression (#12084 deploy, 2026-08-28 onward): duplicate POST /v3/memories 500s.
+
</file context>
## What changed and why
Live `DELETE /v3/memories/{id}` was 500-ing because two concurrent
deletes for one account contend on the exclusive
`destructive_operation_gate`. The router only mapped `ValueError` → 404;
`DestructiveOperationInProgress` escaped as 500. The Windows bulk
cleaner made this worse with `CONCURRENCY = 4` single deletes (three of
every four in-flight requests lose the gate, then retry 5xx).
Smallest fix that closes it: keep the 6h exclusive gate (do not weaken
account deletion / legal holds), map contention to **409** +
`Retry-After: 2` + `detail: account_gate_busy` on the single, batch, and
cascade-conversation delete routes, and send Windows bulk cleanup
through `DELETE /v3/memories/batch` in chunks of ≤100 so one request
holds the gate once.
Closes SCA-441
## Product invariants affected
- INV-MEM-3
- INV-MEM-4
- INV-MEM-1
HTTP mapping only: delete still goes through `MemoryService` / the
existing exclusive `destructive_operation_gate`. No new intake path, no
extra tier, no bypass of canonical delete. Conversation cascade retract
still uses the same memory-delete owner; this PR only maps
`DestructiveOperationInProgress` to 409 instead of 500.
Line-Count-Exception: backend/routers/conversations.py | 2203 -> 2210 |
Map DestructiveOperationInProgress on cascade retract to 409; extracting
a new owner is out of scope.
## How it was verified
Backend (worktree venv):
```
cd backend && .venv/bin/python -m pytest -q \
tests/unit/test_account_gate_busy_http.py \
tests/unit/test_memories_batch_delete.py \
tests/unit/test_legal_holds.py \
tests/unit/test_delete_conversation_cascade_retraction_fence.py
```
**25 + 14 passed** (legal_holds file 25; combined targeted run 14
including the new 409 tests). Concurrent gate test: one
`destructive_operation_gate(uid)` succeeds, the other raises
`DestructiveOperationInProgress`; `external_write_fence` still blocks
while the live gate is held. `GATE_STALE_AFTER_SECONDS` remains 6h.
Windows:
```
cd desktop/windows && ./node_modules/.bin/vitest run src/main/memoryCleanup/bulkDelete.test.ts
```
**11 passed.** `./node_modules/.bin/tsc --noEmit -p tsconfig.node.json
--composite false` exited 0.
Did not serve the live FastAPI process against a real Firestore gate in
this run (no prod/dev GCP writes). The router tests drive the production
handlers with a service that raises the typed exception.
## Tests
Red proof (unfixed tree: only `ValueError` was caught on delete):
- `test_delete_memory_maps_gate_busy_to_409_not_500`:
`pytest.raises(HTTPException)` failed because
`DestructiveOperationInProgress: another destructive operation owns the
account gate` escaped uncaught.
- `test_batch_delete_maps_gate_busy_to_409_not_500`: same uncaught
exception from `delete_batch`.
- `classifyStatus(409)` expected `'retry'`, received `'fail'`.
-
`test_concurrent_single_deletes_one_succeeds_other_raises_typed_exception`
is the reproduction and stays: two concurrent
`destructive_operation_gate(uid)` contexts, one winner, typed exception
on the loser.
Green after: 409 + `Retry-After: 2` + `account_gate_busy` on single and
batch delete; conversation retract source-maps the same helper; Windows
bulk path issues `DELETE /v3/memories/batch` (100+1 for 101 ids) and
retries 409 using the header.
## Failure class (fixes)
Failure-Class: none
First instance of this HTTP mapping. The gate itself is unchanged (still
exclusive, still 6h stale). Existing
`FC-destructive-gate-keyed-on-proxy-for-intent` is a different contract
(empty replacement set vs destroy).
## Part B (POST /v3/memories 503) — findings, not this PR
PR #12524 already resolves an *identical-content* resubmission after the
account head has moved (`_existing_identical_add_row` compares
`content.strip()` only). Windows `POST /v3/memories` does not send an
id; the server derives it from `uid` + `source_id` (`"unknown"` when
omitted) + stripped content. Tags, category, and `source` are outside
that identity, so a focus/insight dual-write with *different text*
cannot share an id. Remaining 503s are likely (1) two in-flight
identical POSTs racing before the winner's snapshot is readable, so
`_existing_identical_add_row` returns `None` and `create_memory` still
wraps every exception as 503, or (2) an `invalid_patch` reason other
than `add patch new_memory_id already exists`. A red-proof fix would be
a bounded snapshot re-read on that specific reason, plus not mapping
unrelated apply failures to 503. Not done here.
## Follow-ups not in this PR
- macOS: bulk delete uses `deleteAllMemories`; single `deleteMemory` is
not fanned out. Insight `TaskGroup` is mark-read, not delete. No change.
- Flutter: `deleteMemoryServer` is per-row; bulk uses `DELETE
/v3/memories`. No fan-out. No change.
- MCP / developer delete routes still let
`DestructiveOperationInProgress` escape as 500.
- Renderer `AdvancedTab` / `deleteMemoriesPaced` still treat 409 as a
hard fail (serial, so they do not self-collide; they can still lose to
another in-flight gated op).
- `DELETE /v3/memories` (delete-all) is ungated in the router the same
way.
Do not merge; coordinator reviews.
What changed and why
POST /v3/memories has 500'd at over a thousand requests per day in production since the #12084 deploy (2026-08-28):
canonical write failed: ApplyStatus.invalid_patch (add patch new_memory_id already exists)fromcreate_memory→write_canonical_extraction_memory. This is gate 1 of the JIT rollout follow-ups ("trace, fix, deploy, and verify the separate /v3/memories idempotency failure").Root cause: manual/API memory ids derive deterministically from content (
document_id_from_seed(content)), but operation identity folds the observed head commit into the operation id (build_operation_id(... observed_head_commit_id ...)). A duplicate submission is therefore replay-idempotent only while the account head has not moved. Any other canonical write in between makes the duplicate propose a fresh operation whose add collides with the existing row id — so a client re-sending the same memory (retry, sync replay, re-import) gets a 500 for a write that is already complete.The fix resolves the collision at the write boundary: when the add's target row exists with identical content and is still active, the write is reported complete with the existing id and the row is left untouched. A collision with different content (a client-supplied id reused for new text) or against a non-active row keeps failing, and the privacy-deleted receipt branch is unchanged and still refuses.
Product invariants affected
How it was verified
backend/.venv/bin/python -m pytest tests/unit/test_ws_j_delete_privacy.py tests/unit/test_memory_apply_store.py tests/unit/test_conversation_replacement_backoff.py tests/unit/test_knowledge_ledger.py tests/unit/test_ws_i_hardening.py— 120 passed.origin/main(verified by stashing the adapter change) and passes with the fix.gcloud logging readonbased-hardwareshows the exact traceback (routers/memories.py:366 → canonical_memory_adapter.py:1458) hitting the 1000-entry query cap every day 2026-08-28 → 2026-09-01.Tests
test_resubmitting_an_identical_manual_memory_resolves_to_the_existing_row— the regression: identical resubmission after the head advances resolves to the existing row and leaves it byte-identical.test_reusing_a_row_id_for_different_content_still_fails— the guard that duplicate resolution never swallows a genuine conflict.Failure class (fixes)
Failure-Class: new
Failure-class transition narrative
No existing class covers this: the registry has destructive-gate, CAS-retry, and delivery-retry classes, but nothing about idempotency identity derived from ambient advancing state. The new class
FC-replay-idempotency-keyed-on-advancing-statenames the contract (duplicate-handling identity must derive from the logical request only, never from state that advances with unrelated writes) and its canonical prevention (resolve deterministic-id collisions at the write boundary by proving the existing row is the same logical write; keep a resubmit-after-head-advance regression test). Prevention artifact:backend/tests/unit/test_ws_j_delete_privacy.py.Line-count exceptions
Oversized files grew by the minimal duplicate-resolution patch; splitting them is out of scope for this production-regression fix.
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 3496 -> 3552 | resolve add collisions to the existing identical row at the shared write boundary