Skip to content

fix(conversations): reject soft-deleted conversation tombstones in update_conversation - #20901

Open
miso466 wants to merge 3 commits into
BasedHardware:mainfrom
miso466:fix/update-conversation-tombstone-guard
Open

miso466 wants to merge 3 commits into
BasedHardware:mainfrom
miso466:fix/update-conversation-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, #20899.

Enforce the gone-owner contract in database.conversations.update_conversation for soft-deleted conversation tombstones to prevent tombstone mutation and unnecessary worker execution.

Problem

database.conversations.update_conversation documents that it:

"Returns False when the conversation no longer exists, so callers that keep producing work for it (e.g. the pusher's private-cloud audio sync) can stop instead of writing into a deleted owner."

However, update_conversation only checked physical existence via if not doc_snapshot.exists: return False and lacked a check for is_soft_deleted(doc_data).

When a conversation was soft-deleted (deleted: True), doc_snapshot.exists remained True. Consequently:

  1. update_conversation returned True and proceeded to commit updates (doc_ref.update(prepared_data)), mutating the tombstone conversation document.
  2. Callers (e.g., pusher audio sync, background processing tasks) received True and continued producing work for a deleted owner instead of ceasing execution and releasing resources.
  3. Downstream side effects—such as search index synchronization (_sync_conversation_search_index) and stats cache invalidation—executed for deleted conversations.

Solution

  • In database.conversations.update_conversation, read doc_data = doc_snapshot.to_dict() or {} and check if is_soft_deleted(doc_data): return False.
  • Reuses doc_data for resolving data_protection_level and match score guards instead of repeated .to_dict() calls.
  • Ensures soft-deleted tombstones are consistently treated as gone/non-existent per the documented contract.

Product invariants affected

none

Regression Risk

Zero. Active live conversations proceed with identical update logic and side effects.

Verification

  • Added unit tests in backend/tests/unit/test_update_conversation_tombstone_guard.py:
    • test_update_conversation_rejects_soft_deleted_tombstone: asserts False return, verifies no document mutation, and confirms search index sync is skipped (demonstrated failure on unpatched code returning True).
    • test_update_conversation_succeeds_for_live_conversation: asserts True return and successful document mutation for live conversations.
  • Ran full regression suites for conversation updates, lifecycle contracts, and delete races (91 passed).
  • Passed automated scripts/pr-preflight verification and Black 26.5.1 code formatting.

Failure-Class: none

Line-Count-Exception: backend/database/conversations.py | 3722 -> 3726 | minimal soft-deleted tombstone guard preventing mutation

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

Verified the core change first: in backend/database/conversations.py, update_conversation now reads doc_data = doc_snapshot.to_dict() or {} and returns False when is_soft_deleted(doc_data) — placed before _prepare_conversation_for_write and doc_ref.update, so neither the tombstone document nor derived state (stats cache invalidation, _sync_conversation_search_index) is touched. This matches the module's shared tombstone predicate (is_soft_deleted, used at the other rejection sites like merge/reprocess/list) and the function's documented gone-owner contract. Reusing doc_data for data_protection_level and _guard_match_score_size also removes the duplicate .to_dict() calls — good.

The new backend/tests/unit/test_update_conversation_tombstone_guard.py covers the tombstone path (False return, no document mutation, _sync_conversation_search_index not called) and the live-conversation path returning True, and the Backend unit suite passes on this head.

Two check failures block merge, both quick fixes:

  1. Formatting (black) — the new test file has a double blank line after import database.conversations as conversations_db; remove one blank line (or run black backend/tests/unit/test_update_conversation_tombstone_guard.py).
  2. Hygiene product-file-line-count-ratchet — backend/database/conversations.py is line-count frozen at 3722 and this change grows it to 3726. Add exactly Line-Count-Exception: backend/database/conversations.py | 3722 -> 3726 | reason to the PR body with a short reason, or restructure so the file doesn't grow.

Once those land, this looks good to go — thanks for the clean, well-tested follow-up in this series.


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 backend Backend Task (python) label Oct 7, 2026
@Git-on-my-level
Git-on-my-level dismissed their stale review October 8, 2026 11:59

Dismissing my earlier changes-requested review: both blockers are resolved on head b62b0b3 — the formatting issue in the test file was fixed in 1ff8ed8, and the hygiene line-count ratchet is now satisfied via the Line-Count-Exception entry in the PR body. Backend unit suite, Formatting, and Hygiene are green at this head.

@Git-on-my-level

Copy link
Copy Markdown
Member

Both blockers from the prior automated review are resolved on this head - thanks for the quick turnaround.

  1. Formatting: the extra blank line after import database.conversations as conversations_db is gone (1ff8ed8) and the Formatting check is green at b62b0b3.
  2. Hygiene line-count ratchet: the PR body now carries Line-Count-Exception: backend/database/conversations.py | 3722 -> 3726 | minimal soft-deleted tombstone guard preventing mutation, and Hygiene is green.

Re-verified the change itself: in backend/database/conversations.py, update_conversation now reads the document once via doc_snapshot.to_dict() or {} and rejects soft-deleted tombstones with is_soft_deleted(doc_data) before _prepare_conversation_for_write, doc_ref.update, stats cache invalidation, and _sync_conversation_search_index - consistent with the module's other tombstone rejection sites and the function's documented gone-owner contract. The new backend/tests/unit/test_update_conversation_tombstone_guard.py asserts the False return, no tombstone mutation, and no search-index sync, plus a live-conversation control case; Backend unit suite and Backend Hermetic Merge Gate pass at head.

From my side this is ready - leaving the merge decision with 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 the positive-signal Automation verified a genuine fix/quality contribution label Oct 8, 2026
@undivisible

Copy link
Copy Markdown
Collaborator

@miso466 this conflicts with main now. Please rebase and push; it still looks valid.

@miso466
miso466 force-pushed the fix/update-conversation-tombstone-guard branch from b62b0b3 to d00aea9 Compare October 16, 2026 02:15
@miso466

miso466 commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main and resolved the merge conflict in backend/database/conversations.py. All unit tests and preflight checks (scripts/pr-preflight 32/32) pass cleanly.

@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed the rebased head — the conflict resolution in backend/database/conversations.py kept the guard intact. update_conversation now reads doc_data once, rejects soft-deleted tombstones via the shared is_soft_deleted predicate before any write, and reuses doc_data for the data_protection_level lookup and the match-score size guard; behavior for live conversations is unchanged.

The new tests in backend/tests/unit/test_update_conversation_tombstone_guard.py cover both branches (tombstone → False with no document mutation and no search-index sync; live → True with mutation). Backend unit suite, Formatting, Hygiene, and the Backend Hermetic Merge Gate are green at this head.

This matches the tombstone-rejection contract already enforced elsewhere in the module (the upsert path rejects existing deleted rows the same way), and the pusher audio-sync caller is exactly the beneficiary of the new False return. Looks merge-ready from my side — leaving formal sign-off to a human maintainer.


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

@miso466
miso466 force-pushed the fix/update-conversation-tombstone-guard branch from d00aea9 to 3631604 Compare October 18, 2026 22:37
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production change is correct and nicely scoped - no blocking issues.

backend/database/conversations.py - update_conversation now reads doc_data = doc_snapshot.to_dict() or {} once and returns False on is_soft_deleted(doc_data) before any write, mutation, or side effect. This matches the function's documented gone-owner contract and the shared tombstone predicate at line 807 (the deleted flag, deliberately distinct from revivable discarded). Lifecycle fields (_LIFECYCLE_FIELDS = status/discarded) are rejected up front, so nothing can mutate or un-delete a tombstone through this path. For live conversations the logic is identical; the refactor also replaces four repeated .to_dict() calls with the single read. I traced the callers - process_conversation.py:948 (raises on False: correct fail-stop), utils/sync/pipeline.py:2030, smart_merge.py:976, and the calendar-event router link - and none relies on writing into a soft-deleted doc; each treats False as owner-gone, which is the right outcome.

backend/tests/unit/test_update_conversation_tombstone_guard.py - new suite with an in-memory Firestore mock pinning the three contract clauses (False return, no tombstone mutation, no search-index sync) plus a live-conversation control case. Good coverage of the exact regression.

USER IMPACT: none - internal change; conversations you deleted stay deleted instead of being quietly updated by background workers.

Nice continuation of the tombstone-guard series. Formal approval left to a human maintainer since this guards user-data deletion semantics in the conversations store.


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

@miso466
miso466 force-pushed the fix/update-conversation-tombstone-guard branch from 3631604 to f1f5a85 Compare October 26, 2026 00:31
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production change here is correct and nicely scoped — one guard, one read consolidation, no behavior change for live conversations. The red Backend unit suite on this head is a pre-existing failure on main (test_open_loops_recap_integration.py, same failures on current main runs), unrelated to this diff.

Findings:

  • backend/database/conversations.py: the new doc_data = doc_snapshot.to_dict() or {} + is_soft_deleted(doc_data) -> return False guard sits exactly where the gone-owner contract needs it, and reusing doc_data removes three repeated .to_dict() calls with zero added Firestore reads. The existing NotFound -> False handler still covers the delete-between-read-and-write race.
  • Behavior note (intended, correct): record_owner_out is no longer populated for soft-deleted rows, since the guard returns before that block — consistent with callers ceasing work on a gone owner rather than keeping lane accounting alive.
  • Checked for regressions in restore paths: undelete goes through dedicated lifecycle functions (restore_conversation_from_discarded for revivable discarded rows); soft-deleted tombstones are terminal by design per is_soft_deleted, so this guard cannot break any revive flow.
  • backend/tests/unit/test_update_conversation_tombstone_guard.py: good hermetic design (mock Firestore monkeypatched onto conversations_db.db); both the tombstone-rejection and live-success cases assert the right things.

Security/blast radius: privacy-positive — prevents writes to user-deleted conversations and stops search-index sync and stats-cache invalidation from firing for tombstones. Performance: no new reads; slightly fewer to_dict() calls per update.

USER IMPACT: once a conversation is deleted from trash, background workers stop writing to it and stop regenerating derived data for it — deleted means deleted.

What I'd still want as a reviewer: (1) in the live-conversation test, also assert _sync_conversation_search_index fires when an indexed root (e.g. structured.*) is touched, so the guard's no-side-effect assertion has a positive control; (2) optionally assert record_owner_out stays empty for a soft-deleted batch-lane row.

CI note for maintainers: the Backend unit suite failure on this head reproduces on main (open-loops recap integration tests) and is not caused by this PR. Leaving for human maintainer merge decision (deletion-contract change in the user-data layer from a contributor outside the automated-approval set).


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

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) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants