Repository navigation
fix(backend): eliminate async event-loop blockers in FastAPI endpoints - #7343
Conversation
Convert 49 async def endpoints with zero await to plain def (FastAPI runs def in threadpool), wrap GCS/auth/file blocking calls in asyncio.to_thread/run_in_executor for 20 mixed async endpoints, and add CLAUDE.md rules to prevent these patterns. Adds improved scan_async_blockers.py that detects wrapped calls to avoid false positives. Fixes BasedHardware#7342 Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR eliminates event-loop blockers across the FastAPI backend by converting 49
Confidence Score: 4/5The production code changes are structurally sound: every async def → def conversion was verified to have zero awaits, and every remaining blocking call in genuinely-async endpoints is correctly offloaded to a threadpool. All 49 async→def conversions and ~30 blocking-call wraps look correct. The scan_async_blockers.py scanner has a false-positive in _collect_nested_func_lines (ast.iter_child_nodes misses nested defs in control-flow blocks), which will produce spurious hits for async helper functions like _stream_handler in transcribe.py. This does not affect the correctness of the production endpoint fixes, but it undermines the scanner's reliability as a CI gate. backend/scripts/scan_async_blockers.py — the _collect_nested_func_lines helper needs ast.walk instead of ast.iter_child_nodes Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
Request([HTTP Request]) --> FastAPI{FastAPI\nrouter dispatch}
FastAPI -->|"def endpoint\n(no await)"| ThreadPool["Default threadpool\n(anyio worker)"]
FastAPI -->|"async def endpoint\n(has await)"| EventLoop["Event loop\n(async def)"]
ThreadPool --> SyncDB["Sync DB calls\n(Firestore/Redis)"]
ThreadPool --> SyncFile["Sync file I/O\n(open / shutil)"]
ThreadPool --> SyncGCS["GCS / Google Auth\n(sync SDK)"]
EventLoop --> AwaitableIO["Await httpx / WebSocket\n/ asyncio.sleep"]
EventLoop -->|"asyncio.to_thread()"| ThreadPool2["Threadpool\n(blocking offload)"]
EventLoop -->|"run_in_executor\n(storage_executor)"| StoragePool["storage_executor\n(GCS uploads)"]
ThreadPool2 --> SyncDB2["Sync DB calls\n(Firestore/Redis)"]
StoragePool --> SyncGCS2["GCS upload_app_logo\nupload_app_thumbnail\ndelete_app_logo"]
style SyncDB fill:#90EE90
style SyncFile fill:#90EE90
style SyncGCS fill:#90EE90
style SyncDB2 fill:#90EE90
style SyncGCS2 fill:#90EE90
style AwaitableIO fill:#90EE90
Reviews (1): Last reviewed commit: "fix(backend): eliminate async event-loop..." | Re-trigger Greptile |
| def _collect_nested_func_lines(node): | ||
| """Collect line ranges of nested def/lambda inside an async function. | ||
|
|
||
| Calls inside nested sync functions are not directly on the event loop. | ||
| """ | ||
| nested = set() | ||
| for child in ast.iter_child_nodes(node): | ||
| if isinstance(child, (ast.FunctionDef, ast.Lambda)): | ||
| for n in ast.walk(child): | ||
| if hasattr(n, 'lineno'): | ||
| nested.add(n.lineno) | ||
| return nested |
There was a problem hiding this comment.
The function uses
ast.iter_child_nodes(node) which only yields the direct children of the AsyncFunctionDef node. Nested def or lambda expressions that live inside control-flow bodies (if/for/try) are not direct children — they're children of the intermediate If/For/Try nodes — so their line numbers are never added to nested. Any blocking call (e.g. open()) inside such a helper will be falsely reported as unprotected. A concrete example already in this PR is the _read_file helper defined inside if file_path: in _stream_handler (transcribe.py) — the scanner will flag its open() call as a blocking hit in async_helpers_with_blocking. Switching to ast.walk fixes the false positives without changing the intent.
| def _collect_nested_func_lines(node): | |
| """Collect line ranges of nested def/lambda inside an async function. | |
| Calls inside nested sync functions are not directly on the event loop. | |
| """ | |
| nested = set() | |
| for child in ast.iter_child_nodes(node): | |
| if isinstance(child, (ast.FunctionDef, ast.Lambda)): | |
| for n in ast.walk(child): | |
| if hasattr(n, 'lineno'): | |
| nested.add(n.lineno) | |
| return nested | |
| def _collect_nested_func_lines(node): | |
| """Collect line ranges of nested def/lambda inside an async function. | |
| Calls inside nested sync functions are not directly on the event loop. | |
| Uses ast.walk so defs/lambdas inside if/for/try bodies are also found. | |
| """ | |
| nested = set() | |
| for child in ast.walk(node): | |
| if child is node: | |
| continue | |
| if isinstance(child, (ast.FunctionDef, ast.Lambda)): | |
| for n in ast.walk(child): | |
| if hasattr(n, 'lineno'): | |
| nested.add(n.lineno) | |
| return nested |
- Scan script now detects `import database.X as X_db` module aliases (catches `conversations_db.get_conversation()` etc.) - Fix false positives: properly skip calls inside nested def/lambda functions at any nesting depth (not just direct children) - CLAUDE.md async rule now mentions asyncio API usage (create_task, get_running_loop) as valid reasons for async def - Wrap import_jobs_db.update_import_job in asyncio.to_thread Co-Authored-By: Claude Opus 4.6 <[email protected]>
When module is exactly 'database', imported names are sub-modules used as X_db.func() — add to db_module_aliases, not db_names. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Required fixes before merge:
Please push a follow-up commit when ready. by AI for @beastoin |
Helpers with blocking calls are informational — exit 1 only for HIGH network I/O in endpoints (blocking GCS/auth on event loop). Co-Authored-By: Claude Opus 4.6 <[email protected]>
- test_sync_v2: assert def get_sync_job_status (was async def) - test_lock_bypass_fixes: remove await from sync endpoints, fix StreamingResponse async iterator consumption in export test Co-Authored-By: Claude Opus 4.6 <[email protected]>
…loading Replace all asyncio.to_thread() and bare loop.run_in_executor() calls with run_blocking(named_executor, fn, *args) from utils.executors. This eliminates the shared default executor (which competes with asyncio internals like DNS resolution) and adds ContextVar propagation to every call site. Fire-and-forget patterns use submit_with_context(). Only pusher.py:115 retains run_in_executor(None, ...) to avoid deadlock from nested critical_executor submission. 27 files, ~120 call sites migrated across routers and utils. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- sync.py: _run_full_pipeline_background → postprocess_executor (was storage_executor — coordinator shouldn't starve GCS/file pool) - vad.py: local VAD fallback → sync_executor (was critical_executor — CPU audio work belongs in sync pool, not DB/auth pool) - payment.py: wrap 12 bare sync Firestore calls in webhook handlers with run_blocking(critical_executor, ...) to avoid blocking the event loop during stripe webhook processing - test_sync_v2.py: update assertion for postprocess_executor Co-Authored-By: Claude Opus 4.6 <[email protected]>
Wrap _retrieve_file_paths_v2 (file I/O) and create_sync_job (Redis) in run_blocking to avoid blocking the event loop during the v2 sync fast-path. Update test mock to passthrough run_blocking. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…d stale tests - apps.py: wrap migrate_app_owner_id_db, get_omi_persona_apps_by_uid_db, update_app_in_db with run_blocking(critical_executor) - sync.py: wrap is_hard_restricted and has_transcription_credits gate calls in sync_v2 with run_blocking(critical_executor) - test_memories_create.py: update assertions from asyncio.to_thread to run_blocking - test_streaming_deepgram_backoff.py: patch run_blocking instead of asyncio.to_thread - test_sync_v2.py: relax is_hard_restricted assertion for wrapped call Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ed_accounts Offload generate_persona_desc (Firestore + LLM) and delete_app_cache_by_id (Redis) via run_blocking(critical_executor) to avoid blocking the event loop in the async task. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…persona - create_persona: wrap increment_username, generate_persona_desc - update_persona: wrap get_available_app_by_id, generate_persona_desc, invalidate_approved_apps_cache Co-Authored-By: Claude Opus 4.6 <[email protected]>
Cover executor routing, args/kwargs passthrough, exception propagation, and ContextVar propagation. Add test_executors.py to test.sh. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
lgtm |
Replace overloaded critical_executor (8 workers handling everything) with purpose-specific pools: db_executor (16), llm_executor (4), stripe_executor (4). Auth/rate-limit gates stay on critical_executor to prevent starvation. Deadlock prevention: worker threads are leaf operations only — orchestration stays in async code via run_blocking(). No cross-pool .result() calls. Co-Authored-By: Claude Opus 4.6 <[email protected]>
1. sync.py: precache coordinators moved from db_executor to postprocess_executor — they fan out to storage_executor and must not compete for the same pool. 2. process_conversation.py: execute_app (LLM call) moved from db_executor to llm_executor — prevents slow LLM calls from starving DB operations. 3. storage.py: _precache_all coordinator moved from storage_executor to postprocess_executor — prevents self-deadlock when all threads become coordinators waiting on children in the same pool. Updated CLAUDE.md with 7-pool architecture, assignment rules, and 3 deadlock prevention rules for future contributors. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…stripe_executor 1. payment.py: wire stripe_executor for 6 bare Stripe SDK calls in async webhook handler; move _update_subscription_from_session to stripe_executor (mixes Stripe+DB, Stripe is the bottleneck) 2. apps.py: wrap bare sync DB/LLM calls in generate_persona_prompt and update_persona_prompt with run_blocking 3. integration.py: wrap 4 bare sync calls in async create_conversation_via_integration with run_blocking 4. sync.py: wrap sync DB calls in async sync_local_files 5. pusher.py: update comment explaining why default executor is correct for process_conversation coordinator Co-Authored-By: Claude Opus 4.6 <[email protected]>
… handlers 1. payment.py: wrap 7 clear_trial_paywall_cache/clear_fair_use_on_upgrade calls in stripe_webhook with run_blocking(db_executor) 2. apps.py: wrap increment_username in get_or_create_user_persona and 4 DB calls in enable_app_endpoint with run_blocking(db_executor) 3. integration.py: wrap verify_api_key and check_rate_limit_inline with run_blocking(critical_executor) — auth gate calls Co-Authored-By: Claude Opus 4.6 <[email protected]>
Wrap stripe_utils.modify_subscription (stripe_executor), set_user_app_sub_customer_id and paid_app (db_executor) in the async stripe_webhook app-payment branch. Co-Authored-By: Claude Opus 4.6 <[email protected]>
1. apps.py: wrap migrate_memories in run_blocking for create_task 2. utils/apps.py: wrap update_persona_in_db and delete_app_cache_by_id 3. imports.py: wrap create_import_job in run_blocking 4. speaker_identification.py: wrap add_person_speech_sample and set_person_speaker_embedding in run_blocking Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tion 1. pusher.py: wrap 7 DB/cache calls in _process_conversation_task and _websocket_util_trigger with run_blocking(db_executor) 2. vad.py: wrap Redis cache get/set in async_vad_is_empty 3. speaker_identification.py: wrap 3 initial Firestore reads in extract_speaker_samples with run_blocking(db_executor) Co-Authored-By: Claude Opus 4.6 <[email protected]>
1. update_personas_async → postprocess_executor (was db_executor) in memories.py, mcp.py, developer.py — it's a coordinator that fans out to db_executor + llm_executor 2. extract_and_update_goal_progress → llm_executor (was db_executor) in chat.py — it calls get_llm().invoke() 3. Root CLAUDE.md: update executor pool references to match 7-pool architecture in backend/CLAUDE.md Co-Authored-By: Claude Opus 4.6 <[email protected]>
- clean_sweep_migrations: update 11 tests asserting critical_executor to match new pool assignments (db/llm/postprocess) - stripe_webhook_none_guard: expand handler search window (2500→4000) since run_blocking wrapping expanded code size Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
lgtm |
#7378) ## Summary Closes #7376 Tunes executor thread pool sizes based on 48h production monitoring data collected by @mon after the bulkhead architecture deploy (PR #7343). - **postprocess**: 8 → 24 workers (CRITICAL — queue grew unboundedly to 1,239 tasks in 8h) - **storage**: 32 → 64 workers (WARNING — re-saturated within 1h of previous bump, queue peaks at 896) - **db**: 16 → 24 workers (proportional — absorb increased Firestore pressure from bigger postprocess/storage) - **llm**: 4 → 6 workers (proportional — postprocess expansion will feed more LLM work) - **sync**: 12 → 16 workers (ELEVATED — 97% util with no headroom) - **critical**: 8 → 8 (unchanged — auth gates, must stay isolated) - **stripe**: 4 → 4 (unchanged — deliberate API throttle) Total threads: 84 → 146 (+74%). All I/O-bound, minimal CPU/memory impact. ## Decision Logic Sizing based on Codex consultation using Little's Law (`workers >= arrival_rate × avg_service_time`) with 25-50% headroom for Cloud Run burst traffic. Key principle: **proportional scaling with downstream protection** — don't oversize postprocess without matching db/llm capacity, or the bottleneck just shifts downstream. Deliberate throttles kept on `llm_executor` (API rate limit backpressure) and `stripe_executor` (external API). If postprocess queue still grows at 24, next step is durable background processing (Cloud Tasks), not more threads. Full decision rationale in #7376. ## Test plan - [x] `test_executors.py` — 24 tests pass (pool metrics, health logging, monitoring) - [x] `test_sync_v2.py` — executor worker count assertions updated - [x] `test_async_http_infrastructure.py` — pool sizing assertions updated - [ ] Post-deploy: monitor `executor_pool_health` logs for 4h — verify postprocess/storage queues drain - [ ] Post-deploy: verify Cloud Run instance count decreases (less queue memory pressure) - [ ] Post-deploy: watch db/llm pool utilization for bottleneck shift 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Summary
Systematic elimination of async event-loop blockers across the FastAPI backend, plus a full executor architecture overhaul to prevent deadlocks.
Phase 1: Async blocker elimination
deftoasync defwith properrun_blocking()offloadingrun_blocking()wrapper inutils/executors.pyfor consistent async-to-sync bridgingscripts/lint_async_blockers.pyscanner to catchrequests.*,time.sleep(), bareThreadin async codePhase 2: Executor bulkhead architecture (7-pool split)
Split the overloaded
critical_executor(8 workers handling everything) into purpose-specific pools:critical_executordb_executorllm_executorstripe_executorsync_executorpostprocess_executorstorage_executorPhase 3: Deadlock structural fixes
Fixed 3 deadlock risks found via
.result()audit:db_executor→postprocess_executor(they fan out tostorage_executor)execute_app(LLM call) moved fromdb_executor→llm_executor_precache_allcoordinator moved fromstorage_executor→postprocess_executor(was self-deadlock: parent + children on same pool)Deadlock prevention rules (documented in CLAUDE.md)
.result()on another pool from inside a workerawait run_blocking(pool, fn)Files changed (backend only)
utils/executors.py— 7-pool architecture,run_blocking(),submit_with_context()routers/— 15 files migrated to correct executor poolsutils/— 15 files migrated to correct executor poolsCLAUDE.md— Full executor architecture docs + deadlock prevention rulesscripts/lint_async_blockers.py— NEW: async blocker scannertests/unit/test_executors.py— NEW: 6 tests for run_blocking behaviortests/unit/test_sync_v2.py— Updated for new executor assignmentsTest plan
pytest tests/unit/ -x -q).result()audit: no cross-pool deadlock patterns remainblack --checkformatting cleanRisks
stripe_executordefined but not yet wired (Stripe calls still inline in sync handlers) — separate PRpusher.pyintentionally uses default executor (None) forprocess_conversationto avoid nesting — documented, not changedCloses #7342
by AI for @beastoin