Skip to content

Model boundaries

The only two modules allowed to load sentence_transformers models (ADR-33), plus device resolution.

noesis.core.embedder

Embedding boundary for the code indexer.

All embedding calls in this codebase go through the Embedder Protocol defined here (CLAUDE.md hard rule 1). Implementations are local-only — remote/hosted embedding was rejected (ADR-25) and the Protocol deliberately exposes no credentials or transport surface.

model_id is the versioning key (§3.4 rule 2): it is written to the Qdrant payload and SQLite projects.embedding_model, and changing implementations triggers a full re-embed. Nothing outside this boundary may know the vector size except by reading dim (§3.4 rule 1). Query-instruction quirks (e.g. CodeRankEmbed's query prefix) live inside implementations' embed_query (§3.4 rule 3) — callers never apply prefixes themselves.

logger = logging.getLogger(__name__) module-attribute

Embedder

Bases: Protocol

Async embedding interface. Local implementations only (ADR-25).

model_id property

dim property

embed_documents(texts) async

Source code in src/noesis/core/embedder.py
43
async def embed_documents(self, texts: list[str]) -> list[list[float]]: ...

embed_query(text) async

Source code in src/noesis/core/embedder.py
45
async def embed_query(self, text: str) -> list[float]: ...

FakeEmbedder(dim=8, model_id='fake-embedder-v1')

Deterministic in-memory Embedder for tests (M1 deliverable).

Vectors are derived from sha256 of the input text, so equal texts embed identically and the suite needs no model download. embed_query hashes a "query:"-prefixed variant of the text, mirroring the instruction- prefix seam of real implementations: a query embedding of some text is never equal to its document embedding, so tests can catch prefix misuse.

Source code in src/noesis/core/embedder.py
58
59
60
61
62
def __init__(self, dim: int = 8, model_id: str = "fake-embedder-v1") -> None:
    self._dim = dim
    self._model_id = model_id
    self.document_calls: list[list[str]] = []
    self.query_calls: list[str] = []

document_calls = [] instance-attribute

query_calls = [] instance-attribute

model_id property

dim property

embed_documents(texts) async

Source code in src/noesis/core/embedder.py
82
83
84
async def embed_documents(self, texts: list[str]) -> list[list[float]]:
    self.document_calls.append(list(texts))
    return [self._vector(t) for t in texts]

embed_query(text) async

Source code in src/noesis/core/embedder.py
86
87
88
async def embed_query(self, text: str) -> list[float]:
    self.query_calls.append(text)
    return self._vector(f"query:{text}")

LocalSTEmbedder(model_id='nomic-ai/CodeRankEmbed', dim=768, device=None, batch_size=32, _load_model=None)

Bases: _DeviceGenerationTracker

Default local Embedder: CodeRankEmbed via sentence-transformers (M2).

Concurrency model (§3.3): one dedicated single worker thread owns the model — forward passes are never concurrent. Jobs go through a queue.PriorityQueue of (priority, seq, job): HIGH for embed_query, LOW for embed_documents, so an interactive query preempts queued indexing batches. seq is a monotonic counter that keeps FIFO order within a priority class and keeps tuple comparison away from job objects.

The worker thread starts lazily on the first embed call (daemon, so never calling close() is safe) and the model loads inside the worker on its first job. sentence_transformers is imported lazily in the loader — never at module top level — so FakeEmbedder users don't pay the torch import; this module is the only place allowed to import it (CLAUDE.md hard rule 1).

CodeRankEmbed's query instruction prefix is applied inside embed_query only (§3.4 rule 3) — callers never see it.

Source code in src/noesis/core/embedder.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def __init__(
    self,
    model_id: str = "nomic-ai/CodeRankEmbed",
    dim: int = 768,
    device: str | None = None,
    batch_size: int = 32,
    _load_model: Callable[[], Any] | None = None,
) -> None:
    self._model_id = model_id
    self._dim = dim
    self._batch_size = batch_size
    self._load_model = _load_model or self._default_load
    self._queue: queue.PriorityQueue[
        tuple[
            int, int, tuple[Callable[[Any], Any], concurrent.futures.Future] | None
        ]
    ] = queue.PriorityQueue()
    self._seq = itertools.count()
    self._lock = threading.Lock()
    self._worker: threading.Thread | None = None
    self._closed = False
    # set_device/_generation/_load_target/_resolved_device (ADR-40, issue
    # #61): shared with reranker.py via model_worker._DeviceGenerationTracker.
    self._init_device_generation(device)

model_id property

dim property

resolved_device property

The device the model loaded on, or None before the first embed (the worker loads lazily on its first job).

embed_documents(texts) async

Source code in src/noesis/core/embedder.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
async def embed_documents(self, texts: list[str]) -> list[list[float]]:
    if not texts:
        return []
    texts = list(texts)
    batch_size = self._batch_size

    def job(model: Any) -> list[list[float]]:
        vectors: list[list[float]] = []
        for start in range(0, len(texts), batch_size):
            batch = texts[start : start + batch_size]
            vectors.extend(v.tolist() for v in model.encode(batch))
        return vectors

    return await asyncio.wrap_future(self._submit(_LOW, job))

embed_query(text) async

Source code in src/noesis/core/embedder.py
261
262
263
264
265
266
267
async def embed_query(self, text: str) -> list[float]:
    prefixed = self._QUERY_PREFIX + text

    def job(model: Any) -> list[float]:
        return model.encode([prefixed])[0].tolist()

    return await asyncio.wrap_future(self._submit(_HIGH, job))

preload() async

Load the model now instead of on the first real job (issue #47 finding 1 — mirrors reranker.preload, ADR-77). LOW priority: a real embed_query racing this at startup should preempt it in the queue, though in practice nothing else is queued yet — the worker processes one job at a time regardless of priority once it starts loading, so a racing query simply waits for whichever job triggered the load, with no added cost either way.

Source code in src/noesis/core/embedder.py
269
270
271
272
273
274
275
276
277
async def preload(self) -> None:
    """Load the model now instead of on the first real job (issue #47
    finding 1 — mirrors ``reranker.preload``, ADR-77). LOW priority: a
    real ``embed_query`` racing this at startup should preempt it in the
    queue, though in practice nothing else is queued yet — the worker
    processes one job at a time regardless of priority once it starts
    loading, so a racing query simply waits for whichever job triggered
    the load, with no added cost either way."""
    await asyncio.wrap_future(self._submit(_LOW, lambda model: None))

close()

Drain queued jobs, then stop the worker. Idempotent; optional — the worker is a daemon thread, so never closing is also safe.

Source code in src/noesis/core/embedder.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def close(self) -> None:
    """Drain queued jobs, then stop the worker. Idempotent; optional —
    the worker is a daemon thread, so never closing is also safe."""
    with self._lock:
        if self._closed:
            return
        self._closed = True
        worker = self._worker
        if worker is None:
            return
        self._queue.put((_SHUTDOWN, next(self._seq), None))
    worker.join(timeout=5.0)
    if worker.is_alive():
        logger.warning(
            "embedder worker did not stop within 5s; abandoning (daemon thread)"
        )

noesis.core.reranker

Reranking boundary for the code indexer (M4, §3.3).

All rerank calls go through the Reranker Protocol defined here — the second and last model-loading boundary next to core/embedder.py (CLAUDE.md hard rule 1, amended by ADR-33). Implementations are local-only (ADR-25): the Protocol exposes no credentials or transport surface, and this module is the only place besides the embedder allowed to import sentence_transformers.

Concurrency (§3.3, ADR-20): the cross-encoder runs on its own dedicated single worker thread, never the embedder's — a rerank of ~50 pairs takes materially longer than a query embed, and sharing one worker would let a rerank head-of-line-block the next query's embedding. Every rerank job is interactive (there is no indexing-path job class on this worker), so a plain FIFO queue implements the HIGH/LOW discipline vacuously.

rerank_score is response-only (§3.7): nothing here touches the Qdrant schema or SQLite state.

logger = logging.getLogger(__name__) module-attribute

Reranker

Bases: Protocol

Async reranking interface. Local implementations only (ADR-25).

rerank scores each candidate text against the query and returns one relevance score per text, same order as the input — reordering is the caller's job, so implementations stay a pure scoring function.

model_id property

rerank(query, texts) async

Source code in src/noesis/core/reranker.py
48
async def rerank(self, query: str, texts: list[str]) -> list[float]: ...

FakeReranker(model_id='fake-reranker-v1')

Deterministic in-memory Reranker for tests.

Scores are lexical-overlap: the fraction of the query's lowercased alphanumeric tokens that appear in the candidate text. Tests can steer the ordering by controlling token overlap, and equal texts always score equally. Records calls for assertion.

Source code in src/noesis/core/reranker.py
60
61
62
def __init__(self, model_id: str = "fake-reranker-v1") -> None:
    self._model_id = model_id
    self.calls: list[tuple[str, list[str]]] = []

calls = [] instance-attribute

model_id property

rerank(query, texts) async

Source code in src/noesis/core/reranker.py
84
85
86
87
88
89
90
91
async def rerank(self, query: str, texts: list[str]) -> list[float]:
    self.calls.append((query, list(texts)))
    query_tokens = self._tokens(query)
    if not query_tokens:
        return [0.0 for _ in texts]
    return [
        len(query_tokens & self._tokens(text)) / len(query_tokens) for text in texts
    ]

LocalCrossEncoderReranker(model_id='BAAI/bge-reranker-v2-m3', device=None, batch_size=16, _load_model=None)

Bases: _DeviceGenerationTracker

Default local Reranker: bge-reranker-v2-m3 via sentence-transformers.

One dedicated single worker thread owns the model — forward passes are never concurrent, and the thread is not the embedder's (ADR-20). The worker starts lazily on the first rerank call (daemon, so never calling close() is safe) and the ~568M model loads inside the worker on its first job — reranker.preload=true calls :meth:preload at startup instead. sentence_transformers is imported lazily in the loader, never at module top level.

Pairs longer than the model's max sequence length are truncated by the model; §3.3 says that should be rare (chunks target 300–800 tokens), so it is counted and logged per call rather than silently ignored.

Source code in src/noesis/core/reranker.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def __init__(
    self,
    model_id: str = "BAAI/bge-reranker-v2-m3",
    device: str | None = None,
    batch_size: int = 16,
    _load_model: Callable[[], Any] | None = None,
) -> None:
    self._model_id = model_id
    self._batch_size = batch_size
    self._load_model = _load_model or self._default_load
    self._queue: queue.Queue[
        tuple[int, tuple[Callable[[Any], Any], concurrent.futures.Future] | None]
    ] = queue.Queue()
    self._lock = threading.Lock()
    self._worker: threading.Thread | None = None
    self._closed = False
    # set_device/_generation/_load_target/_resolved_device (ADR-40, issue
    # #61): shared with embedder.py via model_worker._DeviceGenerationTracker.
    self._init_device_generation(device)

model_id property

resolved_device property

The device the model loaded on, or None before the first rerank (the worker loads lazily on its first job). Read by /healthz's reranker_ready and get_index_status (issue #52), so it means "the model is loaded", not "a device was chosen" — it is assigned only after the CrossEncoder constructor returns.

rerank(query, texts) async

Source code in src/noesis/core/reranker.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
async def rerank(self, query: str, texts: list[str]) -> list[float]:
    if not texts:
        return []
    texts = list(texts)
    batch_size = self._batch_size

    def job(model: Any) -> list[float]:
        truncated = self._count_truncated(model, query, texts)
        if truncated:
            logger.warning(
                "reranker truncated %d/%d pairs to the model max length",
                truncated,
                len(texts),
            )
        pairs = [(query, text) for text in texts]
        scores = model.predict(pairs, batch_size=batch_size)
        return [float(s) for s in scores]

    return await asyncio.wrap_future(self._submit(job))

preload() async

Load the model now (reranker.preload=true) instead of on the first reranked request — a no-op job forces the lazy load.

Source code in src/noesis/core/reranker.py
270
271
272
273
async def preload(self) -> None:
    """Load the model now (``reranker.preload=true``) instead of on the
    first reranked request — a no-op job forces the lazy load."""
    await asyncio.wrap_future(self._submit(lambda model: None))

close()

Drain queued jobs, then stop the worker. Idempotent; optional — the worker is a daemon thread, so never closing is also safe.

Source code in src/noesis/core/reranker.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def close(self) -> None:
    """Drain queued jobs, then stop the worker. Idempotent; optional —
    the worker is a daemon thread, so never closing is also safe."""
    with self._lock:
        if self._closed:
            return
        self._closed = True
        worker = self._worker
        if worker is None:
            return
        self._queue.put((_SHUTDOWN, None))
    worker.join(timeout=5.0)
    if worker.is_alive():
        logger.warning(
            "reranker worker did not stop within 5s; abandoning (daemon thread)"
        )

noesis.core.compute

Compute-device resolution for the model-loading boundaries (M4 follow-up).

Both local model runners (LocalSTEmbedder, LocalCrossEncoderReranker) resolve their device through :func:resolve_device instead of relying on sentence-transformers' implicit device=None auto-detect — that auto-detect was observed returning CPU on a CUDA-available box, silently running the cross-encoder on CPU and producing an uninterpretable latency benchmark (lesson 4). Resolving explicitly and logging the result makes device a recorded, reproducible property of every run.

torch is imported lazily inside the function so importing core (e.g. for the FakeEmbedder test suite) never pays the heavy torch import.

logger = logging.getLogger(__name__) module-attribute

resolve_device(configured=None)

Return the compute device string to hand a model.

A non-empty configured value (from [embedder]/[reranker] device in config.toml) wins verbatim — the operator's explicit choice is never second-guessed. Otherwise auto-detect in preference order cuda → mps → cpu. The result is logged so a latency benchmark always records the hardware it ran on.

Source code in src/noesis/core/compute.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def resolve_device(configured: str | None = None) -> str:
    """Return the compute device string to hand a model.

    A non-empty ``configured`` value (from ``[embedder]``/``[reranker]``
    ``device`` in config.toml) wins verbatim — the operator's explicit choice
    is never second-guessed. Otherwise auto-detect in preference order
    cuda → mps → cpu. The result is logged so a latency benchmark always
    records the hardware it ran on.
    """
    if configured:
        logger.info("compute device: %s (configured)", configured)
        return configured
    import torch

    try:
        # A torch build without the mps backend raises AttributeError on the
        # probe; treat that as "mps not available" so device=None falls
        # through to cpu instead of crashing every model load (matches
        # available_devices, PR #10 review).
        mps_available = torch.backends.mps.is_available()
    except Exception:  # noqa: BLE001 — availability probe must not raise
        mps_available = False

    if torch.cuda.is_available():
        device = "cuda"
    elif mps_available:
        device = "mps"
    else:
        device = "cpu"
    logger.info("compute device: %s (auto-detected)", device)
    return device

available_devices() cached

Devices a model could be placed on right now, best first — the dashboard's GPU-availability surface (ADR-40). Cached: availability does not change within a process, and the torch import is heavy. Returns ("cpu",) when torch is not importable so a broken torch install degrades the UI, never the request handling around it.

Source code in src/noesis/core/compute.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
@functools.cache
def available_devices() -> tuple[str, ...]:
    """Devices a model could be placed on right now, best first — the
    dashboard's GPU-availability surface (ADR-40). Cached: availability
    does not change within a process, and the torch import is heavy.
    Returns ("cpu",) when torch is not importable so a broken torch
    install degrades the UI, never the request handling around it."""
    devices: list[str] = []
    try:
        import torch

        # The probes stay inside the try too: a torch build without the
        # mps backend raises AttributeError, and "must not raise" has to
        # cover that, not just a failed import (PR #10 review).
        if torch.cuda.is_available():
            devices.append("cuda")
        if torch.backends.mps.is_available():
            devices.append("mps")
    except Exception:  # noqa: BLE001 — availability probe must not raise
        pass
    devices.append("cpu")
    return tuple(devices)