Skip to content

fix(folders): enforce access validation in conversation move endpoints to prevent tombstone bypass - #19804

Merged
undivisible merged 2 commits into
BasedHardware:mainfrom
miso466:fix/folders-conversation-tombstone-guard
Oct 19, 2026
Merged

undivisible merged 2 commits into
BasedHardware:mainfrom
miso466:fix/folders-conversation-tombstone-guard

Conversation

@miso466

@miso466 miso466 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

PATCH /v1/conversations/{conversation_id}/folder and POST /v1/folders/{folder_id}/conversations/bulk-move in backend/routers/folders.py previously verified is_locked (returning HTTP 402 for locked conversations) but completely omitted validation for deleted=True (soft-deleted / tombstoned conversations).

This allowed:

  1. PATCH endpoint: A soft-deleted conversation to have its folder assignment mutated after deletion, violating tombstone invariants and leaking the full soft-deleted conversation record in the 200 OK response.
  2. POST bulk-move endpoint: A soft-deleted conversation to be included in bulk folder moves and counted as successfully moved.
  3. Folder conversation count desynchronization: Moving a soft-deleted conversation to a folder invokes update_folder_conversation_count, incrementing the folder's conversation_count. However, get_conversations_in_folder filters out deleted=True conversations (line 334), creating a persistent discrepancy between the folder's displayed count and its actual conversation list.

This change adds if not conversation or conversation.get('deleted', False): raise HTTPException(status_code=404, detail="Conversation not found") to move_conversation_to_folder and if not conv or conv.get('deleted', False): raise HTTPException(status_code=404, detail=f"Conversation {conv_id} not found") to bulk_move_conversations. This matches the tombstone-check pattern used in backend/routers/conversations.py (_get_valid_conversation_by_id, line ~165) and completes the tombstone guard consistency across all conversation mutation routes.

Product invariants affected

  • Soft-deleted (deleted=True) conversations must be treated as non-existent across all API surfaces, including folder assignment operations.
  • Tombstone invariants must hold for single and bulk folder moves.
  • Folder conversation counts must not reflect soft-deleted conversations.

How it was verified

  • Added unit test suite in backend/tests/unit/test_folders_conversation_tombstone_guard.py (8 hermetic unit tests, 0.44s, all pass):
    • test_move_conversation_to_folder_rejects_deleted: verifies PATCH on a soft-deleted conversation returns 404 and does not trigger DB mutation.
    • test_move_conversation_to_folder_rejects_locked: preserves 402 behavior on locked conversations.
    • test_move_conversation_to_folder_rejects_nonexistent: verifies 404 behavior on missing conversation.
    • test_move_conversation_to_folder_allows_valid: verifies normal conversation move succeeds.
    • test_bulk_move_conversations_rejects_deleted: verifies bulk-move returns 404 when any conversation is soft-deleted and aborts the move.
    • test_bulk_move_conversations_rejects_locked: preserves 402 behavior on locked conversations in bulk moves.
    • test_bulk_move_conversations_rejects_nonexistent: verifies 404 behavior on missing conversation in bulk moves.
    • test_bulk_move_conversations_allows_valid: verifies valid bulk move succeeds.
    • Ran pure unit folder regression suite: 19 tests passed in 0.82s — zero regressions.
    • Formatted with scripts/backend-python-format --check (exit code 0).
    • Passed scripts/pr-preflight (32 checks PASS).

Tests

  • backend/tests/unit/test_folders_conversation_tombstone_guard.py::TestFolderConversationTombstoneGuard::test_move_conversation_to_folder_rejects_deleted
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py::TestFolderConversationTombstoneGuard::test_move_conversation_to_folder_rejects_locked
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py::TestFolderConversationTombstoneGuard::test_move_conversation_to_folder_rejects_nonexistent
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py::TestFolderConversationTombstoneGuard::test_move_conversation_to_folder_allows_valid
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py::TestFolderConversationTombstoneGuard::test_bulk_move_conversations_rejects_deleted
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py::TestFolderConversationTombstoneGuard::test_bulk_move_conversations_rejects_locked
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py::TestFolderConversationTombstoneGuard::test_bulk_move_conversations_rejects_nonexistent
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py::TestFolderConversationTombstoneGuard::test_bulk_move_conversations_allows_valid

