Skip to content

fix(backend): fold cross-device duplicate captures at finalization (#3244) - #13703

Merged
kodjima33 merged 4 commits into
BasedHardware:mainfrom
apoorvdarshan:cursor/fix-double-recording-device-macos-ef05
Sep 13, 2026
Merged

kodjima33 merged 4 commits into
BasedHardware:mainfrom
apoorvdarshan:cursor/fix-double-recording-device-macos-ef05

Conversation

@apoorvdarshan

@apoorvdarshan apoorvdarshan commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Fixes #3244.

When an Omi device paired to the phone app and the macOS app both hear the same room, the backend receives two independent /v4/listen streams and each one owns its own conversation (cross-source sockets must stay separate so that captures of different audio survive, #5388). Nothing reconciled two captures of the same audio, so the user saw the same conversation twice — the duplicate list in the issue screenshot. The three closed attempts (#3537, #4352, #6353) all toggled one capture off on a client; maintainers rejected that direction ("allowing multi-device recording is the way, not this toggle on-off"), and the device and the Mac mic are on two different apps anyway.

This PR keeps multi-device recording fully enabled on every client and resolves the duplicate on the backend at finalization, from content:

  • backend/utils/conversations/duplicate_capture.py (new, pure): a conversation is a duplicate capture when another capture client's conversation (different client_device_id, or platform/source pair on legacy rows) covers ≥80% of its wall window for ≥30s and carries ≥50% of its word bigrams. Containment is measured against this conversation's words, so a capture holding speech the other lacks (pendant hears the user, laptop only hears remote participants) scores low and survives as its own conversation. Exactly one side yields under concurrent finalization: a completed counterpart is always primary; a processing one only when created earlier.
  • process_conversation._get_structured: consults that policy just before the LLM discard gate (so no LLM spend on a duplicate). A match takes the existing discard exit — transcript and audio stay on the row, no summary/memories/action items/integrations — and records external_data.duplicate_capture_of = <primary id>. Both clients already hide discarded conversations. force_process (first-open enrichment, manual reprocess, explicit finalize) never consults it, preserving the existing "reprocess never discards" contract. A failed candidate read fails open through record_fallback(component='conversation_finalization') to the pre-fix outcome (two visible conversations), never a lost one.
  • database.conversations.get_conversations_finished_after + registered spec conversations_by_status_finished_after: the candidate read (same user, status ==, finished_at >= started_at, ordered by finished_at, limit 25 per status). It shares the existing (status, finished_at) composite with the stale sweep; firestore.indexes.json is unchanged.

Coverage: live sessions finalized by silence timeout / disconnect (phone+device, Mac cloud STT) via the durable finalizer, and desktop on-device Parakeet uploads via /v1/conversations/from-segments — both call process_conversation with force_process=False.

Product invariants affected

  • INV-MEM-4 — path match on process_conversation.py; a folded duplicate takes the discard exit and produces no canonical intake, so no new Short-term/Long-term path is added.
  • INV-TASK-2 — path match on process_conversation.py; a folded duplicate produces no action items or Candidates.

How it was verified

Backend venv (backend/.venv, Python 3.11.15 via scripts/sync-python-deps.sh):

pytest tests/unit/test_duplicate_capture_policy.py \
       tests/unit/test_process_conversation_duplicate_capture.py \
       tests/unit/test_conversations_finished_after_query.py        -> 34 passed
pytest tests/unit/test_discard_calendar_override.py tests/unit/test_discard_gate_duration_input.py \
       tests/unit/test_conversation_discard_revival.py tests/unit/test_structured_extraction_partial_content.py \
       tests/unit/test_firestore_indexes.py tests/unit/test_firestore_index_config.py \
       tests/unit/test_firestore_query_contract.py                   -> 89 passed
BACKEND_UNIT_TEST_FILE_LIST=<CI selection> bash test.sh   -> full backend unit suite (1116 files, selected because
       database/conversations.py changed): 1111 pass; 5 fail identically on origin/main in this VM
       (test_verify_pusher_config_references / test_verify_pusher_promotion_evidence /
       test_rendered_deployment_contract need `helm`; test_memories_archive_and_read_contracts asserts a
       wall-clock currency band; test_backend_runtime_env_validator trips the 0.30s CPU-time guard) — unrelated
python scripts/generate_firestore_indexes.py     -> "firestore.indexes.json matches the Firestore index registry"
python scripts/firestore_query_coverage.py --check-ratchet -> exit 0 (new query classified `registered`)
bash scripts/typecheck.sh                        -> 0 errors (0 warnings in the new module)
python scripts/scan_async_blockers.py --dirs routers utils -> 0 findings
python scripts/check_module_stub_pollution.py / scan_import_time_side_effects.py -> 0 violations
scripts/pr-preflight --pr-body-file <this body>  -> "PR preflight passed: 31 checks"
git push (scripts/pre-push bounded gate)         -> "Bounded pre-push gate passed"

Measured margins of the bigram-containment metric on the test fixtures (candidate vs primary): unrelated same-window conversation 0.01, pendant-hears-user vs laptop-hears-remote (#5388) 0.00, pendant-user-only vs full-room Mac 0.95 (correctly folded — the Mac holds everything); same-room duplicates 0.68 / 0.78 at 15% word disagreement and 0.53 / 0.60 at 25%, so the 0.5 threshold tolerates roughly a quarter of the words differing between two mics/STT passes and otherwise degrades to today's behavior (two conversations). Window coverage is the guard for a capture that kept running after the other stopped (0.5 coverage at double length → kept).

Not verified: an end-to-end run with a physical Omi device plus the macOS app against a live backend. I do not have the hardware; the regression tests drive the production _get_structured path through the sanctioned stub seam with realistic overlapping transcripts, and the thresholds are constants in one module if real-device margins call for tuning. Maintainer hardware validation would be welcome.

Tests

  • backend/tests/unit/test_duplicate_capture_policy.py — behavioral coverage of the policy: same-room duplicate folded (incl. 25% word noise and a 20s start offset), Bug: Simultaneous device + web app recording fails — both are lost #5388 split-audio and unrelated same-window captures kept, capture that outlasted the other kept, same client never folds into itself, exactly-one-side-yields under concurrent processing, projection of Firestore dicts and models.
  • backend/tests/unit/test_process_conversation_duplicate_capture.py — the regression test: the device conversation finalizing after the Mac one is discarded with duplicate_capture_of set and the LLM discard gate is never called; no overlap / distinct audio / outlasting / same phone / failed lookup / force_process all keep the existing gate exactly as before.
  • backend/tests/unit/test_conversations_finished_after_query.py — the read carries the registered filter chain, orders on finished_at, and shares the stale sweep's index signature.

Line-count exceptions

Line-Count-Exception: backend/utils/conversations/process_conversation.py | 2950 -> 3011 | one import block, one ~40-line _detect_duplicate_capture composition (bounded candidate read + fail-open) and a 10-line hook at the discard decision, which is the coordinator's mandated enforcement point; the policy, its constants, and the marker helper live in the new duplicate_capture.py
Line-Count-Exception: backend/database/conversations.py | 2340 -> 2375 | one registered-spec read helper (get_conversations_finished_after) beside the sibling stale-in-progress read it mirrors; the persistence module is the only place a Firestore read may live
Line-Count-Exception: backend/database/firestore_index_registry.py | 1510 -> 1529 | one FirestoreQuerySpec registration; the registry is the single source of truth for serving query shapes and the coverage ratchet requires it

Failure class (fixes)

Failure-Class: new

Failure-class transition narrative

Adds .github/failure-classes/FC-same-speech-captured-twice-surfaces-twice.json. Violated contract: speech two of one user's capture clients heard at the same time must surface as one conversation. Canonical guard: content-based folding at finalization (duplicate_capture.py) with the two behavioral suites above as canonical_prevention_artifact. Evidence: #3244 and its screenshot of the duplicated list; evidence_prs is empty because this PR is the evidence.

Review in cubic

apoorvdarshan and others added 4 commits September 8, 2026 22:29
chore: sync fork main from BasedHardware/omi
When an Omi device paired to the phone app and the macOS app both hear the
same room, the backend receives two independent /v4/listen streams. Each
stream owns its own conversation (cross-source sockets must stay separate,
BasedHardware#5388), so the same speech surfaced twice in the conversation list (BasedHardware#3244).

Keep multi-device recording fully enabled and resolve the duplicate from
content at finalization instead: before the LLM discard gate,
process_conversation asks the new pure policy in
utils/conversations/duplicate_capture.py whether another capture client's
completed (or earlier-created processing) conversation already carries this
one — different client_device_id, >=80% wall-window coverage for >=30s, and
>=50% word-bigram containment measured against this conversation's words. A
match takes the same discard exit as a scrap, keeps transcript and audio on
the row, and records external_data.duplicate_capture_of. Containment is
one-directional so a capture holding speech the other lacks (pendant hears
the user, laptop hears remote participants) survives; exactly one side
yields under concurrent finalization; a failed candidate read fails open
through record_fallback to the pre-fix outcome.

The candidate read (get_conversations_finished_after) is a registered query
spec served by the existing (status, finished_at) composite; the generated
firestore.indexes.json is unchanged.

Verification (backend/.venv, Python 3.11.15):
  pytest tests/unit/test_duplicate_capture_policy.py
         tests/unit/test_process_conversation_duplicate_capture.py
         tests/unit/test_conversations_finished_after_query.py -> 34 passed
  pytest tests/unit/test_discard_calendar_override.py
         tests/unit/test_discard_gate_duration_input.py
         tests/unit/test_conversation_discard_revival.py
         tests/unit/test_firestore_query_contract.py ... -> passed
  scripts/generate_firestore_indexes.py -> manifest matches registry
  scripts/firestore_query_coverage.py --check-ratchet -> exit 0
  scripts/typecheck.sh -> 0 errors; scan_async_blockers -> 0 findings
  Fixture margins (bigram containment): unrelated same-window text 0.01,
  user-only vs remote-only 0.00; same-room duplicates 0.68/0.78 at 15%
  word disagreement and 0.53/0.60 at 25%.

Failure-Class: new

Co-authored-by: Apoorv Darshan <[email protected]>
Listen/pusher pipeline doc and the conversations package map gain the
finalization-time duplicate-capture rule (BasedHardware#3244) so the lifecycle change
ships with its guide, per the backend AGENTS.md doc-with-code rule.

Co-authored-by: Apoorv Darshan <[email protected]>
…e policy module

process_conversation.py is a line-count-ratcheted file; the pure marker
helper and the candidate page limit belong beside the thresholds they
accompany in utils/conversations/duplicate_capture.py. Behavior unchanged;
the three duplicate-capture suites and test_discard_calendar_override.py
pass (34 + 8).

Co-authored-by: Apoorv Darshan <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

3 issues found across 10 files

Confidence score: 2/5

  • backend/utils/conversations/process_conversation.py returns before _get_structured for deferred free-tier desktop processing, while the first-open retry uses force_process=True and intentionally skips duplicate handling; ensure the required check runs on the relevant retry path.
  • backend/utils/conversations/duplicate_capture.py can omit the only qualifying primary when more than 25 captures finish during a long candidate window, leaving the duplicate visible; fetch subsequent pages until finished_at exceeds the candidate window.
  • backend/tests/unit/test_duplicate_capture_policy.py has a quarter-words-disagree fixture only ~0.03 above the containment threshold, so small sentence or seed changes could silently flip the test; strengthen the fixture margin or assert the intended boundary explicitly.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/utils/conversations/process_conversation.py">

<violation number="1" location="backend/utils/conversations/process_conversation.py:594">
P1: When free-tier desktop processing is deferred, `process_conversation` returns before `_get_structured`, so this check never runs. The first-open retry uses `force_process=True`. That path intentionally skips duplicate detection, leaving cross-device duplicates visible; run this check before the defer path.</violation>
</file>

<file name="backend/utils/conversations/duplicate_capture.py">

<violation number="1" location="backend/utils/conversations/duplicate_capture.py:61">
P2: When more than 25 captures finish during a long candidate window, the bounded read can omit the only qualifying primary and leave the duplicate visible. Fetch subsequent pages until `finished_at` exceeds the candidate’s `finished_at` (or otherwise retain every row that can overlap the candidate) instead of treating this page as exhaustive.</violation>
</file>

<file name="backend/tests/unit/test_duplicate_capture_policy.py">

<violation number="1" location="backend/tests/unit/test_duplicate_capture_policy.py:130">
P3: The quarter-words-disagree test sits ~0.03 above the 0.5 containment threshold with its current seed, so it validates the intended robustness barely. Any future edit to these fixture sentences can silently flip it into a false pass/fail that looks like a policy regression. Pin a comfortable margin (e.g. assert the measured containment explicitly, or pick a rate/seed with clear headroom) so the test documents intent instead of hugging the boundary.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

# transcript and audio stay on the row and the primary is recorded in
# external_data. Deliberately ahead of the calendar override: the primary
# already holds that meeting.
duplicate_capture = _detect_duplicate_capture(uid, main_conv)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: When free-tier desktop processing is deferred, process_conversation returns before _get_structured, so this check never runs. The first-open retry uses force_process=True. That path intentionally skips duplicate detection, leaving cross-device duplicates visible; run this check before the defer path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/conversations/process_conversation.py, line 594:

<comment>When free-tier desktop processing is deferred, `process_conversation` returns before `_get_structured`, so this check never runs. The first-open retry uses `force_process=True`. That path intentionally skips duplicate detection, leaving cross-device duplicates visible; run this check before the defer path.</comment>

<file context>
@@ -535,6 +585,17 @@ def _get_structured(
+        # transcript and audio stay on the row and the primary is recorded in
+        # external_data. Deliberately ahead of the calendar override: the primary
+        # already holds that meeting.
+        duplicate_capture = _detect_duplicate_capture(uid, main_conv)
+        if duplicate_capture is not None:
+            mark_duplicate_capture(main_conv, duplicate_capture)
</file context>

# One bounded page per status. The candidate read is ordered by the activity
# clock from the candidate's start, so the overlapping captures come first;
# anything beyond the page finished long after it and cannot cover it.
CANDIDATE_PAGE_LIMIT = 25

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: When more than 25 captures finish during a long candidate window, the bounded read can omit the only qualifying primary and leave the duplicate visible. Fetch subsequent pages until finished_at exceeds the candidate’s finished_at (or otherwise retain every row that can overlap the candidate) instead of treating this page as exhaustive.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/conversations/duplicate_capture.py, line 61:

<comment>When more than 25 captures finish during a long candidate window, the bounded read can omit the only qualifying primary and leave the duplicate visible. Fetch subsequent pages until `finished_at` exceeds the candidate’s `finished_at` (or otherwise retain every row that can overlap the candidate) instead of treating this page as exhaustive.</comment>

<file context>
@@ -0,0 +1,240 @@
+# One bounded page per status. The candidate read is ordered by the activity
+# clock from the candidate's start, so the overlapping captures come first;
+# anything beyond the page finished long after it and cannot cover it.
+CANDIDATE_PAGE_LIMIT = 25
+
+_PRIMARY_ELIGIBLE_STATUSES = frozenset({'completed', 'processing'})
</file context>


def test_far_field_disagreement_of_a_quarter_of_the_words_still_matches(self):
mac = _desktop('mac-conv', ROOM_TEXT)
pendant = _record('pendant-conv', _noisy(ROOM_TEXT, rate=0.25, seed=7))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The quarter-words-disagree test sits ~0.03 above the 0.5 containment threshold with its current seed, so it validates the intended robustness barely. Any future edit to these fixture sentences can silently flip it into a false pass/fail that looks like a policy regression. Pin a comfortable margin (e.g. assert the measured containment explicitly, or pick a rate/seed with clear headroom) so the test documents intent instead of hugging the boundary.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_duplicate_capture_policy.py, line 130:

<comment>The quarter-words-disagree test sits ~0.03 above the 0.5 containment threshold with its current seed, so it validates the intended robustness barely. Any future edit to these fixture sentences can silently flip it into a false pass/fail that looks like a policy regression. Pin a comfortable margin (e.g. assert the measured containment explicitly, or pick a rate/seed with clear headroom) so the test documents intent instead of hugging the boundary.</comment>

<file context>
@@ -0,0 +1,326 @@
+
+    def test_far_field_disagreement_of_a_quarter_of_the_words_still_matches(self):
+        mac = _desktop('mac-conv', ROOM_TEXT)
+        pendant = _record('pendant-conv', _noisy(ROOM_TEXT, rate=0.25, seed=7))
+
+        assert find_duplicate_capture(pendant, [mac]) is not None
</file context>

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

Bug fix, 4/5 confidence: real linked bug (#3244), stated root cause, CI green, adds unit tests. Diff is large (1195 lines) but proportionate to the described scope (new policy module + call-site + tests + docs); not yet fixed on main. Approving and landing.

@kodjima33
kodjima33 merged commit 6773eff into BasedHardware:main Sep 13, 2026
42 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix double recording when both device and macOS app is on ($100)

3 participants