Skip to content

Backend async blocker audit (2026-05-17) #7342

Closed

Description

@beastoin

Backend async event loop blocker audit

Date: 2026-05-17 | Scope: backend/routers/ + backend/utils/ | Method: AST scan of all async def endpoints and helpers

Scanned 413 endpoints (306 def, 107 async def) across 44 router files + all utils.


HIGH — Blocking network I/O on event loop

1. GCS uploads/deletes in async endpoints

File: routers/apps.py:574,609,615,1900

Code fact: upload_app_logo(), upload_app_thumbnail(), delete_app_logo() from utils/other/storage.py are sync GCS SDK calls. Called directly inside async def create_persona (line 574), async def update_persona (lines 609, 615), and async def upload_app_thumbnail_endpoint (line 1900). Each call blocks the event loop for the duration of the GCS upload/delete.

2. Google auth refresh in async helpers

File: routers/agent_tools.py:41,47,62,81,97

Code fact: _get_gce_access_token() at line 38 calls creds.refresh(google.auth.transport.requests.Request()) — sync HTTP to Google metadata server. Called from async helpers _check_gce_status (line 47), _start_vm_and_wait (lines 62, 81, 97), which are called from ensure_vm and keepalive endpoints. Worst case: polling loop in _start_vm_and_wait calls it up to 30 times (24 operation polls + 6 IP polls).


MEDIUM — Blocking file I/O on event loop

3. File write in voice message endpoint

File: routers/chat.py:602-603

Code fact: async def transcribe_voice_message at line 508 uses open(temp_path, "wb") + shutil.copyfileobj(file.file, buffer) — blocks event loop during WAV file write. User-facing upload endpoint.

4. File open in import endpoint

File: routers/imports.py:61

Code fact: async def import_limitless_data at line 31 uses open(zip_path, 'wb') — the open() itself blocks. Writes inside use run_in_executor but the file descriptor creation doesn't.

5. File read in speaker ID helper

File: routers/transcribe.py:1781

Code fact: async def speaker_identification_task uses open(file_path, 'rb').read() for speech profile audio. Blocks event loop during file read. Called from _stream_handler which runs for every WS connection.


STRUCTURAL — 50 async def endpoints with zero await

These are pure sync functions incorrectly marked async def. FastAPI runs async def on the event loop (blocking), but runs plain def in a threadpool (non-blocking). Changing async def → def fixes all of these with no behavior change.

File Count Endpoints
announcements.py 10 get_changelogs, get_features, get_announcements, get_pending_announcements_endpoint, dismiss_announcement_endpoint, list_all_announcements, get_announcement, create_announcement_endpoint, update_announcement_endpoint, delete_announcement_endpoint
goals.py 10 get_current_goal, get_all_goals, create_goal, update_goal, update_goal_progress, get_goal_history, delete_goal, suggest_goal, get_goal_advice, extract_and_update_progress
payment.py 7 create_connect_account_endpoint, check_onboarding_status, refresh_account_link_endpoint, stripe_return, stripe_success, stripe_cancel, portal_return
integration.py 6 create_memories_via_integration, get_memories_via_integration, get_conversations_via_integration, search_conversations_via_integration, send_notification_via_integration, get_tasks_via_integration
imports.py 3 get_import_jobs, get_import_job_status, delete_limitless_conversations
mcp_sse.py 3 mcp_authorize, mcp_delete_session, mcp_sse_info
apps.py 2 get_twitter_initial_message, migrate_app_owner
sync.py 2 sync_local_files_v2, get_sync_job_status
agents.py 1 hume_expression_measurement_callback
chat.py 1 create_voice_message_stream
conversations.py 1 merge_conversations
oauth.py 1 oauth_authorize
other.py 1 health_check
updates.py 1 clear_desktop_cache
users.py 1 export_all_user_data

STRUCTURAL — 20 async def endpoints mixing await + sync DB calls

These genuinely need async for awaits but also call sync Firestore SDK functions between awaits, blocking the event loop during each DB call.

File Endpoint Sync DB calls
agent_tools.py:159 ensure_vm get_agent_vm
agent_tools.py:195 keepalive get_agent_vm
apps.py:545 create_persona get_user_from_uid, save_username, add_app_to_db
apps.py:589 update_persona save_username, update_app_in_db, delete_app_cache_by_id
apps.py:656 get_or_create_user_persona get_user_persona_by_uid, get_user_from_uid, save_username, add_app_to_db
apps.py:1298 get_twitter_profile_data get_user_persona_by_uid, get_persona_by_twitter_handle_db
apps.py:1331 verify_twitter_ownership_tweet get_user_from_uid
apps.py:1436 add_mcp_server get_user_from_uid, add_app_to_db ×2
apps.py:1580 mcp_oauth_callback get_app_by_id_db, update_app_in_db, delete_app_cache_by_id, enable_app
apps.py:1670 refresh_mcp_tools get_app_by_id_db, update_app_in_db ×2, delete_app_cache_by_id ×2
apps.py:1735 enable_app_endpoint enable_app, increase_app_installs_count
auth.py:142 auth_authorize set_auth_session
auth.py:178 auth_callback_google get_auth_session, set_auth_code
auth.py:219 auth_callback_apple_post get_auth_session, set_auth_code
auth.py:261 auth_token get_auth_code, delete_auth_code
chat.py:698 transcribe_voice_message_stream check_rate_limit
memories.py:87 create_memories_batch upsert_memory_vectors_batch
oauth.py:114 oauth_token get_app_by_id_db, enable_app, increase_app_installs_count
payment.py:594 stripe_webhook set_credits_invalidation_signal ×4
payment.py:826 stripe_webhook get_default_payment_method, set_default_payment_method