Failure class (fixes)

Failure-Class: none


Follow-up to #19762, #19774, and #19796 which applied tombstone access validation to conversation mutation endpoints (patch_conversation_summary, patch_conversation_segment_text, and Developer API conversation endpoints).

Review in cubic

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

Thanks for this — the analysis in the description checks out against the code, and the fix is correct and well-scoped.

backend/routers/folders.py

  • The new guards at move_conversation_to_folder (line 178) and bulk_move_conversations (line 208) close a real gap: without them, a soft-deleted conversation could be folder-mutated, have its full record returned in the 200 response, and increment the target folder's conversation_count while get_conversations_in_folder filters out deleted=True rows — a persistent count/list desync. Verified this gap still exists on main, so this isn't a duplicate fix.
  • Semantics match the canonical tombstone guard: conversations_db.is_soft_deleted() is bool(conversation) and bool(conversation.get('deleted')), identical to the inline check after the existence test. Non-blocking suggestion: consider calling the shared helper instead (as backend/routers/conversations.py does) so any future change to tombstone semantics stays in one place.

backend/tests/unit/test_folders_conversation_tombstone_guard.py

  • Nice coverage matrix: both endpoints × deleted / locked / nonexistent / valid, and the rejection tests assert the move/bulk-move DB functions were never called — exactly the right invariant. Backend unit suite passes.

One blocking item: the Formatting check is failing because black wants a blank line after the docstring before the nested def fake_get_conv in three tests (test_bulk_move_conversations_rejects_deleted, _rejects_locked, _rejects_nonexistent). Running black with the repo config on the test file and pushing the result will clear it — pure whitespace, no logic change needed.

(Note: the OpenAPI Contract run on this head also failed with a stale-spec message, but that looks like base drift at run time rather than anything from this PR — no route signatures or response models changed here.)

Once formatting is green this looks good to merge from my side; leaving the final sign-off to a maintainer since this touches access validation on user conversation data.


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 dismissed their stale review September 30, 2026 19:23

Resolved: the blocking item (black formatting of the tombstone-guard unit tests) is fixed in cf46e64 — Formatting check is green and test logic is unchanged.

@Git-on-my-level

Copy link
Copy Markdown
Member

Formatting looks good now — the new commit is exactly the black pass the prior review asked for, with no test-logic changes, and Formatting / Backend unit suite / Hygiene are all green on this head.

