Repository navigation
fix(sync): keep offline WAL shards in one conversation (#5747) - #14157
apoorvdarshan wants to merge 5 commits into
Conversation
CI investigation (workflow
|
| 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
left a comment
There was a problem hiding this comment.
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_spaninbackend/tests/unit/test_sync_two_lane.pydemonstrates the preserved 300s span and adjacency nicely.backend/utils/sync/pipeline.py: applyingnormalize_capture_windowinprocess_segmentbeforeget_closest_conversation_to_timestamps, with the shared shift threaded through both_run_full_pipeline_background_async(v2) andsync_local_files(v1,backend/routers/sync.py), is correct and consistent across lanes. Thenew_finished_at > now_utcclamp at the merge site is a good belt-and-braces addition.backend/utils/request_validation.py+_retrieve_file_paths_v2: accepting up tonow + SYNC_CAPTURE_MAX_FUTURE_SKEW_SECONDSaligns the parse bound with the boundclassify_sync_lanealready enforced (future_capture_time→ untrusted/backfill), so no lane guard is bypassed. Movingmaximum_future_skew_secondsinto the newbackend/utils/sync/capture_skew.pyto break the import cycle is clean, andbackend/tests/unit/test_request_validation_contracts.pypins the new behavior.backend/tests/unit/test_jit_qa_sweep_repair.py: verifiedrepair_tombstone(..., now=None)already exists inbackend/scripts/jit_qa_sweep_repair.py, so the_FIXED_NOWre-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.pypin the v1+v2 wiring in the established style of that suite, and theutils.sync*stub purge inbackend/tests/unit/test_sync_file_paths_filename_none.pyis sensible harness hygiene now thatrequest_validationimports fromutils.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.idis'${device}_$timerStart'andWal.toFileName()embedstimerStart(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 thatbatch_clock_shiftexists 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:
- On the client, mirror the batch-shared approach (one shift for the recovered set, preserving relative spacing) and/or guarantee clamped
timerStartuniqueness soWal.toFileName/Wal.idcan't collide; please add a test covering ≥2 future-dated equal-duration WALs clamped together. - Non-blocking suggestion: as defense-in-depth,
_retrieve_file_paths_v2could 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.
|
Addressed the client-side clamp collision review point in Client (batch-shared shift) — Added Test — Server (optional) — Server |
…#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]>
…ntracts 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]>
b82c0a4 to
f796145
Compare
|
Rebase + CI fixes pushed (
Local: |
|
@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:
|
Git-on-my-level
left a comment
There was a problem hiding this comment.
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'sbatch_clock_shift) to all still-future WALs so inter-shard spacing survives, and_ensureUniqueWalTimerStarts()guarantees distinct per-devicetimerStarts —Wal.idandgetFileName()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 inbackend/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=intoprocess_segmentin bothbackend/routers/sync.py(v1) and_run_full_pipeline_background_async(v2), withnormalize_capture_windowapplied beforeget_closest_conversation_to_timestamps. - The remaining test changes (
_FIXED_NOWanchoring intest_jit_qa_sweep_repair.py, the mild-skew contract intest_request_validation_contracts.py, theutils.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
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.
|
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. |
|
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:
Before your next PR, please skim:
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! |
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 beforeget_closest_conversation_to_timestamps, preserving relative spacing between ~60s shards so they merge like a single capture session. Client-sidenormalizeWalTimerStartclamps future WAL start times for sync UI/upload filenames (#4770), and upload validation allows mild future skew withinSYNC_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
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
test_sync_two_lane.py)clock_shiftand normalize before closest-conversation lookup (test_sync_ordered_assignment.py)test_request_validation_contracts.py)_retrieve_file_paths_v2guards (missing filename, duplicate filename, staging errors) (test_sync_file_paths_filename_none.py)normalizeWalTimerStartunit testsFailure class (fixes)
Failure-Class: none
CI fix (2026-09-16)
Rebased onto current
BasedHardware/omimain(resolvedtest_jit_qa_sweep_repair.pydate pinning). Hygiene: correctedpipeline.pyline-count exception (2537 -> 2562). Backend shard 2: fixed duplicate-filename regression test stub so the first upload stages before asserting 400.