Skip to content

feat(backend): fold silence-split pendant conversations with Jev (default off, shadow/merge modes) - #19777

Merged
Git-on-my-level merged 5 commits into
mainfrom
lane/smart-merge-jev
Sep 29, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
lane/smart-merge-jev

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Live capture ends a conversation after about two minutes without speech, so one occasion can become many rows (one evening on 2026-09-28 became 7 conversations with 2-10 minute boundaries). Nothing on main merges silence-split live conversations by topic.

This PR adds a default-off, three-mode step to the durable finalizer that asks Jev whether a just-finished pendant conversation continues the immediately preceding one from the same device, and in merge mode folds it in. With the flag unset nothing changes.

CONVERSATION_SMART_MERGE_MODE:

  • off (default, and any unknown value): one env read in the finalizer, no reads, no model call, no writes.
  • shadow: select the candidate, build the state, ask Jev, store a server-only smart_merge_decision record on the new conversation (shadow_would_merge / shadow_keep), emit metrics. Never merges.
  • merge: same, and at p_same >= 0.35 the earlier conversation keeps its id and absorbs the new one.

CONVERSATION_SMART_MERGE_UID_ALLOWLIST (optional): when set, only those users are considered (empty = everyone), so shadow can run on one account first. Neither flag is declared in any deploy manifest. Enabling either mode is a separate decision.

Design (what and why)

  • Trigger: inside finalize_persisted_conversation, after the fanout claim is claimed and before duplicate-capture linking and the derived-effects bundle, for CAPTURE_END jobs and omi (pendant) source only. That point runs exactly once per job under the existing lease. A merged conversation's memories, action items, webhooks and vectors are never produced, so there is nothing to retract. CLIENT_FINALIZE counts as a manual split and is honoured. Sync and desktop are out of scope: the benchmark was 113/138 pendant pairs and desktop recall was 0/2.
  • Merge mechanism: reuses the sync bridge redirect contract instead of perform_merge_async, which mints a new id. The new row becomes deleted + discarded + sync_merged_into=<survivor>, and the survivor gets sync_merged_from. Existing redirect readers work unchanged: detail GET redirects to the survivor, manual speaker assignment follows the chain, list/count/search hide the tombstone, and deleting the survivor purges retained donors. The transcript is appended on the survivor's absolute timeline. Speaker ids are reallocated through ConversationSpeakerIdAllocator so two voices never collapse, and segment ids are kept.
  • Candidate: the newest visible row of the same source created before the new one, then the first row in the same device partition (an unknown device is its own partition, as in sync). If the immediately preceding row is busy, the pair is blocked; the step does not skip past it. Deterministic gates run before any model call:
    • recorded gap 120 s–60 min and speech gap ≥ 120 s
    • ≥ 25 words on each side
    • no user-managed row (user title, starred, folder, restored, shared, photos, manual speakers, locked, capture group, duplicate link)
    • no wake word, predecessor not ended by the user
    • 3 h merged span, 4,000 segments, 12 fragments
  • Query/index: a registered FirestoreQuerySpec whose signature is the existing conversations_discarded_source_status_created index. firestore.indexes.json is unchanged, so no index is provisioned.
  • Jev state: the benchmark's wording A and chain-aware input (variant iv), with the clock in the user's timezone. A is always one fragment taken from the survivor's smart_merge.fragments ledger, never the regenerated merged summary, which the benchmark did not test. Jev goes through the existing utils/llm/jev_client.ask_jev on lane conversation_smart_merge (gateway lane omi:auto:jev-decisions), 3 s, one attempt. Any error keeps both conversations.
  • Survivor refresh: one full reprocess per merge (new ProcessingTrigger.SMART_MERGE: run now, reprocess, bypass JIT, relevance KEEP), plus a re-embed. There is no debounce: a one-refresh-per-chain debounce needs a durable delayed trigger that the live path does not have. Sync appends are not debounced either.
  • Races: a merge requires refreshed_revision == revision on the survivor, and the refresh runs under a short lease, so a refresh can never persist over a newer append. The transaction re-reads both rows, so a concurrent star, title, edit or delete aborts the merge. The decision record is sticky, so a retried job never re-asks Jev. Once the transaction commits, the donor branch resumes cleanup and refresh on every retry, in any mode. It never runs the donor's own derived effects.
  • Sync: a late repair WAL that targets a smart-merge donor now resolves to the survivor. Without this, temporal fallback would recreate the donor's audio as a duplicate row. Sync bridge donors are unchanged.
  • Clients (read from app/lib and desktop/macos, not assumed): neither client knows sync_merged_into. The listen memory_created event for a merged conversation carries the tombstone with discarded=true, so Flutter drops its processing card and hides the row, and macOS reloads a list that no longer contains it. Known client gaps, not fixed here:
    • macOS never deletes GRDB rows the server stops returning. The same is already true for sync bridges and manual merges.
    • Flutter's app-resume incremental fetch does not remove rows.
    • Opening a cached donor row shows stale content, and edits on it return 404.

