Repository navigation
fix(backend): async coordinator pattern for sync v2 pipeline (#7361) - #7362
Conversation
…ing and pool observability Subclasses ThreadPoolExecutor to track active task count per pool. Adds get_executor_metrics() and log_executor_health() for detecting pool saturation before it cascades. Fixes BasedHardware#7361. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace _run_full_pipeline_background (sync, holds postprocess_executor slot for 60-300s) with _run_full_pipeline_background_async (async, holds zero thread pool slots). Coordinator runs on event loop, offloads all blocking work to pools via run_blocking(). Adds asyncio.Semaphore(16) for concurrency cap. Fixes BasedHardware#7361 pool starvation cascade. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Logs pool metrics every 60s when any pool exceeds 70% utilization. Enables early detection of saturation before it cascades. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ity docs Documents the async coordinator pattern for long-running coordinators and the new get_executor_metrics/log_executor_health observability. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…cs tests 9 new tests: active-count tracking, name attribute, submit/exception propagation, metrics fields/pools/utilization, all-monitored assertion. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace behavioral mock tests (called sync function directly) with structural tests validating the async coordinator: run_blocking offload, asyncio.wait_for timeout, semaphore cap, BYOK context inheritance via create_task, no thread pool slot held by coordinator. Co-Authored-By: Claude Opus 4.6 <[email protected]>
… cap Replace module-level asyncio.Semaphore with per-loop-keyed getter following the http_client.py pattern. Prevents RuntimeError when multiple event loops exist. Review feedback from CODEx round 1. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Repo rule: no in-function imports. Review feedback from CODEx round 1. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Tests for loop-keyed semaphore pattern, cache pruning, and 16-slot cap. Update structural tests to reference _get_sync_pipeline_semaphore. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryConverts the sync v2 background pipeline from a long-running thread-worker (held
Confidence Score: 3/5The async-coordinator refactor is architecturally correct and solves the pool-starvation problem, but removal of all executable behavioral tests for billing-critical code means regressions in DG usage recording, error transitions, and cleanup guarantees would not be caught before production. 17 executable behavioral tests that verified billing calls, error transitions, and cleanup were replaced with source-inspection string searches. A bug in the DG usage recording path, an incorrect argument order to mark_job_failed, or a cleanup failure in the finally block would all pass the current test suite undetected. The done_callback also silently discards exceptions that escape the inner handler, which could leave jobs permanently stuck in processing with no log evidence. backend/tests/unit/test_sync_v2.py needs async behavioral tests (using pytest-asyncio) to restore coverage of the DG usage, error-handling, and cleanup paths. backend/routers/sync.py — the done_callback and unprotected _cleanup_files calls in the finally block deserve a second look. Important Files Changed
Sequence DiagramsequenceDiagram
participant Client
participant sync_local_files_v2
participant create_task
participant _run_full_pipeline_background_async
participant Semaphore as asyncio.Semaphore(16)
participant sync_executor
participant db_executor
participant storage_executor
Client->>sync_local_files_v2: POST /v2/sync-local-files
sync_local_files_v2->>db_executor: create_sync_job (run_blocking)
sync_local_files_v2->>create_task: asyncio.create_task(pipeline_async)
sync_local_files_v2-->>Client: 202 Accepted (job_id)
create_task->>_run_full_pipeline_background_async: start (inherits ContextVars)
_run_full_pipeline_background_async->>Semaphore: async with (acquire)
_run_full_pipeline_background_async->>db_executor: mark_job_processing
_run_full_pipeline_background_async->>sync_executor: decode_files_to_wav
_run_full_pipeline_background_async->>sync_executor: _run_vad_bg (gather x N)
_run_full_pipeline_background_async->>storage_executor: _cleanup_files(wav_paths)
_run_full_pipeline_background_async->>db_executor: fair-use checks
_run_full_pipeline_background_async->>sync_executor: _process_one_segment (chunks of 5)
_run_full_pipeline_background_async->>db_executor: record_usage / record_dg_usage_ms
_run_full_pipeline_background_async->>db_executor: mark_job_completed
_run_full_pipeline_background_async->>Semaphore: release
Note over _run_full_pipeline_background_async: finally: set_byok_keys({}), cleanup files
|
|
|
||
| @app.on_event("startup") | ||
| async def startup_event(): | ||
| asyncio.create_task(log_executor_health()) | ||
|
|
There was a problem hiding this comment.
In-function import violates the project's no-in-function-imports rule.
utils.executors can be imported at module level; the deferred import here provides no benefit since utils.executors is already imported transitively via routers at startup, and there is no circular-import risk.
| @app.on_event("startup") | |
| async def startup_event(): | |
| asyncio.create_task(log_executor_health()) | |
| @app.on_event("startup") | |
| async def startup_event(): | |
| from utils.executors import log_executor_health # noqa: PLC0415 | |
| asyncio.create_task(log_executor_health()) |
Context Used: Backend Python import rules - no in-function impor... (source)
| for executor in _ALL_EXECUTORS: | ||
| max_w = executor._max_workers | ||
| active = executor.active_count | ||
| queue_depth = executor._work_queue.qsize() | ||
| utilization = round((active / max_w) * 100, 1) if max_w else 0.0 |
There was a problem hiding this comment.
_max_workers and _work_queue are private CPython internals of ThreadPoolExecutor. They are not part of the public API and could be renamed or removed in a future CPython release, silently breaking observability. Consider exposing queue depth via a queue_depth property on MonitoredThreadPoolExecutor so the private access is isolated in one class.
| for executor in _ALL_EXECUTORS: | |
| max_w = executor._max_workers | |
| active = executor.active_count | |
| queue_depth = executor._work_queue.qsize() | |
| utilization = round((active / max_w) * 100, 1) if max_w else 0.0 | |
| for executor in _ALL_EXECUTORS: | |
| max_w = executor._max_workers # CPython private — stable in 3.9-3.13 | |
| active = executor.active_count | |
| queue_depth = executor._work_queue.qsize() # CPython private — approximate | |
| utilization = round((active / max_w) * 100, 1) if max_w else 0.0 |
… tests Cover tester round 1 gaps: log_executor_health threshold/silent/swallow behavior, plus 30 async coordinator scenario tests covering decode failure, empty decode, VAD error/timeout, zero segments, DG budget exhausted/continue, partial/all segment failure, prefs/cache fallback, target_conversation_id forwarding, and cleanup ordering on success/failure. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…oundary Add 12 behavioral tests that invoke _run_full_pipeline_background_async with mocked dependencies, verifying actual call sequences: decode failure (HTTP + generic), empty decode, VAD errors, zero segments, DG budget exhausted/continue, partial segment failure, person embeddings fallback, target_conversation_id forwarding, and cleanup on success/failure. Add exact-threshold boundary test for log_executor_health (70.0 == 70.0 must not warn since implementation uses >). Co-Authored-By: Claude Opus 4.6 <[email protected]>
CLAUDE.md rule 4: "Don't create raw asyncio.Semaphore outside
http_client.py." Replace the duplicated _sync_semaphores dict and
_get_sync_pipeline_semaphore loop-keying logic with a single call to
the shared _get_semaphore('sync_pipeline', 16) factory.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Live Integration Test Evidence (L1/L2 functional)Happy path — real audio through full pipelineSent 60s Silero VAD test WAV (length-prefixed PCM16, 16kHz mono) through Pipeline ran the full async coordinator path:
{
"status": "completed",
"total_segments": 1,
"successful_segments": 1,
"failed_segments": 0,
"result": {
"new_memories": ["20ed6c9c-53f2-4b67-b539-ed67dca55a35"],
"stage_timings": {"decode_ms": 5, "vad_ms": 482, "stt_llm_ms": 34953, "total_ms": 38856}
}
}Server log confirms async coordinator completion: Error path — corrupt fileSent 1KB random bytes as PCM16. Coordinator handled gracefully:
Endpoint contract (unchanged)
by AI for @beastoin |
Replaces bare asyncio.create_task() with tracked start_background_task() that logs exceptions, prevents GC of unreferenced tasks, and enables graceful drain on shutdown. Updates CLAUDE.md with async dispatch decision tree (run_blocking vs start_background_task vs submit_with_context). - start_background_task(): task tracking set + done_callback + exception logging - drain_background_tasks(): SIGTERM-safe cancellation of in-flight work - get_background_task_count(): observability for background task count - CLAUDE.md: async dispatch rules + long-running pipeline guidance - 5 new tests for start_background_task + drain Co-Authored-By: Claude Opus 4.6 <[email protected]>
Test Results — Post
|
| Test | Status |
|---|---|
test_run_blocking_uses_provided_executor |
PASS |
test_run_blocking_passes_args_and_kwargs |
PASS |
test_run_blocking_propagates_exceptions |
PASS |
test_run_blocking_propagates_contextvars |
PASS |
test_submit_with_context_propagates_contextvars |
PASS |
test_submit_with_context_returns_future_with_result |
PASS |
test_monitored_executor_is_threadpoolexecutor |
PASS |
test_monitored_executor_tracks_active_count |
PASS |
test_monitored_executor_has_name |
PASS |
test_monitored_executor_submit_returns_result |
PASS |
test_monitored_executor_propagates_exceptions |
PASS |
test_get_executor_metrics_returns_all_pools |
PASS |
test_get_executor_metrics_fields |
PASS |
test_get_executor_metrics_idle_utilization |
PASS |
test_all_executors_are_monitored |
PASS |
test_start_background_task_runs_coroutine |
PASS |
test_start_background_task_tracks_and_removes |
PASS |
test_start_background_task_logs_exceptions |
PASS |
test_start_background_task_logs_cancellation |
PASS |
test_drain_background_tasks_cancels_all |
PASS |
test_log_executor_health_warns_above_threshold |
PASS |
test_log_executor_health_silent_below_threshold |
PASS |
test_log_executor_health_silent_at_exact_threshold |
PASS |
test_log_executor_health_swallows_exceptions |
PASS |
Sync v2 tests (147 tests) — all PASS
- Structure (16): endpoint existence, 202 response, async coordinator dispatch, hard restriction gate, job directory, cleanup, heartbeats, stage timings
- Redis job store (18): create/get/update/mark with TTL, stale detection, boundary cases
- Async coordinator structure (16): offloads decode/VAD/segments/cleanup to correct pools, semaphore, BYOK cleanup, chunking, DG usage tracking
- Async coordinator scenarios (30): decode failures (HTTP + generic), empty decode, VAD timeout/errors, zero segments, DG budget gate, segment timeout/errors/capping, partial failure, prefs fetch, embeddings fallback, conversation_id forwarding, finally cleanup ordering
- Async coordinator behavioral (12): actually invokes
_run_full_pipeline_background_asyncwith mocked deps — decode failure, empty decode, VAD errors, zero segments, DG budget, partial failure, embeddings fallback, conversation_id, cleanup on success/failure - Endpoint execution (6): GET poll 404/403/completed/failed/processing, POST 202 + background scheduling
- Bulkhead executors (7): pool existence, worker counts, shutdown registration, context propagation, isolation
- BYOK context (4):
start_background_taskfor context inheritance, BYOK cleared in finally, no plain submit - Timeout configuration (9): LLM/Anthropic/DG timeouts, segment budget
Stress test comparison (12 concurrent sync v2 requests)
| Metric | BEFORE (main) | AFTER (this PR) | Change |
|---|---|---|---|
| Pipeline avg | 14,589ms | 10,906ms | -25% |
| Pipeline max | 23,165ms | 14,012ms | -39% |
| Total e2e max | 28,891ms | 19,093ms | -34% |
| Success/Fail | 12/0 | 12/0 | same |
by AI for @beastoin
|
@ryo does byok still work on sync local files api after your pr merged? |
Yes — BYOK works correctly after this PR. Here's why: Context propagation chain:
This is actually safer than the old pattern. The old Tests that verify this (all PASS):
by AI for @beastoin |
Pusher runs the same executor pools as the main backend but had no health logging or graceful shutdown for background tasks. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
lgtm |
Summary
Fixes #7361 — sync v2 pool starvation cascade.
Root cause:
submit_with_context(postprocess_executor, _run_full_pipeline_background, ...)holds 1 of 8 postprocess thread pool slots for the entire pipeline duration (60-300s). At peak concurrent syncs, all 8 slots fill → newsubmit_with_contextcalls block the asyncio event loop → 202 responses can't return → cascade.Production impact (May 18): 202 P90 jumped from 0.39s → 409.6s. 84K 504 timeouts/week. Cloud Run scaled from 9 → 38 instances trying to cope.
Fix: Replace thread-holding
submit_with_contextwith async coordinator pattern:start_background_task(_run_full_pipeline_background_async(...), name=...)— tracked fire-and-forget with exception loggingawait run_blocking(executor, fn)— borrows thread only for that stepNew utility —
start_background_task()(utils/executors.py):asyncio.create_taskwith task tracking set, exception logging via done_callback, cancellation loggingdrain_background_tasks()for graceful SIGTERM shutdownget_background_task_count()for observabilitycreate_taskwhich silently swallows exceptions and can be GC'dCLAUDE.md rules added — async dispatch decision tree:
await run_blocking(executor, fn)— sync/CPU-bound, caller needs resultstart_background_task(coro, name=...)— async fire-and-forget (pipelines)submit_with_context(executor, fn)— short sync fire-and-forget only, never for >10s pipelinesFollow-up: #7371 — migrate to arq/SAQ task queue for persistence, retry, and cross-instance backpressure.
Stress Test Results (12 concurrent requests)
BEFORE shows clear batching (4 jobs queued at ~23s behind 8-slot limit). AFTER has no batching — all 12 progress concurrently.
Changes
utils/executors.pystart_background_task(),drain_background_tasks(),get_background_task_count()routers/sync.pyasyncio.create_task+ manual callback withstart_background_task(coro, name=...)main.pydrain_background_tasks()on shutdownCLAUDE.mdtests/unit/test_executors.pytests/unit/test_sync_v2.pyTest plan
🤖 Generated with Claude Code