Skip to content

fix(audio): playback merges via Cloud Tasks — 30-day MP3 artifacts, read paths never merge - #7872

Merged
mdmohsin7 merged 17 commits into
mainfrom
feat/audio-merge-tasks
Jun 12, 2026
Merged

mdmohsin7 merged 17 commits into
mainfrom
feat/audio-merge-tasks

Conversation

@mdmohsin7

Copy link
Copy Markdown
Member

Problem

Conversation audio playback is broken for any non-trivial conversation. Verified chain of failure:

  1. GET /v1/sync/audio/{id}/urls merges the first uncached file synchronously and unbounded in-request (download every chunk from GCS → decrypt (enhanced users) → opus-decode → gap-fill → WAV-encode).
  2. Remaining files return pending, and the app immediately falls back to GET /v1/sync/audio/{id}/{file}?format=wav — which also merges inline, under the 120s middleware ceiling, while the app only waits 30s.
  3. Long conversations can't win: the user gets a silent infinite spinner (failures only hit Logger.debug).
  4. The merged cache expires every 3 days (bucket lifecycle on merged/), so all of this cost recurs forever; per Sync infra changes — May 28: storage pool, autoscaling, and app-side rate-limit fixes #7531, 77% of merges were speculative precache.
  5. WAV artifacts are ~115 MB/audio-hour — slow to build, store, and stream.

