fix(8822): the embedding model runs one call at a time, on at most 8 threads

onnxruntime keeps a memory arena per run in flight and never returns it, so
overlapping requests grew the app a step at a time and it never came down:
measured in the live container, 32 concurrent callers reached 17.3 GB where
the same work one call at a time stayed flat at 1.07 GB. Every model call now
runs on a single worker thread, and the model loads with a thread pool capped
at 8 instead of one thread per host core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-06 10:50:23 -05:00
co-authored by Claude Opus 5.5
parent 9cfa07a884
commit 6052a66aca
2 changed files with 73 additions and 3 deletions
+48
View File
@@ -3,10 +3,14 @@
We don't actually load the fastembed model in tests (heavy download).
Instead, mock _get_model to return a fake that produces deterministic vectors.
"""
import asyncio
import threading
import time
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from grimoire.services import embeddings as emb
from grimoire.services.embeddings import (
_cosine_similarity, get_embedding,
)
@@ -74,6 +78,50 @@ async def test_get_embedding_propagates_model_load_failures():
await get_embedding("x")
# ─── one model call at a time ────────────────────────────────────────────────
class _OverlapCountingEmbedder:
"""Records how many embed() calls were inside the model at once."""
def __init__(self):
self._lock = threading.Lock()
self.inside = 0
self.most_at_once = 0
def embed(self, texts):
with self._lock:
self.inside += 1
self.most_at_once = max(self.most_at_once, self.inside)
time.sleep(0.02) # long enough that unserialised calls would overlap
with self._lock:
self.inside -= 1
return iter([MagicMock(tolist=MagicMock(return_value=[0.0]))] * len(texts))
@pytest.mark.asyncio
async def test_concurrent_callers_never_run_the_model_side_by_side():
"""The model's memory arena grows with every run in flight and is never
released, so callers that arrive together must queue for the model rather
than run in parallel."""
embedder = _OverlapCountingEmbedder()
with patch.object(emb, "_get_model", AsyncMock(return_value=embedder)):
out = await asyncio.gather(*(emb.get_embeddings([f"t{i}"]) for i in range(8)))
assert len(out) == 8
assert embedder.most_at_once == 1
@pytest.mark.asyncio
async def test_the_model_loads_with_a_capped_thread_pool():
"""Left to itself the model sizes its thread pool to every core of the
host; it is loaded with a small fixed cap instead."""
loaded = MagicMock()
with patch.object(emb, "_model", None), patch("fastembed.TextEmbedding", loaded):
await emb._get_model()
threads = loaded.call_args.kwargs.get("threads")
assert threads is not None and 1 <= threads <= 8
# ─── query_embedding_memo ────────────────────────────────────────────────────