Benchmark provenance (offline, 2026-09-29)

The private report lives outside git on David's machine (~/.local/share/jev-pilots/adjacent-merge/REPORT.md). No transcript text is in this PR, and all fixtures are synthetic.

  • Labels: 138 adjacent pairs from one account (113 pendant), with the Opus labels frozen and hashed before any Jev call.
  • Selected configuration (wording A, chain-aware state, >= 0.35) on held-out: AUC 0.918 (bootstrap 95% CI 0.84–0.98), 25/49 continuations merged, 0/19 false merges (exact one-sided 95% upper bound 14.6%). The nearest held-out negative scored 0.305.
  • Baselines at zero-dev-false-merge thresholds: gap-only 18 TP / 3 FP; gap+TF-IDF 26 TP / 2 FP.
  • Latency and cost: p50 0.51 s, p95 0.65 s, about $0.00006 per call.
  • Verdict: shadow first. The benchmark's promotion bar is at least 100 reviewed live negatives with at most 1 false merge.

Verification

Worktree lane/smart-merge-jev, base origin/main d97f753. All runs are local and hermetic. Each result names the layer it measured.

  • Unit, via BACKEND_UNIT_TEST_FILE_LIST=… bash backend/test.sh: all passed.
    • New tests:
      • test_conversation_smart_merge_state.py (8): exact template text
      • test_conversation_smart_merge_policy.py (29): every exclusion, gap edges 119/120/3600/3601, speech-gap shard, word minimum, caps, stretch 30-minute link, absorb payloads
      • test_conversation_smart_merge.py (38), which covers:
        • flag parsing and no-I/O when off, donor resume when off
        • shadow at 0.34/0.35, Jev unavailable, decision error
        • merge at 0.35/0.34, sticky replay, user edit/delete mid-merge, neighbour race, owed-refresh payment
        • retry after partial failure, destructive-gate deferral, deleted survivor, idempotent transaction, ambiguous commit
        • a synthetic 7-fragment evening → one survivor, six redirects, 6 refreshes (one per absorb)
        • query/index shape
      • test_conversation_smart_merge_finalizer.py (4): derived effects skipped on absorb, unchanged path when kept or off
    • Extended tests: test_sync_cross_job_assignment.py (+4: donor-redirect repair WAL, deleted survivor, bridge donor unchanged).
    • Related suites re-run green:
      • relevance
      • finalizer logging
      • JIT
      • duplicate capture
      • free-tier harness (stubs the new finalizer import)
      • listen finalization / pusher finalization
      • test_sync_v2, test_sync_cloud_tasks, test_sync_transcription_prefs, test_sync_bridge_lifecycle, archive filter
      • Jev client, owner Jev, metrics sidecar
      • Firestore index/query contracts
      • runtime image contracts, lifecycle write guard
  • Static:
    • backend/scripts/typecheck.sh (pyright): 0 errors
    • scripts/backend-python-format --check: clean
    • check_conversation_lifecycle_writes.py: pass
    • firestore_query_coverage.py --check-ratchet: pass
    • generate_firestore_indexes.py: manifest unchanged
    • check_feature_flag_registry.py: OK
    • make runtime-image-source-closure: pass
    • The pusher image's reachable third-party module set is identical to main (236 modules; no onnxruntime/torch).
  • Not verified:
    • no live Jev call (all Jev answers are faked at ask_jev)
    • no real Firestore (StrictFirestore fixture; no emulator contention run)
    • no real process_conversation refresh (faked at its seam)
    • no client rendering of a merged conversation on either app
    • no dev or prod deploy

Deploy targets (when David decides to deploy)

  • backend (Cloud Run: backend + backend-sync, same image): Cloud Tasks finalization worker and sync assignment.
  • pusher (GKE): live finalization.
  • No listen change is needed. With the flag unset, deploy order does not matter.

Rollback: leave CONVERSATION_SMART_MERGE_MODE unset/off. If merge was ever on, the redirect tombstones keep each donor's full document and original audio. A merge is reversible by an operator (restore the donor, remove its segment ids from the survivor, reprocess both); no route or script for that ships here.

