Repository navigation
fix(backend): unbreak conversation merge and cascade delete behind the canonical fence - #11627
Conversation
… retract Merging conversations has been broken since 13 Aug. The app sits on "merging" until it is restarted, and afterwards the merged conversation and both originals are all listed. perform_merge_async builds the merged conversation, then deletes each source. _delete_conversation_and_related_data retracts the source's canonical memories first and re-raises if that fails, so nothing is deleted while active memories could still point at a deleted conversation. Retraction runs through the canonical replace boundary, which _require_canonical_intake_enabled() fences whenever MEMORY_MODE is not write/read. Production runs off. So every merge: created the merged conversation, raised on the first source, unwound into _handle_merge_failure, and reset the sources to completed. Step 10 — the FCM that tells the app the merge finished — was never reached, which is why the UI never left "merging" without a restart. Production logs, every merge, 1ms apart: Error processing merged conversation: 503: Memory writes are globally paused Error deleting memories for <id>: canonical memory intake is globally paused Merge failed with exception: canonical memory intake is globally paused Merge failed for conversations The fence closes intake, so a conversation ingested while it was closed has no canonical memories to retract in the first place. Cleanup now reads the source cohort — an unfenced read — and skips retraction only when the source has no active canonical memories. Nothing can be left dangling because there is nothing there. A source that does have memories still aborts exactly as before, and a cohort read that fails also aborts rather than assuming the source is empty. The fence callback still fires on the skip path: everything after retraction destroys source state, so failure handling must not treat the source as untouched. Existing canonical-delete tests describe a source that has memories; they now state that precondition in a fixture rather than having their assertions rewritten, so the safety invariant they guard is unchanged. This does not turn canonical intake back on. Merges work again, but memory extraction stays fenced while MEMORY_MODE=off. Verification: pytest test_merge_skips_retraction_without_canonical_memories.py -> 4 passed reverted the fix and re-ran -> 3 of 4 fail, confirming they catch the bug pytest (5 merge test files) -> 59 passed black --line-length 120 --skip-string-normalization -> unchanged Failure-Class: none
There was a problem hiding this comment.
All reported issues were addressed across 3 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
…full scope Review found two real gaps in the first version. The predicate only inspected the canonical memory_items cohort, but retract_conversation_memories also tombstones historical live records whose conversation_id or evidence names the source. A source with historical rows and no canonical items read as "nothing to retract", so it would have been deleted with those rows left pointing at it — the exact dangling-evidence state the abort exists to prevent. _source_retraction_is_a_noop now covers both stores. The skip was also unconditional. With intake enabled a source write can land between the check and the delete, and skipping there would race. The skip now applies only while the fence is closed, which is the only situation it was ever meant to address: with intake enabled, retraction works and the original path is correct. Coverage for both, exercising the real predicate rather than mocking it: intake-enabled always retracts and never consults the probe; historical records naming the source (by conversation_id or by conversation evidence) are not a no-op, while unrelated ids and non-conversation evidence are; an active canonical item is never a no-op. Verification: pytest test_merge_skips_retraction_without_canonical_memories.py -> 12 passed pytest (5 merge test files) -> 67 passed black --line-length 120 --skip-string-normalization -> unchanged Failure-Class: none
|
Both valid — fixed in the latest commit. The second one pointed at a better design than what I'd shipped. Historical records outside the predicate's scope (P2). Correct, and it's the same dangling-evidence bug I was fixing. Race with intake enabled (P1). Also correct, and your suggested remedy is the right one. The skip now applies only while the fence is closed — which is the only case it was ever meant to address. With intake enabled, retraction works and the original always-retract path is correct, so there is no window to race. New coverage exercises the real predicate rather than mocking it: intake-enabled always retracts and never consults the probe; historical records naming the source (by Worth noting the shape of what you caught: my first version widened a safety invariant further than the bug required. The fix is narrower now — it changes behaviour only in the state that is actually broken in production, and leaves every other path exactly as it was. |
…uard
Self-review before re-review found a third feature broken by the same fence, and
two problems in my own change.
DELETE /v1/conversations/{id}?cascade=true is the app's only delete path
(app/lib/backend/http/api/conversations.dart:136). It called
retract_conversation_memories with no error handling, so the canonical fence
turned every delete into a 500. Production, sampled per day:
11 Aug 0
12 Aug 0
13 Aug 300 (query cap; 400 of 400 sampled requests were 500)
14 Aug 300
Same 13 Aug onset as the merge failure and the knowledge-graph 503s. Nobody
reported it — users have simply been unable to delete conversations for two days.
The skip logic moves to utils/memory/retraction_scope.py and both call sites use
it, so merge and delete cannot drift apart.
Two defects in my own previous commit:
- The predicate used history.all_live(), whose docstring says explicit export
only: it materializes and sorts every live row before returning. It now
streams with iter_all_live and stops at the first match.
- MemoryService was constructed twice per source. Now once, passed in.
The first version of the delete test patched the skip helper and then called it,
which tested the mock rather than the router, and importing routers.conversations
into a unit-test session broke test_ws_j_delete_privacy through global state. It
is now a static checker over the endpoint source, labelled as such, asserting the
retraction sits inside the `if not retraction_can_be_skipped(...)` branch rather
than merely appearing near it. Behavioural coverage stays on the shared helper.
Verification:
pytest (8 merge + delete + privacy test files) -> 108 passed
reverted the delete guard and re-ran -> 3 of 3 fail
pytest test_ws_j_delete_privacy.py alongside the new file -> no pollution
black --line-length 120 --skip-string-normalization -> unchanged
Failure-Class: none
There was a problem hiding this comment.
2 issues found across 6 files
Confidence score: 2/5
- In
backend/utils/memory/retraction_scope.py, the intake-close path can reportTruebefore an in-flight canonical replacement is committed, which creates a real race where merge/cascade delete can remove a conversation without retracting the newly copied memory first; gate success on replacement commit visibility (or re-check after commit) before allowing deletion. - In
backend/utils/memory/retraction_scope.py, the deployment-wide MEMORY_MODE-off fence currently forces fulliter_all_livepagination for each conversation delete and merge-source step, which can turn routine operations into expensive user-history scans and cause latency spikes under load; add a bounded/indexed check or cached marker to avoid full scans in the fenced path.
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/utils/memory/retraction_scope.py">
<violation number="1" location="backend/utils/memory/retraction_scope.py:56">
P2: While the deployment-wide fence (MEMORY_MODE off) is closed, every conversation delete and every source step of every merge now runs a full paginated scan of the user's entire live memory history via `iter_all_live`. The loop only exits early on a record that references the source; in the common 'nothing to retract' case it exhausts every live row (potentially thousands of reads/decrypts) just to conclude the retraction is a no-op. Since `off` is the documented default, this is the hot path for all deletes, not an edge case. Consider bounding the scan (e.g. a targeted query for the conversation source rather than streaming the whole history) before merging.</violation>
<violation number="2" location="backend/utils/memory/retraction_scope.py:76">
P1: When intake closes while a canonical replacement is already in flight, this helper can return `True` before that replacement commits, so merge or cascade delete removes the conversation without retracting the newly committed memory. Couple the fence/cohort decision with canonical writes and source deletion, or revalidate under a shared transaction/lock before skipping retraction.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| failure abort. The ``and`` short-circuits, so the history scan never runs on | ||
| the healthy path. | ||
| """ | ||
| return canonical_intake_is_fenced() and source_retraction_is_a_noop( |
There was a problem hiding this comment.
P1: When intake closes while a canonical replacement is already in flight, this helper can return True before that replacement commits, so merge or cascade delete removes the conversation without retracting the newly committed memory. Couple the fence/cohort decision with canonical writes and source deletion, or revalidate under a shared transaction/lock before skipping retraction.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/retraction_scope.py, line 76:
<comment>When intake closes while a canonical replacement is already in flight, this helper can return `True` before that replacement commits, so merge or cascade delete removes the conversation without retracting the newly committed memory. Couple the fence/cohort decision with canonical writes and source deletion, or revalidate under a shared transaction/lock before skipping retraction.</comment>
<file context>
@@ -0,0 +1,81 @@
+ failure abort. The ``and`` short-circuits, so the history scan never runs on
+ the healthy path.
+ """
+ return canonical_intake_is_fenced() and source_retraction_is_a_noop(
+ uid,
+ conversation_id,
</file context>
| if any(item.status != MemoryItemStatus.tombstoned for item in canonical_items): | ||
| return False | ||
|
|
||
| for record in memory_service.history.iter_all_live(uid): |
There was a problem hiding this comment.
P2: While the deployment-wide fence (MEMORY_MODE off) is closed, every conversation delete and every source step of every merge now runs a full paginated scan of the user's entire live memory history via iter_all_live. The loop only exits early on a record that references the source; in the common 'nothing to retract' case it exhausts every live row (potentially thousands of reads/decrypts) just to conclude the retraction is a no-op. Since off is the documented default, this is the hot path for all deletes, not an edge case. Consider bounding the scan (e.g. a targeted query for the conversation source rather than streaming the whole history) before merging.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/retraction_scope.py, line 56:
<comment>While the deployment-wide fence (MEMORY_MODE off) is closed, every conversation delete and every source step of every merge now runs a full paginated scan of the user's entire live memory history via `iter_all_live`. The loop only exits early on a record that references the source; in the common 'nothing to retract' case it exhausts every live row (potentially thousands of reads/decrypts) just to conclude the retraction is a no-op. Since `off` is the documented default, this is the hot path for all deletes, not an edge case. Consider bounding the scan (e.g. a targeted query for the conversation source rather than streaming the whole history) before merging.</comment>
<file context>
@@ -0,0 +1,81 @@
+ if any(item.status != MemoryItemStatus.tombstoned for item in canonical_items):
+ return False
+
+ for record in memory_service.history.iter_all_live(uid):
+ memory = record.memory
+ if memory.conversation_id == conversation_id:
</file context>
…sition, and test the real path Third review round. All three findings were valid. Full history scan on the hot path. With the fence closed — the current production state — every delete and every merge source paginated the user's whole live history. Measured before changing anything: median 0 memories, p90 24, p99 280 over a 120-user random sample, so a single page for most accounts. The heavy cohort is where it bites: median 54, max 6,352, and 9 of 41 sampled need more than one page. Merge scanned per source, so that account merging five conversations paid it five times. Merge now takes one pass, collects the conversation ids referenced by live history, and reuses the set for every source. Single deletes still scan once, which the measurements say is a page. Fence transition. If the fence closed while a canonical write was in flight against the old deployment mode, the scope reads could observe an empty source and the write commit afterwards. The fence is re-read after the reads; if it changed, the skip is refused and the caller retracts as before. This does not make check-and-delete atomic — that needs a transaction spanning the memory store and the conversation document — but it removes the transition case the review described. Tests never drove the real decision. Every _delete_conversation_and_related_data test stubbed retraction_can_be_skipped to a fixed boolean, so a helper with the fence check inverted would have shipped green. Added end-to-end cases that mock only the two data reads and let the real canonical_intake_is_fenced -> source_retraction_is_a_noop -> retraction_can_be_skipped chain decide, in both fence states. Confirmed by inverting the fence comparison: 2 of those fail, and every previously existing test still passed. Also fixed test pollution, one mine and one pre-existing. These merge suites replace attributes on real modules, which restore_sys_modules cannot undo, so they break any later suite that calls the real database.conversations helpers. CI has never seen it because collection is alphabetical and the cascade suite sorts first. Both files now restore what they stubbed. Verification: pytest (8 merge + delete + privacy files, merge first) -> 113 passed same set before this commit, same order -> 3 failed fence comparison inverted -> 2 end-to-end tests fail black --line-length 120 --skip-string-normalization -> unchanged Failure-Class: none
|
All three valid. Fixed in Full history scan on the hot path (P2). Right, and I measured it before changing anything rather than guessing. Random 120-user sample: median 0 memories, p90 24, p99 280 — a single page for most accounts. The heavy cohort is where it bites: median 54, max 6,352, and 9 of 41 sampled need more than one page. Merge scanned per source, so that account merging five conversations paid it five times. Merge now takes one pass, collects the conversation ids referenced by live history, and reuses the set across sources. Single deletes still scan once, which the measurements say is one page. I did not add a targeted Firestore query — there is no index on Fence transition race (P1). Valid. The fence is now re-read after the scope reads; if it changed during them, the skip is refused and the caller retracts as before. To be precise about what this does and does not do: it removes the transition case you described, it does not make check-and-delete atomic. That needs a transaction spanning the memory store and the conversation document, which is a larger change than this fix warrants — flagging rather than quietly claiming it is closed. Tests never drove the real decision (P2). The sharpest of the three, and correct. Every One thing you did not flag, found while fixing yours. These merge suites replace attributes on real modules, which |
There was a problem hiding this comment.
1 existing issue remains and 1 new issue found across 6 files
Confidence score: 2/5
- In
backend/utils/memory/retraction_scope.py, the scope-read path can miss a concurrent pre-fence canonical commit because both fence checks can stay closed against a stale empty snapshot, which risks silently skipping a required retraction and leaving inconsistent memory state — add an atomic fence epoch/control validation that excludes stale snapshots before deciding to skip. - In
backend/utils/memory/retraction_scope.py, the historical-row tracking can keep a stale “live” mark when one row points to two source conversations, so retracting one source can cause the second source’s fenced retraction to abort incorrectly and leave data unretracted — recompute or invalidate the per-source live set after each row removal to keep source liveness accurate.
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/utils/memory/retraction_scope.py">
<violation number="1" location="backend/utils/memory/retraction_scope.py:80">
P1: When one historical row references two source conversations, retracting the first source removes the row but this stale set still marks the second source as live. The second source then calls fenced retraction and aborts the merge; refresh the scope after each cleanup or scan current history when the precomputed set contains the ID.</violation>
</file>
Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.
Re-trigger cubic
| if any(item.status != MemoryItemStatus.tombstoned for item in canonical_items): | ||
| return False | ||
|
|
||
| if historical_source_ids is not None: |
There was a problem hiding this comment.
P1: When one historical row references two source conversations, retracting the first source removes the row but this stale set still marks the second source as live. The second source then calls fenced retraction and aborts the merge; refresh the scope after each cleanup or scan current history when the precomputed set contains the ID.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/retraction_scope.py, line 80:
<comment>When one historical row references two source conversations, retracting the first source removes the row but this stale set still marks the second source as live. The second source then calls fenced retraction and aborts the merge; refresh the scope after each cleanup or scan current history when the precomputed set contains the ID.</comment>
<file context>
@@ -0,0 +1,124 @@
+ if any(item.status != MemoryItemStatus.tombstoned for item in canonical_items):
+ return False
+
+ if historical_source_ids is not None:
+ return conversation_id not in historical_source_ids
+
</file context>
Fourth review round. One of the two findings holds; the other cannot occur. Held: a canonical write already in flight against the pre-fence deployment mode can commit while the scope reads run. The fence never moves in that window, so re-reading it cannot catch the case. retraction_can_be_skipped now captures the canonical commit epoch — account generation, commit sequence and head commit id from memory_state/head, which the apply boundary writes on every committed canonical write — before the reads and compares it after. Any advance refuses the skip. A missing head is a stable value rather than a mismatch, which matters because most accounts have no head at all while intake is fenced. This still is not atomic. Closing it fully needs a transaction spanning the memory store and the conversation document, which this fix does not attempt; the epoch narrows the window to "nothing canonical committed while we looked". Not reproducible: the report that a historical row referencing two sources leaves a stale precomputed set, so the second source aborts. The set is built only when the fence is closed, and retraction_can_be_skipped short-circuits on the fence before consulting it. With the fence closed, the first source in the set skips nothing, its retraction raises, and the merge aborts before reaching the second. For the first retraction to succeed and remove the row the fence must be open, and then the set is never read. The reachable worst case is a conservative abort, which is the behaviour that predates this PR. Verification: pytest test_merge_skips_retraction_without_canonical_memories.py -> 21 passed pytest (8 merge + delete + privacy files, merge first) -> 116 passed black --line-length 120 --skip-string-normalization -> unchanged Failure-Class: none
|
One of the two holds and is fixed. The other I don't think can occur — reasoning below, happy to be shown wrong. Commit epoch across the scope reads (re-detected P1) — valid, fixed. You're right that the fence re-read is insufficient: a write already in flight against the pre-fence mode commits without the fence ever moving, so both reads see it closed and the snapshot is stale. Still not atomic, and I'm not claiming otherwise. Closing it fully needs a transaction spanning the memory store and the conversation document. The epoch narrows the window to "nothing canonical committed while we looked". Stale precomputed set with a row referencing two sources (new P1) — I can't reproduce it. The set is built only when the fence is closed ( So with the fence closed: source A is in the set → not a no-op → retraction runs → the fence makes it raise → the merge aborts. The loop never reaches source B. For A's retraction to succeed and remove the shared row, the fence must be open — and then the set is never read, because the short-circuit returns False first. The reachable worst case is a stale entry causing a conservative abort, which is exactly the behaviour that predates this PR, not a missed retraction. If there's a path I've missed where the set is consulted with the fence open, I'd genuinely like to see it — that would change the answer. New tests cover the epoch directly: an epoch that advances during the reads refuses the skip, a stable one allows it, and a missing state head reads as stable rather than as a change. |
There was a problem hiding this comment.
All reported issues were addressed across 6 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
…stablished
Review round five, and a genuine hole in the previous commit.
canonical_commit_epoch returned ("unavailable", reason) for every failure,
including a transient Firestore read error. When the same read failed at both
ends of the scope reads the two tuples compared equal, the guard read that as
"nothing changed", and the skip was allowed — during exactly the outage where
canonical state is least knowable. The docstring claimed "no head" and "read
failed" were never conflated while the == comparison did precisely that.
Only a missing head is a knowable stable state, and it is the normal shape for
an account with no canonical memories, which is the case this module exists to
allow. Every other reason now yields None, and None at either end refuses the
skip.
Tests cover each failure reason mapping to None, both epoch reads failing
identically, and an epoch that becomes unknowable only on the second read. The
end-to-end fenced case now also stubs the state-head read, because the real
chain makes three data reads rather than two — it failed first without that,
which is the fail-closed path proving itself.
Verification:
pytest test_merge_skips_retraction_without_canonical_memories.py -> 29 passed
pytest (8 merge + delete + privacy files, merge first) -> 124 passed
black --line-length 120 --skip-string-normalization -> unchanged
Failure-Class: none
There was a problem hiding this comment.
1 issue found across 6 files
Confidence score: 4/5
- In
backend/utils/memory/retraction_scope.py, malformedMEMORY_MODEhandling diverges fromensure_canonical_mutation_ready, so an invalid mode can take a skip path that deletes a conversation instead of failing closed with 503; this creates a user-visible data-loss risk under misconfiguration—align both code paths to the same malformed-mode behavior (prefer consistent hard-fail semantics).
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/utils/memory/retraction_scope.py">
<violation number="1" location="backend/utils/memory/retraction_scope.py:34">
P3: A malformed `MEMORY_MODE` is treated here as 'fenced/closed', which lets the skip path delete a conversation, while the real mutation boundary `ensure_canonical_mutation_ready` treats a malformed mode as a hard 503. Conflating a misconfigured deployment with an intentionally-closed intake silently enables the skip gate in exactly a state you'd otherwise want to fail loudly. Return False (do not skip) on `ValueError` so a malformed mode routes to the aborting retraction path instead.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| return MemoryRolloutMode(rollout_mode_env_value()) not in {MemoryRolloutMode.write, MemoryRolloutMode.read} | ||
| except ValueError: | ||
| # A malformed mode fences intake too, so treat it as closed. | ||
| return True |
There was a problem hiding this comment.
P3: A malformed MEMORY_MODE is treated here as 'fenced/closed', which lets the skip path delete a conversation, while the real mutation boundary ensure_canonical_mutation_ready treats a malformed mode as a hard 503. Conflating a misconfigured deployment with an intentionally-closed intake silently enables the skip gate in exactly a state you'd otherwise want to fail loudly. Return False (do not skip) on ValueError so a malformed mode routes to the aborting retraction path instead.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/memory/retraction_scope.py, line 34:
<comment>A malformed `MEMORY_MODE` is treated here as 'fenced/closed', which lets the skip path delete a conversation, while the real mutation boundary `ensure_canonical_mutation_ready` treats a malformed mode as a hard 503. Conflating a misconfigured deployment with an intentionally-closed intake silently enables the skip gate in exactly a state you'd otherwise want to fail loudly. Return False (do not skip) on `ValueError` so a malformed mode routes to the aborting retraction path instead.</comment>
<file context>
@@ -0,0 +1,166 @@
+ return MemoryRolloutMode(rollout_mode_env_value()) not in {MemoryRolloutMode.write, MemoryRolloutMode.read}
+ except ValueError:
+ # A malformed mode fences intake too, so treat it as closed.
+ return True
+
+
</file context>
kodjima33
left a comment
There was a problem hiding this comment.
Conversation merge + cascade delete behind the canonical fence reads correct; holding the merge on the red Backend unit suite and the 787-line diff.
…s isolation fixtures (#11633) ## What Five backend unit files have been failing on `main` since `6316415534` (merged today, 14:44 UTC) with the same error: ``` ModuleNotFoundError: No module named 'utils.memory.retraction_scope' ``` - `tests/unit/test_batch_upload_storage.py` - `tests/unit/test_conversation_events_bounds.py` - `tests/unit/test_conversation_search_date_validation.py` - `tests/unit/test_conversations_date_range_validation.py` - `tests/unit/test_merge_validation.py` Red lane on `main`: [run 31890773063](https://github.com/BasedHardware/omi/actions/runs/31890773063). ## Why PR #11627 added a new module, `utils/memory/retraction_scope.py`, and imported it from both `utils/conversations/merge_conversations.py:25` and `routers/conversations.py:51`. All five files load their module under test through the `stub_modules` + `load_module_fresh` isolation seam, and each stubs `utils.memory` as a package with an empty `__path__` plus a hand-listed set of submodules (`memory_service`, `memory_system`, `canonical_activation`). An empty `__path__` means any submodule that is *not* on that list cannot resolve at all — so the new import fails at fixture setup rather than falling through to the real module. Nothing in these five files exercises retraction; they cover audio-copy helpers, merge validation, event index bounds, and search/date validation. The stubs simply had not caught up with a new import in the graph they load. ## Fix Register a `utils.memory.retraction_scope` stub in each fixture, in that file's local idiom, exposing only the symbols its importer binds: - the two `merge_conversations` loaders get `canonical_intake_is_fenced`, `historical_source_conversation_ids`, `retraction_can_be_skipped` - the three `routers.conversations` loaders get `retraction_can_be_skipped` Test files only — no production code changes, and no assertion in any of the five was touched. ## On #11531 The issue's original cause (the customer-Firestore split, #11522) was fixed by #11535 and the issue was left open. Verified at `6316415534` that all nine files it named now pass: ``` BACKEND_UNIT_TEST_FILE_LIST=<the 9 files> bash test.sh -> 34 passed in 23.52s ``` The lane was red again for the unrelated cause above. With this change the lane is green, so the issue's condition is resolved. ## Tested ``` # the 5 failing files, before the fix (reproduced locally at 6316415) -> ModuleNotFoundError: No module named 'utils.memory.retraction_scope' in all 5 # after BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-fail5.txt bash test.sh -> 40 + 9 + 9 + 23 + 27 = 108 passed # full backend unit suite bash test.sh -> the 5 files pass. 14 other files fail; the identical 14 fail on unmodified main (stashed, same runner, same machine), so none are attributable to this diff. test_sync_v2.py failed only under full-suite parallel load and passes standalone (168 passed) both before and after. black --line-length 120 --skip-string-normalization --check -> 5 files would be left unchanged scripts/pr-preflight --pr-body-file <this body> -> PR preflight passed: 24 checks in 117.98s (includes backend-module-isolation, backend-import-purity) ``` Local runner is Python 3.12 / pytest 9.1.1 against CI's 3.11 / 8.4.1, which accounts for some of the 14 pre-existing local failures. ## Follow-up (not in this PR) This is the second time in two weeks that a new import into the conversations/memory graph broke hand-listed stub sets (#11531 was the same shape). The durable fix is to derive the stub set rather than hand-list it — e.g. letting a stubbed package auto-provide `AutoMockModule` submodules instead of failing on an empty `__path__`. That is a change to the shared `testing/import_isolation.py` seam with a much wider blast radius than a red-lane repair, so it is deliberately left out here. Auto-generated from issue feedback by the mini issues-improver — tested and merged. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/11633?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…s isolation fixtures Five unit files have failed on main since 6316415 with ModuleNotFoundError: No module named 'utils.memory.retraction_scope'. PR BasedHardware#11627 added utils/memory/retraction_scope.py and imported it from utils/conversations/merge_conversations.py and routers/conversations.py. All five files load their module under test through the stub_modules + load_module_fresh seam and stub utils.memory as a package with an empty __path__ plus a hand-listed set of submodules, so a submodule that is not on that list cannot resolve at all and the import fails at fixture setup. Register the missing stub in each fixture, in that file's local idiom, exposing only the symbols its importer binds. None of these files exercise retraction; no assertion changed. Verification: BACKEND_UNIT_TEST_FILE_LIST=<the 5 files> bash test.sh -> 108 passed full backend unit suite -> the 5 pass; the 14 other failures are byte-identical on unmodified main (test_sync_v2 was a full-suite flake and passes standalone) black --line-length 120 --skip-string-normalization --check -> unchanged fixes BasedHardware#11531
…#11726) Concurrent same-uid canonical writes — parallel cascade deletes, extractions, merges — all bump the one account-global memory_state/apply_control document. The three immediate attempts in replace_conversation_sourced_memories exhausted under that contention and raised an unhandled RuntimeError, so DELETE /v1/conversations/{id}?cascade=true returned 500 while the Flutter client retried one conversation up to 12x and kept the storm fed. A repeat delete whose committed receipt went stale after another conversation's replacement advanced source_generation livelocked on 'source replacement operation already exists' the same way. Retraction now converges on the retract entry (cascade delete + merge path only; extraction keeps its existing contract): - each conflict round re-checks, under the same double-read control fence the replacement loop uses, whether the source is already empty — a peer worker's committed retraction or a stale repeat receipt returns the committed-empty result instead of fighting the CAS; - bounded backoff (0.05→0.5s, five rounds) between retries; - exhaustion raises typed ConversationReplacementConflictError (a RuntimeError subclass, so existing callers are unchanged), which delete_conversation maps to a retryable 503 — nothing has been deleted at that point, so the #11627 never-orphan-live-memories fence holds and a retried delete is idempotent. Behavioral tests: injected control-change conflicts converge; repeat retract with a stale receipt returns already-retracted; exhausted conflicts with live items fail closed with the conversation intact; route maps the typed conflict to 503 before any delete. Co-authored-by: multica-agent <[email protected]>
…#11726) Concurrent same-uid canonical writes — parallel cascade deletes, extractions, merges — all bump the one account-global memory_state/apply_control document. The three immediate attempts in replace_conversation_sourced_memories exhausted under that contention and raised an unhandled RuntimeError, so DELETE /v1/conversations/{id}?cascade=true returned 500 while the Flutter client retried one conversation up to 12x and kept the storm fed. A repeat delete whose committed receipt went stale after another conversation's replacement advanced source_generation livelocked on 'source replacement operation already exists' the same way. Retraction now converges on the retract entry (cascade delete + merge path only; extraction keeps its existing contract): - each conflict round re-checks, under the same double-read control fence the replacement loop uses, whether the source is already empty — a peer worker's committed retraction or a stale repeat receipt returns the committed-empty result instead of fighting the CAS; - bounded backoff (0.05→0.5s, five rounds) between retries; - exhaustion raises typed ConversationReplacementConflictError (a RuntimeError subclass, so existing callers are unchanged), which delete_conversation maps to a retryable 503 — nothing has been deleted at that point, so the #11627 never-orphan-live-memories fence holds and a retried delete is idempotent. Behavioral tests: injected control-change conflicts converge; repeat retract with a stale receipt returns already-retracted; exhausted conflicts with live items fail closed with the conversation intact; route maps the typed conflict to 503 before any delete. Co-authored-by: multica-agent <[email protected]>
…#11726) Concurrent same-uid canonical writes — parallel cascade deletes, extractions, merges — all bump the one account-global memory_state/apply_control document. The three immediate attempts in replace_conversation_sourced_memories exhausted under that contention and raised an unhandled RuntimeError, so DELETE /v1/conversations/{id}?cascade=true returned 500 while the Flutter client retried one conversation up to 12x and kept the storm fed. A repeat delete whose committed receipt went stale after another conversation's replacement advanced source_generation livelocked on 'source replacement operation already exists' the same way. Retraction now converges on the retract entry (cascade delete + merge path only; extraction keeps its existing contract): - each conflict round re-checks, under the same double-read control fence the replacement loop uses, whether the source is already empty — a peer worker's committed retraction or a stale repeat receipt returns the committed-empty result instead of fighting the CAS; - bounded backoff (0.05→0.5s, five rounds) between retries; - exhaustion raises typed ConversationReplacementConflictError (a RuntimeError subclass, so existing callers are unchanged), which delete_conversation maps to a retryable 503 — nothing has been deleted at that point, so the #11627 never-orphan-live-memories fence holds and a retried delete is idempotent. Behavioral tests: injected control-change conflicts converge; repeat retract with a stale receipt returns already-retracted; exhausted conflicts with live items fail closed with the conversation intact; route maps the typed conflict to 503 before any delete. Co-authored-by: multica-agent <[email protected]>
…+ converge cascade-retract CAS (#11684, #11726) (#11731) ## What changed and why Two production 5xx classes from the 2026-08-17 incident window (watchdog `75afe342f6f8`, serving SHA `6316415` = merged #11627), fixed in two independent commits: 1. **Missing opposite-direction Firestore list-scan indexes → 503 (#11684).** Serving queries order `updated_at DESC, __name__ ASC` (`read_canonical_scan_page`, plus the historical dual-stream scans and the review-queue status scan). Firestore automatic single-field indexes only cover `field+__name__` in the *same* direction, so these need real composites — but `_query_spec_index_requirements()` dropped every spec with ≤1 non-`__name__` field. Prod answered `FailedPrecondition: The query requires an index`, mapped to 503 `Canonical memory unavailable` / `Historical memory unavailable` on `GET /v3/memories` and the cascade-delete skip-guard scan. Fix: the predicate now declares exactly the opposite-direction pairs and regenerates the manifest with the four missing indexes (`memory_items` `updated_at DESC`+`__name__ ASC`; `memories` `updated_at DESC`+`__name__ ASC`; `memories` `created_at DESC`+`__name__ ASC`; `memory_review_queue` `status ASC`+`__name__ DESC`). Same-direction singles and array-contains pairs stay out (deploy rejects those as redundant). 2. **Cascade-retract CAS exhaustion → 500 (#11726).** Concurrent same-uid canonical writes all bump the one account-global `memory_state/apply_control` document. `replace_conversation_sourced_memories`' three *immediate* CAS attempts exhausted under that contention and raised an unhandled `RuntimeError` → `DELETE /v1/conversations/{id}?cascade=true` returned 500 while the Flutter client retried one conversation up to 12× and kept the storm fed. A repeat delete whose committed receipt went stale (another conversation's replacement advanced `source_generation`) livelocked on `source replacement operation already exists` the same way. Fix on the retract entry only (cascade delete + merge; the extraction replace path keeps its existing contract): bounded backoff retry (5 rounds, 0.05→0.5s), and after each conflict an epoch-guarded empty-cohort check — the same double-read control fence the replacement loop uses — returns the committed-empty result when a peer already retracted the source. Exhaustion raises typed `ConversationReplacementConflictError` (a `RuntimeError` subclass, so existing callers are unchanged), which `delete_conversation` maps to a retryable **503** *before anything is deleted*: the #11627 never-orphan-live-memories fence holds, and a retried delete is idempotent (receipt replay / already-retracted short-circuit). Closes #11684 Closes #11726 ## Relationship to open work - **Supersedes #11687** (aryanorastar's index fix). That branch conflicts with current main — main refactored the predicate into `_query_spec_index_requirements()` — so this PR re-expresses the same semantic change there, ports its test fix verbatim (`test_firestore_config_does_not_declare_same_direction_single_field_composites` + the four-tuple declaration test), and regenerates the manifest through the generator rather than hand-patched JSON hunks. Credit for the measured predicate direction belongs to #11684/#11687. - **Does not replace #11727** (draft: zero-write retraction while intake is paused). That PR targets the fenced-intake path; this PR converges the open-intake CAS path. Whichever lands second will need a small rebase; the touched regions barely overlap. - Out of scope, per #11726: #11685/#11688 extract abort, MEMORY_MODE/cohort/control-schema redesign, client-only backoff. ## Merge sequencing (required) `firestore_readiness` runs `reconcile_firestore_indexes.py --check-only` on backend deploys and **fails closed until every manifest index is READY**. Merge only after a human runs `Reconcile Firestore Indexes` → `prod` → `APPLY_FIRESTORE_INDEXES` (dev first is fine) — that APPLY alone stops the 503s even before this PR merges. Split-merging (declaration after APPLY lands separately) is a later human decision; nobody should run APPLY from this PR. ## How it was verified - `pytest tests/unit/test_firestore_index_config.py tests/unit/test_firestore_indexes.py tests/unit/test_reconcile_firestore_indexes.py tests/unit/test_firestore_query_contract.py` → **62 passed** (was 61 on the wrong predicate; the renamed same-direction test no longer codifies the bug and the new opposite-direction declaration test pins all four indexes). - `python3 backend/scripts/generate_firestore_indexes.py --write` then read-mode → `firestore.indexes.json matches the Firestore index registry`; diff adds exactly the 4 entries (+56 lines, same shape as #11687). - `python3 backend/scripts/firestore_query_coverage.py --check-ratchet` → exit 0 (coverage keys on query signatures; QUERY_SPECS unchanged → no baseline drift). - `pytest tests/unit/test_cascade_retract_convergence.py tests/unit/test_delete_conversation_cascade_retraction_fence.py` → **7 passed**: injected `ConversationSourceReplacementConflict` rounds converge with bounded backoff; repeat retract with a stale receipt returns already-retracted instead of livelocking; exhausted conflicts with live items still raise (conversation + memories intact, #11627 fence); route maps the typed conflict to 503 before any delete. - Affected memory suites: `pytest tests/unit/test_ws_i_hardening.py tests/unit/test_ws_j_delete_privacy.py tests/unit/test_memory_apply_store.py tests/unit/test_memory_replace_policy.py tests/unit/test_merge_conversations_canonical_delete.py tests/unit/test_merge_skips_retraction_without_canonical_memories.py tests/unit/test_universal_memory_service.py tests/unit/test_atomicity_lifecycle_regressions.py` → **173 passed**. - Scan-read/fake-contract: `pytest tests/unit/test_bounded_firestore_list_reads.py tests/unit/test_firestore_fake_contract.py` → **12 passed**. - `scripts/pr-preflight --suggest` → INV-MEM-1 required; failure-class protocol honored below. Not verified here: live Firestore behavior (no APPLY, no prod/dev writes — the four indexes must be provisioned by a human via the workflow above). ## Tests - Index half regression: `backend/tests/unit/test_firestore_index_config.py::test_firestore_config_declares_opposite_direction_universal_list_scans` (fails on main's manifest) and the renamed same-direction test (fails if the predicate over-declares). - CAS half regression: `backend/tests/unit/test_cascade_retract_convergence.py` (three behavioral tests: convergence under injected conflicts, stale-receipt idempotency, fail-closed exhaustion) + `test_delete_conversation_cascade_retraction_fence.py::test_exhausted_replacement_conflict_maps_to_retryable_503_before_any_delete`. ## Product invariants affected INV-MEM-1 ## Failure class (fixes) Failure-Class: FC-undeclared-serving-query-index (That class covers the index half exactly — a serving query's composite index missing from the registry manifest. The CAS half has no existing class in the registry; it is a candidate for a new class — "account-global CAS exhaustion surfaced as an unhandled 500 on a retryable, idempotent operation" — to be registered separately per the transition-narrative protocol, not inline in this fix PR.) Line-Count-Exception: backend/routers/conversations.py | 1515 -> 1527 | retryable-503 mapping for the cascade-retract conflict (#11726) is a few lines inside the existing delete route; splitting the router is out of scope for an incident fix Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 2388 -> 2491 | retract convergence loop + epoch-guarded completion check + typed conflict error live with the CAS loop they wrap (#11726); extraction into a new module would split the replace/retract boundary mid-incident ## Residual risk - The 503-after-exhaustion path is still a 5xx by design — but only after 5 backoff rounds *and* a proven-non-empty source, with nothing deleted and a safe client retry; the incident's unbounded 12×-retry 500 loop is gone (converges or fails closed). - The already-retracted short-circuit trusts the same double-read fence the replacement loop uses; it cannot skip a retract that still has live items (live items → keep retrying → raise). - Multi-instance Cloud Run: the backoff converges cross-instance via the control CAS itself; there is no cross-instance lock (deliberately — the smallest shape #11726 sanctioned). <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/11731?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…CAS races (#11897) Every same-account canonical memory write races the one account-global memory_state/apply_control document. #11726 fixed that for retraction (cascade delete + merge) with a converging, backed-off loop and explicitly left extraction on its existing contract: three immediate attempts inside replace_conversation_sourced_memories. Extraction has no outer convergence loop. It is called straight from conversation processing (process_conversation -> _extract_memories -> _extract_memories_canonical) and is intentionally fail-closed, so when the three attempts exhaust, ConversationReplacementConflictError propagates out of _emit_derived_effects and the whole enrichment fails: the user's conversation gets no memories and no summary, and the deferred-open path re-arms and retries, feeding the storm. Prod evidence (Cloud Run service `backend`, project based-hardware, 2026-08-19): 11 x "canonical conversation replacement conflicted repeatedly" raised from canonical_memory_adapter.replace_conversation_sourced_memories, each caused by ConversationSourceReplacementConflict("memory control changed during conversation replacement") from the transaction fence in database/memory_apply_store.py. Bursts at 15:45:43-15:51Z (revision backend-79a585b, four distinct instances failing concurrently), 17:33Z, and again at 22:55Z on the current revision backend-920fc55 - so it is live, not a one-off. An immediate retry re-reads the control the peer just advanced, so a burst of same-account writers keeps losing in lockstep. The replacement loop now takes a bounded backoff schedule (0.05 -> 0.5s, five rounds), matching the one the retraction path already proved. The number of attempts is derived from the schedule, exhaustion still raises the same typed error, and nothing is committed on the way out - the #11627 never-orphan-live-memories fence is unchanged. Retraction keeps its inner rounds immediate (it passes the explicit immediate schedule) so the cascade-delete latency budget is not multiplied by its own outer converging loop; its three existing convergence tests pass untouched, which is the proof that path did not move. Verification: - backend/tests/unit/test_conversation_replacement_backoff.py (3 new tests) drives the real production function through the store boundary with a fake Firestore: conflicts that outlast the old immediate budget now converge and commit the memory item; the budget stays bounded at five rounds with the 0.05/0.1/0.25/0.5 schedule and fails closed leaving apply_control at source_generation 1 and no item written; a caller passing an immediate schedule still gets three no-sleep rounds. - All 3 fail against origin/main (2 on the un-backed-off budget, 1 on the absent parameter) and pass on this branch. - backend/tests/unit/test_cascade_retract_convergence.py: 3 passed, unmodified. - 16-file memory/canonical selection: 273 passed, 1 pre-existing ordering failure (test_ws_c_backfill.py::test_stage_all_candidate_can_be_reviewed_ processed_and_routed_by_l2) reproduced identically on origin/main and passing when that file runs alone. Failure-Class: new
Summary
Conversation merge and cascade delete have both been broken since 13 Aug, from the same cause. Reported symptom: the app sits on "merging" until it is restarted, and afterwards the merged conversation and both originals are all listed.
Root cause
perform_merge_asyncbuilds the merged conversation, then deletes each source._delete_conversation_and_related_dataretracts the source's canonical memories first and re-raises if that fails — deliberately, so a source is never deleted while active memories still point at it.Retraction runs through the canonical replace boundary, which
_require_canonical_intake_enabled()fences wheneverMEMORY_MODEis notwrite/read. Production runsoff.So every merge created the merged conversation, raised on the first source, unwound into
_handle_merge_failure, and reset the sources tocompleted. Step 10 — the FCM that tells the app the merge finished — was never reached, which is why the UI never left "merging" without a restart, and why both originals came back.Production logs, every merge, 1 ms apart:
Same origin as #11623:
5724a10084introduced_require_canonical_intake_enabled, and the first revision carrying it deployed 13 Aug 05:09.Fix
The fence closes intake, so a conversation ingested while it was closed has no canonical memories to retract in the first place. Cleanup now reads the source cohort — an unfenced read — and skips retraction only when the source has no active canonical memories. Nothing can dangle because there is nothing there.
Unchanged:
On the existing tests
test_merge_conversations_canonical_delete.pydescribes a source that has memories. Rather than rewrite its assertions — which would delete the guard it exists to provide — the precondition is stated in a fixture. Every assertion in that file is byte-identical; all 8 still pass.A third breakage, found by self-review and unreported
DELETE /v1/conversations/{id}?cascade=trueis the app's only delete path (app/lib/backend/http/api/conversations.dart:136). It calledretract_conversation_memorieswith no error handling, so the same fence turned every delete into a 500:Users have been unable to delete conversations for two days and nobody reported it. Same 13 Aug onset as merge and as the knowledge-graph 503s in #11623.
The skip logic now lives in
utils/memory/retraction_scope.pyand both call sites share it, so merge and delete cannot drift apart.Scope
This does not turn canonical intake back on. Merges work again; memory extraction stays fenced while
MEMORY_MODE=off. That flag is still the underlying condition behind this, #11623, and the silently-skipped memory extraction on every processed conversation — worth a separate decision.Verification
Not exercised against production — the fenced path is covered by unit tests, but I have not run a real merge on the deployed backend.
Line-Count-Exception
Line-Count-Exception: backend/routers/conversations.py | 1508 -> 1515 | guards the cascade-delete retraction behind the shared skip helper; the fence otherwise makes every delete a 500
Product invariants affected
Worth noting INV-MEM-3 (no legacy fallback after canonical selection) is not violated: nothing here falls back to a legacy store. When retraction is required it still runs through the canonical path and still aborts on failure; the skip applies only where the canonical scope is provably empty.
Failure class (fixes)
Failure-Class: none