Repository navigation
fix(sync): keep real skewed-capture audio admissible; typed invalid_capture_time 400 - #23746
Conversation
…apture_time 400 Phone live-capture files are named after the audio START, so filenames ahead of the server clock are phone-clock skew (prod 24h to 2026-10-26: ~980/day real recordings, median 171 s, max 349 s ahead), yet the sync filename parser rejected ANY future timestamp with a terminal 400 while the configured SYNC_CAPTURE_MAX_FUTURE_SKEW_SECONDS tolerance never ran. One shared window (utils/sync/capture_clock.py, default 600 s) now governs the parser, the v2 staging gate, and lane classification. Within-tolerance captures stay admissible without untrusted-backfill demotion; conversation started_at/finished_at clamp to server now while identity/lineage keys keep raw filename times. Beyond tolerance, pre-2024, or malformed names keep the 400 with unchanged detail text plus code 'invalid_capture_time' (released clients ignore the body). Per-file dispositions are counted in omi_sync_capture_time_total with closed reason labels. 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: 4b49364c99
ℹ️ 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".
| started_at = datetime.fromtimestamp(clamp_capture_time(timestamp), tz=timezone.utc) | ||
| create_memory = CreateConversation( | ||
| started_at=started_at, | ||
| finished_at=datetime.fromtimestamp(segment_end_timestamp, tz=timezone.utc), | ||
| finished_at=datetime.fromtimestamp(clamp_capture_time(segment_end_timestamp), tz=timezone.utc), |
There was a problem hiding this comment.
Keep transcript and playback timestamps on the same clock
For a skewed upload processed while its filename timestamp is still ahead of the server, clamping started_at changes the transcript's origin without changing the audio's origin. process_segment still passes the raw timestamp to _store_intake_audio, and utils/sync/playback.py::build_conversation_artifact computes playback wall_offset from that raw chunk timestamp minus the clamped conversation start. For example, a 30-second recording still 170 seconds ahead gets transcript offsets near 0–30 but a playback span starting near 170; the app's AudioTimelineMapper.wallToArtifactStrict cannot map those transcript lines to their audio. Preserve a consistent clock translation for transcript offsets and playback placement while retaining stable raw retry identities.
Useful? React with 👍 / 👎.
| rejection = capture_time_rejection(timestamp_dt) | ||
| if rejection is not None: | ||
| raise CaptureTimeWindowError(rejection) |
There was a problem hiding this comment.
Apply the admission window to source timestamps, not VAD offsets
An upload accepted near the future-skew limit can still fail later because this parser also validates internally generated VAD filenames. retrieve_vad_segments names each WAV using source_timestamp + segment['start'], and the pipeline subsequently parses those names when computing segment identities and sorting segment_list. With a source timestamp 590 seconds ahead and a speech segment starting 60 seconds into the file, that derived timestamp exceeds the 600-second window if processing takes less than 50 seconds, so an admitted recording fails before transcription. Validate the source capture time once and allow trusted derived segment offsets rather than applying the source admission bound again.
Useful? React with 👍 / 👎.
Review fix round for the capture-time skew admission change. A skewed upload no longer half-normalizes: the request's furthest file end minus server now yields one offset (capture_clock_offset) that shifts every temporal comparison into server-clock time - the recording-session audio bounds at the v2 staging seam (so the 60 s trailing allowance sees server-clock bounds), the minimal-redrive attach lookup, and the +/-120 s closest-conversation lookup - so a +171 s skewed live capture targets its existing conversation instead of creating a new one. Stored started_at/finished_at shift as a pair by that offset with one captured now: duration is preserved (a 10 s segment stays 10 s) and finish stays at or before server now. Chunk identity, lineage and coverage keys keep raw capture-clock times. Admission validates the source capture time once: staging boundaries enforce the shared window (v1 gained the explicit check the lenient internal reader needs), while get_timestamp_from_path accepts derived VAD names (source time + speech offset) that can sit past the window, so an admitted near-tolerance upload cannot fail mid-pipeline on its own segment names. Lineage fixtures move T0 to a past epoch so the frozen-main parity and span-bucket tests stop colliding with the stored-time policy. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… retry scope Review fixes for PR #23750, one behavior change per finding, each with a test: - invalid_capture_time never deletes audio: the quiet discard of <=1s fragments is gone. A fragment that cannot be re-dated stays as an attention row with the reason kept, Delete left to the user. - A capture time is re-stamped only from audio proven contiguous: a neighbour that is frame-adjacent on the source's own clock (same captureRoot + sourceClockEpoch, ending exactly where this WAL begins in frame positions), or shares this WAL's clock run / recording session with its end within one 120 s pause of the WAL's position in that run's clock — and whose end the server itself accepts. The latest-plausible-end-on-device guess and the file-mtime fallback are dropped: mtime is the copy time, not the capture time. - The re-stamp move is crash-safe: copy to the new name, durably save the WAL index pointing there, only then delete the old file; a failed or interrupted index save rolls the row back to the old name and never unlinks the last reachable copy. - A 400 counts as invalid capture time by bounded code (server #23746) or by the deployed route's exact detail line "Invalid sync file format: invalid timestamp". - too_large (413) rows offer Delete only — the same bytes are the same size — on On the Way, in Sync Details rows, and in the Needs Attention retry-all. Invalid-date rows keep a Retry that resends unchanged. - On the Way row actions cover the whole recording: Retry and Delete go over every member WAL of the grouped block, like the Offline Sync block action. - Heard today counts only the active live episode's own interval since its start or anchor (never liveCaptureStartedAt, which an all-day pendant stream never resets), and every contribution is clipped to the local day and merged before summing, so overlaps between the episode interval and already-counted transcript segments are counted once. - The stats tile column no longer stretches to the leftover viewport height; evidence captures the tiles' real height. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f05f650b0c
ℹ️ 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".
| request_capture_offset = await run_blocking( | ||
| sync_executor, | ||
| lambda: capture_clock_offset( | ||
| max(get_timestamp_from_path(path) + get_wav_duration(path) for path in segmented_paths) | ||
| ), |
There was a problem hiding this comment.
Persist the capture-clock offset across job retries
When a skewed upload partially succeeds and Cloud Tasks retries it, this recomputes the offset against the retry's current server time rather than reusing the first attempt's translation. _process_one_segment skips already-processed segments, so their stored timestamps retain the original offset while remaining segments receive a smaller offset. For example, retrying 60 seconds later while the capture timestamps are still ahead moves the remaining transcript 60 seconds forward relative to its already-persisted siblings, introducing artificial gaps and potentially changing conversation assignment. Persist the chosen offset with the durable job/content state before processing any segments and reuse it on subsequent attempts.
Useful? React with 👍 / 👎.
…back timing Review fix round 2 for the capture-time skew admission change — four bounded gaps from re-review: 1. The recording-lineage planner compared raw capture-clock segment spans against server-clock generation rows, so a +171 s skewed capture missed its conversation and fell through to the unqualified closest lookup. plan_segment_targets now shifts its comparison spans and the started_before/finished_after query bounds by the request offset; span keys keep the raw capture-clock segment identity. 2. V1 keeps the pre-PR zero future tolerance: retrieve_file_paths (also the chat/desktop transcribe seam) rejects any future capture time again, because the deprecated V1 inline pipeline runs at capture-time offset 0 and nothing downstream of it normalizes skew. V2 owns skew admission. 3. The staging-seam offset no longer derives from the client-claimed audio_end_seconds: it comes from admitted data only — the staged filename starts at the seam (durations are not decoded yet; the pipeline recomputes from decoded durations after VAD). A claimed session end past the admitted span plus one live-capture chunk of trailing slack is clamped, so an inflated claim can neither grow the claimed span nor move the session matching interval. 4. Playback timing is persisted: retained private-cloud chunks store their skew-normalized playback start (v2_playback_start blob metadata -> audio_files[].playback_start when every chunk in the part carries one) beside the raw capture-clock chunk key, and conversation playback wall_offset values are computed from that normalized basis, so a +171 s skewed chunk yields wall_offset ~0 against its conversation start. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…back_start The optional playback_start field on the conversation audio-file model (new in the playback-timing commit) is additive and nullable; the app-client surface snapshot regenerates to include it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Derived from the refreshed app-client OpenAPI snapshot: the new optional playback_start decodes as Double? and old payloads stay decodable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ck_start Derived from the refreshed app-client OpenAPI snapshot: the new optional playback_start field decodes as double? and existing payloads are unaffected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… field The only app change on this PR is the regenerated conversation wire model picking up the optional audio_files.playback_start decode field; internal-only, so the fragment is kind none. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Derived from the refreshed app-client OpenAPI snapshot: the new optional playback_start field is additive on the AudioFile interface. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Automations to automatically generate PRs for you. |
…re-time label Safety-coverage derivatives abstain on any future derived time (the pre-skew contract), now that the shared parser admits skew. The capture time counter passes reason_label() inline so the closed-label check sees it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eb9cd874de
ℹ️ 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".
| chunk_ts, | ||
| data_protection_level, | ||
| playback_start=chunk_ts - playback_clock_offset, |
There was a problem hiding this comment.
Avoid subtracting skew twice from partial-survivor playback
When deduplication retains only part of a skewed upload, assignment.py already sets each survivor's timestamp to incoming['started_at'] + segment['start'], which is on the normalized server clock. Consequently, chunk_ts here is already normalized, and subtracting playback_clock_offset again places the retained audio earlier than its transcript by the entire skew offset. This path also uses the normalized timestamp as the blob key instead of preserving the raw capture-clock identity. Derive the raw chunk key from file_timestamp + segment['start'] and normalize its playback start exactly once.
Useful? React with 👍 / 👎.
| session_clock_offset = capture_clock_offset(max(admitted_file_starts)) | ||
| if session_clock_offset > 0: | ||
| audio_start_seconds -= session_clock_offset | ||
| audio_end_seconds -= session_clock_offset |
There was a problem hiding this comment.
Normalize session bounds using the decoded audio end
For a skewed single-file upload with lineage resolution disabled, using the filename start as the offset basis moves audio_start_seconds to server now rather than to the recording's actual start. For example, raw bounds of now+111 through now+161 become now through now+50; select_recording_session_target rejects a matching live conversation ending at now−10 because the shifted start exceeds its end. The pipeline subsequently normalizes transcript times using the segment end, so session binding and ingestion use different clock translations. Defer session-bound normalization until decoded durations are available and use the same offset as ingestion; otherwise valid recording-session proof is lost and assignment falls back to temporal matching.
Useful? React with 👍 / 👎.
| rejection = capture_time_rejection(time_val, now=now) | ||
| if rejection is not None: | ||
| # Defense in depth: the shared parser already enforces this window. | ||
| _record_capture_time_admission(rejection, ahead_seconds=ahead_seconds) | ||
| raise SyncCaptureTimeRejected() |
There was a problem hiding this comment.
Normalize skewed captures on the batch processing path too
For users routed to the batch pipeline, this staging change admits future capture timestamps, but the new normalization in _run_full_pipeline_background_async never runs: sync_local_files_v2 instead returns through accept_batch_upload. capture_decode.decode_units preserves the raw filename timestamp, intake persists it as item.capture_at, and projection.build_incoming uses it directly for conversation start/end times. If processing completes while that timestamp is still ahead, the conversation is stored in the future; for record replacement, live_projection.replace_record also shifts incoming words against the live row's server-clock origin, placing them minutes too late. Apply a consistent clock translation to batch projection as well, while retaining raw capture identities.
Useful? React with 👍 / 👎.
…large retry scope, equal stat tiles Owner decision: automatic re-stamping leaves this PR entirely. The SD-card marker plausibility window stops new bad dates at the source, server PR #23746 accepts clocks ahead by up to 600 s so a plain resend now succeeds for those, and the remaining re-stamp edges (day misfiling from the gap estimate, chained estimates, a collision pushing the time into the future, duplicate files after a crash) are not worth their custody risk. - invalid_capture_time: the neighbour-estimate, copy-save-delete move and capture_time_restamped latch are deleted, with their tests. A refusal — by bounded body code or the deployed detail line, both still parsed — parks the WAL on attention with "Invalid recording date", never deletes or renames audio; Retry resends the same file unchanged; Delete still confirms first. Multi-file refusals keep the batch isolation so only the refused file is marked. - P1: a block Delete re-checks every member at delete time and skips any that is syncing or not terminal/attention (walDeletionAllowed, one shared attention-state set with SyncPendingWork), toasting "Some parts are still uploading and were kept" when something was skipped; LocalWalSyncImpl.deleteWal refuses a mid-upload target as the last line of defense. - too_large shows no Retry anywhere: the failed-sync banner state (failedWal/hasError) no longer puts a Retry back on a too-large row — the row shows its refusal label and Delete — the error card's retrySync skips a too-large failedWal, and the Auto Sync file/block rows use the same walRetryCanHelp scope. - Device stats tiles share one row height via IntrinsicHeight + CrossAxisAlignment.stretch: the On Device captions raise the whole row, 84 pt minimum kept, no stretch to the viewport. Evidence 004 regenerated; the On the Way rows image is byte-identical. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… rows (#23750) ## What changed and why Sync attention became honest after David's dogfooding of iOS 1.0.578: the server rejected 6,387 one-second SD-card fragments in 24h with 400 `invalid timestamp` (filename dates 2030–2035), On the Way answered with rows that only said "Failed", Device Settings showed "Heard today 0s" during a 33-minute live episode and "On Device 0s" with 7h45m queued on the phone, and a per-account `dispatch_hold` cooldown read "Omi servers are busy". - **SD-card parser** (`sdcard_wal_sync.dart`): a `0xFF` timestamp marker is accepted only inside 2024-01-01..now+1 day — the same window the backend's filename gate enforces. Implausible markers (audio bytes the desynchronized packet walk decoded as a clock) are ignored, so the recording keeps the app-estimated clock instead of splitting into garbage-dated fragments. The storage-listing start timestamp gets the same gate. - **400 handling** (`conversations.dart`, `wal_policy.dart`): a 400 counts as `invalid_capture_time` when the body carries the bounded `code` (server PR #23746) or the exact detail line the deployed route still returns (`Invalid sync file format: invalid timestamp`). The audio is never deleted for its claimed time, however short: a fragment whose capture time cannot be proven stays as an attention row with the reason kept ("Invalid recording date"), Delete left to the user, and a Retry that resends unchanged. When contiguous audio of the same source run proves when the fragment began, the file is re-stamped once with that time, crash-safely (see the review-round section), and re-offered; the re-stamp is latched so it cannot loop. Other 400s stay terminal, with the server's reason kept as a bounded token on the WAL (`invalid_capture_time` / `too_large` / `server_refused`). - **On the Way**: every row is tappable and opens the same Sync Details; rows show the recording's length and a short reason ("Invalid recording date", "Rejected by server", "Too large"); rows that need attention act on the whole recording — Retry and Delete go over every member WAL of the grouped block, like the Offline Sync block action, with one confirmation. Sync Details rows name the same reasons. - **Retry only where it can help** (`wal.dart`, `sync_provider.dart`, `sync_page.dart`, `on_the_way_page.dart`): a `too_large` refusal (413) is deterministic — the same bytes are the same size — so its rows offer Delete only, on On the Way, in Sync Details, and the Offline Sync Needs-Attention retry-all skips it. Every other retryable state keeps its Retry. - **Heard today** (`heard_today.dart`, `device_settings.dart`): speech is measured on the transcript clock — the segment time that falls inside today's local day across the loaded conversations (a conversation crossing midnight counts its after-midnight half; a session-origin `startedAt` no longer hides today's speech). The active live episode contributes its own interval since its start or anchor — never `liveCaptureStartedAt`, which a pendant that streams without a break never resets. Every contribution is an interval on one clock, clipped to today and merged before summing, so audio the episode's own transcript segments already counted is not counted again from the running interval. Without segment data (list responses may omit it) a conversation keeps its length on its reported day. - **On Device**: the tile keeps its meaning and adds a secondary line naming audio queued on the phone ("7h 45m on phone") when there is any; the tile column sizes to its own lines instead of stretching to the leftover viewport height. - **dispatch_hold copy**: its own honest text — "Uploads paused for a moment — they'll resume automatically" — no longer reuses the `backendBusy` capacity text. ## Review round (this push) Eight review findings, each fixed with a test: 1. **No audio deletion.** The quiet discard of ≤1 s fragments is removed; an `invalid_capture_time` refusal never deletes audio. Short fragments follow the same rules as long ones and stay as attention rows when they cannot be re-dated. 2. **Crash-safe re-stamp.** The move is copy → durably save the WAL index that points at the new path → only then delete the old file. A failed or interrupted index save rolls the in-memory row back to the old name and never unlinks the last reachable copy; the worst residue is an orphaned duplicate file, never unreachable audio. Tests cover the failed-save rollback, the crash window after a durable save (a restart finds the audio under a name the index points at), and the completed move. 3. **Current server reply recognised.** A 400 classifies by bounded `code` or the deployed route's exact detail line; both body shapes are tested, including the real current body. 4. **Re-date only from contiguous audio.** A neighbour proves the time when it is frame-adjacent on the source's own clock (same `captureRoot` + `sourceClockEpoch`, ending exactly where this WAL begins in frame positions — `walExtendsRun`'s own idiom), or shares this WAL's clock run / recording session with its end within one 120 s pause of the WAL's position in that run's clock — and its end is a time the server itself accepts (≥ 2024-01-01, ≤ now, so a run sharing one wrong clock cannot chain a second refusal). Without such a neighbour, no date is invented. The file-mtime fallback is dropped: mtime names when the phone wrote its copy (every SD drain re-writes chunks as they arrive), not when the pendant sampled the audio, so it is not the capture time for any source here. 5. **Retry only where it can help.** `walRetryCanHelp` gates Retry on the refusal reason; `too_large` shows Delete only in On the Way rows, Sync Details rows, and the Needs-Attention retry-all. 6. **Whole-recording actions.** On the Way block actions iterate every member WAL; Retry covers the members a retry can help, Delete every member after one confirmation. 7. **Only the live episode counts.** The interval is the active live episode's own start (episode `startedAt` kept stable by the shared `LiveStartAnchor`, restart-aware), not the capture session's origin; it merges with transcript intervals instead of adding on top. 8. **No double-counted overlaps.** Clipped intervals (segments, segmentless lengths, the live interval) are unioned before summing: 10:00–10:30 + 10:20–10:40 reads 40 minutes. ## Product invariants affected INV-CAP-1 (pendant audio retention) — `app/lib/services/wals/**` changed. No change drops sampled audio: the parser fix keeps recordings whole instead of splitting them, and the repair path re-offers refused audio or parks it honestly for the user's own Delete. There is no deletion anywhere in the `invalid_capture_time` path. Capture, ring retention, and drain scheduling are untouched. ## How it was verified - `flutter test` on the touched suites (169 tests across 14 files: sdcard custody/packet, invalid-capture-time recovery incl. crash-safety, heard-today, On the Way days + attention, sync row recovery window, needs-attention retry, recording blocks, episodes UI, home pending row, device catching-up, evidence render, sync-indicator isolation, background admission) — all green. - `bash app/scripts/analyze_ratchet.sh` — passed, no new analyzer issues. - `make preflight` — 28 checks passed. - Flutter widget screenshots before/after under UI evidence below: before captured at the PR's first commit (25ca68a) with the same fixtures and viewport, after at this PR's head. The after images in this push show the too-large row without Retry and the stats tiles at their real height. Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2636 -> 2653 | two `on SyncInvalidCaptureTimeException` clauses (drain + single retry), one import, and the delete-time isSyncing guard in deleteWal; all repair logic lives in wal_policy.dart, and the batch-isolation duplication moved out with it ## Tests - Regression for the parser bug: `sdcard_custody_sync_test.dart` — future (2035) and pre-2024 markers no longer split a recording; plausible markers still do; window boundary unit-tested. - Recovery path: `invalid_capture_time_recovery_test.dart` — a 1 s fragment stays a row and keeps its file; no proven neighbour keeps the claimed time (a same-device plausible bystander never qualifies); a shared-clock-run fragment is re-stamped at its run predecessor's end and re-offered once; one-restamp cap terminal with reason; other 400s terminal with reason; `contiguousCaptureStartSeconds` unit tests (frame-adjacent predecessor, run predecessor within the pause gap, over-gap silence, wrong-clock future end, no run identity); crash-safety (failed index save rollback with the audio reachable under its old name, interrupted save after the durable write leaves a restart-reachable name, completed move deletes the old file); both 400 body shapes including the deployed detail line. - Retry scope: `sync_row_recovery_window_test.dart` — too-large row offers Delete only; invalid-date keeps its Retry. `sync_provider_needs_attention_retry_test.dart` — the retry-all skips too-large refusals and re-offers the rest. - Block actions: `on_the_way_attention_test.dart` — a three-WAL recording reads as one row of 3m 45s; Retry covers every member; one confirmation deletes every member; too-large row offers Delete only. - Heard today: `heard_today_test.dart` — midnight-crossing conversation, misfiled session day, overlapping segments counted once (10:00–10:30 + 10:20–10:40 = 40 min), live-episode interval clipped to midnight, earlier same-day segments plus an active episode counted as a union, segmentless fallback, discarded exclusion. - `sync_attention_evidence_test.dart` — layout assertions for both surfaces and the real-tile-height bound (writes the PR evidence PNGs on demand). ## UI evidence Before/after Flutter widget screenshots, dark theme, 390×844 viewport, captured by the same fixture harness (before at `origin/main`):     Manifest: `.agent-artifacts/ui-evidence/lane-sync-attention-honesty/evidence.json`. David must approve these before merge. ## Failure class (fixes) Failure-Class: new ## Failure-class transition narrative **Violated contract:** a client that turns device-supplied bytes into recording times must only accept a timestamp it can prove is a clock, not merely a positive number — and when the server refuses a recording, the app must show which refusal it was, never destroy the audio for it, and only offer actions that can change the outcome. The SD-card packet walk accepted any `0xFF` byte plus four bytes decoding above zero as a timestamp marker, so desynchronized audio split real recordings into ~1 s fragments dated 2030–2035 (6,387 rejected uploads in 24h), the 400 body was discarded, each fragment parked terminally as a bare "Failed" row, and the surrounding stats (Heard today, On Device, dispatch_hold copy) hid where the work actually was. **Canonical guard:** `markerEpochPlausible` gates every device timestamp — packet markers and storage-listing starts — on the server's own filename window (≥ 2024-01-01, ≤ now + 1 day), keeping the estimated clock when it fails. `isInvalidCaptureTimeResponse` recognises the refusal by bounded code or the deployed detail line; `contiguousCaptureStartSeconds` is the only source of a replacement capture time — a frame-adjacent or same-run neighbour whose end the server accepts — and the re-stamp move is copy → durable index save → delete, so audio stays reachable across a crash. `walRetryCanHelp` keeps guaranteed-fail uploads off every Retry surface. Guard artifacts: `app/lib/services/wals/sdcard_wal_sync.dart`, `app/lib/services/wals/wal_policy.dart`, `app/lib/services/wals/wal.dart`, `app/lib/backend/http/api/conversations.dart` and their tests. **Evidence:** this PR is the evidence (dogfooding iOS 1.0.578, 2026-10-26); `evidence_prs` is `[]`. ## Scoped cleanups (optional) The standing visual-audit `on-the-way` scenario now also shows refused rows with reason tokens, so future audits capture this surface. `sync_attention_evidence_test.dart` doubles as a render/evidence test (PNG output only with `--dart-define=SYNC_ATTENTION_EVIDENCE_OUTPUT=<dir>`), following `open_loop_evidence_test.dart`'s pattern. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Summary
Stop rejecting real sync audio on the capture-time check.
POST /v2/sync-local-fileswas returning 9,058/day of HTTP 400Invalid sync file format: invalid timestampto 160 devices (24h to 2026-10-26T17:35Z); released apps treat that 400 as terminal and never retry, so those recordings were lost. This PR applies one shared future-skew tolerance to every capture-time check, accepts and normalizes genuinely-skewed captures onto the server clock, and keeps refusing implausible stamps with a typed 400.One shared tolerance.
utils/sync/capture_clock.pynow owns the future-skew window (SYNC_CAPTURE_MAX_FUTURE_SKEW_SECONDS). Both zero-tolerance checks —parse_sync_filename_timestamp(backend/utils/request_validation.py) and_retrieve_file_paths_v2's explicit datetime re-check (backend/utils/sync/pipeline.py) — plusclassify_sync_lane's guard now use it. Previously the setting existed in prod (300) but had no effect: the parser raised on any future timestamp before the lane guard ever ran.Admission validates the source once; derived names ride along. The window is enforced once per upload at the staging boundaries (V2
_retrieve_file_paths_v2and the V1 staging gate inutils/sync/files.py, both with explicit typed rejection). Internal WAL/VAD clock reads (get_timestamp_from_path) no longer re-apply the window:retrieve_vad_segmentsnames each WAV after source capture time plus a speech offset, so a name derived from an admitted near-tolerance source can legitimately sit past the window — previously that name raised mid-pipeline and failed an already-admitted upload before transcription.One server-clock offset per request, used everywhere. For an accepted skewed upload the pipeline computes a single offset —
max(0, furthest file end − server now)(capture_clock_offset) — and shifts every temporal comparison into server-clock time: the recording-sessionaudio_start/audio_endbounds the router passes into intake (so the 60 s trailing allowance inselect_recording_session_targetsees server-clock bounds), the minimal-redrive attach-first lookup, and the ±120 s closest-conversation lookup. A +171 s skewed live-capture upload therefore targets its existing live conversation — through the session path and through the closest-lookup path — instead of creating a new conversation.Stored times shift as a pair. Conversation
started_at/finished_atminted by the sync pipeline shift by that same request offset as a pair with one capturednowbackstopping both clamps: duration is preserved (a 10 s segment stays 10 s),finished_at ≤ server now, and a skewed phone clock can no longer produce zero-duration or future-started conversations. Identity/lineage math (chunk identity, redrive targets, coverage maps, lineage spans) keeps the raw filename timestamp so retry anchors stay stable.Implausible times still refused, now typed. Beyond tolerance, before 2024-01-01, or malformed → status 400 with the same
detailtext plus a new top-levelcode: 'invalid_capture_time'. Released clients ignore the body (app/lib/backend/http/api/conversations.dartmaps any 400 to a genericSyncUploadHttpException), so behavior is unchanged for them; new clients can act on the code.Observability. New closed vocabulary
SyncCaptureTimeReason(utils/observability/reasons.py, familysync_capture_time) with counteromi_sync_capture_time_total{outcome}counting per-fileaccepted/accepted_future_skew/rejected_future/rejected_early/rejected_malformed, plus anevent=sync_capture_time outcome=… ahead_seconds=…log line for every non-plain-accepted outcome — the readback can count all three question groups.Config. Deploy manifests bump
SYNC_CAPTURE_MAX_FUTURE_SKEW_SECONDS300 → 600 (see sizing below). The lane-admission counter/log (sync_lane_admission,omi_sync_lane_admissions_total) is unchanged.Fix round 2 — lineage planner on the server clock. The recording-lineage planner compared raw capture-clock segment spans against server-clock generation rows, so a +171 s skewed capture missed its conversation and fell through to the unqualified closest lookup.
plan_segment_targetsnow shifts its comparison spans and thestarted_before/finished_afterquery bounds by the request offset; span keys keep the raw capture-clock segment identity.Fix round 2 — V1 keeps the pre-PR zero future tolerance.
retrieve_file_paths(the V1 staging boundary, shared with the chat/desktop transcribe seams) rejects any future capture time again: the deprecated V1 inline pipeline runs at capture-time offset 0 and nothing downstream of it normalizes skew, so the simpler safe option is the exact pre-PR wire behaviour (legacy 400) rather than propagating the offset into a deprecated path. V2 owns skew admission.Fix round 2 — offset from admitted data only. The staging-seam offset no longer derives from the client-claimed
audio_end_seconds: it comes from the staged filename starts alone at the seam (decode has not run; the pipeline recomputes from decoded durations after VAD), and a claimed session end past the admitted span plus one live-capture chunk of trailing slack is clamped — an inflated claim can neither grow the claimed span nor move the session matching interval.Fix round 2 — persisted playback timing. Retained private-cloud chunks store their skew-normalized playback start (
v2_playback_startblob metadata →audio_files[].playback_start, present only when every chunk in the part carries one) beside the raw capture-clock chunk key; conversation playbackwall_offsetvalues are computed from that normalized basis, so a +171 s skewed chunk yieldswall_offset ≈ 0against its conversation start instead of ≈ 171.Root cause of the ahead-of-server group (980/day, real speech)
The app names every phone live-capture file after the start of the audio it holds —
Wal.getFileNameByTimeStarts(timerStart)withtimerStart = timerEnd - chunkDuration(app/lib/services/wals/local_wal_sync.dart:659) andMobileBatchBuffer.append'sstart = now.microsecondsSinceEpoch / 1e6(app/lib/services/wals/mobile_batch_buffer.dart:68); selection-run names usepreciseEnd - frameCount/fps(app/lib/services/wals/wal_evidence_runs.dart:28). No path names by segment end or rounds up, so the filename can only be ahead of server-now through plain phone-clock skew ahead of the server clock (median 171 s, max 349 s observed). This is a server-side admission bug, not an app naming-semantics mismatch: no app change is needed for this group. (Group A — SD-card fragments stamped 2030–2035 — is a separate bogus-device-clock problem with its own app-side lane; the server keeps rejecting those, now with the typed reason.)Tolerance sizing: 600 s
Observed max ahead-of-server skew is 349 s. The default doubles past that max (1.7× headroom): uncalibrated phone clocks routinely drift minutes, so a single outlier phone above the day-observed max must keep syncing rather than strand recordings terminally. 600 s is still two orders of magnitude below the 6-hour fresh window and meaningless against year-scale bogus stamps (2030+ stays ~10⁷ s outside), and since accepted requests are normalized onto the server clock (stored times end at server now), the wider bound cannot move stored times into the future — it only widens admission.
Tests
backend/tests/unit/test_sync_capture_time_skew.py: within-tolerance parse/accept (+170 s), beyond-tolerance and pre-2024 rejection with closed reasons, shared-setting override, lane classification (skew stays FRESH + clamped decision times; beyond is untrusted backfill),_retrieve_file_paths_v2staging/typed rejection/counter outcomes, route tests (+170 s upload → 202, +5-year upload → 400{'code': 'invalid_capture_time', 'detail': 'Invalid sync file format: invalid timestamp'}), and the fix-round additions: the request-offset helper, derived-name reads past the window (get_timestamp_from_pathlenient while admission still refuses), the recording-session selector binding a +171 s skewed capture only after the offset shift, the v2 route shifting session bounds into the intake context,process_segmenttargeting the existing live conversation through the closest lookup (no new conversation), the minimal-redrive attach lookup comparing on server-clock bounds, and the 10 s segment stamped +171 s stored with its full 10 s duration ending by server now.test_sync_two_lane.py(old zero-tolerance +301 expectation → within-tolerance FRESH and beyond-tolerance UNTRUSTED),test_sync_legacy_fresh.py(future guard boundary −601, within-tolerance promotion preserved),test_request_validation_contracts.py(tolerance acceptance + env override),test_sync_geolocation_enrichment.py(coordinator harness now supplies a numeric WAV duration — the coordinator reads durations for the request offset),test_sync_v2.py(behavioral harness default clock reader), andtest_sync_lineage_dedupe_replay.py(shared fixtureT0moved to a past epoch: the frozen-parity/dedupe fixtures verify timeless behavior and a futureT0collided with the stored-time policy — this restores the fourtest_sync_lineage_flags_off_parity.pyfrozen-main parity cases and thetest_sync_lineage_diagnostics.pyspan-bucket case that the first commit had left red).BACKEND_UNIT_TEST_FILE_LIST=<106-file list: every test_sync_*, playback and lineage suite> BACKEND_PYTEST_WORKERS=1 bash test.sh— all 106 files pass; plus an 11-file follow-on list covering the changed storage/validation seams (upload_audio_chunk metadata, request-validation contracts, chunk grouping callers). New round-2 tests: V1 zero-tolerance staging, stricter-tolerance kwarg, lineage planner binding a +171 s span on the server clock (shifted query bounds asserted; unshifted span proven unbound), lineage-bound segment never consulting the closest lookup, inflated claimed end leaving the session interval in place, chunk playback-start metadata round-trip + store-chain forwarding + process_segment persisting the normalized basis, audio-file group playback_start derivation (all-carry vs mixed), and the skewed-partwall_offset ≈ 0span math with a legacy part keeping the raw basis.BACKEND_UNIT_TEST_FILE_LIST=<35-file list> BACKEND_PYTEST_WORKERS=1 nice -n 10 bash test.sh— all 35 files pass (~2,600 tests; covers the skew suite plus every coordinator, assignment, lineage, coverage, playback and parser-adjacent suite);scripts/scan_async_blockers.py --dirs routers utils— 0 findings;black --line-length 120 --skip-string-normalizationon all changed files.Product invariants affected: INV-MEM-4 (sync intake continues to create Short-term conversations through the unchanged canonical path; this change only widens which capture times are admissible and normalizes skewed times onto the server clock — it does not alter promotion/consolidation routing).
Failure-Class: new
UI-Evidence: none
Line-Count-Exception: backend/routers/sync.py | 4026 -> 4084 | staging-seam offset from admitted filename starts with claimed-end clamp, and the playback-basis fallback for conversations without started_at
Line-Count-Exception: backend/utils/metrics.py | 1593 -> 1599 | one new OMI_SYNC_CAPTURE_TIME_TOTAL counter beside the existing sync admission counters
Line-Count-Exception: backend/database/conversations.py | 4542 -> 4550 | playback_start derivation on the v2 audio-file group beside the existing span projection
Line-Count-Exception: backend/utils/other/storage.py | 2683 -> 2693 | optional playback_start persisted beside the chunk span metadata by upload_audio_chunk
Line-Count-Exception: backend/utils/sync/pipeline.py | 3758 -> 3846 | shared-tolerance admission in _retrieve_file_paths_v2, disposition counter helper, the one request-wide offset computation (now also handed to the lineage planner), pair-shifted stored times, and playback timing through the retained-audio store chain
🤖 Generated with Claude Code