Known risks / for review

  • The threshold margin is thin (0.03–0.045 above the nearest negatives), and calibration is tied to the exact state text and typesafe/jev-1.13.
  • Merge mode reprocesses the survivor once per absorb. For a k-fragment chain that is about k(k+1)/2 − 1 extra fragment-units of summary, memory and action-item work.
  • The macOS GRDB cache and the Flutter resume path can keep showing a donor row until a full refresh. This is pre-existing behaviour for sync bridges and manual merges.
  • Custom-STT rows are excluded because budget denial can prevent the required refresh. A BYOK-only survivor can still owe a refresh if its request-scoped key is unavailable; keep merge mode off until that path is resolved.

Product invariants affected

  • INV-MEM-4 — the refresh still uses the existing canonical memory replacement path; the review fences its persistence to the current survivor revision and lease.
  • INV-TASK-2 — the change passes a refresh fence through the existing processor; it does not add a task writer or change capture proposal policy.

Line-Count-Exception: backend/database/firestore_index_registry.py | 1527 -> 1545 | the registry is the single place a serving compound query may be declared; the new spec reuses an existing index signature
Line-Count-Exception: backend/database/conversations.py | 3191 -> 3204 | the canonical processor persistence transaction must fence smart-merge refresh leases
Line-Count-Exception: backend/utils/conversations/process_conversation.py | 3416 -> 3421 | the processor must pass the refresh fence to canonical persistence

🤖 Generated with Claude Code

Review round 1 (Codex Sol)

Confirmed and fixed: invalid Jev scores could merge or be stored; merge decisions were not durable before absorb; stale processors could overwrite a newly merged live survivor; a revisioned survivor could lose live-target sync repair semantics; a refresh could be marked complete after its lease was lost or after vector failure; custom-STT budget denial could leave a survivor permanently owing refresh; metric reasons and fragment metadata were insufficiently bounded. The lifecycle guard now inventories the variable-payload tombstone writer.

Hermetic regression tests went red before each fix. Three deliberate mutants (revision fence, flag-off path, user-managed exclusion) each made its targeted test fail. The 33-file backend suite named above plus new regression files passed locally through backend/test.sh; pyright reported 0 errors; formatter, runtime image source closure, and lifecycle guard passed. Pusher's reachable third-party set contains no onnxruntime or torch. No live Jev, Firestore, client, deployment, or merge-mode acceptance was run. BYOK refresh without a reusable key remains a merge-mode blocker; shadow mode does not refresh.

Review in cubic

Git-on-my-level and others added 4 commits September 29, 2026 18:46
…efault off)

Adds the pieces that decide whether a finished pendant conversation continues
the immediately preceding one and, in merge mode, fold it in:

- config/conversation_smart_merge.py: CONVERSATION_SMART_MERGE_MODE
  (off|shadow|merge, default off) and the benchmark-derived constants
  (threshold 0.35, gap 120 s-60 min, 3 s / one attempt, state caps, snowball caps).
- smart_merge_state.py: benchmark question wording A and chain-aware state.
- smart_merge_policy.py: deterministic eligibility, gaps, stretch, and absorb
  payloads reusing the sync bridge redirect contract.
- database/smart_merge.py: preceding-row query (registered spec on the existing
  conversations_discarded_source_status_created index), decision record,
  absorb transaction, survivor refresh lease.
- smart_merge.py: orchestration, fail-open before commit, replayable after.
- ProcessingTrigger.SMART_MERGE and omi_conversation_smart_merge_* metrics.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…repair WALs to the survivor

The finalizer calls the smart-merge step behind the fanout claim and before
duplicate-capture linking or any derived effect, for CAPTURE_END jobs only.
An absorbed conversation skips its own derived effects and completes fanout;
a donor always resumes its cleanup and survivor refresh on retry, whatever
the mode. Flag off adds one env read and no I/O.

Sync assignment follows a smart-merge donor's redirect when a late repair WAL
targets it, so the audio appends to the survivor instead of recreating the
donor as a duplicate row. Sync bridge donors keep the temporal fallback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Registers CONVERSATION_SMART_MERGE_MODE and CONVERSATION_SMART_MERGE_UID_ALLOWLIST
(no deploy manifest declares either) and records the finalizer, redirect and
sync-assignment contracts in the conversations/sync ARCHITECTURE files and the
listen/pusher pipeline doc.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 026c9af into main Sep 29, 2026
56 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/smart-merge-jev branch September 29, 2026 15:58
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.

1 participant