Clean (no findings)

  • requests library — 0 in production code (banned by test_clean_sweep_migrations.py)
  • time.sleep on event loop — 0 (all 5 instances are inside sync helper functions submitted to thread pool executors)

Scan script

Run from repo root:

python3 scripts/scan_async_blockers.py
python3 scripts/scan_async_blockers.py --json
python3 scripts/scan_async_blockers.py --dirs backend/routers backend/utils
scripts/scan_async_blockers.py (click to expand)
#!/usr/bin/env python3
"""
FastAPI async blocker scanner for backend/.

Detects dangerous patterns in async def endpoints:
  1. async def with zero await (should be plain def)
  2. async def mixing await + sync DB calls (needs run_in_executor)
  3. Blocking file I/O (open, shutil) in async def
  4. Blocking network I/O (GCS uploads, google auth refresh) in async def
  5. time.sleep on event loop

Usage:
  python3 scripts/scan_async_blockers.py [--dirs backend/routers backend/utils] [--json]

Exit codes:
  0 = clean (no HIGH findings)
  1 = HIGH findings present
"""
import ast, os, sys, json, argparse

def get_db_imports(source):
    db_names = set()
    tree = ast.parse(source)
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom) and node.module and 'database' in node.module:
            for alias in node.names:
                db_names.add(alias.asname or alias.name)
    return db_names

def get_storage_imports(source):
    names = set()
    tree = ast.parse(source)
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom) and node.module and 'storage' in node.module:
            for alias in node.names:
                names.add(alias.asname or alias.name)
    return names

def has_await(node):
    for child in ast.walk(node):
        if isinstance(child, ast.Await):
            return True
    return False

def get_route_info(decorators):
    for dec in decorators:
        if isinstance(dec, ast.Call) and isinstance(dec.func, ast.Attribute):
            method = dec.func.attr.upper()
            if dec.args and isinstance(dec.args[0], ast.Constant):
                return method, dec.args[0].value
    return "?", "?"

def scan_async_function(node, db_names, storage_names):
    db_calls, file_io, network_io, sleeps = [], [], [], []
    for child in ast.walk(node):
        if not isinstance(child, ast.Call):
            continue
        if isinstance(child.func, ast.Name):
            if child.func.id in db_names:
                db_calls.append({"line": child.lineno, "call": child.func.id})
            if child.func.id in storage_names:
                if any(kw in child.func.id.lower() for kw in ["upload", "delete", "download"]):
                    network_io.append({"line": child.lineno, "call": child.func.id})
            if child.func.id == 'open':
                file_io.append({"line": child.lineno, "call": "open()"})
        if isinstance(child.func, ast.Attribute):
            if isinstance(child.func.value, ast.Name):
                if child.func.value.id == 'time' and child.func.attr == 'sleep':
                    sleeps.append({"line": child.lineno, "call": "time.sleep()"})
                if child.func.value.id == 'requests':
                    network_io.append({"line": child.lineno, "call": f"requests.{child.func.attr}()"})
                if child.func.value.id == 'shutil':
                    file_io.append({"line": child.lineno, "call": f"shutil.{child.func.attr}()"})
            if child.func.attr == 'refresh' and isinstance(child.func.value, ast.Name) and child.func.value.id == 'creds':
                network_io.append({"line": child.lineno, "call": "creds.refresh() [sync HTTP]"})
    return db_calls, file_io, network_io, sleeps

def collect_py_files(dirs):
    files = []
    for d in dirs:
        for root, _, fnames in os.walk(d):
            for fname in sorted(fnames):
                if fname.endswith('.py') and fname != '__init__.py':
                    files.append(os.path.join(root, fname))
    return sorted(files)

def scan_dirs(dirs):
    results = {
        "high_network_io": [], "medium_file_io": [], "no_await_should_be_def": [],
        "mixed_await_sync_db": [], "time_sleep": [], "async_helpers_with_blocking": [],
    }
    total_def, total_async, files_scanned = 0, 0, 0

    for fpath in collect_py_files(dirs):
        with open(fpath) as f:
            source = f.read()
        try:
            tree = ast.parse(source, filename=fpath)
        except Exception:
            continue
        files_scanned += 1
        db_names = get_db_imports(source)
        storage_names = get_storage_imports(source)

        for node in ast.walk(tree):
            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
                is_endpoint = any('router' in ast.dump(d).lower() for d in node.decorator_list)
                if is_endpoint:
                    if isinstance(node, ast.AsyncFunctionDef):
                        total_async += 1
                    else:
                        total_def += 1

            if not isinstance(node, ast.AsyncFunctionDef):
                continue
            is_endpoint = any('router' in ast.dump(d).lower() for d in node.decorator_list)
            db_calls, file_io, network_io, sleeps = scan_async_function(node, db_names, storage_names)
            endpoint_has_await = has_await(node)

            if is_endpoint:
                method, path = get_route_info(node.decorator_list)
                entry = {"file": fpath, "line": node.lineno, "endpoint": node.name,
                         "method": method, "path": path, "has_await": endpoint_has_await}
                if network_io:
                    results["high_network_io"].append({**entry, "calls": network_io})
                if file_io:
                    results["medium_file_io"].append({**entry, "calls": file_io})
                if sleeps:
                    results["time_sleep"].append({**entry, "calls": sleeps})
                if not endpoint_has_await:
                    results["no_await_should_be_def"].append({
                        **entry, "db_calls": db_calls, "all_blocking": db_calls + file_io + network_io})
                elif db_calls:
                    results["mixed_await_sync_db"].append({**entry, "db_calls": db_calls})
            else:
                if network_io or file_io or sleeps:
                    results["async_helpers_with_blocking"].append({
                        "file": fpath, "line": node.lineno, "function": node.name,
                        "network_io": network_io, "file_io": file_io, "sleeps": sleeps})

    results["summary"] = {
        "files_scanned": files_scanned, "total_def_endpoints": total_def,
        "total_async_endpoints": total_async,
        "high_network_io": len(results["high_network_io"]),
        "medium_file_io": len(results["medium_file_io"]),
        "no_await_should_be_def": len(results["no_await_should_be_def"]),
        "mixed_await_sync_db": len(results["mixed_await_sync_db"]),
        "time_sleep_on_loop": len(results["time_sleep"]),
        "async_helpers_with_blocking": len(results["async_helpers_with_blocking"]),
    }
    return results

def main():
    parser = argparse.ArgumentParser(description="Scan FastAPI for async blocking patterns")
    parser.add_argument("--dirs", nargs="+", default=["backend/routers", "backend/utils"])
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()
    for d in args.dirs:
        if not os.path.isdir(d):
            print(f"Error: {d} not found", file=sys.stderr)
            sys.exit(2)
    results = scan_dirs(args.dirs)
    if args.json:
        json.dump(results, sys.stdout, indent=2)
    else:
        s = results["summary"]
        print(f"=== FastAPI Async Blocker Audit ===")
        print(f"Files: {s['files_scanned']} | Endpoints: {s['total_def_endpoints']} def + {s['total_async_endpoints']} async def")
        print(f"HIGH: {s['high_network_io']} network + {s['async_helpers_with_blocking']} helpers | MEDIUM: {s['medium_file_io']} file I/O")
        print(f"STRUCTURAL: {s['no_await_should_be_def']} no-await + {s['mixed_await_sync_db']} mixed | time.sleep: {s['time_sleep_on_loop']}")
        for cat, label in [("high_network_io","HIGH endpoints"), ("async_helpers_with_blocking","HIGH helpers"),
                           ("medium_file_io","MEDIUM file I/O")]:
            if results[cat]:
                print(f"\n--- {label} ---")
                for e in results[cat]:
                    name = e.get("endpoint", e.get("function","?"))
                    calls = e.get("calls", e.get("network_io",[])+e.get("file_io",[])+e.get("sleeps",[]))
                    cs = ", ".join(f"{c['call']}:{c['line']}" for c in calls)
                    print(f"  {e['file']}:{e['line']} | {name} | {cs}")
    has_high = results["summary"]["high_network_io"] > 0 or results["summary"]["async_helpers_with_blocking"] > 0
    sys.exit(1 if has_high else 0)

if __name__ == "__main__":
    main()

Summary

Category Count Action
HIGH — network I/O 3 endpoints + 2 helpers Wrap in run_in_executor
MEDIUM — file I/O 2 endpoints + 1 helper Wrap in run_in_executor or use aiofiles
async def → def 50 endpoints Change to def (FastAPI auto-threads)
Mixed await + sync DB 20 endpoints Wrap DB calls in run_in_executor
time.sleep on loop 0 Clean
requests library 0 Clean (banned by test suite)

Note: the pervasive sync Firestore SDK usage across all database modules is architectural — not fixable per-endpoint without migrating to an async Firestore client.

by AI for @beastoin

Activity

  1. added
    bug
    backend
    p2
    on May 17, 2026
  2. added a commit that references this issue on May 18, 2026
    db341b4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendbugp2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions