Skip to content

fix(sync): keep offline WAL shards in one conversation (#5747) - #14157

Closed
apoorvdarshan wants to merge 5 commits into
BasedHardware:mainfrom
apoorvdarshan:cursor/fix-offline-sync-segmentation-5747-d02a
Closed

apoorvdarshan wants to merge 5 commits into
BasedHardware:mainfrom
apoorvdarshan:cursor/fix-offline-sync-segmentation-5747-d02a

Conversation

@apoorvdarshan

@apoorvdarshan apoorvdarshan commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #5747

Line-Count-Exception: backend/routers/sync.py | 2072 -> 2079 | batch-shared clock shift computation before ordered segment assignment (#5747/#4771)
Line-Count-Exception: backend/utils/sync/pipeline.py | 2537 -> 2562 | offline sync batch clock shift + normalize_capture_window before closest-conversation merge (#5747/#4770/#4771)

What changed and why

Offline sync was creating many short (~1 minute) conversations when successive WAL shards uploaded together, especially with mild device RTC ahead of the phone. Live sync already segments on silence/voice; offline merge was failing because each shard's capture window was normalized independently to [now−60s, now], so closest-conversation lookup could not chain shards into one conversation.

This change applies one batch-shared clock shift (newest_end − now) across v1 and v2 sync pipelines before get_closest_conversation_to_timestamps, preserving relative spacing between ~60s shards so they merge like a single capture session. Client-side normalizeWalTimerStart clamps future WAL start times for sync UI/upload filenames (#4770), and upload validation allows mild future skew within SYNC_CAPTURE_MAX_FUTURE_SKEW_SECONDS (default 300s) while the pipeline clamps conversation bounds to server now.

Parallel assignment races were already addressed (#7819 turnstile); this closes the clock-skew / shard-collapse path called out on the issue (same approach as the unmerged #11094 work for #4771).

Product invariants affected

none

How it was verified

cd backend && ./scripts/sync-python-deps.sh && source .venv/bin/activate
python -m pytest tests/unit/test_sync_two_lane.py tests/unit/test_sync_ordered_assignment.py \
  tests/unit/test_request_validation_contracts.py tests/unit/test_sync_file_paths_filename_none.py \
  -k 'normalize_capture or batch_clock or clock_shift or allows_mild_future_skew or retrieve_file_paths' -q

Result: 12 passed (includes duplicate-filename 400 regression in test_sync_file_paths_filename_none.py).

Flutter WAL unit test added (app/test/unit/wal_timer_start_normalize_test.dart); not executed on this VM (Flutter toolchain not installed).

Tests

  • Backend: batch clock shift + normalize capture window contracts (test_sync_two_lane.py)
  • Backend: static contracts that v1/v2 pass shared clock_shift and normalize before closest-conversation lookup (test_sync_ordered_assignment.py)
  • Backend: mild future filename timestamp acceptance (test_request_validation_contracts.py)
  • Backend: _retrieve_file_paths_v2 guards (missing filename, duplicate filename, staging errors) (test_sync_file_paths_filename_none.py)
  • App: normalizeWalTimerStart unit tests

Failure class (fixes)

Failure-Class: none

CI fix (2026-09-16)

Rebased onto current BasedHardware/omi main (resolved test_jit_qa_sweep_repair.py date pinning). Hygiene: corrected pipeline.py line-count exception (2537 -> 2562). Backend shard 2: fixed duplicate-filename regression test stub so the first upload stages before asserting 400.

@apoorvdarshan

Copy link
Copy Markdown
Collaborator Author

CI investigation (workflow 35047915608)

Backend unit suite failed in the aggregator step Require every shard and the guardrails to pass because shard 3/4 failed — not an aggregator flake.

Job Result
Backend unit shard 1/4 success
Backend unit shard 2/4 success
Backend unit shard 3/4 failure
Backend unit shard 4/4 success
Backend unit guardrails success

Failures (unrelated to #5747 offline sync):

tests/unit/test_jit_qa_sweep_repair.py::test_repair_joins_gateway_accounting_and_writes_single_receipt
tests/unit/test_jit_qa_sweep_repair.py::test_repair_without_a_joinable_sweep_run_fails_closed
AssertionError: assert '2026-09-16' == '2026-09-15'

collect_provider_outcome_evidence queries llm_gateway_attempts by UTC calendar day(s) in the tombstone claim window (derived from real now), while the test fake DB still expected the hardcoded date 2026-09-15. CI ran on 2026-09-16 UTC, so the query date no longer matched.

Fix (a4e1bf2fab on cursor/fix-offline-sync-segmentation-5747-d02a): Pin a fixed UTC anchor (_FIXED_NOW) and pass now= into repair_tombstone; align attempt rows and attempt_date with that anchor. Offline sync / clock-shift tests were not involved in this failure.

Local verification: python -m pytest tests/unit/test_jit_qa_sweep_repair.py -q → 4 passed.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for this — the write-up is thorough and the root-cause analysis matches the code. The server-side approach is the right shape and the test coverage for it is genuinely good. One blocking issue on the client side, below.

What looks good

  • backend/utils/sync/lanes.py: batch_clock_shift() deriving a single shared offset (newest_end − now) instead of per-segment normalization is exactly the right fix for the shard-collapse symptom — test_batch_clock_shift_preserves_five_minute_offline_shard_span in backend/tests/unit/test_sync_two_lane.py demonstrates the preserved 300s span and adjacency nicely.
  • backend/utils/sync/pipeline.py: applying normalize_capture_window in process_segment before get_closest_conversation_to_timestamps, with the shared shift threaded through both _run_full_pipeline_background_async (v2) and sync_local_files (v1, backend/routers/sync.py), is correct and consistent across lanes. The new_finished_at > now_utc clamp at the merge site is a good belt-and-braces addition.
  • backend/utils/request_validation.py + _retrieve_file_paths_v2: accepting up to now + SYNC_CAPTURE_MAX_FUTURE_SKEW_SECONDS aligns the parse bound with the bound classify_sync_lane already enforced (future_capture_time → untrusted/backfill), so no lane guard is bypassed. Moving maximum_future_skew_seconds into the new backend/utils/sync/capture_skew.py to break the import cycle is clean, and backend/tests/unit/test_request_validation_contracts.py pins the new behavior.
  • backend/tests/unit/test_jit_qa_sweep_repair.py: verified repair_tombstone(..., now=None) already exists in backend/scripts/jit_qa_sweep_repair.py, so the _FIXED_NOW re-anchoring is a legitimate hermeticity fix for the date-rollover flake you diagnosed — thanks also for the detailed CI investigation comment.
  • The source-contract tests in backend/tests/unit/test_sync_ordered_assignment.py pin the v1+v2 wiring in the established style of that suite, and the utils.sync* stub purge in backend/tests/unit/test_sync_file_paths_filename_none.py is sensible harness hygiene now that request_validation imports from utils.sync.

Blocking: the client-side clamp collapses future shards onto one timerStart

normalizeWalTimerStart in app/lib/services/wals/wal.dart clamps each WAL independently to now − seconds. For the exact cohort this PR targets (device RTC ahead of the phone, _chunk() producing equal-duration ~60s shards), every still-future WAL recovered via addExternalWal or _initializeWals in app/lib/services/wals/local_wal_sync.dart is clamped at the same moment to the same value. Consequences, checked against this head:

  • Wal.id is '${device}_$timerStart' and Wal.toFileName() embeds timerStart (audio_..._${timerStart}.bin), so colliding WALs share id and filename.
  • The server stages uploads by filename under syncing/{uid}/{job_id}/ in _retrieve_file_paths_v2 — a colliding filename overwrites the earlier shard's staged audio, i.e. silent shard loss.
  • Even without a collision, clamping each shard to its own [now − duration, now] destroys the inter-shard spacing that batch_clock_shift exists to preserve — reintroducing the #5747 symptom on the phone-local path.

Note the asymmetry: live _chunk() WALs derive timerStart from real frame timestamps, so active sessions are mostly safe; the risk concentrates in recovery/init clamping multiple future-dated WALs at once. And since the server now tolerates ≤ now+300s filenames and applies the batch shift itself, the client barely needs to rewrite these timestamps at all — the four cases in app/test/unit/wal_timer_start_normalize_test.dart cover the helper in isolation but not this multi-WAL interaction.

Requested changes:

  1. On the client, mirror the batch-shared approach (one shift for the recovered set, preserving relative spacing) and/or guarantee clamped timerStart uniqueness so Wal.toFileName/Wal.id can't collide; please add a test covering ≥2 future-dated equal-duration WALs clamped together.
  2. Non-blocking suggestion: as defense-in-depth, _retrieve_file_paths_v2 could reject or disambiguate duplicate filenames within one job.

Everything else can land as-is once the client side is reworked. Separately, leaving the timestamp-validation relaxation in parse_sync_filename_timestamp/_retrieve_file_paths_v2 for maintainer sign-off, since it widens which client-proposed capture times the Offline Sync trust boundary accepts.


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 Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Sep 16, 2026
@apoorvdarshan

Copy link
Copy Markdown
Collaborator Author

Addressed the client-side clamp collision review point in b82c0a4107:

Client (batch-shared shift) — Added batchWalClockShiftSeconds / normalizeWalCaptureWindow / normalizeWalTimerStartsInBatch in wal.dart, mirroring server batch_clock_shift + shared clock_shift. LocalWalSync now batch-normalizes on _initializeWals and after each addExternalWal (instead of per-WAL now − seconds), preserving inter-shard spacing and distinct Wal.id / toFileName(). A small _ensureUniqueWalTimerStarts pass is defense-in-depth if anything still collides.

Test — wal_timer_start_normalize_test.dart: five-shard span + three equal 60s future shards → unique ids/filenames and expected spaced starts.

Server (optional) — _retrieve_file_paths_v2 returns 400 on duplicate filenames within one upload batch (+ unit test).

Server batch_clock_shift unchanged. Flutter tests not run here (no Flutter on cloud VM); please run flutter test test/unit/wal_timer_start_normalize_test.dart locally/CI.

cursoragent and others added 5 commits September 16, 2026 22:21
…#5747)

Offline sync was splitting successive ~60s WAL segments into many short
conversations when device RTC ran ahead of the phone. Apply one batch-shared
clock shift before closest-conversation assignment so relative capture times
stay contiguous and merge like live sync.

Also clamp future-dated WAL timerStart on the client (BasedHardware#4770) and allow mild
upload timestamp skew within SYNC_CAPTURE_MAX_FUTURE_SKEW_SECONDS.

Verification:
  cd backend && source .venv/bin/activate && python -m pytest \
    tests/unit/test_sync_two_lane.py -k 'normalize_capture or batch_clock' \
    tests/unit/test_sync_ordered_assignment.py -k clock_shift \
    tests/unit/test_request_validation_contracts.py::test_parse_sync_filename_timestamp_allows_mild_future_skew -q
  (7 passed)

Co-authored-by: Apoorv Darshan <[email protected]>
Shard 3/4 failed because collect_provider_outcome_evidence queries
llm_gateway_attempts by the claim window's UTC calendar day while the
fake DB expected a hardcoded 2026-09-15. CI ran on 2026-09-16.

Verification: python -m pytest tests/unit/test_jit_qa_sweep_repair.py -q (4 passed)

Co-authored-by: Apoorv Darshan <[email protected]>
Mirror backend batch_clock_shift on the client so recovered offline shards
with a fast device clock no longer collapse to the same timerStart/id.
LocalWalSync batch-normalizes on init and after addExternalWal; a uniqueness
pass prevents Wal.id collisions. Server staging rejects duplicate filenames
per job as defense-in-depth.

Verification: flutter test unavailable in cloud VM; wal_timer_start_normalize_test.dart
covers batch shift + distinct ids for three future 60s shards.

Co-authored-by: Apoorv Darshan <[email protected]>
Duplicate-filename coverage must stage the first upload before asserting the
400; MagicMock file handles made shutil.copyfileobj fail with 500.

Co-authored-by: Apoorv Darshan <[email protected]>
@cursor
cursor Bot force-pushed the cursor/fix-offline-sync-segmentation-5747-d02a branch from b82c0a4 to f796145 Compare September 16, 2026 22:25
@apoorvdarshan

Copy link
Copy Markdown
Collaborator Author

Rebase + CI fixes pushed (f796145864 on cursor/fix-offline-sync-segmentation-5747-d02a)

  • Rebased onto current main; kept batch clock-shift / WAL uniqueness + upstream JIT QA sweep repair date pinning (_ATTEMPT_DATE).
  • Hygiene: PR body line-count exception for backend/utils/sync/pipeline.py updated to 2537 -> 2562 (was 2558).
  • Backend unit shard 2/4: test_sync_file_paths_filename_none.py duplicate-filename case now uses BytesIO for upload bodies so the first file stages and the duplicate guard returns 400 (was 500 from copyfileobj on MagicMock).

Local: test_sync_file_paths_filename_none.py (4/4) + related sync/WAL pytest selection (12/12).

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai please re-review — auto review was skipped after the branch rewrite/rebase.

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 17, 2026

Copy link
Copy Markdown

@cubic-dev-ai please re-review — auto review was skipped after the branch rewrite/rebase.

@apoorvdarshan cubic can't start this review because your workspace has reached its free monthly review limit. cubic has reviewed 402,637 of the 400,000 allowed lines of code this month. Reviews resume on 1 October 2026 (in 14 days). Paid plans include much higher monthly review limits. Upgrade now to resume reviews.

To help optimise your usage, you can tune cubic to get the most out of your usage limits:

Learn more →

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Both items from my earlier review are resolved on the current head — thanks for the quick turnaround and the clean implementation.

Verified on f7961458

  • app/lib/services/wals/wal.dart: normalizeWalTimerStartsInBatch() now applies one shared shift (batchWalClockShiftSeconds, mirroring the server's batch_clock_shift) to all still-future WALs so inter-shard spacing survives, and _ensureUniqueWalTimerStarts() guarantees distinct per-device timerStarts — Wal.id and getFileName() can no longer collide after clamping.
  • app/lib/services/wals/local_wal_sync.dart: both recovery paths are covered — addExternalWal() normalizes after insert, and _initializeWals() re-normalizes on load, persisting only when a value actually shifted.
  • app/test/unit/wal_timer_start_normalize_test.dart: the requested multi-WAL test is in place — "batch normalize keeps distinct Wal ids for equal-duration future shards" checks 3 equal-duration future WALs for distinct ids/filenames and the preserved −3d/−2d/−d spacing.
  • backend/utils/sync/pipeline.py: _retrieve_file_paths_v2() now rejects duplicate filenames within a job (400 "Duplicate sync filename in upload batch") — the defense-in-depth suggestion, implemented, with real byte staging exercised in backend/tests/unit/test_sync_file_paths_filename_none.py.
  • v1/v2 wiring is symmetric and pinned by the source-contract tests in backend/tests/unit/test_sync_ordered_assignment.py: batch_clock_shift(batch_windows) → clock_shift= into process_segment in both backend/routers/sync.py (v1) and _run_full_pipeline_background_async (v2), with normalize_capture_window applied before get_closest_conversation_to_timestamps.
  • The remaining test changes (_FIXED_NOW anchoring in test_jit_qa_sweep_repair.py, the mild-skew contract in test_request_validation_contracts.py, the utils.sync* stub purge) are hermeticity/pinning only.

Full CI is green on this head, including Dart Analyze & Tests, the backend unit shards, and the Sync Cloud Tasks gauntlet.

Still leaving the timestamp-validation relaxation (parse_sync_filename_timestamp / _retrieve_file_paths_v2 accepting capture times up to now + SYNC_CAPTURE_MAX_FUTURE_SKEW_SECONDS) for maintainer sign-off before merge — it intentionally widens which client-proposed capture times the Offline Sync boundary accepts, which is a trust-boundary decision rather than a correctness one.


by AI on behalf of David

@Git-on-my-level
Git-on-my-level dismissed their stale review September 17, 2026 06:01

Dismissed: both concerns from this review are resolved on f796145 — client clamping is now batch-shared (normalizeWalTimerStartsInBatch + _ensureUniqueWalTimerStarts preserving shard spacing and unique ids/filenames, with the requested multi-WAL test), and _retrieve_file_paths_v2 now rejects duplicate filenames per job.

@Git-on-my-level Git-on-my-level added the positive-signal Automation verified a genuine fix/quality contribution label Sep 17, 2026
@aryanorastar

Copy link
Copy Markdown
Collaborator

Closing because this reintroduces the same clock-shift/client-clamp approach from #11094 without new device evidence.

The code owner, @mdmohsin7, closed #11094 after confirming the reported behavior was no longer occurring and had been fixed in firmware 3.0.17 when device RTC support was enabled. This PR does not provide a reproduction on current firmware or an on-device offline-sync run; its verification is hermetic/backend plus CI, and the author explicitly notes no local Flutter/device execution.

The implementation is thoughtful and its collision tests are useful, but it changes device WAL timestamps and widens the server’s future-capture trust boundary based on a diagnosis the code owner already retired. Unit tests cannot establish that the present firmware still needs this behavior.

If #5747 can still be reproduced on current firmware, please update the issue first with firmware version, device logs, original WAL timestamps/filenames, upload ordering and resulting conversation IDs. A new shrink-only fix can then target the demonstrated remaining failure.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @apoorvdarshan 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Offline sync: fix conversation segmentation (too many short convos)

4 participants