Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: avoid blocking the embedding event loop

Codex1203141f6356
diff --git a/deeptutor/services/embedding/client.py b/deeptutor/services/embedding/client.py
index 836fc013d..eabf6eab4 100644
--- a/deeptutor/services/embedding/client.py
+++ b/deeptutor/services/embedding/client.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from contextlib import asynccontextmanager
import logging
from typing import Any, Dict, List, Optional
@@ -58,11 +59,18 @@ class EmbeddingClient:
return cls._spacing_lock
@staticmethod
- def _hold_spacing_lock():
- """Blocking acquire — cross-thread, loop-agnostic."""
+ @asynccontextmanager
+ async def _hold_spacing_lock():
+ """Acquire the cross-thread lock without blocking the current loop."""
+ import asyncio
+
lock = EmbeddingClient._global_spacing_lock()
- lock.acquire()
- return lock
+ while not lock.acquire(blocking=False):
+ await asyncio.sleep(0.05)
+ try:
+ yield
+ finally:
+ lock.release()
def __init__(self, config: Optional[EmbeddingConfig] = None):
self.config = config or get_embedding_config()
@@ -140,22 +148,16 @@ class EmbeddingClient:
try:
# 全局发帖节流:线程级锁串行化"等待间隔+发帖",跨线程/跨
# event loop 互斥(asyncio 锁在新 loop 模型下失效的教训)。
- # asyncio.sleep 换成阻塞等待发帖侧可接受:DT 的 embedding
- # 并发都在后台线程里,阻塞不伤 API 主线程。
- import time as _time
+ # 非阻塞轮询避免同一 loop 内的并发调用在 acquire() 上互锁。
from time import monotonic as _mono
- _lock = EmbeddingClient._hold_spacing_lock()
- try:
- delay = self.config.batch_delay
- if delay > 0:
+ async with EmbeddingClient._hold_spacing_lock():
+ if batch_delay > 0:
elapsed = _mono() - EmbeddingClient._last_request_monotonic
- if elapsed < delay:
- _time.sleep(delay - elapsed)
+ if elapsed < batch_delay:
+ await asyncio.sleep(batch_delay - elapsed)
EmbeddingClient._last_request_monotonic = _mono()
response = await self.adapter.embed(request)
- finally:
- _lock.release()
except Exception as exc:
# Capture batch context so the task log stream / KB diagnostics
# show actionable info instead of a bare exception string.
diff --git a/tests/services/embedding/test_client_runtime.py b/tests/services/embedding/test_client_runtime.py
index 6c0f03a56..fc45e5924 100644
--- a/tests/services/embedding/test_client_runtime.py
+++ b/tests/services/embedding/test_client_runtime.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import asyncio
+import threading
from typing import Any
import pytest
@@ -75,6 +77,66 @@ async def test_embedding_client_batches_requests(monkeypatch) -> None:
assert adapter.config["dimensions"] == 8
+async def test_embedding_client_serializes_concurrent_calls_without_blocking_loop(
+ monkeypatch,
+) -> None:
+ class _NonBlockingOnlyLock:
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+
+ def acquire(self, blocking: bool = True) -> bool:
+ if blocking:
+ raise AssertionError("embedding spacing lock must not block the event loop")
+ return self._lock.acquire(blocking=False)
+
+ def release(self) -> None:
+ self._lock.release()
+
+ class _ConcurrentAdapter(_FakeAdapter):
+ in_flight = 0
+ max_in_flight = 0
+
+ async def embed(self, request):
+ type(self).in_flight += 1
+ type(self).max_in_flight = max(type(self).max_in_flight, type(self).in_flight)
+ try:
+ await asyncio.sleep(0.02)
+ return await super().embed(request)
+ finally:
+ type(self).in_flight -= 1
+
+ _FakeAdapter.instances = []
+ monkeypatch.setattr(
+ "deeptutor.services.embedding.client._resolve_adapter_class",
+ lambda _b: _ConcurrentAdapter,
+ )
+ monkeypatch.setattr(EmbeddingClient, "_spacing_lock", _NonBlockingOnlyLock())
+ monkeypatch.setattr(EmbeddingClient, "_last_request_monotonic", 0.0)
+ _ConcurrentAdapter.in_flight = 0
+ _ConcurrentAdapter.max_in_flight = 0
+ client = EmbeddingClient(_build_config("openai"))
+
+ heartbeat = asyncio.Event()
+
+ async def mark_loop_responsive() -> None:
+ await asyncio.sleep(0)
+ heartbeat.set()
+
+ first, second, _ = await asyncio.wait_for(
+ asyncio.gather(
+ client.embed(["first"]),
+ client.embed(["second"]),
+ mark_loop_responsive(),
+ ),
+ timeout=1.0,
+ )
+
+ assert heartbeat.is_set()
+ assert len(first) == len(second) == 1
+ assert _ConcurrentAdapter.max_in_flight == 1
+
+
@pytest.mark.asyncio
async def test_embedding_client_forwards_input_type_to_every_batch(monkeypatch) -> None:
class _RoleAwareAdapter(_FakeAdapter):