Skip to content

fix(merge): propagate source deletion failure and withhold false success (refs #20603) - #21525

Closed
Dragonire9 wants to merge 2 commits into
BasedHardware:mainfrom
Dragonire9:fix/merge-source-delete-failure-20603
Closed

Dragonire9 wants to merge 2 commits into
BasedHardware:mainfrom
Dragonire9:fix/merge-source-delete-failure-20603

Conversation

@Dragonire9

@Dragonire9 Dragonire9 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Refs #20603

Scope & Non-Goals

Problem

In backend/utils/conversations/merge_conversations.py, _delete_conversation_and_related_data previously caught and swallowed all exceptions during authoritative conversation document deletion:

    try:
        if purge_sync_sources:
            delete_conversation_with_sync_sources(uid, conversation_id)
        else:
            conversations_db.delete_conversation(uid, conversation_id)
    except Exception as e:
        logger.error(f"Error deleting conversation {conversation_id}: {e}")

Because the exception was swallowed rather than re-raised, the caller _merge_conversations_worker proceeded to record_capture_outcome(uid, 'manual_merge', ...) and send_merge_completed_message(uid, new_conversation_id, ...) despite the source conversation document still existing in the database.
When the user restarted the app or refreshed conversations, both the newly merged conversation and the undeleted original source conversations remained visible in the list.

Solution

  1. Propagate Deletion Failure: Re-raised exceptions in the conversation document deletion handler so failures propagate to the merge worker.
  2. Withhold False Success: When source deletion fails, the worker error handler _handle_merge_failure is invoked:
    • Because failure_phase == MergeFailurePhase.SOURCE_DELETION_STARTED, the merged target is safely preserved to prevent data loss.
    • The false-positive manual_merge outcome record and FCM completion notification are strictly withheld.
    • Source conversation lifecycle statuses are reset back to completed.
  3. Preserve Best-Effort Policies: Non-authoritative artifact cleanup (action items, photos, audio chunks, vector embeddings) remains best-effort.

Verification

Added hermetic regression test suite in backend/tests/unit/test_merge_source_delete_failure.py:

  • test_source_document_deletion_failure_propagates: validates that delete_conversation failure raises across both purge_sync_sources=True and purge_sync_sources=False.
  • test_merge_delete_failure_preserves_target_and_withholds_success: simulates deletion failure on both first and second sources, asserting that the merged target is preserved, _cleanup_merged_target_after_failure is not called, neither record_capture_outcome nor send_merge_completed_message is called, and lifecycle statuses are reset.
  • test_merge_reports_success_only_after_both_sources_are_deleted: verifies that success outcome and notification fire only after all source conversations have been deleted.
  • test_artifact_cleanup_remains_best_effort: asserts that failures in action items, photos, audio, or vector cleanup do not abort source document deletion.

Failure-Class: none
UI-Evidence: none

Payout Details:
PayPal: https://paypal.me/Dragonire9 ([email protected])

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified this end to end against the head — nice, surgical fix for #20603.

backend/utils/conversations/merge_conversations.py: re-raising from the authoritative document-deletion handler is correct. I traced the worker path: on_authoritative_retraction flips failure_phase to SOURCE_DELETION_STARTED before the document delete, _handle_merge_failure then preserves the merged target (data-loss safe) and resets source statuses to completed, and record_capture_outcome / send_merge_completed_message sit after the delete loop inside the try, so the false-success path is genuinely closed in both purge_sync_sources modes.

backend/tests/unit/test_merge_source_delete_failure.py: solid hermetic coverage — propagation in both modes, target preservation with the outcome record and FCM notification withheld, strict success-only-after-both-deletions ordering, and best-effort artifact cleanup. The import-isolation fixture stubs only I/O modules, which is the right level for this regression.

One scope note for maintainers (not a change request): delete_conversation_with_sync_sources also calls the changed helper for sync-bridge donors, so donor-deletion failures in user-initiated delete flows (e.g. the developer conversations delete route and the frame-evidence outbox path) now surface as errors instead of being logged and swallowed. Fail-loud is the safer posture here — the frame-deletion outbox is written before the deleter runs, so convergence survives a retry — but it does change failure semantics of delete endpoints beyond the merge path, so that trade-off deserves a maintainer sign-off before merge.

Checks green on head (backend unit suite, hermetic merge gate, hygiene, formatting). Leaving for human maintainer review on the delete-flow failure-semantics change before merge.

This is automated AI-generated feedback posted on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Oct 14, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @Dragonire9 — verified this end to end on the current head; the fix is correct and well-targeted.

backend/utils/conversations/merge_conversations.py — the re-raise lands in the only block whose failure was previously invisible: the authoritative conversation-document delete (delete_conversation_with_sync_sources / conversations_db.delete_conversation). I traced the worker semantics: the deletion loop's mark_source_deletion_started callback (including the skip-retraction branch) sets failure_phase = SOURCE_DELETION_STARTED before any source delete, so your re-raise reaches _handle_merge_failure in the phase where the merged target is preserved, sources reset to completed, and record_capture_outcome / send_merge_completed_message — which sit after the loop — are correctly withheld. That's exactly the false-success scenario from #20603.

Blast radius beyond the merge worker checks out too: the retain_capture=True sync-bridge path returns before the changed block, and the memories/action-items blocks already had propagate semantics. Two non-merge callers do see a deliberate behavior change through delete_conversation_with_sync_sources: the developer conversation-delete route now returns an error instead of a false {"success": true} (same bug class — desirable), and conversation_frame_evidence.py persists its deletion outbox before calling the deleter, so its converge-on-retry flow is unaffected. Worth a maintainer's explicit OK on that widened propagation, but I see no issue with it.

backend/tests/unit/test_merge_source_delete_failure.py — good hermetic suite using the repo's import_isolation harness with the real worker. Coverage hits the right cases: propagation for both purge_sync_sources values, target preservation + withheld outcome/FCM + status reset for a failure on either source (including partial progress after source-a succeeds), strict success-event ordering, and best-effort artifact cleanup preserved. Backend unit suite and Hermetic Merge Gate are green on this head.

Leaving this for maintainer merge review — the one judgment call is the intentional error-surfacing on the two non-merge deletion callers above.


by AI on behalf of David — if you need David's attention urgently, please @Git-on-my-level and escalate with need human response.

@aryanorastar aryanorastar left a comment

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.

Reviewed head 3e85c0c. No additional blocking code defect found: the re-raise correctly reaches the existing merge failure handler, preserves the merged target once source deletion has started, and withholds the success outcome and completion notification. I ran 32 focused tests, including all 9 new regression cases; removing the fix makes 4 of those regressions fail.

Before merge, please change Resolves #20603 to Refs #20603 and clarify the limited scope. This fixes a confirmed code-level false-success path, but does not establish the Android reporter's root cause, repair historical duplicates, or provide durable retry/client refresh recovery. #20603 should remain open for that investigation and end-to-end verification.

The intentional wider error propagation also needs explicit human maintainer acceptance: delete_conversation_with_sync_sources is used by the developer conversation-delete endpoint and frame-evidence deletion, so donor-deletion failures now surface to those callers. The frame-deletion outbox is persisted before the deleter runs, which preserves its retry path. This looks safer than false success, but it is a change to shared deletion failure semantics beyond merging.

Leaving this as a comment, not an approval, pending the scope correction and human maintainer sign-off.

@Dragonire9 Dragonire9 changed the title fix(merge): propagate source deletion failure and withhold false success (#20603) fix(merge): propagate source deletion failure and withhold false success (refs #20603) Oct 17, 2026
@Dragonire9

Copy link
Copy Markdown
Contributor Author

Thank you @aryanorastar for the detailed review and test verification!

Per your request:

  1. Changed Resolves #20603 to Refs #20603 in both the PR description and title.
  2. Added an explicit Scope & Non-Goals section clarifying that this targets the confirmed code-level false-success path and leaves bug(android): original conversations remain after merged conversation appears #20603 open for root-cause and client-recovery investigation.
  3. Noted the maintainer sign-off on the intentional shared error propagation behavior.

Ready for human maintainer review and sign-off.

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified independently on head 3e85c0c: the production change is correct and the remaining item is maintainer sign-off, not contributor work.

  • backend/utils/conversations/merge_conversations.py — the only production change (3 lines): the except block around authoritative document deletion (delete_conversation_with_sync_sources / conversations_db.delete_conversation, ~lines 857-868) now re-raises after logging. I traced the propagation end-to-end: the raise exits _delete_conversation_and_related_data, aborts the per-source loop in perform_merge_async before record_capture_outcome and send_merge_completed_message, and lands in _handle_merge_failure — where mark_source_deletion_started has already flipped failure_phase to SOURCE_DELETION_STARTED, so the merged target is preserved instead of cleaned up and sources are reset to completed. That is exactly the false-success fix bug(android): original conversations remain after merged conversation appears #20603 describes: no more "merge completed" while undeleted sources still exist. Artifact cleanup above the document delete (photos/audio/vector) correctly stays best-effort.
  • backend/tests/unit/test_merge_source_delete_failure.py — solid isolation hygiene (real worker, stubbed I/O, no cloud clients constructed) and the right assertions: propagation for both purge_sync_sources values, per-source failure preserving the target and withholding outcome/notification, strict ordering (both deletes before outcome before notification), and best-effort artifact cleanup.

Blast radius: the re-raise also changes behavior for the other callers of delete_conversation_with_sync_sources — the developer conversation-delete endpoint and frame-evidence deletion. Failures there now surface instead of being swallowed after logging; the frame-deletion outbox is persisted before the deleter runs, so its retry path survives. Safer than false success, but it is a shared deletion-failure semantics change beyond merging.

Performance/cost: none — control-flow-only change, no new queries or external calls.

USER IMPACT: if a merge's source deletion fails, users no longer receive a success notification while the original conversations still exist — the merge fails visibly instead of silently duplicating.

Nothing further needed from the contributor. Remaining before merge: maintainer acceptance of the widened deletion-failure propagation (developer delete + frame-evidence callers), and keeping #20603 open for the Android-side root cause. Leaving for human maintainer review on that semantics decision.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

aryanorastar added a commit that referenced this pull request Oct 26, 2026
…out push (#21417)

## What changed and why

Closes #19247 and #20603. Manual merge must finish in the running app
without depending on push, and a completed result must not retain cached
original rows. All manual admissions now use the existing durable merge
coordinator regardless of the broader lifecycle canary. The admitted
target ID remains stable through partial cleanup/retry; authoritative
transfer receipts prevent already-incorporated originals from being
merged again, while ordinary semantic duplicate hints retain merge
eligibility. Capture/transcription rollout behavior is unchanged.

The client uses typed source absence and target readiness, journals IDs
by account/backend, and commits list/search/pagination/cache changes
together. Cache transactions, page-cache writes and merge-journal
retirement are serialized; concurrent completions retain both targets
after offline reopen, failed transactions remain retryable, and queued
work rechecks account/backend ownership. Merges still processing after
the fast polling window remain observed at a lower bounded rate. A read
failure or locked response never proves deletion, and observation never
resubmits a merge.

This extends Dragonire9's existing PR, preserving the contributor
commits. Main's #21544 already covers the source-deletion propagation
proposed by #21525; current-owner tests preserve that guard. No
contributor PR is closed and no bounty is accepted or promised.

## Verification

- 129 focused Flutter provider/cache/search/processing/Spotlight tests
and 31 adjacent delete/undo, auth retry, date-filter and recap tests
passed. Seven new regressions cover concurrent completions with/without
refresh, failed cache-read retry, queued account/backend replacement, a
stale former target and old-server preservation of unrelated rows
pending deletion for Undo. The concurrent offline-cache regression fails
at the previous green head 353761f and passes with this fix.
- 97 focused file-isolated backend tests and all 34 batch-upload storage
tests passed, covering route modes off/shadow/serve, atomic admission
loss, source receipts, cleanup refusal, same-target retry, worker
rereads and validation.
- 9 integration tests passed against the pinned Firestore emulator
(firebase-tools 15.22.0): competing admissions, correction transfer,
lease expiry/fencing, partial cleanup failure, restart/retry into the
same target without paid processing, and consumed-source refusal.
- Local HTTP foreground, reopen, delayed completion and simultaneous
completion/offline-reopen journeys passed twice: 16 recorded assertions.
The offline case shuts down the loopback backend before reopening. Real
client decoding/provider/cache/row widgets execute; auth and backend
worker/storage effects are synthetic. Backend emulator tests exercise
the durable owners separately.
- Three cache/failed-read regressions fail on byte-exact current-main
provider code and pass in this PR. The batch-upload fixture resolves the
real pure merge policy while retaining isolated client/IO dependencies;
all 34 file tests pass.
- The nine WAL live-custody tests pass twice. Their gated-index test
observes the actual disk/index persistence checkpoint and releases its
gate in finally; strict durability assertions and production WAL code
are unchanged.
- Changed-file Flutter analysis is clean. Exact-head CI at
f66450e passes: 34 successful checks,
19 conditional skips, one neutral docs preview, no failures or pending
checks. Full Dart analysis/tests passed with 7,640 tests and four skips;
all six backend shards, aggregate backend suite and seeded journeys
passed. Linux packaging passed a same-commit retry after an Ubuntu
package-download timeout. Unselected native-compile/far-timezone lanes
are not claimed as verified.

## Technical readiness and release

Final diff review, local integration evidence and required exact-head CI
pass at f66450e. The PR remains draft for maintainer review; it has
not been merged or deployed. Customer confirmation is not a technical
readiness or GitHub-closure gate.

Deploy the additive backend response before mobile release. No
LIFECYCLE_V2_MODE serve-cohort change is needed for manual merge
correctness. Existing finalization recovery infrastructure remains
required (production runtime manifests already declare the
conversation-finalization Cloud Tasks queue). This PR does not change
production configuration, deploy, merge, or mutate customer records.

Support separately owns historical-account investigation and
post-release customer confirmation; those remain in the support tracker
and do not keep a verified technical fix open on GitHub.

## Product invariants affected

none

UI-Evidence: none -- No layout/control code changed. The local HTTP
journey renders the production row and verifies only the completed
target remains without a merging overlay in foreground, reopen, delayed
completion and concurrent-completion offline reopen.

Failure-Class: new

## Failure-class transition narrative

FC-merge-completion-depends-on-push records the demonstrated contract: a
best-effort push is not a completion authority. Its reusable guard is
typed target/source observation and a shared provider/cache commit;
behavioral provider and HTTP journey tests cover recurrence. Durable
manual admission removes the legacy recovery bypass rather than adding
another recovery owner.

Line-Count-Exception: app/lib/providers/conversation_provider.dart |
2197 -> 2420 | Keep canonical admission/projection ownership in the
established owner; bounded observation and journal serialization live in
small separate services.
@Dragonire9

Copy link
Copy Markdown
Contributor Author

Withdrawing this pull request and closing it. For the record: I committed and engineered these fixes under the expectation of the repository's paid bug bounty program, not as unpaid open-source charity. All unmerged contributions are permanently withdrawn.

@Dragonire9 Dragonire9 closed this Oct 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hey @Dragonire9 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants