Repository navigation
refactor(backend): async-native HTTP and Thread+join elimination (#6369) - #6377
Conversation
Greptile SummaryThis large async-migration PR eliminates
Confidence Score: 4/5Safe to merge after wiring close_all_clients() to a FastAPI shutdown event; missing hook causes resource leaks but not runtime request failures One P1 finding (close_all_clients not called on shutdown) warrants a 4 rather than 5; all async migration logic is correct, the _batch()/set_event_loop pattern is safe in background threads, and social.py correctly uses per-call clients to avoid cross-loop issues backend/main.py (add shutdown hook for close_all_clients), backend/utils/conversations/process_conversation.py (remove dead _update_personas_async) Important Files Changed
Sequence DiagramsequenceDiagram
participant App as FastAPI App
participant HC as http_client.py
participant Router as Router (auth/oauth/apps)
participant Ext as External Service
App->>HC: get_webhook_client() [lazy init on first call]
HC-->>App: shared AsyncClient (64 conn, 15s timeout)
Router->>HC: get_auth_client() / get_maps_client()
HC-->>Router: shared AsyncClient
Router->>Ext: await client.post/get(...)
Ext-->>Router: HTTP response
Note over App,HC: Shutdown (MISSING — main.py not updated)
App--xHC: close_all_clients() [never called]
HC->>HC: await each client.aclose()
Note over App: Background thread path
App->>App: threading.Thread(target=update_personas_async)
App->>App: loop = asyncio.new_event_loop()
App->>App: asyncio.set_event_loop(loop)
App->>App: loop.run_until_complete(_batch())
Note over App: fresh AsyncClient inside get_twitter_timeline
App->>App: loop.close()
|
| async def close_all_clients(): | ||
| """Close all shared HTTP clients. Call at app shutdown.""" | ||
| global _webhook_client, _maps_client, _auth_client, _stt_client | ||
| for client in (_webhook_client, _maps_client, _auth_client, _stt_client): | ||
| if client is not None: | ||
| try: | ||
| await client.aclose() | ||
| except Exception as e: | ||
| logger.warning(f"Error closing HTTP client: {e}") | ||
| _webhook_client = None | ||
| _maps_client = None | ||
| _auth_client = None | ||
| _stt_client = None |
There was a problem hiding this comment.
close_all_clients() never registered in main.py shutdown
main.py was not modified in this PR, so no @app.on_event('shutdown') or lifespan handler calls this function. All four shared clients (_webhook_client, _maps_client, _auth_client, _stt_client) will be abandoned on process exit, leaking OS-level TCP connections and generating ResourceWarning noise.
Add to main.py:
from utils.http_client import close_all_clients
@app.on_event('shutdown')
async def shutdown_event():
await close_all_clients()
Live Test Evidence (L1 + L2) — CP9A/CP9BL1: Backend Standalone (curl + Python module verification)Build: HTTP Endpoints (all 200):
P1 http_client.py — Circuit Breaker + Semaphore + Latest-Wins: P2 executors.py — Critical + Storage Executors: P3 webhooks.py — Async delivery: P4-P6: async geocoding (httpx), sync.py (critical_executor.submit() x4, no threading.Thread), usage tracking (REALTIME_INTEGRATIONS feature constant) Non-happy paths: CB OPEN blocks requests, HALF_OPEN allows 1 probe then blocks, failure reopens, invalid URL fallback, close_all_clients resets semaphore cache L2: Backend + Pusher Integrated (wscat + curl)Build: Backend on :10241 ( wscat to /v4/listen: Backend logs (end-to-end): Pusher logs (received): L1 SynthesisAll 6 changed paths (P1-P6) proven functional standalone: http_client circuit breaker state machine, executor thread pools, async webhooks, async geocoding, sync.py executor migration, usage tracking. Non-happy paths verified (CB OPEN/HALF_OPEN, stale latest-wins, invalid URL fallback, shutdown cleanup). L2 SynthesisBackend + Pusher integrated via WebSocket. End-to-end flow proven: client → /v4/listen WS → Deepgram STT connection → Pusher WS ( by AI for @beastoin |
Test Results (post-review cycle)All tests run via
Coverage highlightsCoordinator deadlock prevention (6 tests)
Circuit breaker boundary (33 tests)
Lint script functional detection (5 tests)
Async webhook structural (6 tests)
Live testing (L1/L2)
by AI for @beastoin |
Live Test Evidence (L1 + L2) — CP9A/CP9B (post-review-cycle rerun)L1: Backend Standalone (curl + Python module verification)Build: HTTP Endpoints (all 200):
P1 http_client.py — Circuit Breaker + Semaphore + Latest-Wins: P2 executors.py — Critical + Storage Executors: P3 webhooks.py — Async delivery: P4 async geocoding: P5 sync.py: no threading.Thread, uses executors. Coordinator ( P6 usage tracking: P7 pusher.py coordinator: Non-happy paths: L2: Backend + Pusher Integrated (WebSocket + curl)Build: Backend on :10240 ( WebSocket to /v4/listen (Python websockets client): Backend logs (end-to-end): Pusher logs (received): HTTP endpoints with both services (all 200):
L1 SynthesisAll 7 changed paths (P1-P7) proven functional standalone: http_client circuit breaker full state machine (CLOSED→OPEN→HALF_OPEN→CLOSED, HALF_OPEN→OPEN on failed probe), executor thread pools with named threads and parallel execution, async webhooks (4 functions verified as async coroutines using httpx not requests), async geocoding, sync.py executor migration with deadlock-safe coordinator, usage tracking feature constant, pusher coordinator deadlock fix. Non-happy paths verified for CB OPEN/HALF_OPEN transitions and latest-wins stale version dropping. L2 SynthesisBackend + Pusher integrated via WebSocket. End-to-end flow proven: client → /v4/listen WS → Deepgram STT connection → Pusher WS ( by AI for @beastoin |
Clean-sweep review cycle resultsChanges made4 additional files fixed to complete the async migration:
Review cycle
Test evidence16 new structural tests in
All pass. Lint: Live test (L1+L2)
by AI for @beastoin |
Review cycle complete — all checkpoints passedCP7 — Reviewer approved (iteration 2)
CP8 — Tester approved (iteration 2)
CP9A — L1 live test: Backend standalone
CP9B — L2 live test: Backend + emulator
Migration summary: 22+ files, zero
|
L2 Live Verification — Changed-Path Coverage ChecklistBackend: local dev (port 10240, worktree
Global checks (from unit tests)
Backend startup
L2 Evidence SynthesisAll 26 changed code paths verified (P1-P26). HTTP API paths tested via curl with ADMIN_KEY auth against running backend. WebSocket endpoint confirmed route registration via 403 auth gate. Source-verified paths confirmed httpx migration and executor wiring. Unit test suite (61 tests in by AI for @beastoin |
L2 WebSocket Live Test —
|
L2 Full Lifecycle Test —
|
| Component | Evidence |
|---|---|
| Backend WS handler | 300s session, 3000 chunks received |
| Deepgram streaming | Connected, 109 segments returned |
| VAD gate (dev GKE) | speech/hangover transitions 0ms→300000ms, 78.9% speech ratio |
| Conversation lifecycle | 120s timeout triggered, _process_conversation called |
| Pusher processing | Received conversation, ran LLM post-processing |
| LLM summarization | Title + overview generated |
| GCS audio upload | 5 chunks (60s batches), 303s total |
| Firestore write | Conversation status=completed, 15 segments stored |
| httpx clients | All outbound HTTP via shared pools (zero requests) |
| Executors | critical_executor + storage_executor (zero threading.Thread) |
by AI for @beastoin
ba0130b to
7d2f552
Compare
…learnings from PR #6377 Co-Authored-By: Claude Opus 4.6 <[email protected]>
d0053eb to
919b336
Compare
…learnings from PR #6377 Co-Authored-By: Claude Opus 4.6 <[email protected]>
919b336 to
62149aa
Compare
…learnings from PR #6377 Co-Authored-By: Claude Opus 4.6 <[email protected]>
62149aa to
f7964d6
Compare
…learnings from PR #6377 Co-Authored-By: Claude Opus 4.6 <[email protected]>
Phase 1: Webhook & geocoding — requests.post → shared httpx.AsyncClient Phase 2: Auth/OAuth/social — blocking requests → async httpx, time.sleep → asyncio.sleep Phase 3: Thread+join → ThreadPoolExecutor.map + asyncio.gather with _batch() wrapper Phase 4: Async STT variants with asyncio.to_thread file I/O offload Phase 6: AST-based lint script for async-blocker regression prevention Key changes: - utils/http_client.py: 4 shared httpx clients with connection pooling - social.py: local httpx.AsyncClient per call (avoids cross-loop RuntimeError) - oauth.py: httpx.RequestError catch for transport failures - sync.py: fixed NameError from removed chunk_threads - apps.py + process_conversation.py: asyncio.gather wrapped in async _batch() helper with set_event_loop for background thread safety 30 unit tests, 0 lint violations, full test.sh passes. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…6369) Introduces critical_executor (4 workers) and storage_executor (2 workers) replacing ad-hoc ThreadPoolExecutor creation throughout the codebase. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…client (Lane 1) (#6369) Adds WebhookCircuitBreaker (CLOSED->OPEN->HALF_OPEN state machine), per-service asyncio.Semaphore for bounded concurrency, and latest-wins dropping pattern for audio byte webhook calls. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…+ semaphore (#6369) Converts conversation_created_webhook and day_summary_webhook from sync requests.post to async httpx. All webhook functions now use circuit breakers and bounded semaphore concurrency. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ircuit breaker (#6369) Converts from sync Thread+requests.post to async def with asyncio.gather, httpx, circuit breakers, semaphore, and latest-wins for audio byte calls. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rocess_conversation (#6369) Replaces 7 fire-and-forget threading.Thread().start() calls with critical_executor.submit() for bounded concurrency and proper lifecycle. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ecutor in RAG (#6369) Migrates 3 inline ThreadPoolExecutor usages to the shared critical_executor. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…gather (#6369) Replaces ad-hoc ThreadPoolExecutor creation with storage_executor, critical_executor, and asyncio.gather for VAD/transcription work. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…integrations (#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rations (#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tegrations (#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…l_integrations (#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…cio.sleep (#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rt to top level (#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…les (#6369) 59 structural tests verifying zero import requests in production code, proper executor lane selection, and httpx behavioral parity. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ebhook in asyncio.run (#6369) Reviewer caught: day_summary_webhook is async def — submitting to ThreadPoolExecutor returns a coroutine that never executes. Wrap in asyncio.run(). Also switch from critical_executor to storage_executor since this is batch cron work. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…vious behavior (#6369) Reviewer caught: old code used timeout=30 per-call but shared client had 15s, breaking slow but valid partner webhooks. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Reviewer caught: lazy import for generate_wrapped_2025 was unnecessary — no circular dependency exists. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…storage_executor) (#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…onfig tests (#6369) Tester-requested additions: - Webhook client read timeout = 30s, connect timeout = 2s - critical_executor = 8 workers, storage_executor = 4 workers - Notification webhook uses storage_executor.submit(asyncio.run, ...) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…learnings from PR #6377 Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…es router New code on main used threading.Thread for update_personas_async in an async function. Migrated to loop.run_in_executor(critical_executor) to stay consistent with the 3-lane async architecture. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tests Main added get_user_language_preference() calls to _get_structured but the test stubs were not updated, causing 5 test failures. Co-Authored-By: Claude Opus 4.6 <[email protected]>
f7964d6 to
4d78da9
Compare
|
lgtm |
Live Verification Results (post-rebase)Branch HEAD: Async Lintcurl/wscat Tests (backend on port 10241,
|
| # | Test | Endpoint | Result |
|---|---|---|---|
| 1 | GET conversations | /v1/conversations?limit=3 |
✅ 200 |
| 2 | GET memories | /v3/memories?limit=3 |
✅ 200 |
| 3 | GET webhook status | /v1/users/developer/webhooks/status |
✅ 200 |
| 4 | POST set webhook | /v1/users/developer/webhook/memory_created |
✅ 200 |
| 5 | POST enable webhook | /v1/users/developer/webhook/memory_created/enable |
✅ 200 |
| 6 | WebSocket connect | /v4/listen?sample_rate=16000&codec=opus&language=en |
✅ Connected — received service_status messages |
Infrastructure Verification (Python script)
| Component | Result |
|---|---|
| httpx webhook client | ✅ OK |
| httpx maps client | ✅ OK |
| httpx auth client | ✅ OK |
| httpx stt client | ✅ OK |
| Circuit breaker (allow + record_success) | ✅ OK |
| Semaphore (acquire/release) | ✅ OK |
| critical_executor | ✅ OK |
| storage_executor | ✅ OK |
| close_all_clients() shutdown | ✅ OK |
Server Logs
No unexpected errors. Pusher connection refusal is expected (no Pusher service locally) — WebSocket correctly enters degraded mode. Deepgram connection lifecycle handled cleanly.
by AI for @beastoin
…oc Thread backend/CLAUDE.md and the root CLAUDE.md both say: never `Thread().start().join()` (use `critical_executor` / `storage_executor`) The async-native refactor (PR BasedHardware#6377) removed the remaining ad-hoc threads and added a lint script that catches this pattern in async def. The delete-account wipe added in PR BasedHardware#6669 brought one back — inside a sync def, so the lint at scripts/lint_async_blockers.py doesn't see it (it only walks async functions and only matches .join()). Two follow-on problems with the daemon=True form: 1. Cloud Run sends SIGTERM during scale-down or rolling deploys. Daemon threads are killed mid-wipe, leaving partial deletion and no retry — Firebase auth has already been revoked, so the user can no longer sign in to retry. 2. The lint script will keep missing the pattern as long as the trigger lives in a sync endpoint. Switching to critical_executor.submit(...) reuses the bounded shared pool, runs as non-daemon (graceful shutdown blocks on the wipe), and keeps the trigger fire-and-forget. Behavior is otherwise unchanged. A separate issue (BasedHardware#6750) tracks the bigger move to Cloud Tasks / Pub-Sub for proper retry + DLQ; this PR is the in-place fix that gets us back inside the documented executor lane in the meantime.
…edHardware#6369) (BasedHardware#6377) * refactor(backend): async-native HTTP and Thread+join elimination (BasedHardware#6369) Phase 1: Webhook & geocoding — requests.post → shared httpx.AsyncClient Phase 2: Auth/OAuth/social — blocking requests → async httpx, time.sleep → asyncio.sleep Phase 3: Thread+join → ThreadPoolExecutor.map + asyncio.gather with _batch() wrapper Phase 4: Async STT variants with asyncio.to_thread file I/O offload Phase 6: AST-based lint script for async-blocker regression prevention Key changes: - utils/http_client.py: 4 shared httpx clients with connection pooling - social.py: local httpx.AsyncClient per call (avoids cross-loop RuntimeError) - oauth.py: httpx.RequestError catch for transport failures - sync.py: fixed NameError from removed chunk_threads - apps.py + process_conversation.py: asyncio.gather wrapped in async _batch() helper with set_event_loop for background thread safety 30 unit tests, 0 lint violations, full test.sh passes. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(backend): add dedicated shared thread pool executors (Lane 2) (BasedHardware#6369) Introduces critical_executor (4 workers) and storage_executor (2 workers) replacing ad-hoc ThreadPoolExecutor creation throughout the codebase. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(backend): add circuit breakers, semaphores, latest-wins to HTTP client (Lane 1) (BasedHardware#6369) Adds WebhookCircuitBreaker (CLOSED->OPEN->HALF_OPEN state machine), per-service asyncio.Semaphore for bounded concurrency, and latest-wins dropping pattern for audio byte webhook calls. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate webhooks to async httpx + circuit breaker + semaphore (BasedHardware#6369) Converts conversation_created_webhook and day_summary_webhook from sync requests.post to async httpx. All webhook functions now use circuit breakers and bounded semaphore concurrency. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate trigger_external_integrations to async + circuit breaker (BasedHardware#6369) Converts from sync Thread+requests.post to async def with asyncio.gather, httpx, circuit breakers, semaphore, and latest-wins for audio byte calls. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): replace ad-hoc threads with critical_executor in process_conversation (BasedHardware#6369) Replaces 7 fire-and-forget threading.Thread().start() calls with critical_executor.submit() for bounded concurrency and proper lifecycle. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): replace ad-hoc ThreadPoolExecutor with critical_executor in RAG (BasedHardware#6369) Migrates 3 inline ThreadPoolExecutor usages to the shared critical_executor. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate sync router to shared executors + asyncio.gather (BasedHardware#6369) Replaces ad-hoc ThreadPoolExecutor creation with storage_executor, critical_executor, and asyncio.gather for VAD/transcription work. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): update conversations router for async trigger_external_integrations (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): update workflow router for async trigger_external_integrations (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): update integration router for async trigger_external_integrations (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): update pusher router for natively async trigger_external_integrations (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(backend): add tests for circuit breaker, semaphore, latest-wins, executors (BasedHardware#6369) 25 tests covering WebhookCircuitBreaker state machine, registry, latest-wins dropping pattern, semaphore getters, and shared executor functionality. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(backend): update lock bypass tests for async webhooks/integrations (BasedHardware#6369) Updates 4 tests to use asyncio.run() for now-async trigger_external_integrations and conversation_created_webhook functions. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(backend): update async app integration test stubs for new imports (BasedHardware#6369) Adds stubs for circuit breaker, semaphore, latest-wins, and executors modules. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(backend): update thread join elimination tests for shared executor pattern (BasedHardware#6369) Updates assertions to check for critical_executor/storage_executor instead of raw ThreadPoolExecutor/concurrent.futures usage. Co-Authored-By: Claude Opus 4.6 <[email protected]> * chore(backend): add test_async_http_infrastructure to test.sh (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): make semaphores per-event-loop, circuit breaker per-URL (BasedHardware#6369) Fixes two reviewer findings: 1. Semaphores now keyed by event loop ID so asyncio.run() callers (sync endpoints) get isolated semaphores instead of sharing a loop-bound global. 2. Circuit breaker registry keyed by URL path (not host) so different webhook endpoints on the same host are isolated. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): restore requests import for get_github_docs_content (BasedHardware#6369) The sync get_github_docs_content function uses requests.get but the import was accidentally removed during async migration. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(backend): update tests for per-URL circuit breaker and per-loop semaphore (BasedHardware#6369) Adds tests for URL-path keying, query param stripping, and cross-loop semaphore isolation. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): add semaphore cache pruning to prevent unbounded growth (BasedHardware#6369) Adds _SEMAPHORE_CACHE_MAX=100 threshold with clear-on-overflow to prevent unbounded growth from short-lived asyncio.run() loops in sync endpoints. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): wire close_all_clients to FastAPI shutdown event (BasedHardware#6369) Ensures shared httpx.AsyncClient pools and semaphore registry are properly cleaned up when the application shuts down. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): update test stub for renamed update_persona_prompt (BasedHardware#6369) Replaces sync_update_persona_prompt stub with update_persona_prompt to match the async refactor, fixing test collection failure. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: align test_sync_v2.py assertions with executor-based implementation Tests were still asserting old threading.Thread/daemon/.join patterns while sync.py now uses critical_executor.submit(). Updated 6 structural tests and added utils.executors stub to 2 test harnesses. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add async_get_google_maps_location using httpx.AsyncClient Async version of get_google_maps_location that uses the shared maps httpx client instead of blocking requests.get, completing the Lane 1 async conversion for geocoding. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: add missing http_client stubs for realtime integrations test Add circuit breaker, semaphore, and latest-wins stubs to prevent import failures when utils.app_integrations is loaded. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test: add circuit breaker integration tests for webhook functions Cover circuit breaker short-circuiting (skip HTTP when open), record_success on 200, and record_failure on exception for both transcript and audio byte webhooks. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test: add shutdown lifecycle and semaphore cleanup tests Cover shutdown_executors callability, atexit registration, and close_all_clients semaphore cache reset. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): bump executor pool sizes for 40-connection headroom (BasedHardware#6369) critical_executor: 4→8 workers (handles VAD, process_conversation, process_segment, mentor notification) storage_executor: 2→4 workers (handles audio chunk uploads, GCS operations) Sized to prevent queuing under 40 concurrent WebSocket connections while keeping thread count bounded. Healthcheck endpoints remain unaffected (pure async, no executor deps). Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate pusher to Lane 2 executors + async geocoding (BasedHardware#6369) - process_conversation: asyncio.to_thread → critical_executor - geocoding: asyncio.to_thread(get_google_maps_location) → async_get_google_maps_location (Lane 1 httpx) - audio upload/DB ops: asyncio.to_thread → storage_executor - Frees the default thread pool so healthcheck stays responsive under load Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate sync v1 VAD + process_segment to critical_executor (BasedHardware#6369) Replace asyncio.to_thread (default pool) with loop.run_in_executor(critical_executor) for VAD processing and process_segment in both v1 and v2 sync paths. Keeps all blocking work on the dedicated Lane 2 executor, preventing default pool saturation. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate mentor notification to critical_executor (BasedHardware#6369) Replace asyncio.to_thread(process_mentor_notification) with loop.run_in_executor(critical_executor) for architecture consistency. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): add shutdown handler to pusher/main.py (BasedHardware#6369) Wire close_all_clients() to pusher's FastAPI shutdown event, matching backend/main.py. Ensures httpx connection pools are cleanly closed on pod termination. shutdown_executors is already registered via atexit. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(backend): update v1 sync test for critical_executor migration (BasedHardware#6369) Align test_v1_uses_synchronous_gather assertion with run_in_executor pattern replacing asyncio.to_thread. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): update thread-safety comment in http_client.py (BasedHardware#6369) The WebhookCircuitBreaker docstring incorrectly claimed "all callers are on the same event loop". In reality, circuit breakers use only time.monotonic() and simple int/bool fields with no asyncio primitives, making them inherently thread-safe. httpx.AsyncClient is also thread-safe per httpx docs. Updated the comment to document the actual safety model. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): wire maps semaphore into async geocoding (BasedHardware#6369) The get_maps_semaphore() getter existed in http_client.py but was never acquired by any caller. Wire it into async_get_google_maps_location so outbound Google Maps requests are bounded to 8 concurrent calls. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate apps.py file I/O from asyncio.to_thread to storage_executor (BasedHardware#6369) Replace asyncio.to_thread(_write_file, ...) with loop.run_in_executor(storage_executor, ...) for all three call sites (create persona, update persona, upload thumbnail). This routes file I/O through the dedicated storage_executor with bounded concurrency. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate imports.py file write from asyncio.to_thread to storage_executor (BasedHardware#6369) Replace asyncio.to_thread(f.write, ...) with loop.run_in_executor(storage_executor, ...) for chunked file upload writes. Routes I/O through the dedicated storage_executor. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate speaker_embedding.py file read to storage_executor (BasedHardware#6369) Replace asyncio.to_thread(_read_file, ...) with loop.run_in_executor(storage_executor, ...) for audio file reads before embedding extraction HTTP calls. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate speech_profile.py file read to storage_executor (BasedHardware#6369) Replace asyncio.to_thread(_read_file, ...) with loop.run_in_executor(storage_executor, ...) for audio file reads before speech profile matching HTTP calls. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor(backend): migrate vad.py from asyncio.to_thread to dedicated executors (BasedHardware#6369) Replace asyncio.to_thread with run_in_executor for both call sites: - _read_file → storage_executor (file I/O) - _local_vad → critical_executor (compute-bound VAD inference) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(test): use real ThreadPoolExecutor for critical/storage executor stubs (BasedHardware#6369) asyncio's run_in_executor calls executor.submit() and wraps the returned concurrent.futures.Future. MagicMock returns a MagicMock from submit(), which fails the isinstance check. Replace with real ThreadPoolExecutor instances for both critical_executor and storage_executor. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(test): update STT file I/O check from asyncio.to_thread to run_in_executor (BasedHardware#6369) The test_stt_async_offloads_file_io assertion checked for asyncio.to_thread in STT source files. Update to check for run_in_executor now that file I/O is routed through dedicated executors. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(test): add get_maps_semaphore stub for async geocoding tests (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(pusher): prevent executor deadlock by using default pool for coordinator (BasedHardware#6369) process_conversation submits child tasks to critical_executor — running it in the same pool risks deadlock under concurrent load. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(sync): prevent executor deadlock in v2 segment background processing (BasedHardware#6369) _process_segments_background fans out child tasks to critical_executor — running the coordinator in the same pool risks deadlock under load. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(lint): add Thread().start() detection to async blocker lint script (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(test): update v2 assertion for default executor coordinator pattern (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(test): update sync v2 assertions for default executor coordinator pattern (BasedHardware#6369) Tests now validate against _process_segments_background dispatch rather than critical_executor.submit, matching the deadlock-safe coordinator pattern. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(sync): add coordinator pattern enforcement and pusher structural tests (BasedHardware#6369) Validates that v2 dispatch uses run_in_executor(None, ...) and pusher uses default executor for process_conversation coordinator. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(lint): add functional detection tests for async blocker lint script (BasedHardware#6369) Tests validate requests.get, time.sleep, Thread().start() detection and clean code false-negative avoidance. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(circuit-breaker): add half-open single-probe-failure reopens test (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(webhooks): add structural tests for async webhook migrations (BasedHardware#6369) Validates conversation_created_webhook and day_summary_webhook are async, use httpx via get_webhook_client, and don't import requests. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(memories): replace threading.Thread with critical_executor for persona update (BasedHardware#6369) Migrate fire-and-forget Thread().start() to shared critical_executor.submit() in update_memory_visibility endpoint, consistent with 3-lane async architecture. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(imports): replace threading.Thread with critical_executor for limitless import (BasedHardware#6369) Migrate fire-and-forget daemon thread to shared critical_executor.submit(), remove unused threading import. Consistent with 3-lane async architecture. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(hume): migrate from requests to httpx for Hume API calls (BasedHardware#6369) Replace blocking requests.post() with httpx.post() in HumeClient. Maps exception types: requests.exceptions → httpx equivalents. Removes last requests import from utils/other/. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(knowledge_graph): add missing threading import for Lock in rebuild (BasedHardware#6369) The rebuild_knowledge_graph function uses threading.Lock() but never imported the threading module. Add the import. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(imports): use storage_executor for long-running import batch (BasedHardware#6369) Limitless import is a long-running batch loop (ZIP extraction + DB writes) that would starve critical_executor's 8 latency-sensitive workers. Move to storage_executor which is designed for batch I/O operations. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(knowledge_graph): use storage_executor for batch rebuild (BasedHardware#6369) rebuild_knowledge_graph submits one task per memory (LLM calls + DB writes). Using critical_executor (8 workers) for large rebuilds would monopolize the request-path pool. Move to storage_executor for batch isolation. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(hume): add follow_redirects and use RequestError for httpx parity (BasedHardware#6369) httpx does not follow redirects by default (unlike requests), so TooManyRedirects was unreachable. Add follow_redirects=True for behavioral parity. Use httpx.RequestError (closer match to requests.RequestException). Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(clean-sweep): add structural tests for async migration fixes (BasedHardware#6369) 16 tests covering: - memories.py: critical_executor for persona updates, no threading.Thread - imports.py: storage_executor for batch import, no critical_executor/Thread - hume.py: httpx with follow_redirects, RequestError, TimeoutException - knowledge_graph.py: threading import, storage_executor for batch rebuild Co-Authored-By: Claude Opus 4.6 <[email protected]> * chore(test): add test_clean_sweep_migrations.py to test.sh (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(sync): migrate requests to httpx in _download_audio_bytes (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(app_integrations): migrate requests to httpx for GitHub docs fetching (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(speaker_embedding): migrate requests to httpx for embedding API calls (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(speech_profile): migrate requests to httpx for speech profile API (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(location): migrate requests to httpx for Google Maps geocoding (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(action_items): replace threading.Thread with critical_executor (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(calendar_onboarding): migrate requests to httpx and threading to executor (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(chat): replace threading.Thread with critical_executor for goal progress (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(developer): replace threading.Thread with critical_executor for persona update (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(mcp): replace threading.Thread with critical_executor for persona update (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(wrapped): replace threading.Thread with critical_executor for wrapped generation (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(chat_utils): replace threading.Thread with storage_executor for file cleanup (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(postprocess): replace threading.Thread with storage_executor for audio cleanup (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(notifications): replace threading.Thread with critical_executor for webhooks (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(storage): replace ad-hoc ThreadPoolExecutor with storage_executor (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(calendar_tools): migrate requests to httpx and time.sleep to asyncio.sleep (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(google_utils): migrate requests to httpx for OAuth token refresh (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(perplexity): migrate requests to httpx async client for web search (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(test): update speaker embedding test mock from requests to httpx (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * docs: add 3-lane async I/O architecture to CLAUDE.md (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(apps): migrate requests to httpx for manifest fetching, move import to top level (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(clean-sweep): expand migration tests to cover all 22 migrated files (BasedHardware#6369) 59 structural tests verifying zero import requests in production code, proper executor lane selection, and httpx behavioral parity. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(notifications): use storage_executor for batch cron, wrap async webhook in asyncio.run (BasedHardware#6369) Reviewer caught: day_summary_webhook is async def — submitting to ThreadPoolExecutor returns a coroutine that never executes. Wrap in asyncio.run(). Also switch from critical_executor to storage_executor since this is batch cron work. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(http_client): increase webhook client timeout to 30s to match previous behavior (BasedHardware#6369) Reviewer caught: old code used timeout=30 per-call but shared client had 15s, breaking slow but valid partner webhooks. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(wrapped): move in-function import to module top level (BasedHardware#6369) Reviewer caught: lazy import for generate_wrapped_2025 was unnecessary — no circular dependency exists. Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(clean-sweep): add tests for reviewer-driven fixes (asyncio.run, storage_executor) (BasedHardware#6369) Co-Authored-By: Claude Opus 4.6 <[email protected]> * test(infra): add webhook timeout, executor sizing, and async wiring config tests (BasedHardware#6369) Tester-requested additions: - Webhook client read timeout = 30s, connect timeout = 2s - critical_executor = 8 workers, storage_executor = 4 workers - Notification webhook uses storage_executor.submit(asyncio.run, ...) Co-Authored-By: Claude Opus 4.6 <[email protected]> * docs(backend): expand async I/O architecture guide with patterns and learnings from PR BasedHardware#6377 Co-Authored-By: Claude Opus 4.6 <[email protected]> * docs(backend): trim async I/O guide — concise hierarchical format Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(backend): replace Thread().start() with run_in_executor in memories router New code on main used threading.Thread for update_personas_async in an async function. Migrated to loop.run_in_executor(critical_executor) to stay consistent with the 3-lane async architecture. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(test): add missing database.users stubs for process_conversation tests Main added get_user_language_preference() calls to _get_structured but the test stubs were not updated, causing 5 test failures. Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
Summary
Complete elimination of
requestslibrary andthreading.Threadfrom all backend production code, enforcing the 3-lane async I/O architecture consistently across 22 files.Lane 1 —
requests→httpxmigrations (12 files)utils/other/hume.pyrequests.post→httpx.postwithfollow_redirects=True, proper exception hierarchyrouters/sync.pyrequests.get→httpx.getwith float timeout in_download_audio_bytesutils/app_integrations.pyrequests.get→httpx.getfor GitHub docs fetchingutils/apps.pyrequests.get→httpx.getfor manifest fetching, moved import to top levelutils/stt/speaker_embedding.pyrequests.post→httpx.postfor embedding API (2 call sites)utils/stt/vad.pyrequests.post→httpx.postfor hosted VADutils/stt/speech_profile.pyrequests.post→httpx.postfor speech profile matchingutils/conversations/location.pyrequests.get→httpx.getfor Google Maps geocodingrouters/calendar_onboarding.pyrequests→httpx+ threading → executorutils/retrieval/tools/calendar_tools.pyrequests→httpx+time.sleep→asyncio.sleeputils/retrieval/tools/google_utils.pyrequests→httpxfor OAuth token refreshutils/retrieval/tools/perplexity_tools.pyrequests→ asynchttpxfor web searchLane 2 —
threading.Thread→ executor migrations (10 files)routers/memories.pycritical_executorrouters/imports.pystorage_executorrouters/action_items.pycritical_executorrouters/chat.pycritical_executorrouters/developer.pycritical_executorrouters/mcp.pycritical_executorrouters/wrapped.pycritical_executorutils/chat.pystorage_executorutils/conversations/postprocess_conversation.pystorage_executorutils/other/notifications.pycritical_executorLane 2 — Ad-hoc ThreadPoolExecutor → shared executor (1 file)
utils/other/storage.pyThreadPoolExecutor(max_workers=10)withstorage_executorLane 2 — Batch rebuild executor fix (1 file)
utils/llm/knowledge_graph.pycritical_executor→storage_executorfor batch rebuild + added missingimport threadingLane 3 — Lint & Documentation
python scripts/lint_async_blockers.pyreports zero violationsCLAUDE.mdandbackend/CLAUDE.mdwith 3-lane async I/O architecture docshttpx behavioral parity notes
follow_redirects=Trueadded whererequestsfollowed redirects by default (Hume API)float(httpx requirement)requests.Timeout→httpx.TimeoutException,requests.RequestException→httpx.RequestError,requests.TooManyRedirects→httpx.TooManyRedirectsTest plan
test_clean_sweep_migrations.pyverify:import requestsacross all routers/ and utils/ production codethreading.Threadin routers/test_short_audio_embedding.pymock fromrequests.post→httpx.posttest_conversation_source_unknownfailures unrelated)Closes #6369
🤖 Generated with Claude Code
by AI for @beastoin