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 | |
embed_query(text)
async
¶
Source code in src/noesis/core/embedder.py
45 | |
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 | |
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 | |
embed_query(text)
async
¶
Source code in src/noesis/core/embedder.py
86 87 88 | |
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 | |
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 | |
embed_query(text)
async
¶
Source code in src/noesis/core/embedder.py
261 262 263 264 265 266 267 | |
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 | |
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 | |
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.
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |