Repository navigation
fix(sync): never merge offline audio across an estimated recording clock - #22925
Conversation
When the pendant gives no trustworthy recording time, the app stamped offline audio as "now - duration" and laid its chunks end to end, so audio recorded on different days reached the backend with adjacent invented timestamps and the 120 s temporal merge stitched it into one conversation. App: chunks carry a clock run (`_clke<run>_` before the filename timestamp) whenever their start is estimated; ring transfers break chunks at device timestamp discontinuities and give a stale post-restart clock its own run. Backend: the run is a capture partition (compatible_capture, assignment index, chunk identity, smart-merge partition), so estimated audio merges only within its own contiguous recording. Untagged uploads are unchanged. Kill switch: SYNC_CLOCK_RUN_PARTITION_ENABLED=false. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7f1821256
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return all( | ||
| left.get(key) == right.get(key) for key in ('source', 'client_device_id', SYNC_CLOCK_RUN_FIELD) | ||
| ) and bool(left.get('is_locked')) == bool(right.get('is_locked')) |
There was a problem hiding this comment.
Make the kill switch ignore persisted clock partitions
When SYNC_CLOCK_RUN_PARTITION_ENABLED is turned off after any tagged audio has been ingested, clock_run_from_path() removes the run from new/retried uploads, but this unconditional comparison still partitions against sync_clock_run stored on existing conversations. Consequently retries from the same recording create separate conversations, and previously partitioned rows still cannot use plain temporal merging, so the documented incident switch does not actually restore the old behavior. Gate all clock-field comparisons, including assignment and smart-merge partitioning, on the same switch.
Useful? React with 👍 / 👎.
| timerStart = DateTime.now().millisecondsSinceEpoch ~/ 1000 - seconds; | ||
| clockRun = Wal.newClockRun(); | ||
| } |
There was a problem hiding this comment.
Reuse the clock run when retrying an SD-card transfer
If a legacy SD-card transfer durably registers some chunks and then disconnects, the card is deliberately left uncleared; the next connection calls start()/setDevice(), rebuilds _wals, and this line assigns a fresh nonce. The already-saved chunks therefore carry the old run while the remaining or replayed chunks carry the new run, causing the backend's new partition rule to split one continuous recording after an ordinary BLE retry. The run needs retry-stable persistence or derivation until that device recording is successfully cleared.
Useful? React with 👍 / 👎.
| final boundary = ringRecordClockBoundary( | ||
| previousTs: lastRecordTs, | ||
| ts: ts, | ||
| rtcValid: rtcValid, | ||
| currentRun: currentRun, | ||
| ); |
There was a problem hiding this comment.
Track clock boundaries across skipped live records
When a ring read begins with custody-proven live records, the continue above leaves lastRecordTs unset because boundary tracking only happens here for non-duplicates. If the first offline record follows a reboot and its clock steps backward from that live prefix, it is treated as the first record and receives no estimated-clock run; its stale timestamp can then merge with unrelated device-clocked audio, defeating this change for the live-to-offline handoff. Observe each record's timestamp before skipping its already-durable audio.
Useful? React with 👍 / 👎.
| if (!rtcValid || ts <= 0) { | ||
| return (breaks: false, run: currentRun ?? Wal.newClockRun()); | ||
| } |
There was a problem hiding this comment.
Break the chunk when entering an untimed clock run
When rtcValid is true at download time but a historical record carries the uptime flag, readRecordTimestamp() returns zero and this branch starts an estimated run without setting breaks. If a trusted positive-timestamp record precedes it, both records can therefore enter one chunk; flushChunks() takes only the first record's run, so the estimated audio is uploaded untagged and may merge with unrelated device-clocked audio. Entering an untimed stretch from any timed record must start a new chunk (and entering it from another boot should not silently reuse the prior run).
Useful? React with 👍 / 👎.
| for (var m in timestampMarkers) { | ||
| if (m.key == nextMarkerIdx) { | ||
| timerStart = m.value; | ||
| _activeClockRun = null; |
There was a problem hiding this comment.
Apply timestamp markers at exact chunk boundaries
If an SD-card timestamp marker lands exactly after a full 60-second chunk, the preceding loop advances bytesLeft to nextMarkerIdx, making bytesLeft < nextMarkerIdx false and skipping this entire marker-application block. Later scans require marker indices greater than bytesLeft, so that marker is never applied: subsequent device-timed chunks keep both the estimated timeline and _activeClockRun instead of switching to the marker epoch. Apply the marker even when there are zero residual frames to flush before it.
Useful? React with 👍 / 👎.
| return ( | ||
| row.get('source'), | ||
| row.get('client_device_id'), | ||
| bool(row.get('is_locked')), | ||
| row.get(SYNC_CLOCK_RUN_FIELD), |
There was a problem hiding this comment.
Include the clock run in smart-merge predecessor projections
For a tagged conversation, smart-merge compares this four-field partition against the metadata returned by database/smart_merge.py::find_preceding_conversations, but that query's _PRECEDING_FIELDS projection does not include sync_clock_run. Every same-run predecessor therefore appears to have a null run and is rejected as NO_PREDECESSOR before its full document is read, so pieces from one estimated recording that fall outside assignment's 120-second bridge cannot use the intended smart-merge path. Add the run field to the predecessor projection.
Useful? React with 👍 / 👎.
Summary
Offline sync has been stitching pendant audio from different days into one conversation. Titles, notes, memories and daily recaps of every pendant user who syncs offline audio are affected, and so are the conversation boundaries that Episodes (#22877) and agentic notes (#22853) build on. The notes models summarize faithfully; the conversation boundaries upstream of them are wrong.
The cause is not a merge-rule bug in isolation. The app invents recording times, and the backend trusts them.
Root cause
1. The app writes the download wall clock as the recording time. When the device supplies no trustworthy start time, every transfer path stamps the audio as
now - durationand advances chunk by chunk:app/lib/services/wals/sdcard_wal_sync.dart:192: the listing falls back tonow - secondswhen there is nostorageFiles[2].app/lib/services/wals/sdcard_wal_sync.dart:461: the legacy (no-marker) read ignores even that and always usesnow - accurateDuration, thentimerStart += chunkSecs.app/lib/services/wals/storage_sync.dart:702: a multi-file entry withtimestamp == 0gets the same fallback.app/lib/services/wals/ring_storage_sync.dart:705and:533: without a valid RTC the anchor isnow - estSecs, and later chunks arefirstRecordTs + elapsed.The device stored the audio back to back, with no record of the hours or days between recordings. So audio from Monday, Wednesday and Friday arrives as one dense chain ending at sync time.
2. On current firmware (ring, 3.0.20+), device times can be stale, and a chunk can straddle a gap. After a power loss the pendant restores its clock from the last persisted phone sync and marks it valid (
omi/firmware/omi/src/rtc.c:201-214). Records then carry times that run backwards, on top of earlier ones. Separately,ring_storage_sync.dart:524packs records into 60 s chunks with no check for timestamp continuity, so one chunk can hold the end of one day and the start of the next, under the first record's time. Firmware is read-only here; nothing in this PR changes it.3. The backend trusts the filename timestamp and merges anything within 120 s.
backend/utils/request_validation.py:107: recording time is the trailing_<ts>of the filename.backend/utils/sync/pipeline.py:958,:1626,:1689: segment time is that timestamp plus the VAD offset, which becomesstarted_at.backend/utils/sync/assignment.py:101(interval_matches) and:395(the bridging loop): a piece joins every compatible row withinDEFAULT_GAP_SECONDS = 120(backend/utils/conversation_continuity.py:7,16). Overlap counts as connecting too, which is why stale-clock records glue onto real ones.backend/utils/sync/live_overlap.py:10(compatible_capture) partitions only on source, device and lock. Nothing distinguishes an invented time from a real one.Evidence (owner-lab snapshot, metadata only): the three reported conversations have no
smart_mergestate. They are pure sync-assignment merges (sync_merged_fromof 23, 12 and 4 pieces). Theiraudio_files.chunk_timestampsform a regular chain: 60 s or 75 s steps, at most about 89 s between chunks, over 147 and 66 minutes. That is the shape oftimerStart += chunkSecs, not of real recordings.Still on current main: yes. Every fallback above is present at
origin/main43577cb.Fix
The clock run is a capture partition. When the app estimates a start, the chunk's filename carries
_clke<run>_directly before the timestamp.<run>names one contiguous device recording. The backend (utils/sync/clock_run.py) reads the token, carries it through the VAD segment names toincoming['sync_clock_run'], and treats it likeclient_device_id:compatible_captureandcapture_mismatch(newclocktoken);chunk_identity(two runs can invent the same timestamp);partition();Estimated audio now merges only inside its own run, never with another run or with device-clocked rows.
Device times are kept. No device timestamp is rewritten. In the ring path a chunk now breaks wherever consecutive records step more than 60 s forward (pendant off) or step backwards (stale restart clock), and each chunk starts at its first record's own device time. A backwards step opens a new run, because those times are known to be stale.
Compatibility. Untagged uploads (every device-clocked file, and every older app) behave exactly as before; their rows carry no field and no new index key. Older backends ignore the token: they parse only
_fs<n>and the trailing part.Kill switch:
SYNC_CLOCK_RUN_PARTITION_ENABLED=false. It stops reading the token, which restores today's merging.Limitation. On legacy SD firmware with no timestamp markers, one card download is still one run, because the device recorded no boundaries. The audio from that download can still merge with itself; it can no longer merge with anything else. Real boundaries there need firmware markers.
Tests
backend/tests/unit/test_sync_clock_run_partition.py): five chunks from three recordings on different days, stamped 60 s apart the way the app's estimate packs them.test/unit/wal_clock_run_test.dart: filename, persistence, the alphabet the backend accepts, and the ring boundary rules.ring_custody_download_test.dart: a real ring transfer with day-1 records, then day-2 records, then a backwards restart. It produces three chunks at their own device times; only the stale stretch carries a run.test.sh. No assertion failures. Three files tripped only the CPU-time guard on a host at load average 70 (test_conversation_smart_merge_policy.pypasses alone;test_sync_enrichment_task_probe.pyandtest_sync_phase_metrics.pydon't touch this code).flutter teston the ring, SD-card, upload and new suites, 77 passed.dart analyzeclean on the changed files.How often (prod, read-only aggregate)
Read with the
ro-prodtier. It was a metadata-only scan (field mask:started_at,finished_at,created_at,source,sync_merged_from,audio_filestiming,deleted,discarded); no transcripts were read and no ids were kept.There is no collection-group
created_atindex, and creating one would be a prod write, so I sampled the first 60,000 conversation documents by name: 363 users.sync_merged_from≥ 1)Merged-row spans: < 30 min 349, 30–60 min 127, 1–2 h 91, 2–4 h 19, ≥ 4 h 1.
The "gaps > 30 min" count under-reports this bug. Stitched cross-day merges have no gap at all, because the invented chain is dense. The stitched-looking row is the better detector, but it is an upper bound: it also counts real long conversations.
Repair of already-corrupted conversations (proposal only, no prod writes)
source=omi,sync_merged_from≥ 2,capture_groupunset, andaudio_files.chunk_timestampsforming a regular chain (constant step equal to the chunk length, no gap > 3 min), with integer-second chunk origins. Rank by span. Score a sample against a human judgment first; David's three are the seed labels.sync_merged_into) without separate audio. So the repair splits on content, not time: re-segment each candidate's transcript at topic or speaker-set changes, with a cheap LLM boundary pass over the decrypted transcript in the user's own processing context. Write each part as its own conversation, flaggedrecording_time_estimated, and keep the original as the redirect survivor, so the change can be undone.Product invariants affected
Rollout
On by default. The kill switch is the env flag above. The backend part is inert until a new app build sends tokens. Backend deploys go through the rollout lead session; this PR does not merge or deploy.
Line-Count-Exception: backend/utils/sync/pipeline.py | 3609 -> 3617 | carries the estimated-clock run from the upload filename through VAD segment names into the assignment row; the parsing and policy live in the new utils/sync/clock_run.py
Failure-Class: FC-recovery-time-used-as-event-time
UI-Evidence: none -- no UI change; WAL transfer timing and upload filenames only
🤖 Generated with Claude Code
UI-Evidence: none -- sync-service clock-run partitioning only; no UI changes