Repository navigation
fix(audio): playback merges via Cloud Tasks — 30-day MP3 artifacts, read paths never merge - #7872
Conversation
_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 SummaryThis 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
Confidence Score: 5/5Safe 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
Sequence DiagramsequenceDiagram
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
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.
|
@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.
|
@greptile-apps re-review |
|
Deployment runbook correction (hit during prod rollout): the env section said prod needs vars on Failure mode while misconfigured was graceful as designed: enqueue errors are swallowed and logged ( |
…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)
Problem
Conversation audio playback is broken for any non-trivial conversation. Verified chain of failure:
GET /v1/sync/audio/{id}/urlsmerges the first uncached file synchronously and unbounded in-request (download every chunk from GCS → decrypt (enhanced users) → opus-decode → gap-fill → WAV-encode).pending, and the app immediately falls back toGET /v1/sync/audio/{id}/{file}?format=wav— which also merges inline, under the 120s middleware ceiling, while the app only waits 30s.Logger.debug).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.Fix (mirrors the validated #7801 pattern)
Merges become Cloud Tasks jobs; request paths never merge; the app polls.
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.audio_merge_failed_finallog, 600s request-timeout override (< 1800s lock TTL). Named tasksam-{conv}-{file}dedupe enqueues from polling.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 arepending+poll_after_mswith 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.AUDIO_MERGE_DISPATCH_MODEdefaults toinline— merging behavior is byte-for-byte today's until flipped. Rollback = flip back.Clients
/urls(3s cadence frompoll_after_ms, 90s budget) and build theConcatenatingAudioSourceplaylist 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) + newaudioPlaybackFailedanalytics event instead of a silent infinite spinner. Share/export uses the artifact's real extension.AudioPlayer.tsxpolls the same way; blob-through-proxy fallback removed.Tests
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 intest.sh.scan_async_blockersclean;dart analyze0 errors;tscclean.🚀 Deployment (ordered — ships inert)
1. Merge (regular merge) + deploy — no behavior change (
inlinedefault).2. One-time infra (per project — dev
based-hardware-devfirst, then prodbased-hardware):IAM: nothing new — the project-level
cloudtasks.enqueuergrants 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):
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-mergequeue depth, handler 5xx,audio_merge_failed_finalevents,/urlslatency (target always <2s),audioPlaybackFailedanalytics.6. Rollback =
AUDIO_MERGE_DISPATCH_MODE=inline(queued tasks drain harmlessly; artifacts already built keep serving).Out of scope (documented)
🤖 Generated with Claude Code