Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(relevance): hand the embedding arena back after each run on macOS (#4567)

gglucass2363f8330920
diff --git a/headroom/relevance/embedding.py b/headroom/relevance/embedding.py
index 06b1cc5b9..b52b76152 100644
--- a/headroom/relevance/embedding.py
+++ b/headroom/relevance/embedding.py
@@ -27,6 +27,7 @@ from __future__ import annotations
import logging
import os
+import sys
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
@@ -43,6 +44,32 @@ from .base import RelevanceScore, RelevanceScorer
# proxy. 16 holds ~10x less and runs faster, with less padding per batch.
EMBED_BATCH_SIZE = 16
+
+def _shrink_arena_after_each_run(model: Any) -> None: # reaches into fastembed internals
+ """Have ORT hand its free CPU arena regions back after every run.
+
+ The batch cap bounds one run, but concurrent relevance splits share the
+ session and still stack its arena: ~2.2 GB retained after four parallel
+ 128-record splits in a macOS proxy, ~80 MB with arena shrinkage, same speed.
+ Only on macOS under ``MallocLargeCache=0``, which the proxy CLI's malloc
+ re-exec sets: with libmalloc's large cache on, the freed regions stay dirty
+ and shrinking re-grows the arena (~3.8 GB). Other platforms are unmeasured.
+ """
+ model._headroom_arena_shrink_checked = True
+ if sys.platform != "darwin" or os.environ.get("MallocLargeCache") != "0":
+ return
+ try:
+ import onnxruntime as ort
+
+ session = model.model.model # TextEmbedding -> OnnxTextEmbedding -> InferenceSession
+ options = ort.RunOptions()
+ options.add_run_config_entry("memory.enable_memory_arena_shrinkage", "cpu:0")
+ run = session.run
+ session.run = lambda names, feed, run_options=None: run(names, feed, run_options or options)
+ except Exception as exc: # noqa: BLE001 - memory only, the arena keeps its high-water mark
+ logger.debug("ORT arena shrinkage unavailable: %s", exc)
+
+
# numpy is an optional dependency - import lazily
_numpy = None
@@ -335,6 +362,8 @@ class EmbeddingScorer(RelevanceScorer):
"""
np = _get_numpy()
model = self._get_model()
+ if not getattr(model, "_headroom_arena_shrink_checked", False):
+ _shrink_arena_after_each_run(model)
embeddings = list(model.embed(texts, batch_size=EMBED_BATCH_SIZE))
return np.array(embeddings)
diff --git a/tests/test_relevance_extra.py b/tests/test_relevance_extra.py
index f6cae3b2a..aa33162a2 100644
--- a/tests/test_relevance_extra.py
+++ b/tests/test_relevance_extra.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import builtins
+import sys
from dataclasses import dataclass
from types import SimpleNamespace
@@ -140,6 +141,45 @@ def test_embedding_encode_caps_the_onnx_batch(monkeypatch) -> None:
assert calls == [{"batch_size": embedding.EMBED_BATCH_SIZE}]
+ ("platform", "large_cache", "shrinks"),
+ [("darwin", "0", True), ("darwin", None, False), ("linux", "0", False)],
+)
+def test_embedding_encode_shrinks_the_arena_only_without_the_large_cache(
+ monkeypatch, platform, large_cache, shrinks
+) -> None:
+ # Shrinking under libmalloc's large cache re-grows the arena, so the run
+ # options are passed only on macOS with MallocLargeCache=0 (the CLI re-exec).
+ pytest.importorskip("onnxruntime")
+ seen = []
+
+ class Session:
+ def run(self, names, feed, run_options=None):
+ seen.append(
+ run_options
+ and run_options.get_run_config_entry("memory.enable_memory_arena_shrinkage")
+ )
+
+ class FakeModel:
+ model = SimpleNamespace(model=Session())
+
+ def embed(self, texts, **kwargs):
+ self.model.model.run(["out"], {})
+ return [[1.0, 0.0] for _ in texts]
+
+ monkeypatch.setattr(sys, "platform", platform)
+ if large_cache is None:
+ monkeypatch.delenv("MallocLargeCache", raising=False)
+ else:
+ monkeypatch.setenv("MallocLargeCache", large_cache)
+ model = FakeModel()
+ scorer = EmbeddingScorer()
+ monkeypatch.setattr(scorer, "_get_model", lambda: model)
+ scorer._encode(["a"])
+ scorer._encode(["b"])
+ assert seen == (["cpu:0", "cpu:0"] if shrinks else [None, None])
+
+
def test_hybrid_constructor_alpha_variants_and_single_score_paths(monkeypatch) -> None:
bm25_result = RelevanceScore(score=0.1, reason="bm25", matched_terms=["term"])
emb_result = RelevanceScore(score=0.9, reason="emb", matched_terms=[])