Skip to content

fix(backend): async coordinator pattern for sync v2 pipeline (#7361) - #7362

Merged
beastoin merged 14 commits into
BasedHardware:mainfrom
beastoin:fix/async-coordinator-sync-7361
May 18, 2026
Merged

beastoin merged 14 commits into
BasedHardware:mainfrom
beastoin:fix/async-coordinator-sync-7361

Conversation

@beastoin

@beastoin beastoin commented May 18, 2026 •

Copy link
Copy Markdown
Collaborator

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 → new submit_with_context calls 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_context with async coordinator pattern:

  • start_background_task(_run_full_pipeline_background_async(...), name=...) — tracked fire-and-forget with exception logging
  • Pipeline runs as async coroutine on event loop
  • Each CPU-bound step uses await run_blocking(executor, fn) — borrows thread only for that step
  • Zero thread pool slots held between steps

New utility — start_background_task() (utils/executors.py):

  • Wraps asyncio.create_task with task tracking set, exception logging via done_callback, cancellation logging
  • drain_background_tasks() for graceful SIGTERM shutdown
  • get_background_task_count() for observability
  • Replaces bare create_task which silently swallows exceptions and can be GC'd

CLAUDE.md rules added — async dispatch decision tree:

  • await run_blocking(executor, fn) — sync/CPU-bound, caller needs result
  • start_background_task(coro, name=...) — async fire-and-forget (pipelines)
  • submit_with_context(executor, fn) — short sync fire-and-forget only, never for >10s pipelines
  • Long-running pipelines must be async coordinators

Follow-up: #7371 — migrate to arq/SAQ task queue for persistence, retry, and cross-instance backpressure.

Stress Test Results (12 concurrent requests)

Metric BEFORE (submit_with_context) AFTER (start_background_task) 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

BEFORE shows clear batching (4 jobs queued at ~23s behind 8-slot limit). AFTER has no batching — all 12 progress concurrently.

Changes

File What
utils/executors.py start_background_task(), drain_background_tasks(), get_background_task_count()
routers/sync.py Replace asyncio.create_task + manual callback with start_background_task(coro, name=...)
main.py Call drain_background_tasks() on shutdown
CLAUDE.md Async dispatch rules (run_blocking vs start_background_task vs submit_with_context)
tests/unit/test_executors.py 5 new tests (run, track/remove, exception logging, cancellation, drain)
tests/unit/test_sync_v2.py Updated structural assertions for start_background_task

Test plan

  • 24 executor tests pass (including 5 new for start_background_task)
  • 171 sync_v2 tests pass (147 sync + 24 executor)
  • Stress test: 12 concurrent BEFORE vs AFTER comparison
  • Live integration test with real audio files
  • CLAUDE.md compliance verified (semaphore delegation, import rules)

🤖 Generated with Claude Code

beastoin and others added 9 commits May 18, 2026 06:32
…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-apps

greptile-apps Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Converts the sync v2 background pipeline from a long-running thread-worker (held postprocess_executor slot for 60–300 s) to an async coordinator that runs on the event loop and offloads blocking work to pools via run_blocking(), fixing the pool-starvation deadlock described in #7361. It also adds MonitoredThreadPoolExecutor with active-task tracking, a get_executor_metrics() / log_executor_health() observability layer, and an asyncio.Semaphore(16) concurrency cap.

  • utils/executors.py: New MonitoredThreadPoolExecutor subclass wraps every submitted task in _tracked() for live active_count reporting; all seven pools migrated to the new class.
  • routers/sync.py: _run_full_pipeline_background_async dispatched via asyncio.create_task; BYOK context inherited automatically and cleared in finally.
  • tests/unit/test_sync_v2.py: TestBackgroundWorkerBehavioral (17 executable tests) replaced with TestAsyncCoordinatorStructure (12 source-inspection tests), removing verified runtime coverage of billing-critical paths.

Confidence Score: 3/5

The 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

Filename Overview
backend/tests/unit/test_sync_v2.py 17 executable behavioral tests replaced with 12 source-inspection tests; cannot catch runtime failures in billing-critical paths such as DG usage recording, mark_job_failed dispatch, or cleanup guarantees.
backend/routers/sync.py Core async-coordinator logic is correct but done_callback silently discards exceptions escaping the finally block, potentially leaving jobs stuck in processing state.
backend/utils/executors.py Adds MonitoredThreadPoolExecutor, get_executor_metrics(), log_executor_health(), and _ALL_EXECUTORS registry. Minor concern: _max_workers and _work_queue are private CPython internals.
backend/main.py Minimal startup event change; in-function import of log_executor_health violates project import rules.
backend/tests/unit/test_executors.py 9 new executable tests for MonitoredThreadPoolExecutor covering active_count tracking, exception propagation, and metrics fields.
backend/CLAUDE.md Documents Rule 4 and pool observability; accurate and consistent with the code changes.

Sequence Diagram

sequenceDiagram
    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
Loading

Comments Outside Diff (2)

  1. backend/tests/unit/test_sync_v2.py, line 1117 (link)

    P1 Behavioral test coverage replaced with source-inspection tests

    TestBackgroundWorkerBehavioral (17 executable tests) was removed and replaced with TestAsyncCoordinatorStructure (12 string-search tests against source code). The removed tests actually ran the function with mocks and verified runtime behavior: mark_job_failed was called on exception, DG usage was recorded correctly for the billing path, partial failure counts matched, and job directories were actually cleaned up. The new tests only verify that the right strings appear in the source file — they cannot catch a runtime NameError, a wrong argument order to record_dg_usage_ms, or a silently-swallowed exception in the finally block. With @pytest.mark.asyncio and async mocks (AsyncMock), the same behavioral coverage can be restored for the async coordinator.

  2. backend/routers/sync.py, line 588 (link)

    P2 Done callback silently discards unlogged exceptions

    lambda t: t.exception() if not t.cancelled() else None suppresses the asyncio warning, but the retrieved exception is thrown away. If any await run_blocking(...) in the finally block raises — for instance because storage_executor was already shut down — that exception propagates past the inner except Exception, becomes the task's stored exception, and is silently consumed here with no logging and no mark_job_failed call. The job would be left permanently in processing state.

Reviews (1): Last reviewed commit: "test(backend): add semaphore loop-scopin..." | Re-trigger Greptile

Comment thread backend/main.py
Comment on lines 152 to +156

@app.on_event("startup")
async def startup_event():
asyncio.create_task(log_executor_health())

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

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

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

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

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

beastoin and others added 3 commits May 18, 2026 06:49
… 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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

Live Integration Test Evidence (L1/L2 functional)

Happy path — real audio through full pipeline

Sent 60s Silero VAD test WAV (length-prefixed PCM16, 16kHz mono) through POST /v2/sync-local-files:

POST response: {"job_id":"76b6b662-...","status":"queued","total_files":1,"poll_after_ms":3000}

Pipeline ran the full async coordinator path:

  • Decode (5ms): PCM16 → WAV
  • VAD (482ms): Local ONNX Silero (hosted VAD fallback worked), found 1 speech segment
  • STT+LLM (34.9s): Deepgram pre-recorded → conversation processing
  • Result: 1 new memory created
{
    "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:

sync_v2 bg complete job=76b6b662-... uid=test-integ-uid success=1/1 timings={'decode_ms': 5, 'vad_ms': 482, 'stt_llm_ms': 34953, 'total_ms': 38856}

Error path — corrupt file

Sent 1KB random bytes as PCM16. Coordinator handled gracefully:

  • Decode produced empty WAV (random bytes aren't valid length-prefixed frames)
  • Pipeline completed with total_segments: 0, no crash, no error

Endpoint contract (unchanged)

Request Response Expected
POST without auth 401 ✅
POST with invalid file 400 ✅
GET nonexistent job 404 ✅
V1 POST (no files) 422 ✅
POST with real audio 202 + job_id ✅
GET completed job 200 + result ✅

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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

Test Results — Post start_background_task() commit (4afd0a9)

171/171 passed, 0 failed (0.82s)

Executor tests (24 tests)

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_async with 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_task for 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

@beastoin

Copy link
Copy Markdown
Collaborator Author

@ryo does byok still work on sync local files api after your pr merged?

@beastoin

Copy link
Copy Markdown
Collaborator Author

@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:

  1. BYOKMiddleware.dispatch() (utils/byok.py:123) sets _byok_ctx ContextVar via _byok_ctx.set(keys) before the request handler runs
  2. sync_local_files_v2 handler runs with BYOK keys in its ContextVar scope
  3. start_background_task() wraps asyncio.create_task() — create_task automatically inherits the parent task's ContextVars (Python asyncio guarantee, unlike threads which need explicit copy_context())
  4. Inside _run_full_pipeline_background_async, all await run_blocking(executor, fn) calls use contextvars.copy_context() to propagate BYOK keys into worker threads
  5. finally block calls set_byok_keys({}) to clear keys after pipeline completes (sync.py:1623)

This is actually safer than the old pattern. The old submit_with_context(postprocess_executor, fn) required explicit contextvars.copy_context() to propagate keys into the thread. asyncio.create_task() gets context inheritance for free.

Tests that verify this (all PASS):

Test What it checks
test_v2_uses_start_background_task_for_context_inheritance start_background_task present in dispatch code
test_async_coordinator_clears_byok_in_finally set_byok_keys({}) in finally block
test_finally_clears_byok_keys BYOK cleanup ordering verified
test_cleanup_order_byok_before_files BYOK cleared before file cleanup
test_no_plain_submit_in_sync No raw executor.submit() that would skip context

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]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

lgtm

@beastoin
beastoin merged commit 1e6b712 into BasedHardware:main May 18, 2026
1 check passed
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.

fix(backend-sync): 202 accept path regression from executor bulkhead PR #7343

1 participant