Skip to content

fix(chat-first): reject blocks referencing soft-deleted conversation and task tombstones - #20783

Merged
aryanorastar merged 1 commit into
BasedHardware:mainfrom
miso466:fix/chat-first-tombstone-validation-guard
Oct 30, 2026
Merged

aryanorastar merged 1 commit into
BasedHardware:mainfrom
miso466:fix/chat-first-tombstone-validation-guard

Conversation

@miso466

@miso466 miso466 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

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

Review in cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified a real gap and a clean fix.

_entity_available in backend/routers/chat_first.py accepted journal blocks referencing soft-deleted entities: get_action_item (database/action_items.py:496) and get_conversation (database/conversations.py:1078) both return tombstone rows unfiltered, so a task with deleted: True or a soft-deleted conversation passed the old discarded/is_locked-only checks. The five added guards (TaskCardSpec, CaptureLinkSpec, ConversationLinkSpec, and both subject.kind branches) close exactly those paths, correctly reusing the canonical conversations_db.is_soft_deleted predicate rather than inventing new semantics, and only narrow acceptance — no behavior change for live entities. The GoalLinkSpec branch needs no equivalent (goals have no soft-delete field).

backend/tests/unit/test_chat_first_tombstone_guard.py covers every guarded branch plus an active-entity regression case; all five tests ran and passed in CI (Backend unit shard 3/4).

Note on the red "Backend unit suite" check: the failing tests (test_shared_action_items.py, test_dev_api_folder_filters.py, test_desktop_tts_updates.py) fail identically on current main and are unrelated to this change — this PR's own tests are green. Thanks for the continued tombstone-invariant work across 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

Copy link
Copy Markdown
Member

Verified this change — the guards are load-bearing and the fix is correct.

backend/routers/chat_first.py — _entity_available previously checked only is_locked/discarded, and both read paths really do return tombstones: get_action_item returns the raw document (and prepare_action_item_for_read doesn't strip deleted), while get_conversation applies no deleted filter. So POST /v1/chat-first/blocks/validate could previously return accepted: true for a soft-deleted task or conversation. The new not task.get('deleted', False) (TaskCardSpec + questionCard task-subject) and not conversations_db.is_soft_deleted(...) (CaptureLinkSpec, ConversationLinkSpec, capture-subject) checks close that gap, matching is_soft_deleted's documented contract that content operations must reject tombstones.

backend/tests/unit/test_chat_first_tombstone_guard.py — good coverage: all five rejection paths plus an active-entity regression asserting accepted receipts, using the same seams as the sibling test_chat_first*.py suites. This file passed CI on this head.

About the failing Backend unit suite: the shard failures are in test_shared_action_items.py (AttributeError: routers.action_items does not have the attribute '_wake_task_changes' — test/production skew at your merge base), test_dev_api_folder_filters.py, and test_desktop_tts_updates.py — none of which this PR touches, and the suite runs per-file isolation. Main is green on newer commits, so a rebase (or a re-run after main catches up) should clear it.

Thanks for the tight, well-tested fix — the invariant that tombstones are invisible to user-facing workflows is exactly right. Leaving merge 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.

…and task tombstones

Guard `_entity_available` in `backend/routers/chat_first.py` against
admitting journal blocks referencing soft-deleted conversation tombstones
or soft-deleted tasks. Rejects them with entity_unavailable to preserve
entity invariants and avoid leaking deleted records into chat workflows.

Failure-Class: none
@Git-on-my-level

Copy link
Copy Markdown
Member

The production change here is correct and nicely scoped — the chat-first block validator now honors the tombstone invariant, and every branch is tested.

Findings (all verified against the head):

  • backend/routers/chat_first.py — _entity_available: the two task branches (TaskCardSpec and subject.kind == 'task') now reject task.get('deleted', True), and the three conversation branches (CaptureLinkSpec, ConversationLinkSpec, subject.kind == 'capture') now reject via conversations_db.is_soft_deleted(...). I verified is_soft_deleted is the canonical tombstone predicate (backend/database/conversations.py:798, the same contract used by eligible_merge_target), and that get_action_item → prepare_action_item_for_read (backend/database/action_item_codec.py:77) preserves the stored deleted field, so both checks read real persisted state rather than a projection that strips the flag.
  • backend/tests/unit/test_chat_first_tombstone_guard.py — 5 tests covering all five guarded branches (soft-deleted task card, capture link, conversation link, question-card task/capture subjects) plus an active-entity regression case asserting accepted receipts still issue. The tests monkeypatch only the DB readers, so the real is_soft_deleted predicate is exercised under CI, not a stub of the code under test. Backend unit suite and Backend Hermetic Merge Gate are green on this head.

Security/privacy: this is the material dimension — before this change, a validation request referencing a soft-deleted conversation or task returned accepted: true, letting user-visible journal blocks point at data the user deleted. The fix closes that leak in the fail-closed direction. Blast radius: strictly narrowing; only references that should never have been admitted are now rejected. Performance: the new checks are in-memory field reads on documents already fetched; no extra queries.

USER IMPACT: journal entries can no longer link to conversations or tasks you've deleted — previously they could still pass validation and resurface deleted content.

Still wanted as a reviewer: nothing blocking. Optional niceties: a test asserting a conversation with deleted explicitly absent (legacy doc) still validates, and one for subject.kind == 'conversation' if that path ever exists separately.

Verified correct; formal approval is left 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.

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

Approved fb9a963bd50144e27c9113d84d3b5c8521afd844. _entity_available in backend/routers/chat_first.py on main accepts a deleted task or capture. This head rejects it and Hygiene succeeded.

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
aryanorastar merged commit 90a2b18 into BasedHardware:main Oct 30, 2026
48 checks passed
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.

3 participants