Repository navigation
fix(backend): bound storage_executor fan-out with per-request semaphores (#7387) - #7388
Conversation
Greptile SummaryThis PR introduces per-request semaphore gating to bound unbounded fan-out patterns on
Confidence Score: 3/5Merging is safe for immediate load relief, but two structural issues survive that could resurface under sustained high traffic. The precache path in storage.py still submits _cache_single to storage_executor where it internally blocks waiting for child storage_executor tasks, the exact pattern explicitly fixed for speaker_identification.py. Separately, _precache_all_parallel and _cache_uncached_parallel in sync.py can exhaust all 24 postprocess_executor threads by blocking them on _PRECACHE_FILE_SEM.acquire() when global capacity is held by concurrent storage work, stalling unrelated background tasks. backend/utils/other/storage.py (precache parent-child pattern) and backend/routers/sync.py (postprocess thread exhaustion) deserve a closer look before merging to production at high traffic volumes. Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Precache Request] --> B[postprocess_executor\n_precache_all_parallel]
B --> C{_PRECACHE_FILE_SEM\nBoundedSemaphore 4}
C -->|slot acquired| D[storage_executor\n_cache_single]
D --> E[download_audio_chunks_and_merge\nrunning on storage_executor thread]
E --> F{_STORAGE_CHUNK_SEM\nBoundedSemaphore 32}
F -->|slot acquired| G[storage_executor\ndownload_single_chunk child]
G -->|done callback| F
D -->|done callback| C
I[speaker_identification] --> J[sync_executor\ndownload_audio_chunks_and_merge]
J --> F
K[KG Rebuild] --> L[llm_executor\nprocess_memory]
L -->|_KG_REBUILD_SEM 4| M[LLM + DB work]
style C fill:#f90,color:#000
style F fill:#f90,color:#000
style E fill:#fcc,color:#000
|
| futures = [] | ||
| for af in audio_files: | ||
| _PRECACHE_FILE_SEM.acquire() | ||
| try: | ||
| f = storage_executor.submit(_cache_single, af) | ||
| f.add_done_callback(lambda _: _PRECACHE_FILE_SEM.release()) | ||
| futures.append(f) | ||
| except Exception: | ||
| _PRECACHE_FILE_SEM.release() | ||
| raise |
There was a problem hiding this comment.
Parent-child deadlock still present on
storage_executor for precache
_cache_single is submitted to storage_executor. Internally it calls get_or_create_merged_audio → download_audio_chunks_and_merge, which now uses the sliding window that submits additional child tasks to the same storage_executor pool and blocks via wait() until they complete. This is the identical parent-waits-for-child-on-same-pool pattern that was explicitly fixed for speaker_identification.py (by moving the parent to sync_executor). The _PRECACHE_FILE_SEM(4) cap (max 4 parent slots + 32 child slots = 36 of 96 workers) keeps the risk low, but under sustained traffic with other storage work queued, the remaining 60 free slots could be consumed, stalling all 4 parents indefinitely. The fix applied to speaker_identification — submitting the parent to a different pool (sync_executor) — should be applied here too.
| from utils.executors import db_executor, llm_executor | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _KG_REBUILD_SEM = threading.BoundedSemaphore(4) | ||
|
|
||
| from langchain_core.output_parsers import PydanticOutputParser |
There was a problem hiding this comment.
The
_KG_REBUILD_SEM module-level assignment is interleaved between two import blocks. PEP 8 and most linters (E402) require all imports to appear before any executable statements at module level. Move it after the full import block to avoid triggering linter errors.
| from utils.executors import db_executor, llm_executor | |
| logger = logging.getLogger(__name__) | |
| _KG_REBUILD_SEM = threading.BoundedSemaphore(4) | |
| from langchain_core.output_parsers import PydanticOutputParser | |
| from utils.executors import db_executor, llm_executor | |
| from langchain_core.output_parsers import PydanticOutputParser |
|
@beastoin Not approved yet: Please push the follow-up and rerun by AI for @beastoin |
|
The stale assertion issues flagged in the previous review have all been fixed:
All 134 tests pass. Re-review iteration 3 approved with by AI for @beastoin |
…asedHardware#7387) Add module-level semaphores and sliding window to prevent unbounded task submission that causes storage queue spikes to 844 at 96 workers. - _STORAGE_CHUNK_SEM(32): global cap on concurrent chunk downloads - _PRECACHE_FILE_SEM(4): global cap on concurrent audio file precache - _CHUNK_WINDOW_SIZE=8: per-call sliding window with FIRST_COMPLETED - Semaphore acquired before submit, released in done callback (exception-safe) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…edHardware#7387) Both _precache_all_parallel and _cache_uncached_parallel now acquire the global file-level semaphore before submitting to storage_executor. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…asedHardware#7387) process_memory does LLM invoke + DB writes, not storage I/O. Moved to llm_executor with BoundedSemaphore(4) to avoid monopolizing the pool. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…sedHardware#7387) Avoids parent-child deadlock on storage_executor when download_audio_chunks_and_merge submits child tasks to the same pool. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…e#7387) 22 source-level tests verifying semaphore placement, sliding window pattern, and pool assignment for all 4 fan-out sites. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…are#7387) Replace storage_executor assertions with llm_executor + BoundedSemaphore checks to match the new pool assignment. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…dware#7387) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…asedHardware#7387) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…process_executor (BasedHardware#7387) _send_summary_notification does paywall checks, DB reads, LLM calls, and webhook delivery — not storage I/O. Moved to postprocess_executor with batch-of-8 to prevent unbounded fan-out. Co-Authored-By: Claude Opus 4.6 <[email protected]>
… tests (BasedHardware#7387) 3 behavioral tests: window caps inflight, semaphore released on exception, global semaphore limits cross-request. 2 notification source-level tests. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…sedHardware#7387) Prevents one failed user summary from blocking remaining batches. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ecutor (BasedHardware#7387) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…asedHardware#7387) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…asedHardware#7387) Logs cache hits, misses, concurrent merges, and recent re-merges with caller attribution to inform future architecture decisions on precache. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ing (BasedHardware#7387) Tags each merge call site (precache_endpoint, sync_urls_first, sync_urls_bg, sync_download) so logs show which path triggers merges. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Structured log format with consistent key=value pairs, human-readable sizes, bounded tracker dicts to prevent unbounded growth per CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <[email protected]>
6ef4f8f to
f58c844
Compare
…ware#7387) - cache_hit, cache_expired: DEBUG (happy path, ~35/sec at peak) - gap-fill per-chunk log: DEBUG (pre-existing, ~700/sec at peak) - cache_miss, complete, cached: stays INFO (rare after warm-up) - duplicate_concurrent, duplicate_recent: stays WARNING (actionable) Co-Authored-By: Claude Opus 4.6 <[email protected]>
Post-Deploy Monitoring (backfill T+0 through T+1h)Deploy time: 2026-05-23 08:56 UTC Baseline (pre-fix): 202 P99 = 158.9s, storage queue peak = 844, instances = 21.8/25
Remaining checkpoints: T+2h, T+4h, T+8h (peak), T+12h, T+24h — will post updates here. by AI for @beastoin |
Post-Deploy Monitoring — T+2h (10:57 UTC)Does the fix work as expected?Yes. backend-sync 202 accept latency is stable and healthy:
Instance count steady at ~20% of max capacity (was ~87% pre-fix at peak). No saturation. Any regressions?No regressions detected.
Next checkpointT+4h (~12:56 UTC) Monitoring by @mon — [automated post-deploy check] |
Post-Deploy Checkpoint T+2h (10:57 UTC) — off-peak
Pod health: All pods Running, no new restarts since deploy. One pod had 1 restart at T+30m, stable since. Errors: Zero storage_executor or semaphore errors. Background noise only — pre-existing create_memory tracebacks (low freq), baseline uvicorn/httptools noise, transient openai API errors. None related to this PR.
Next checkpoint: T+4h (12:56 UTC) by AI for @beastoin |
Post-Deploy Checkpoint T+4h (12:57 UTC) — approaching peak
Pod health: All Running. One additional pod restart since T+2h (2 pods with 1 restart each, 18 with 0). No CrashLoop. Errors investigated:
Next checkpoint: T+8h (16:56 UTC) — peak hours, most critical check. by AI for @beastoin |
Post-Deploy Checkpoint T+8h (16:04 UTC) — PEAK HOURS
Pod health: 46 pods total — 43 with 0 restarts, 3 with 1 restart. All Running. PR #7388 fix status: Storage fan-out fix confirmed working through peak hours. Zero storage_executor or semaphore errors. 202 latency stable. Unrelated error found:
Next checkpoint: T+12h (20:56 UTC) by AI for @beastoin |
Post-Deploy Checkpoint T+12h (20:10 UTC) — post-peak
Pod health: 42 pods 0 restarts, 4 pods 1 restart. All Running. One additional restart since T+8h — no concern. PR #7388 fix status: Confirmed stable through full peak cycle. Zero storage_executor errors across all 12 hours. 202 latency consistent at ~0.4s avg / ~4.5s P99. Unrelated errors:
Next checkpoint: T+24h (08:56 UTC May 24) — final verification. by AI for @beastoin |
Deploy Monitor — T+24h FINAL Checkpoint (08:51 UTC May 24)Status: PASS — Monitoring series COMPLETE Does the fix work?Yes. Any regressions?No. No new error patterns introduced by this PR. Metrics
Full monitoring summary (T+0 → T+24h)
Note: T+24h latency is a 24h aggregate (includes peak hours) vs earlier point-in-time samples. All values within normal operating range. Related
Monitoring series complete. No further checkpoints scheduled. by AI for @beastoin |
Summary
Fixes #7387 — bounds all unbounded fan-out patterns in
storage_executorsubmissions that cause queue spikes to 844+ at 96 workers during sustained traffic (~3,300 req/min across 3 instances).Changes
storage.py— Sliding window for chunk downloads: Replaced unbounded dict-comprehension submit withFIRST_COMPLETEDsliding window (_CHUNK_WINDOW_SIZE=8) gated by_STORAGE_CHUNK_SEM(32)global semaphore. Handles both individual chunks and batch blobs as one job stream.storage.py— Precache file semaphore: Added_PRECACHE_FILE_SEM(4)to gate concurrent file precache submissions inprecache_conversation_audio._precache_all().sync.py— Precache semaphore in sync endpoints: Both_precache_all_paralleland_cache_uncached_parallelnow use_PRECACHE_FILE_SEMfrom storage to bound their fan-out.knowledge_graph.py— Wrong pool fix: Movedrebuild_knowledge_graphfromstorage_executortollm_executor(correct pool for LLM+DB work) with_KG_REBUILD_SEM(4)bounded semaphore.speaker_identification.py— Parent-child deadlock fix: Changed parent call todownload_audio_chunks_and_mergefromstorage_executortosync_executorto prevent coordinator-child deadlock.notifications.py— Wrong pool fix: Moved notification fan-out fromstorage_executortopostprocess_executorwith batched processing (_BATCH_SIZE=8) and error isolation viareturn_exceptions=True.Semaphore safety pattern (all sites)
Test plan
test_storage_fanout_limits.py(source-level + behavioral)test_clean_sweep_migrations.py— KG and notification assertionstest_async_http_infrastructure.py— webhook wiring testtest.shbeast omi dev boot-check— clean importsExpected production impact
Changed-path coverage checklist
storage.py:_STORAGE_CHUNK_SEM + sliding windowstorage.py:_PRECACHE_FILE_SEM + _precache_allsync.py:_precache_all_parallel + _cache_uncached_parallelknowledge_graph.py:llm_executor + _KG_REBUILD_SEMspeaker_identification.py:sync_executor parent callnotifications.py:postprocess_executor + batching🤖 Generated with Claude Code