Fix (mirrors the validated #7801 pattern)

Merges become Cloud Tasks jobs; request paths never merge; the app polls.

conversation completes ──► enqueue merge task per audio_file            (eager)
app taps play ──► GET /urls ──► artifact? signed URL : pending + enqueue (lazy backfill)
                              app polls /urls (90s budget → error UI + retry)

queue `audio-merge` ──► POST /v2/audio-merge-jobs/run (OIDC, backend-sync)
    run-lock → artifact exists? ack : download/decrypt/decode/gap-fill (existing code)
    → MP3 ~48kbps mono (pydub/ffmpeg, already in image) → playback/{uid}/{conv}/{file}.mp3
  • Artifacts: MP3 ~48kbps mono (~21.6 MB/audio-hour, −84% vs WAV; plays natively in just_audio iOS+Android, HTML5, and stays playable when shared). Expiry via a 30-day bucket lifecycle rule on the playback/ prefix — existence == validity, no metadata; expired artifacts are lazily rebuilt by the same task path. Source chunks (chunks/) verified to have no deletion lifecycle, so rebuild is always possible.
  • Handler semantics (same discipline as sync-jobs): per-artifact Redis run-lock (409 on duplicate delivery), artifact-exists ack, chunks-missing consume, final-attempt consume with audio_merge_failed_final log, 600s request-timeout override (< 1800s lock TTL). Named tasks am-{conv}-{file} dedupe enqueues from polling.
  • Read paths (when AUDIO_MERGE_DISPATCH_MODE=cloud_tasks):
    • /urls: pure metadata read — never >2s. Cached files get signed URLs (new MP3 or legacy unexpired WAV); the rest are pending + poll_after_ms with tasks enqueued.
    • /download: serves prebuilt artifacts only (Range support kept, content-type per artifact); 202 {pending} on miss. Old app versions hitting this uncached get a fast 202 instead of the inline merge that mostly timed out anyway.
    • /precache + eager precache at conversation completion: enqueue instead of in-process merging.
  • Flag-gated rollout: AUDIO_MERGE_DISPATCH_MODE defaults to inline — merging behavior is byte-for-byte today's until flipped. Rollback = flip back.

Clients

  • Flutter: play taps poll /urls (3s cadence from poll_after_ms, 90s budget) and build the ConcatenatingAudioSource playlist only from cached signed URLs — the uncached→stream-endpoint fallback (the death path) is removed. Budget exhaustion now shows an error snackbar (existing l10n key) + new audioPlaybackFailed analytics event instead of a silent infinite spinner. Share/export uses the artifact's real extension.
  • Web: AudioPlayer.tsx polls the same way; blob-through-proxy fallback removed.

Tests

  • New tests/unit/test_audio_merge_tasks.py (11): enqueue naming/env, dispatch flag default, handler contract (OIDC/lock/409/consume paths), structural no-merge guarantees on /urls, 202-on-miss on /download, mp3 export settings, timeout wiring, storage helpers. Registered in test.sh.
  • All touched suites at main baseline; scan_async_blockers clean; dart analyze 0 errors; tsc clean.

🚀 Deployment (ordered — ships inert)

1. Merge (regular merge) + deploy — no behavior change (inline default).

2. One-time infra (per project — dev based-hardware-dev first, then prod based-hardware):

gcloud tasks queues create audio-merge --location=us-central1 \
  --max-concurrent-dispatches=48 --max-dispatches-per-second=20 \
  --max-attempts=5 --min-backoff=30s --max-backoff=300s

# 30-day lifecycle for playback artifacts (chunks bucket; prod shown, dev = same on its bucket)
# NOTE: must APPEND to existing rules (merged/ age-3 rule must stay) — read-modify-write the lifecycle config

IAM: nothing new — the project-level cloudtasks.enqueuer grants to the ADC service accounts from #7801 cover the new queue; same invoker SA.

3. Env vars (prod: backend-sync only; dev: backend-sync and backend due to dev's LB routing quirk):

AUDIO_MERGE_DISPATCH_MODE=inline   # initially
AUDIO_MERGE_TASKS_QUEUE=audio-merge
AUDIO_MERGE_HANDLER_URL=https://backend-sync-<hash>-uc.a.run.app/v2/audio-merge-jobs/run
HTTP_AUDIO_MERGE_RUN_TIMEOUT=600

4. Dev validation: flip dev to cloud_tasks → app test: new conversation (instant play via eager artifact), old conversation (short poll → play), enhanced-protection user (decryption path), share/export.

5. Prod flip → watch: audio-merge queue depth, handler 5xx, audio_merge_failed_final events, /urls latency (target always <2s), audioPlaybackFailed analytics.

6. Rollback = AUDIO_MERGE_DISPATCH_MODE=inline (queued tasks drain harmlessly; artifacts already built keep serving).

Out of scope (documented)

  • Deleting source chunks after artifact build (storage win; loses re-merge ability).
  • Removing the legacy inline-merge code path (after old app versions age out).

🤖 Generated with Claude Code

mdmohsin7 added 13 commits June 12, 2026 21:17
_enqueue_named_task shared by sync and audio-merge jobs; audio tasks are
named am-{conversation_id}-{audio_file_id} for enqueue-side dedup and
gated by AUDIO_MERGE_DISPATCH_MODE (default inline).
…queue

Artifact existence == validity; expiry is the bucket's 30-day lifecycle
rule on the prefix (added at deploy), replacing per-blob metadata. The
eager precache path enqueues merge tasks instead of merging in-process
when dispatch is enabled.
…erge

Playback was broken for long conversations: /urls merged the first
uncached file synchronously and unbounded, and the app's pending
fallback hit /download which also merged in-request under a 120s
ceiling while the app waits 30s — guaranteed timeouts.

With AUDIO_MERGE_DISPATCH_MODE=cloud_tasks:
- /urls is a pure metadata read: cached files get signed URLs (new MP3
  artifact or legacy unexpired wav), the rest are pending + poll_after_ms
  with a deduped merge task enqueued.
- /download serves prebuilt artifacts only (Range kept); on miss it
  enqueues and returns 202 instead of merging inline.
- POST /v2/audio-merge-jobs/run (OIDC) builds one artifact per task:
  run-lock, artifact-exists ack, chunks-missing consume, final-attempt
  consume; MP3 ~48kbps mono via pydub/ffmpeg.

Inline behavior is fully preserved when the flag is off.
…endpoint

The pending fallback streamed /v1/sync/audio/{id}/{file} which merges
in-request and times out on long conversations — silent infinite
spinner. Now polls /urls (90s budget) until artifacts are cached, plays
only signed URLs, and surfaces an error snackbar + analytics event when
the budget is exhausted.
@greptile-apps

greptile-apps Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR replaces inline audio merging (which caused timeouts for long conversations) with an async Cloud Tasks pipeline: merge jobs run off-request, build 30-day MP3 artifacts under playback/, and request paths become pure metadata reads. Both Flutter and web clients now poll /urls with a server-driven poll_after_ms hint instead of falling back to the merge-in-request endpoint.

  • Backend: new /v2/audio-merge-jobs/run Cloud Tasks handler with OIDC auth, Redis run-lock, artifact-exists ack, named-task deduplication, and a flag-gated dispatch mode (AUDIO_MERGE_DISPATCH_MODE); /urls and /download are reworked to never merge in-request; download_legacy_merged_wav closes the previously-flagged inline-merge bypass for legacy blobs.
  • Flutter: playback and download paths poll /urls with backoff (90 s / 60 s budgets), emit audioPlaybackFailed analytics on timeout or empty sources, concatenate MP3 via raw byte streams; dead streaming-endpoint fallback removed.
  • Web: AudioPlayer.tsx polls getConversationAudioUrlsWithPoll (surfaces poll_after_ms); prior ignored-hint P2 resolved.

Confidence Score: 5/5

Safe to merge — all three previously-flagged concerns have been addressed, the new pipeline is flag-gated to inline by default, and rollback is a single env-var flip.

The previously-flagged inline-merge bypass for legacy WAV blobs is explicitly fixed via download_legacy_merged_wav. Both prior P2s (web client ignoring poll_after_ms, Flutter empty-sources silent failure) are also resolved. The new handler follows the established sync-jobs discipline (OIDC auth, Redis run-lock, named-task dedup, final-attempt consume). Remaining findings are minor: a missing try/finally around MP3 sink concatenation in the Dart download service, and the audio-merge handler reusing SYNC_TASKS_MAX_ATTEMPTS where a dedicated env var would be cleaner. Neither affects correctness in the standard configuration.

No files require special attention for merge; backend/routers/sync.py carries the most logic and has unit test coverage for all stated invariants.

Important Files Changed

Filename Overview
backend/routers/sync.py Adds _get_audio_urls_via_artifacts (pure metadata read, never merges), adds /v2/audio-merge-jobs/run Cloud Tasks handler, gates /urls and /download behind is_audio_merge_dispatch_enabled(), fixes legacy-merge bypass via download_legacy_merged_wav.
backend/utils/cloud_tasks.py Refactors enqueue_sync_job into generic _enqueue_named_task; adds enqueue_audio_merge_job (named am-{conv}-{file}) and is_audio_merge_dispatch_enabled flag check.
backend/utils/other/storage.py Adds playback artifact helpers, download_legacy_merged_wav (direct blob download without inline-merge risk), and enqueue_conversation_audio_merge; gates precache_conversation_audio to enqueue in cloud_tasks mode.
app/lib/widgets/conversation_bottom_bar.dart Playback path polls /urls (90 s deadline), shows error snackbar and fires audioPlaybackFailed on both timeout and empty-sources cases; removes the dead inline-streaming fallback.
app/lib/services/audio_download_service.dart Download/export path polls /urls (60 s deadline), handles mixed WAV/MP3 artifacts, concatenates MP3 via raw byte stream; missing finally for sink.close() in MP3 concatenation error path could leak a file handle.
web/app/src/components/conversations/AudioPlayer.tsx Replaces blob-proxy approach with /urls polling loop (90 s deadline), uses pollAfterMs hint, sets cancelled flag on unmount.
web/app/src/lib/api.ts Adds getConversationAudioUrlsWithPoll returning { files, pollAfterMs }; bulk of file is quote-style reformatting.
backend/tests/unit/test_audio_merge_tasks.py New unit tests (11) covering enqueue naming, dispatch flag, handler contract, no-merge structural guarantees, 202-on-miss, mp3 export settings, timeout wiring, and storage helpers.
app/lib/backend/http/api/audio.dart Adds AudioUrlsResponse wrapper exposing pollAfterMs; adds contentType/fileExtension to AudioFileUrlInfo; updates getConversationAudioSignedUrls return type.

Sequence Diagram

sequenceDiagram
    participant App as Flutter/Web App
    participant API as /v1/sync/audio/urls
    participant CT as Cloud Tasks (audio-merge)
    participant Handler as /v2/audio-merge-jobs/run
    participant GCS as GCS (playback/)

    Note over App,GCS: Conversation completes (eager path)
    API->>CT: enqueue_conversation_audio_merge (per file)

    Note over App,GCS: User taps Play (lazy path)
    App->>API: GET /urls
    API->>GCS: get_playback_artifact_signed_url (exists?)
    alt artifact exists
        GCS-->>API: signed URL (MP3)
        API-->>App: status cached, signed_url, content_type audio/mpeg
        App->>GCS: stream MP3 directly
    else artifact missing
        GCS-->>API: null
        API->>CT: enqueue named am-conv-file deduped
        API-->>App: status pending, poll_after_ms 3000
        loop Poll every poll_after_ms up to 90s
            App->>API: GET /urls
            API->>GCS: exists?
            GCS-->>API: signed URL once built
            API-->>App: status cached signed_url
        end
        App->>GCS: stream MP3
    end

    Note over CT,GCS: Off-request build
    CT->>Handler: POST /v2/audio-merge-jobs/run OIDC
    Handler->>Handler: acquire Redis run-lock 409 if held
    Handler->>GCS: artifact exists ack
    Handler->>GCS: download chunks decrypt decode gap-fill
    Handler->>Handler: AudioSegment export mp3 48kbps mono
    Handler->>GCS: upload playback artifact
    Handler-->>CT: 200 done
Loading

Reviews (3): Last reviewed commit: "fix(app): share audio handles MP3 artifa..." | Re-trigger Greptile

Greptile P1: get_merged_audio_signed_url treats missing expires_at
metadata as valid, but get_or_create_merged_audio treats it as a miss
and falls through to a full inline merge — breaking the no-merge
guarantee for pre-metadata cache blobs. Download the blob directly
since the signed-url check already proved it exists and is unexpired.
Mirrors the poll-timeout path: snackbar + audioPlaybackFailed instead
of a silent frozen spinner.
@mdmohsin7

Copy link
Copy Markdown
Member Author

@greptile-apps re-review

- Polls /urls (60s budget) instead of giving up when artifacts aren't
  built yet — the request itself enqueues the builds.
- Multi-file conversations: MP3 parts are frame-concatenated (WavCombiner
  is wav-only and would corrupt them); mixed legacy/new formats share the
  first part instead of producing a broken file.
- Combined filename extension matches the artifact format.
@mdmohsin7

Copy link
Copy Markdown
Member Author

@greptile-apps re-review

@mdmohsin7
mdmohsin7 merged commit 2691471 into main Jun 12, 2026
2 checks passed
@mdmohsin7
mdmohsin7 deleted the feat/audio-merge-tasks branch June 12, 2026 19:39
@mdmohsin7

Copy link
Copy Markdown
Member Author

Deployment runbook correction (hit during prod rollout): the env section said prod needs vars on backend-sync only (LB routes all /v1/sync/audio/* there). That's right for the read paths, but the eager enqueue at conversation completion runs on whichever service processes the conversation — backend for live listening. Both services therefore need the full set: AUDIO_MERGE_* plus the shared SYNC_TASKS_PROJECT/SYNC_TASKS_LOCATION/SYNC_TASKS_INVOKER_SA/SYNC_TASKS_OIDC_AUDIENCE (the audience must be set explicitly when the enqueuing service lacks SYNC_TASKS_HANDLER_URL, or minted tokens fail verification).

Failure mode while misconfigured was graceful as designed: enqueue errors are swallowed and logged (audio_merge: enqueue failed ... env vars are incomplete), affected conversations just miss the eager build and lazily build on first play.

mdmohsin7 added a commit that referenced this pull request Jun 13, 2026
…ead of pending-forever (#7877)

## Bug (found in prod ~1h after flipping #7872)

A March conversation got stuck at "preparing audio" until timeout on
share/play. Trace:

1. The merge task ran and correctly found **the source chunks no longer
exist in storage** (`audio_merge: chunks missing ... dropping`) — that
conversation's audio predates current chunk retention and is
unrecoverable by any pipeline (it failed under the old inline merge too,
with a different timeout flavor).
2. But nothing recorded that verdict: `/urls` kept reporting the file as
`pending`, while Cloud Tasks **named-task tombstones** silently blocked
every re-enqueue (`already enqueued, skipping duplicate` on each poll).
3. Result: clients poll to exhaustion — pending forever for audio that
can never exist.

## Fix

A terminal **`unavailable`** state:

- **Handler**: on `chunks_missing`, writes a tiny marker blob
(`playback/{uid}/{conv}/{file}.unavailable`, content = reason) before
consuming the task.
- **`/urls`**: artifact missing + marker present → `status:
"unavailable"` — no enqueue, no poll hint.
- **Flutter**: `unavailable` is excluded from `hasPending`, so the poll
loop exits immediately and the existing error path (snackbar +
`audioPlaybackFailed`) fires instead of 90s of spinning. Share fails
fast the same way.
- **Web**: shows "Audio is no longer available" immediately.

The marker lives under `playback/`, so the existing 30-day lifecycle
rule auto-clears it — even genuinely transient chunk-listing failures
get a retry within a month, with zero extra machinery.

## Tests

4 new structural tests in `test_audio_merge_tasks.py` (marker written on
chunks-missing, `/urls` unavailable branch without enqueue, storage
helpers, app terminal handling) — 15/15 passing; tsc + dart analyze
clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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