Skip to content

fix(sync): never merge offline audio across an estimated recording clock - #22925

Merged
Git-on-my-level merged 3 commits into
mainfrom
fix/sync-clock-run-partition
Oct 21, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
fix/sync-clock-run-partition

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

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 - duration and advances chunk by chunk:

  • app/lib/services/wals/sdcard_wal_sync.dart:192: the listing falls back to now - seconds when there is no storageFiles[2].
  • app/lib/services/wals/sdcard_wal_sync.dart:461: the legacy (no-marker) read ignores even that and always uses now - accurateDuration, then timerStart += chunkSecs.
  • app/lib/services/wals/storage_sync.dart:702: a multi-file entry with timestamp == 0 gets the same fallback.
  • app/lib/services/wals/ring_storage_sync.dart:705 and :533: without a valid RTC the anchor is now - estSecs, and later chunks are firstRecordTs + 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:524 packs 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 becomes started_at.
  • backend/utils/sync/assignment.py:101 (interval_matches) and :395 (the bridging loop): a piece joins every compatible row within DEFAULT_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_merge state. They are pure sync-assignment merges (sync_merged_from of 23, 12 and 4 pieces). Their audio_files.chunk_timestamps form 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 of timerStart += chunkSecs, not of real recordings.

Still on current main: yes. Every fallback above is present at origin/main 43577cb.

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 to incoming['sync_clock_run'], and treats it like client_device_id:

    • in compatible_capture and capture_mismatch (new clock token);
    • in the assignment index entry;
    • in chunk_identity (two runs can invent the same timestamp);
    • in the smart-merge partition();
    • in the minimal-redrive attach.

    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

  • Regression (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.
    • With runs: three conversations. Without the token, the same adjacency still merges into one, which is the bug as it stood.
    • A stale-clock piece no longer joins the device-clocked conversation it overlaps.
    • Also covered: token parsing (it can't be spoofed through the device-name part), segment-name round trip, partition parity, and the kill switch.
  • App:
    • 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.
  • Results:
    • Backend: 152 sync/merge/batch-pipeline unit files under 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.py passes alone; test_sync_enrichment_task_probe.py and test_sync_phase_metrics.py don't touch this code).
    • App: flutter test on the ring, SD-card, upload and new suites, 77 passed. dart analyze clean on the changed files.

How often (prod, read-only aggregate)

Read with the ro-prod tier. It was a metadata-only scan (field mask: started_at, finished_at, created_at, source, sync_merged_from, audio_files timing, deleted, discarded); no transcripts were read and no ids were kept.

There is no collection-group created_at index, and creating one would be a prod write, so I sampled the first 60,000 conversation documents by name: 363 users.

Measure Count
Conversations since 2026-09-01 13,036
Sync-merged (sync_merged_from ≥ 1) 587 (4.5%), across 17 users
Merged rows with an internal chunk gap > 30 min 6 (1.1%); > 3 h: 1
Merged rows that look stitched: ≥ 60 min, ≥ 5 pieces, no chunk gap > 3 min 25 (4.3% of merged)

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)

  1. Identify candidates offline: source=omi, sync_merged_from ≥ 2, capture_group unset, and audio_files.chunk_timestamps forming 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.
  2. We can't re-time from the data. The real recording times were never uploaded for these rows, and the source pieces are tombstones (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, flagged recording_time_estimated, and keep the original as the redirect survivor, so the change can be undone.
  3. Gate it. Dry-run report first, then the owner-lab account only, then an opt-in "split this conversation" action in the app, rather than a silent bulk rewrite. Memories, daily recaps and episodes derived from a split conversation need reprocessing; the existing reprocess contract covers that.
  4. Prevention first. This PR stops new corruption. The repair is worth running only once prod has run this PR's app build.

Product invariants affected

  • INV-CAP-1: touched only in where chunk files split and how they are named. Every frame still lands in a durable WAL before custody advance; no frame is dropped, paused or skipped.

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

View guided diff Turn on auto-fix

UI-Evidence: none -- sync-service clock-run partitioning only; no UI changes

Git-on-my-level and others added 3 commits October 21, 2026 01:31
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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T19:45:43.734974Z b7f1821 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment on lines +16 to +18
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'))

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 Badge 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 👍 / 👎.

Comment on lines 193 to 195
timerStart = DateTime.now().millisecondsSinceEpoch ~/ 1000 - seconds;
clockRun = Wal.newClockRun();
}

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 Badge 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 👍 / 👎.

Comment on lines +765 to +770
final boundary = ringRecordClockBoundary(
previousTs: lastRecordTs,
ts: ts,
rtcValid: rtcValid,
currentRun: currentRun,
);

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 Badge 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 👍 / 👎.

Comment on lines +63 to +65
if (!rtcValid || ts <= 0) {
return (breaks: false, run: currentRun ?? Wal.newClockRun());
}

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 Badge 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 👍 / 👎.

Comment on lines 672 to +675
for (var m in timestampMarkers) {
if (m.key == nextMarkerIdx) {
timerStart = m.value;
_activeClockRun = null;

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 Badge 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 👍 / 👎.

Comment on lines +116 to +120
return (
row.get('source'),
row.get('client_device_id'),
bool(row.get('is_locked')),
row.get(SYNC_CLOCK_RUN_FIELD),

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 Badge 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 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit c8a9e7d into main Oct 21, 2026
62 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/sync-clock-run-partition branch October 21, 2026 02:39
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