Repository navigation
feat(sync): dispatch v2 sync pipeline via Cloud Tasks - #7801
Conversation
The Cloud Tasks sync-job handler runs the whole pipeline inside the request and needs a cap above the 120s default. Path overrides take precedence over method timeouts.
…S_RUN_TIMEOUT, default 1500s)
- per-job run lock (fail-closed, compare-and-delete release) so duplicate task deliveries can never run a job concurrently - mark_job_queued_for_retry: stale-detector-exempt reset before retries - processed-segment ledger so retries skip segments that already landed - try_mark_once guards so fair-use/usage metering counts once per job
enqueue_sync_job creates one named HTTP task per job (task id = job_id for enqueue-side dedup) with an OIDC token for the invoker SA. verify_cloud_tasks_oidc fails closed when SYNC_TASKS_* env is unset so services sharing the image never accept task traffic.
Blob name = local relative path (existing pipeline convention). download returns False on NotFound so the handler can consume tasks whose blobs were removed by the bucket's 1-day lifecycle rule.
The pipeline previously ran as a fire-and-forget asyncio task on the instance that received the upload: invisible to the Cloud Run autoscaler, killed on scale-in, no retries, no fleet-wide balancing. Fast path now stages raw .bin files in GCS and enqueues one Cloud Task per job (SYNC_DISPATCH_MODE=cloud_tasks); the task POSTs back to /v2/sync-jobs/run which runs the same pipeline inside the request. Inline path is kept for rollback, BYOK requests (header-scoped keys cannot follow a task), and enqueue failures. Handler semantics: per-job run lock (409 while held), terminal jobs acked without re-running, queued-reset before retryable 500s so the stale detector cannot kill jobs during backoff, final attempt marks failed and consumes. Staged blobs are deleted on every terminal outcome; the bucket's 1-day lifecycle covers hard crashes. Metering once-guards and a processed-segment ledger make retries idempotent.
Greptile SummaryThis PR replaces the fire-and-forget asyncio background task in
Confidence Score: 5/5Safe to merge. The default SYNC_DISPATCH_MODE=inline means deploying changes nothing until the flag is flipped; the new Cloud Tasks path is fully gated and falls back to inline on any enqueue failure. All three concerns from the previous review cycle are addressed. The only new observations are a partial-download cleanup gap that is practically unreachable (all blobs in a job expire simultaneously), and a lazy-singleton init pattern harmless under the GIL. Flag-based rollout and automatic inline fallback make the change low-risk. No files require special attention - routers/sync.py has the most new logic but retry/idempotency paths are well-tested by 24 new unit tests. Important Files Changed
Sequence DiagramsequenceDiagram
participant App
participant SyncEndpoint as POST /v2/sync-local-files
participant GCS as GCS syncing-local
participant CT as Cloud Tasks queue
participant Handler as POST /v2/sync-jobs/run
participant Redis
participant Pipeline as Pipeline decode-VAD-STT-LLM
App->>SyncEndpoint: multipart upload
SyncEndpoint->>GCS: stage raw bin blobs
SyncEndpoint->>CT: enqueue named task job_id
SyncEndpoint-->>App: 202 job_id
CT->>Handler: POST payload plus OIDC token
Handler->>Handler: verify_cloud_tasks_oidc
Handler->>Redis: try_acquire_job_run_lock
Redis-->>Handler: token or None
Handler->>Redis: get_sync_job
Redis-->>Handler: job status
alt terminal status
Handler->>GCS: delete staged blobs
Handler-->>CT: 200 acked
else normal run
Handler->>GCS: download blobs to local paths
Handler->>Pipeline: run pipeline task_mode True
Pipeline->>Redis: mark_job_processing
Pipeline->>Pipeline: decode VAD STT LLM
Pipeline->>Redis: add_processed_segment
Pipeline->>Redis: try_mark_once metering
alt success
Handler->>GCS: delete staged blobs
Handler-->>CT: 200 done
else retryable error
Handler->>Redis: mark_job_queued_for_retry
Handler-->>CT: 500 retry
else final attempt
Handler->>Redis: mark_job_failed
Handler->>GCS: delete staged blobs
Handler-->>CT: 200 failed_final
end
end
Handler->>Redis: release_job_run_lock
Reviews (2): Last reviewed commit: "fix(sync): log OIDC verification failure..." | Re-trigger Greptile |
| timeout = self.paths_timeout.get(request.url.path) or self.methods_timeout.get( | ||
| request.method, self.default_timeout | ||
| ) |
There was a problem hiding this comment.
Using
or to select the path timeout means any falsy value (specifically 0.0) silently falls back to the method timeout instead of applying the configured value. If HTTP_SYNC_JOBS_RUN_TIMEOUT=0 were ever set, the sync-jobs path would get the POST method timeout (120 s) rather than 0 s, with no error or warning. An explicit is not None check matches the intent.
| timeout = self.paths_timeout.get(request.url.path) or self.methods_timeout.get( | |
| request.method, self.default_timeout | |
| ) | |
| path_timeout = self.paths_timeout.get(request.url.path) | |
| timeout = path_timeout if path_timeout is not None else self.methods_timeout.get( | |
| request.method, self.default_timeout | |
| ) |
| try: | ||
| claims = id_token.verify_oauth2_token(auth_header[len('Bearer ') :], _get_auth_request(), audience=audience) | ||
| except Exception: | ||
| raise HTTPException(status_code=403, detail='Invalid OIDC token') |
There was a problem hiding this comment.
The bare
except Exception: catches both genuine token-validation failures and transient errors (e.g. a network timeout while fetching Google's JWKS endpoint), then raises the same 403 without logging the underlying cause. When cert-fetch latency spikes, operators would see a flood of "Invalid OIDC token" 403s with nothing in the logs to distinguish them from actual bad tokens, making the failure very hard to triage.
| try: | |
| claims = id_token.verify_oauth2_token(auth_header[len('Bearer ') :], _get_auth_request(), audience=audience) | |
| except Exception: | |
| raise HTTPException(status_code=403, detail='Invalid OIDC token') | |
| try: | |
| claims = id_token.verify_oauth2_token(auth_header[len('Bearer ') :], _get_auth_request(), audience=audience) | |
| except Exception as e: | |
| logger.warning('OIDC token verification failed: %s', e) | |
| raise HTTPException(status_code=403, detail='Invalid OIDC token') |
| except Exception as e: | ||
| logger.error(f'sync_v2: Cloud Tasks dispatch failed job={job_id}, falling back inline: {e}') | ||
| start_background_task(_delete_staged_blobs_async(owned_paths), name=f'sync_unstage:{job_id}') |
There was a problem hiding this comment.
The
except block deletes staged blobs unconditionally, but dispatched = True is set before the local-cleanup steps. If an exception were to propagate after that point (e.g. a future change makes _cleanup_files raise), this code would delete the blobs that the already-enqueued task is about to download, silently breaking the job — the task would run, find no blobs, and mark the job staged_audio_expired. Both _cleanup_files and shutil.rmtree(_, True) currently swallow errors, so this path is unreachable today, but the guard is cheap and keeps the invariant explicit.
| except Exception as e: | |
| logger.error(f'sync_v2: Cloud Tasks dispatch failed job={job_id}, falling back inline: {e}') | |
| start_background_task(_delete_staged_blobs_async(owned_paths), name=f'sync_unstage:{job_id}') | |
| except Exception as e: | |
| logger.error(f'sync_v2: Cloud Tasks dispatch failed job={job_id}, falling back inline: {e}') | |
| if not dispatched: | |
| start_background_task(_delete_staged_blobs_async(owned_paths), name=f'sync_unstage:{job_id}') |
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Skipping this one per project convention: we don't add guards for paths that are unreachable by design — _cleanup_files and shutil.rmtree(_, True) both swallow errors deliberately, so nothing after dispatched = True can raise. Please remember this preference for future reviews on this repo.
There was a problem hiding this comment.
Got it, makes sense. I've noted this for future reviews: View rule
Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.
|
@greptile-apps re-review |
kodjima33
left a comment
There was a problem hiding this comment.
Backend sync feature (Cloud Tasks dispatch) — approve only, features stay for Nik
Resolves sync.py conflicts with #7819 (chronological assignment turnstile): - process_segment keeps both the turnstile finally-release and the success-bool return used by the processed-segment ledger - coordinator combines the ledger skip with the ordered turnstile; skipped segments release their assignment slot so later segments don't stall waiting for a turn that would never complete
Deployment runbook corrections (learned from dev-env testing)Dev testing validated the full path end-to-end (enqueue → task → OIDC handler → pipeline → blob cleanup, including the 409 run-lock correctly blocking a retry that raced a slow in-flight job). Three corrections to the runbook in the PR description:
Also merged |
…gle janitor thread (#7855) ## Problem Four call sites (1 in `routers/sync.py`, 3 voice-message flows in `utils/chat.py`) delete temporal GCS blobs by parking a `storage_executor` thread in `time.sleep(480)` per file. At current sync volume (~20 jobs/min post-#7801) that keeps **~90 of the pool's 128 threads asleep as ad-hoc timers** — confirmed in prod `executor_pool_health` logs (~70–80% \"utilization\" with queue_depth 0, i.e. occupancy without work). This is the remaining root cause behind #7531's storage-pool saturation: the pool was bumped 32→64→96→128 in ten days and `_PRECACHE_FILE_SEM` was halved (#7526) largely to feed threads whose only job was waiting. ## Change - **New `utils/other/deferred_delete.py`**: `DeferredDeleter` — a due-time min-heap plus one lazily-started daemon thread. `schedule()` is an O(log n) heap push; the janitor wakes when the next deletion is due. An earlier-due schedule arriving mid-wait re-notifies and re-peeks, so ordering holds. Delete failures are logged and skipped (the syncing bucket's lifecycle rule remains the backstop, exactly as it was for the sleeping threads). - **`storage.py`**: `schedule_syncing_temporal_file_deletion(path, delay=480s)` wraps a module-level janitor bound to `delete_syncing_temporal_file`. Same 480s semantics (under the 15-min signed-URL validity). - **All four call sites** switch to the scheduler; `chat.py` drops its now-unused `storage_executor`/`time` imports. - **`_PRECACHE_FILE_SEM` 2 → 4**, reverting #7526's load-shed now that the sleepers are gone — audio merge/precache get the freed headroom. Deletion timing, crash semantics (pending deletions die with the process either way), and the lifecycle backstop are all unchanged. Hundreds of pending deletions now cost one thread instead of hundreds. ## Expected impact (measurable immediately after deploy) `executor_pool_health` storage `active_count` should drop from ~90–100 to real work only (~5–15). That single number is the before/after check. ## Tests - New `tests/unit/test_deferred_blob_janitor.py` (11 tests): real-module behavioral coverage (due-order with out-of-order schedules, near-term schedule interrupting a long wait, failure doesn't kill the janitor, 200 pending = exactly 1 thread) + structural guards (no `time.sleep(480)` remains, all four sites use the scheduler, sem = 4). Registered in `test.sh`. - `test_storage_fanout_limits.py`: semaphore value assertion updated 2 → 4 with rationale. - `test_sync_silent_failure.py`: removed the executor-swap setup/teardown machinery that existed solely to neutralize the old sleeping deleters in tests; all 41 pass. - `scan_async_blockers.py`: no new findings (the one `chat.py` hit pre-exists on main). - `test_sync_v2.py` remains at the main baseline (5 pre-existing failures from #7819, unrelated). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…ead paths never merge (#7872) ## 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 #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`):** ```bash 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](https://claude.com/claude-code)
Problem
The
/v2/sync-local-filespipeline (decode → VAD → fair-use → STT → LLM) runs as a fire-and-forget asyncio task on whicheverbackend-syncinstance received the upload. Consequences:202. Instances grind up to 16 pipelines each while Cloud Run sees them as idle, so sync bursts overload the service (the min-10 instance floor exists to compensate).Change
With
SYNC_DISPATCH_MODE=cloud_tasks, the fast path stages the raw.binfiles in thesyncing-localGCS bucket (blob name = local path, the pipeline's existing convention), enqueues one named Cloud Task per job (task id = job_id, enqueue-side dedup), and returns the same202 {job_id}. The task POSTs back to a new OIDC-verifiedPOST /v2/sync-jobs/runon the same service, which runs the same pipeline code inside the request — autoscaler-visible, durable, retried with backoff, rate-limitable at the queue.Zero app changes. Endpoint contract, multipart format,
conversation_idparam,202+poll flow, and/v1/sync-local-filesare untouched.Inline path is preserved and used when: the flag is off (default), the request carries BYOK headers (keys are request-scoped and cannot follow a task), or staging/enqueue fails (automatic fallback — a Cloud Tasks outage degrades to today's behavior).
Idempotency / failure handling
409and re-check terminal status later.500s so the 600s stale detector can't terminally fail a job while the retry backoff elapses.X-CloudTasks-TaskRetryCount) marks the job failed, deletes blobs, returns200(consume).record_speech_ms/record_dg_usage_ms/record_usagefire at most once per job across retries (no fair-use double-counting)./v2/sync-jobs/rungetsHTTP_SYNC_JOBS_RUN_TIMEOUT(default 1500s) instead of the 120s default that would otherwise kill every attempt.backend/backend-integrationrun the same image but reject all task traffic.Tests
tests/unit/test_sync_cloud_tasks.py(24 tests): lock semantics incl. fail-closed Redis errors, queued-reset, ledger, once-guards, OIDC rejection matrix, structural contract. Registered intest.sh.scripts/scan_async_blockers.py: no findings in changed files.🚀 Deployment (ordered — the code ships inert)
The default is
SYNC_DISPATCH_MODE=inline, so merging + deploying changes nothing until step 4.1. Merge + deploy (regular merge, no squash):
2. One-time infra (Cloud Tasks API is currently NOT enabled on
based-hardware):3. Env vars on backend-sync only (deploy workflow preserves env vars; one-time update):
Invariants to keep in sync:
SYNC_TASKS_MAX_ATTEMPTSmust mirror the queue's--max-attempts;HTTP_SYNC_JOBS_RUN_TIMEOUT(1500) must stay below the 1800s run-lock TTL. Do NOT set theSYNC_TASKS_*vars onbackend/backend-integration— unset env keeps the handler inert there.4. Smoke test, then flip:
# smoke: upload a small WAL sync from the app (inline mode still active), confirm unchanged behavior gcloud run services update backend-sync --region us-central1 --update-env-vars SYNC_DISPATCH_MODE=cloud_tasksWatch: queue depth (
cloudtasks.googleapis.com/queue/depth), handler 5xx ratio on/v2/sync-jobs/run, job terminal-status mix, andfailed_final/staged_audio_expiredlog events. Suggested alert: queue depth > 200 for 15 min.5. Rollback = flip the flag back:
In-flight queued tasks still drain through the handler — harmless.
6. Later (separate change): once autoscaling-on-real-load is proven for
a week, lower backend-sync$1k/month at current always-on pricing).minScale10 → 2 (🤖 Generated with Claude Code