To recap where this stands:

  • backend/routers/folders.py — the guards at move_conversation_to_folder and bulk_move_conversations correctly close the soft-delete bypass (folder mutation of tombstoned conversations, full-record leak in the 200 response, and the target folder's conversation_count counting conversations the folder listing filters out). Semantics match the canonical pattern in backend/routers/conversations.py.
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py — solid coverage matrix (both endpoints × deleted / locked / nonexistent / valid, with the DB move functions asserted never called on rejection).

The earlier non-blocking note stands and is purely optional: consider using the shared conversations_db.is_soft_deleted() helper instead of the inline check, so any future change to tombstone semantics stays in one place.

Since this changes access-validation behavior on user conversation data, the final merge sign-off belongs to a human maintainer — leaving it in their queue.


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 labels Sep 30, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed both changed files against the head sources — this is a correct, well-scoped tombstone guard.

backend/routers/folders.py

  • move_conversation_to_folder and bulk_move_conversations now treat deleted=True conversations as 404 before any mutation. I verified this is semantically identical to the shared predicate is_soft_deleted (backend/database/conversations.py:516, bool(conversation.get('deleted'))) and consistent with _get_valid_conversation_by_id in backend/routers/conversations.py:123-140.
  • I also confirmed these two routes are the only conversation-mutating endpoints in the folders router, so the guard coverage is now complete for this file.
  • The count-desync motivation checks out: update_folder_conversation_count would increment while get_conversations_in_folder filters deleted rows, so rejecting the move is the right call.
  • Non-blocking nit: the inline conversation.get('deleted', False) could reuse conversations_db.is_soft_deleted(conversation) so the tombstone definition stays in one place if it ever evolves. Fine to address in a follow-up.

backend/tests/unit/test_folders_conversation_tombstone_guard.py

  • Good coverage: deleted/locked/nonexistent/valid for both endpoints, and the rejection tests assert the move/bulk-move DB functions are never called, which is the important negative-path check.
  • The direct-router-call style with monkeypatched database modules matches the existing unit suite conventions, and the dummy env fixtures match what other unit tests already use.

Backend unit suite is green on this head. Thanks for the thorough PR description — the invariant analysis made review straightforward. Noting @aryanorastar's approval of this head; I've removed the stale needs-maintainer-review label since that sign-off is done. 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 removed the needs-maintainer-review Needs a human maintainer to sign off before merge label Oct 1, 2026
aryanorastar added a commit that referenced this pull request Oct 2, 2026
…event tombstone mutation (#19870)

Follow-up to #19762, #19774, #19796, #19804, #19860, #19864, and #19867.

Line-Count-Exception: backend/routers/sync.py | 2494 -> 2500 | enforce
conversation tombstone guard in audio merge jobs

## Problem

In `backend/routers/sync.py`, the Cloud Tasks background merge endpoint:
- `POST /v2/audio-merge-jobs/run` (`run_audio_merge_job` and
`_run_conversation_merge_job`)

builds playback MP3 artifacts from audio chunks and updates Firestore
conversations with the resulting `conversation_audio` metadata.

However, neither the v2 conversation-level merge
(`_run_conversation_merge_job`) nor the legacy single-file merge
validated `deleted=True` (tombstone) on the conversation:
- `_run_conversation_merge_job` fetched
`conversations_db.get_conversation(uid, conversation_id)` but only
checked `if not conversation or not conversation.get('audio_files'):`.
- `run_audio_merge_job` proceeded to load chunks and build MP3s without
checking the parent conversation's existence or tombstone status.

When a user deletes a conversation, queued Cloud Tasks merge jobs would
still execute heavy audio concatenation (FFmpeg/AudioSegment), upload
playback MP3 artifacts to GCS, and write `conversation_audio` metadata
into the soft-deleted Firestore conversation document. As documented
across conversation lifecycle contracts (e.g.
`merge_conversations.py:147`), tombstones must not be resurrected or
mutated with newly generated artifacts.

## Fix

1. In `_run_conversation_merge_job`: add tombstone validation after
conversation lookup:
   ```python
conversation = await run_blocking(db_executor,
conversations_db.get_conversation, uid, conversation_id)
   if not conversation or conversation.get('deleted', False):
return JSONResponse(status_code=200, content={'status': 'dropped',
'reason': 'deleted_conversation'})
   ```
2. In `run_audio_merge_job`: verify the conversation before reading
chunks, dropping tasks for missing or soft-deleted conversations with
`status=dropped` and `reason=deleted_conversation`.

Returning 200 with `status=dropped` safely consumes and acks the Cloud
Tasks task without triggering unnecessary retries.

## Verification

Added unit tests in
`backend/tests/unit/test_sync_audio_merge_job_tombstone_guard.py`:
- `TestV2ConversationAudioMergeTombstoneGuard`:
- `test_v2_merge_drops_soft_deleted_conversation` (dropped, no
build/upload/mutation)
  - `test_v2_merge_drops_nonexistent_conversation` (dropped)
- `test_v2_merge_drops_conversation_without_audio_files` (dropped,
reason=no_audio_files)
- `test_v2_merge_proceeds_for_active_conversation` (done, artifact built
and stamped)
- `TestV1SingleFileAudioMergeTombstoneGuard`:
  - `test_v1_merge_drops_soft_deleted_conversation` (dropped, no build)
  - `test_v1_merge_drops_nonexistent_conversation` (dropped)

Ran tests:
```bash
backend/.venv/bin/pytest backend/tests/unit/test_sync_audio_merge_job_tombstone_guard.py -v
# 12 passed in 2.64s
backend/.venv/bin/pytest backend/tests/unit/test_audio_merge_tasks.py -v
# 23 passed in 2.64s
```

Product invariants affected: none
Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/19870?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. -->
@Git-on-my-level

Copy link
Copy Markdown
Member

Verified the tombstone guard on both changed endpoints — this closes a real gap. Confirmed main has no deleted check in either path, so the fix is not redundant.

  • backend/routers/folders.py — move_conversation_to_folder: if not conversation or conversation.get('deleted', False) now returns 404 for soft-deleted rows before the is_locked (402) check, matching the _get_valid_conversation_by_id contract in backend/routers/conversations.py. bulk_move_conversations gets the same guard per conversation id in the validation loop, so a tombstone can no longer be counted as moved or increment the target folder's conversation_count (the count desync analyzed in the PR body).
  • backend/tests/unit/test_folders_conversation_tombstone_guard.py — solid coverage matrix: deleted / locked / missing / valid for both endpoints, asserting exact status codes and detail strings, plus move_mock.assert_not_called() / bulk_mock.assert_not_called() to prove the underlying folders_db mutation never runs for rejected rows. The module-level env stubs follow the existing convention in this suite.

Two optional nits, neither blocking:

  1. The inline conversation.get('deleted', False) could reuse conversations_db.is_soft_deleted(conversation) so the tombstone predicate stays defined in one place if its semantics ever widen (e.g. sync-redirect tombstones).
  2. bulk_move_conversations validation remains all-or-nothing — one bad id rejects the whole batch. That is consistent with the existing locked-conversation behavior, so fine to keep; just noting the API contract.

With @aryanorastar's approval on this head and the backend unit suite green, this looks merge-ready from my side. Thanks @miso466 — the folder-count desync analysis in the description was spot on.


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

@undivisible
undivisible merged commit ea693e2 into BasedHardware:main Oct 19, 2026
53 of 56 checks passed
miso466 added a commit to miso466/omi that referenced this pull request Oct 20, 2026
…mbstones

Enforce is_soft_deleted check in submit_mobile_feedback to reject feedback
targeting soft-deleted conversation tombstones with HTTP 404, and avoid
extracting provenance metadata from soft-deleted conversations in recording targets.

Follow-up to BasedHardware#19762, BasedHardware#19774, BasedHardware#19796, BasedHardware#19804, BasedHardware#19860, BasedHardware#19864, BasedHardware#19867, BasedHardware#19870, BasedHardware#20763.

Failure-Class: none
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 Oct 29, 2026
…rame request promotion (#20895)

### Summary

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

Reject soft-deleted conversation tombstones in
`attach_frame_request_to_conversation` to prevent tombstone bypass
during just-in-time frame evidence promotion.

### Problem

`attach_frame_request_to_conversation` validated conversation existence
using `conversation_snapshot.exists` inside the promotion transaction,
but did not check `is_soft_deleted(conversation_data)`.

Even when a conversation was soft-deleted (`deleted: True`), callers of
`POST /v1/frame-requests/{request_id}/promote` could:
1. Write permanent photo metadata into the soft-deleted conversation's
`photos` subcollection (`photo_ref`).
2. Mutate the tombstone conversation document with `has_content: True,
has_photos: True`.
3. Transition the temporary frame request to `attached` state with
permanent evidence linked to a deleted conversation.

This violated Omi's conversation tombstone invariant and allowed
resurrecting evidence references on deleted conversations.

### Solution

- Import `is_soft_deleted` from `database.conversations`.
- In `attach_frame_request_to_conversation`, check `if not
conversation_snapshot.exists or is_soft_deleted(conversation_data):
raise KeyError("conversation not found")`.
- Reuse `conversation_data` for resolving `data_protection_level`
instead of redundant `.to_dict()` calls.
- The router layer continues mapping `KeyError` to HTTP 404
`frame_request_not_found`.

### Product invariants affected

none

### Regression Risk

Zero. Only affects soft-deleted conversations (`deleted: True`). All
active conversations continue to attach and promote frame evidence
identically.

### Verification

- Added unit tests in
`backend/tests/unit/test_frame_request_promotion_safety.py`:
-
`test_attach_frame_request_rejects_soft_deleted_conversation_tombstone`:
asserts `KeyError("conversation not found")` on tombstone conversation.
- `test_promote_frame_request_maps_tombstone_rejection_to_404`: asserts
router-level HTTP 404 response.
- Verified all frame request test suites pass hermetically (70 passed).
- Formatted via Black 26.5.1 specification.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/20895?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. -->
aryanorastar added a commit that referenced this pull request Oct 29, 2026
…mbstones (#20772)

### Summary

Follow-up to #19762, #19774, #19796, #19804, #19860, #19864, #19867,
#19870, #20763.

Ensures `submit_mobile_feedback` rejects operations targeting
soft-deleted
conversation tombstones with HTTP 404, and avoids extracting provenance
metadata from soft-deleted conversations in recording targets.

### Problem

In `backend/routers/mobile_feedback.py`:
- For conversation feedback (`summary_helpfulness` or `target_kind ==
'conversation'`), `conversations_db.get_conversation` fetches the
conversation record, but only checks `if not conversation:`. The
tombstone check `conversations_db.is_soft_deleted(conversation)` is
missing.
- For recording feedback (`binding` path), provenance metadata (such as
`model_name`, `prompt_name`, `trace_id`) is extracted from
`conversation` even if that conversation was soft-deleted.
- For legacy mobile feedback fallback (`payload.target_kind is None`),
`conversations_db.is_soft_deleted` is likewise not checked.

As a result, client feedback requests targeting soft-deleted
conversations succeed and persist records in Firestore, violating the
invariant that "a tombstone is invisible to the user"
(conversations.py).

### Solution

- Add `or conversations_db.is_soft_deleted(conversation)` check in both
conversation target branches, raising HTTP 404.
- In recording target path, only extract provenance if `not
conversations_db.is_soft_deleted(conversation)`.

### Verification

- Unit test passed: `pytest backend/tests/unit/test_mobile_feedback.py`
(15/15 passed in 0.53s)
- Formatting: `scripts/backend-python-format --check` (exit code 0)
- Preflight: `scripts/pr-preflight`

## Regression Risk

Zero. Only adds rejection paths for soft-deleted tombstone documents;
all existing feedback actions for active conversations and recordings
continue to work identically.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/20772?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. -->
aryanorastar added a commit that referenced this pull request Oct 30, 2026
…and task tombstones (#20783)

### Summary

Follow-up to #19762, #19774, #19796, #19804, #19860, #19864, #19867,
#19870, #20763, #20772.

Guards the chat-first block validation endpoint against admitting
journal blocks that reference soft-deleted conversation tombstones or
soft-deleted tasks.

### Problem

In `backend/routers/chat_first.py`:
- `_entity_available` validates entity references for
`ChatFirstJournalBlockSpec` during `POST
/v1/chat-first/blocks/validate`.
- For conversation and capture references (`CaptureLinkSpec`,
`ConversationLinkSpec`, and `subject.kind == 'capture'`), the check
inspected `discarded` and `is_locked`, but omitted
`conversations_db.is_soft_deleted`.
- For task references (`TaskCardSpec` and `subject.kind == 'task'`), the
check inspected `is_locked`, but omitted `task.get('deleted')`.

As a result, client validation requests referencing soft-deleted
conversation tombstones or soft-deleted tasks returned `accepted: true`
instead of `accepted: false, code: 'entity_unavailable'`, violating the
invariant that tombstones are invisible and inaccessible to user-facing
workflows.

### Solution

- Added `not conversations_db.is_soft_deleted(...)` checks to
`CaptureLinkSpec`, `ConversationLinkSpec`, and `subject.kind ==
'capture'` branches in `_entity_available`.
- Added `not task.get('deleted', False)` checks to `TaskCardSpec` and
`subject.kind == 'task'` branches in `_entity_available`.
- Blocks referencing soft-deleted records now deterministically fail
validation with `entity_unavailable`.

### Verification

- Unit tests passed: `pytest
backend/tests/unit/test_chat_first_tombstone_guard.py` (5/5 passed in
1.60s)
- Regression test suite passed: `pytest
backend/tests/unit/test_chat_first*.py` (127/127 passed in 2.77s)
- Formatting: `scripts/backend-python-format --check` (exit code 0)
- Preflight: `scripts/pr-preflight`

## Regression Risk

Zero. Only rejects soft-deleted records (`deleted: True`). All active
conversations, captures, and tasks continue to validate identically.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/20783?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. -->
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. -->
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.

4 participants