grimoire_app's memory stops climbing: one embedding call at a time, and a streamed backup #244

Merged
bvandeusen merged 2 commits from dev into main 2026-12-06 11:19:54 -05:00
2 changed files with 73 additions and 3 deletions
Showing only changes of commit 6052a66aca - Show all commits
+25 -3
View File
@@ -16,6 +16,7 @@ import math
import os
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from contextvars import ContextVar
@@ -60,6 +61,23 @@ _CACHE_DIR = os.environ.get("FASTEMBED_CACHE_DIR", "/data/fastembed-cache")
_model = None # lazy singleton; first call downloads model files
_model_lock = asyncio.Lock()
# ONE MODEL CALL AT A TIME, ON A FEW THREADS.
#
# onnxruntime keeps a memory arena for each run in flight and never hands it
# back to the system, so the process keeps the memory of its busiest moment.
# With calls running side by side, every burst of overlapping requests grows
# the arena a step: 32 concurrent callers took a process past 17 GB, where
# the same work done one call at a time stays at about 1 GB. Every model call
# therefore runs on this single worker thread, and the others queue for it.
#
# Queuing costs little: each call already spreads across `_MODEL_THREADS`
# cores, so calls run side by side only competed for the same CPUs. The cap
# keeps the model from sizing its thread pool to every core of a large shared
# host; a query embeds in milliseconds on a few cores, and more threads than
# this only add hand-off overhead.
_MODEL_THREADS = min(8, len(os.sched_getaffinity(0)))
_model_worker = ThreadPoolExecutor(max_workers=1, thread_name_prefix="embed")
async def _get_model():
"""Return the singleton fastembed.TextEmbedding instance, loading on first call."""
@@ -74,6 +92,7 @@ async def _get_model():
TextEmbedding,
model_name=_MODEL_NAME,
cache_dir=_CACHE_DIR,
threads=_MODEL_THREADS,
)
logger.info("Loaded fastembed model %s (cache: %s)", _MODEL_NAME, _CACHE_DIR)
return _model
@@ -150,9 +169,12 @@ async def get_embeddings(texts: list[str]) -> list[list[float]]:
calls. Raises like get_embedding; callers catch and degrade.
"""
embedder = await _get_model()
# embed() is synchronous CPU work; offload so we don't block the event loop.
vecs = await asyncio.to_thread(lambda: list(embedder.embed(texts)))
return [v.tolist() for v in vecs]
# embed() is synchronous CPU work: it runs off the event loop, on the one
# model worker, so calls never overlap (see `_model_worker`).
vecs = await asyncio.get_running_loop().run_in_executor(
_model_worker, lambda: [v.tolist() for v in embedder.embed(texts)],
)
return vecs
def _cosine_similarity(a: list[float], b: list[float]) -> float:
+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 ────────────────────────────────────────────────────