Skip to content

fix(sync): stop safety-WAL dual writes (duplicate transcript + audio), keep unproven speech - #21403

Merged
Git-on-my-level merged 3 commits into
BasedHardware:mainfrom
Git-on-my-level:lane/dual-write-fix
Oct 13, 2026
Merged

Git-on-my-level merged 3 commits into
BasedHardware:mainfrom
Git-on-my-level:lane/dual-write-fix

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Problem

About 4% of conversations (24 of 561 sampled since 09-01, up to 190 duplicated segments in one) store the same speech twice, in both the transcript and the audio. The phone/desktop safety WAL of audio the live socket already transcribed is uploaded to /v2/sync-local-files. Batch STT runs on it, and it is appended to the live conversation. The copies come out like this:

  • the second copy has no stt_provider;
  • it uses fresh SPEAKER_n labels;
  • it has no owner;
  • it sits about 25–50 s later.

The existing dedupe misses it for three reasons:

  • it compares exact text only;
  • its clock slop drops to 0 after the first sync append;
  • the proof-gated paths are allowlisted to one uid and need an S1 claim that shipped clients don't send.

Fix, behind SYNC_SAFETY_WAL_DEDUPE_ENABLED (ON in dev and prod config, off by default in code)

Design rule: keep a duplicate rather than lose speech the live socket missed.

  1. Pre-STT coverage cut. WAL audio is skipped only where each removed ~6 s interval independently matches the stored live audio's energy envelope at a uniquely corroborated clock offset.

    • Silence, dropouts, weak or ambiguous matches, and unsafe future timestamps keep the original audio.
    • Live chunks are listed and probed once per conversation per job.
  2. Transcript dedupe on overlap, not exact strings. A line is dropped only when all of these hold:

    • the offset is locked, or ≥2 exact anchor lines agree within 2 s;
    • the speaker identity is compatible;
    • alignment is within 2 s after correction;
    • the live line has not already been used (one-use).

    Lines of 8–11 tokens need exact tokens. Longer lines need an order-sensitive similarity ≥0.95.

  3. Batch provider stamp on sync segments, gated by the same flag. Flag off restores today's segment shape.

  4. Metrics and a structured log for WAL seconds skipped, segments deduped and audio bytes not stored, with a closed reason set and no transcript text.

The legacy playback merge (download_audio_chunks_and_merge) is unchanged. No historical rewrite.

Review

  • Trace: Cursor Grok.
  • Implementation: Codex Sol, two rounds.
  • Adversarial review: Cursor Grok. Round 1 found two data-loss blockers (fuzzy over-drop, playback trim); both were fixed. Round 2 verdict: ship. Remaining follow-up: a 12+ token line differing by one word within the same 2 s slot is still treated as the same utterance.

Rollout and kill switch

  • Deploy with the normal Cloud Run release.
  • Kill switch: set SYNC_SAFETY_WAL_DEDUPE_ENABLED=false on backend, backend-sync, backend-sync-backfill and backend-integration, and redeploy runtime env.
  • Watch omi_sync_safety_wal_* by reason. Check that real gap recovery still lands before judging suppression rates.

Out of scope: the client-side 30 s edge test in local_wal_sync.dart. #20688 touches different hunks of pipeline.py. #21362 touches client recovery only.

Product invariants affected

  • INV-MEM-4: runtime env adds only the WAL switch. Canonical short-term intake and promotion authority are unchanged.

Failure-Class: FC-offline-merge-clock-offset-dup

Line-Count-Exception: backend/utils/other/storage.py | 2043 -> 2049 | One bounded single-chunk read helper for coverage probes; the logic lives in dedicated modules.
Line-Count-Exception: backend/utils/sync/pipeline.py | 3099 -> 3146 | Sync integration only; coverage and corroboration logic live in dedicated modules.

🤖 Generated with Claude Code

View guided diff

Failure-Class: FC-offline-merge-clock-offset-dup
Require corroborated clock and speaker identity for text drops, consume live matches once, and verify every audio interval. Restore legacy playback and gate provider stamps with the kill switch.

Failure-Class: FC-offline-merge-clock-offset-dup
@Git-on-my-level Git-on-my-level added the ci:full Maintainer-granted: run full CI on this fork PR label Oct 13, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 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-13T14:38:36.255532Z cdac7dc New commits
ℹ️ 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: 482afbbb77

ℹ️ 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".

segment['timestamp'] = incoming['started_at'].timestamp() + segment['start']
indexed_new = list(zip(segment_indices, new))
live_row = next((row for row in records if row['id'] == canonical), None)
fleet_live_dedupe = bool(result['sync_live_target'] and sync_safety_wal_enabled())

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 Return repeat-only when fleet dedupe removes every line

When the new fuzzy branch removes every incoming WAL segment, live_stats remains None, so the later repeat-only return in assign_in_transaction is skipped. The normal path still writes finished_at from the skewed incoming extent, increments sync_content_revision, and calls clear_client_processing; then complete_sync_intake enrolls the row for reprocessing because no _sync_lineage_repeat_only marker exists. Thus a fully suppressed 25–50 s-offset WAL can stretch the conversation and clear/rebuild its projection even though survivors is empty; return the same no-op marker used by the existing live-dedupe path.

AGENTS.md reference: backend/AGENTS.md:L145-L145

Useful? React with 👍 / 👎.

fleet_live_dedupe = bool(result['sync_live_target'] and sync_safety_wal_enabled())
live_dedupe = bool(
plan_target is not None
not fleet_live_dedupe

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 Preserve scoped exact-retry handling under the fleet gate

When a sync job is retried after conversation assignment commits but before the processed-segment acknowledgement, process_segment reuses the same sync:<segment_id> speaker scope. This condition now disables the existing branch that feeds that provenance to drop_proven_exact_retries, while _fuzzy_survivors ignores the scope and cannot form two anchors for a common one-line or unidentified-speaker segment; the retry is therefore appended a second time. Keep the scoped exact-retry pass active before fuzzy cross-clock matching.

AGENTS.md reference: backend/AGENTS.md:L145-L145

Useful? React with 👍 / 👎.

origin,
existing,
new,
fuzzy_live_overlap=fleet_live_dedupe,

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 Propagate probed clock offsets into transcript dedupe

When the energy probe locks an offset but leaves audio for STT (for example an unmatched six-second tile or the mandatory boundary margin), this only production call enables fuzzy mode without passing estimated_offset_seconds. A repo-wide search finds that argument supplied only by tests, so _fuzzy_survivors falls back to requiring two exact anchor lines; a single duplicated line, or a batch whose providers produce only fuzzy-equivalent wording, is appended (and its audio is stored again when private-cloud sync is enabled) despite the locked clock. Carry the probed offset, or a zero offset for corrected derivative paths, into this call so the locked-offset path is reachable.

Useful? React with 👍 / 👎.

@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: cdac7dc1f2

ℹ️ 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 +306 to +308
row = await run_blocking(
db_executor, conversations.get_closest_conversation_to_timestamps, uid, start, start + duration
)

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 Skip coverage cuts without an assignment target

When a /v2/sync-local-files upload omits both an explicit conversation and a resolvable recording-session target, target_id is None, yet this branch still cuts the WAL against a closest live row. The later assign_in_transaction call still receives target_id=None; its candidate loop deliberately excludes every live authority accepted here (sync_live_target rows and rows without sync_content_revision) unless it is an explicit target. Consequently matched audio is removed before STT while any retained margin/gap transcript is written to a different sync conversation, producing a truncated/split recording for targetless clients. Either abstain here without a target or return/bind the proven authority as the assignment target.

Useful? React with 👍 / 👎.

payload = source.readframes(end - begin)
if len(payload) != (end - begin) * params.nchannels * params.sampwidth:
raise ValueError('short coverage read')
output = os.path.join(directory, f'wal_{timestamp + offset + begin / rate:.6f}.wav')

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 Prevent retained margins from overwriting proof chunks

For private-cloud sync, when the coverage probe is an existing safety-WAL .opus/.opus.enc chunk and the incoming leading margin contains at least one second of speech, an offset-aligned interval beginning at zero is materialized with exactly that chunk's timestamp. Downstream process_segment uploads the surviving margin through upload_audio_chunk, which uses the same .../{timestamp:.3f}.opus[.enc] key with no generation precondition, so it overwrites the longer chunk that supplied the proof and removes its remaining playback audio. Use non-colliding derivative keys or make this upload preserve/verify the existing object.

Useful? React with 👍 / 👎.

Comment on lines +120 to +123
Before VAD/STT, stored chunks are listed and decoded once per conversation per job.
A uniquely locked clock offset is reused, but each six-second WAL tile requires
its own non-silent envelope correlation and per-bin energy agreement before it
can supply coverage. Spans alone and an opening fingerprint authorize no cut.

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 Update the owning listen/pusher pipeline contract

This adds a production-enabled pre-VAD audio-coverage and transcript/assignment flow, but the reviewed diff updates only this sync architecture document and leaves backend/docs/listen_pusher_pipeline.mdx unchanged. The backend guide requires that owning map to be updated in the same PR for audio, transcription, or conversation-lifecycle changes, so the overlap/env contract used by operators remains stale.

AGENTS.md reference: backend/AGENTS.md:L159-L159

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 72d7f4a into BasedHardware:main Oct 13, 2026
49 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci:full Maintainer-granted: run full CI on this fork PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant