Skip to content

Retrieval modules

Hybrid dense + sparse retrieval over Qdrant, and live-filesystem structural search.

noesis.core.retriever

Retrieval pipeline — hybrid dense + BM25 with RRF fusion (M3), optional cross-encoder rerank (M4) per §3.3 and Overview §6.

Query embedding goes through the Embedder Protocol at HIGH priority so searches preempt any running index batch; the sparse channel needs only the raw query text (BM25 TF is encoded inside the vector store's client, IDF server-side). channel selects hybrid (default), dense-only, or sparse-only — the single-channel modes exist because the M3 eval gate measures hybrid against them.

Reranking (§3.3 contract): when a reranker is wired and the request wants it, the store returns the top candidates (~50) fused results with their stored chunk text, the reranker scores (query, chunk_text) pairs on its own worker thread, and the reordered top_k carry rerank_score. The rerank flag defaults to reranker availability (config reranker.enabled); rerank=true without a wired reranker is not an error — the response just states reranking was not applied. Results are candidates, not ground truth — callers read the live file before acting.

logger = logging.getLogger(__name__) module-attribute

search_code(store, embedder, query, project_id, *, top_k=10, language=None, channel='hybrid', reranker=None, rerank=None, candidates=50, gate) async

Search one project's chunks; returns {"hits": [...], "reranked": bool} so adapters state whether reranking was applied (§3.3) without re-deriving the decision. Skips the query embed entirely for sparse-only searches — no reason to queue on the embed worker for a channel that won't use the vector.

Source code in src/noesis/core/retriever.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
async def search_code(
    store: VectorStore,
    embedder: Embedder,
    query: str,
    project_id: str,
    *,
    top_k: int = 10,
    language: str | None = None,
    channel: SearchChannel = "hybrid",
    reranker: Reranker | None = None,
    rerank: bool | None = None,
    candidates: int = 50,
    gate: SearchGate | None,
) -> dict[str, Any]:
    """Search one project's chunks; returns ``{"hits": [...], "reranked":
    bool}`` so adapters state whether reranking was applied (§3.3) without
    re-deriving the decision. Skips the query embed entirely for sparse-only
    searches — no reason to queue on the embed worker for a channel that
    won't use the vector."""
    t0 = time.perf_counter()
    dense_vector = await embedder.embed_query(query) if channel != "sparse" else None
    t_embed = time.perf_counter()
    apply_rerank = (
        rerank if rerank is not None else reranker is not None
    ) and reranker is not None
    pool = max(top_k, candidates) if apply_rerank else top_k
    # Per-channel prefetch stays `candidates` deep even when no reranker
    # runs: RRF recall depends on each channel's candidate depth, not on how
    # many fused results the caller keeps. With prefetch collapsed to top_k,
    # a hit ranked just outside one channel's top_k loses that channel's
    # RRF contribution entirely and can drop out of the fused top_k.
    prefetch = max(top_k, candidates)
    run_search = functools.partial(
        store.search,
        project_id,
        dense_vector=dense_vector,
        query_text=query,
        top_k=pool,
        language=language,
        channel=channel,
        prefetch_limit=prefetch,
        with_text=apply_rerank,
    )
    # The gate is the real path: it runs this on the bounded search executor
    # whose slots are paired 1:1 with the store's query connections, and
    # raises SearchOverloaded rather than letting a backlog grow without
    # limit (ADR-84).
    #
    # ``gate`` is keyword-only with NO default, deliberately (PR #50 round-7
    # review). It used to default to None, and a reviewer mutation-tested
    # that: deleting ``gate=ctx.search_gate`` from both adapters left the
    # entire default suite green while every bound this PR adds silently
    # ceased to exist. A missing argument is now a TypeError at the call
    # site. Passing None explicitly is still allowed and still falls back to
    # the default executor — that is for direct unit-test calls where
    # boundedness is not what is under test — but it has to be said out
    # loud, which is the whole point. ``test_adapters_pass_a_real_gate``
    # covers the remaining hole, someone silently changing it to None.
    hits = await (
        gate.run(run_search) if gate is not None else asyncio.to_thread(run_search)
    )
    t_search = time.perf_counter()
    if apply_rerank and hits:
        scores = await reranker.rerank(query, [hit["text"] for hit in hits])
        # Stable sort: fusion order breaks rerank-score ties. A non-finite
        # score (NaN from fp16 overflow / degenerate text, or ±inf from any
        # Reranker implementation) sorts as -inf: any non-finite value in the
        # key breaks the total order and silently permutes the whole ranking
        # — guarded here so it covers every Reranker implementation.
        # Non-finite scores are also nulled in the payload below: JSONResponse
        # serializes with allow_nan=False and would 500 the response.
        order = sorted(
            range(len(hits)),
            key=lambda i: -math.inf if not math.isfinite(scores[i]) else scores[i],
            reverse=True,
        )
        hits = [
            hits[i]
            | {"rerank_score": (None if not math.isfinite(scores[i]) else scores[i])}
            for i in order[:top_k]
        ]
    # Per-query stage timing at DEBUG (INFO stays clean; telemetry.py remains
    # the metadata source of truth). No query text or hit content — counts,
    # channel, and durations only (ADR-25).
    logger.debug(
        "search: project=%s channel=%s hits=%d reranked=%s "
        "embed=%.3fs search=%.3fs rerank=%.3fs",
        project_id,
        channel,
        len(hits),
        apply_rerank,
        t_embed - t0,
        t_search - t_embed,
        time.perf_counter() - t_search,
    )
    for hit in hits:
        hit.pop("text", None)
    return {"hits": hits, "reranked": apply_rerank}

noesis.core.vectorstore

Qdrant vector store — hybrid dense + BM25-sparse collection wrapper (M3).

Thin wrapper over qdrant_client.QdrantClient implementing the approved Overview §7 Qdrant point and the expanded doc's Embedder-boundary rules: the dense VectorParams(size=...) is read from embedder.dim at collection-creation time, never hardcoded (§3.4 rule 1), and embedding_model is written to every payload as the versioning key (§3.4 rule 2). Payload keyword indexes on project_id and language are created right after the collection so they exist before any bulk load (§3.6).

The sparse channel is BM25 with server-side IDF (Modifier.IDF, §3.6). The TF half is computed client-side by qdrant-client's fastembed integration via models.Document(model="Qdrant/bm25") — verified against qdrant-client 1.18: there is no server-side text inference on a local deployment, so fastembed is a runtime dependency (ADR-32; the expanded doc's "fastembed deliberately absent" note predates this check). Fusion is server-side RRF via query_points prefetch (§3.3); the RRF constant is fixed by the server and not exposed by FusionQuery, so the doc's k=60 default is aspirational, not configured (ADR-32).

Point ids are deterministic UUIDv5s of project_id:file_path:start_line:file_hash (Overview §6 step "Upsert"), so re-indexing an unchanged file rewrites the same points — idempotent.

Still deliberately absent: no server-side path_prefix filter — Qdrant's MatchText needs a full-text payload index (a keyword index won't serve it on a real server, even though local :memory: mode happens to accept it), so path filtering lands with the M5 filter work rather than shipping a filter that only works in tests.

The Qdrant client talks only to localhost or :memory: — no code or metadata leaves the machine (ADR-25). The caller constructs the client and decides which.

CHUNK_NAMESPACE = uuid.UUID('6a3d61a6-97a1-4a3a-9f6b-2e5a8f0c4d17') module-attribute

DENSE_VECTOR_NAME = 'dense' module-attribute

SPARSE_VECTOR_NAME = 'bm25' module-attribute

BM25_MODEL_ID = 'Qdrant/bm25' module-attribute

SearchChannel = Literal['hybrid', 'dense', 'sparse'] module-attribute

VectorStore(client, collection_name='noesis_chunks', index_client=None, query_clients=None)

Dense-only Qdrant collection wrapper. One shared collection, project_id payload filter at query time (Overview §6).

The hazard this class exists to contain (ADR-83, issue #48). qdrant-client keeps its client-side inference bookkeeping — a _batch_accumulator dict and an _embed_storage FIFO — on the QdrantClient object, unsynchronized and keyed only by model name. Any two threads that build a models.Document on one client can receive each other's embeddings. Worse, the drain step recomputes only when the FIFO is empty and otherwise pop(0)s, so a single race that leaves one residual entry offsets that client permanently: every later query silently returns another query's results, with no exception, until the process restarts. Reproduced 5/5 through this class's own methods, and measured at up to 15,864 wrong results in 16,000 queries against a live server. Independent of transport — REST and gRPC latch at the same rate — and unfixed upstream as of qdrant-client 1.19.

Which methods are exposed. Only upsert_chunks (write) and search's sparse and hybrid channels (read) build a models.Document. Dense-only search and every other method here (deletes, counts, scroll, retrieve, collection setup) touch no inference state at all — verified by instrumenting ModelEmbedder._accumulate and _drain_accumulator: zero calls for a dense query, one each for sparse and hybrid. Those paths are deliberately left unpooled and unlocked on client, because there is nothing there to protect.

How it is contained, in two layers.

query_clients is the primary mechanism: a pool of connections, one checked out for the duration of each sparse/hybrid query, so no two threads ever meet on one client's inference state. Structural, not defensive — there is no shared object left to corrupt. Sized by [qdrant] query_connections and paired 1:1 with the search executor's slots (ADR-84), so a checkout finds a free connection whenever a thread is free. Checkout blocks when all are busy: that is the correct back-pressure primitive at this layer, and admission control — a bounded queue that rejects rather than queues without limit — belongs one layer up in the executor.

_locks is the correctness floor, one lock per distinct client object. It matters because query_clients cannot always be a pool: two QdrantClient(":memory:") instances are two different databases, not two connections to one, so the ~25 in-memory tests and any embedded caller necessarily share a single client. Keying the locks to the object rather than to the role is what makes that configuration correct: when client, index_client and the pool are all the same object, every path takes the same mutex. Keying by role instead would have search and upsert holding two different locks over one ModelEmbedder — issue #48's original race, reopened. In the production wiring the objects are distinct, so each lock is uncontended and costs an atomic.

index_client stays separate from the pool so an index run never consumes a query connection, and its lock also guards it against itself: jobs.launch_index_run's guard (state.try_start_run) is per project_id, so two different projects can reach upsert_chunks at once (routine under opt-in auto_reindex on 2+ projects). max_concurrent_index_runs (ADR-85) bounds how many such runs exist at all, but that cap is machine-wide and this lock is what makes the overlap safe within a process.

Source code in src/noesis/core/vectorstore.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def __init__(
    self,
    client: QdrantClient,
    collection_name: str = "noesis_chunks",
    index_client: QdrantClient | None = None,
    query_clients: Sequence[QdrantClient] | None = None,
) -> None:
    self._client = client
    self._index_client = index_client if index_client is not None else client
    self._collection = collection_name
    # Falling back to ``[client]`` keeps the single-connection shape every
    # existing caller has: correct (the shared lock below serializes it),
    # just not concurrent. Only ``runtime.py`` passes a real pool.
    self._query_clients: tuple[QdrantClient, ...] = tuple(
        query_clients if query_clients else (client,)
    )
    self._query_pool: queue.Queue[QdrantClient] = queue.Queue()
    for qc in self._query_clients:
        self._query_pool.put(qc)
    # One lock per distinct client OBJECT, not per role — see the class
    # docstring. Built once here from the complete, fixed set of clients,
    # and every one of them is retained for this object's lifetime, so
    # keying on ``id()`` cannot collide with a recycled address.
    self._locks: dict[int, threading.Lock] = {}
    for c in (self._client, self._index_client, *self._query_clients):
        self._locks.setdefault(id(c), threading.Lock())

collection_name property

close()

Close every distinct connection this store holds (issue #48 teardown gap: the client was never closed at all before ADR-76).

De-duplicated by object identity, so the single-client default closes exactly once however many roles that one object fills. Each close is attempted even if an earlier one raised — one failure must never leak the remaining connections (PR #50 review finding 3, generalized from two connections to the pool) — and the first exception is re-raised once all of them have been tried, which is the contract the two-connection version already had.

Source code in src/noesis/core/vectorstore.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def close(self) -> None:
    """Close every distinct connection this store holds (issue #48
    teardown gap: the client was never closed at all before ADR-76).

    De-duplicated by object identity, so the single-client default
    closes exactly once however many roles that one object fills. Each
    close is attempted even if an earlier one raised — one failure must
    never leak the remaining connections (PR #50 review finding 3,
    generalized from two connections to the pool) — and the first
    exception is re-raised once all of them have been tried, which is
    the contract the two-connection version already had."""
    seen: set[int] = set()
    first: BaseException | None = None
    for client in (self._client, self._index_client, *self._query_clients):
        if id(client) in seen:
            continue
        seen.add(id(client))
        try:
            client.close()
        except BaseException as exc:  # noqa: BLE001 — re-raised below
            if first is None:
                first = exc
    if first is not None:
        raise first

ensure_collection(embedder)

Create the collection if missing, sized from embedder.dim (§3.4 rule 1). Raises ValueError if it exists with a different dense size — the system refuses to serve mixed-model results (§3.4 rule 2) — or without the BM25 sparse vector (an M2-era collection): points written before M3 carry no sparse vector, so silently adding the config would leave the lexical channel empty for every existing chunk. The fix is the same as a model change: drop the collection and state, re-index fully.

Returns True iff this call actually created the collection. The caller uses that to detect the wipe signature — a missing collection while the state DB still tracks indexed files.

Source code in src/noesis/core/vectorstore.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def ensure_collection(self, embedder: Any) -> bool:
    """Create the collection if missing, sized from ``embedder.dim``
    (§3.4 rule 1). Raises ValueError if it exists with a different
    dense size — the system refuses to serve mixed-model results
    (§3.4 rule 2) — or without the BM25 sparse vector (an M2-era
    collection): points written before M3 carry no sparse vector, so
    silently adding the config would leave the lexical channel empty
    for every existing chunk. The fix is the same as a model change:
    drop the collection and state, re-index fully.

    Returns ``True`` iff this call actually created the collection.
    The caller uses that to detect the wipe signature — a missing
    collection while the state DB still tracks indexed files."""
    if self._client.collection_exists(self._collection):
        info = self._client.get_collection(self._collection)
        vectors = info.config.params.vectors
        existing = (
            vectors.get(DENSE_VECTOR_NAME) if isinstance(vectors, dict) else None
        )
        if existing is None or existing.size != embedder.dim:
            found = "absent" if existing is None else f"size {existing.size}"
            raise ValueError(
                f"collection {self._collection!r} has dense vector {found}, "
                f"but embedder {embedder.model_id!r} produces dim "
                f"{embedder.dim}; refusing mixed-model state. A model "
                f"change requires a full re-embed into a fresh collection."
            )
        sparse = info.config.params.sparse_vectors or {}
        if SPARSE_VECTOR_NAME not in sparse:
            raise ValueError(
                f"collection {self._collection!r} predates the M3 sparse "
                f"channel (no {SPARSE_VECTOR_NAME!r} sparse vector). Its "
                f"points have no BM25 vectors, so hybrid search would "
                f"silently lose the lexical channel. Delete the collection "
                f"and the project file state, then re-index."
            )
        return False
    try:
        self._client.create_collection(
            collection_name=self._collection,
            vectors_config={
                DENSE_VECTOR_NAME: models.VectorParams(
                    size=embedder.dim, distance=models.Distance.COSINE
                )
            },
            sparse_vectors_config={
                SPARSE_VECTOR_NAME: models.SparseVectorParams(
                    modifier=models.Modifier.IDF
                )
            },
        )
    except (UnexpectedResponse, ValueError):
        # Lost a first-startup race: the co-process (HTTP + stdio MCP
        # starting together against an empty Qdrant) created the
        # collection between our exists-check and this create. Not an
        # error — re-enter to run the same shape verification the
        # exists branch applies; the winner also creates the indexes.
        if not self._client.collection_exists(self._collection):
            raise
        # The race winner created the collection (and its indexes); this
        # process did not, so report False like the exists branch.
        self.ensure_collection(embedder)
        return False
    # Keyword indexes must exist before the first bulk load (§3.6).
    for field in ("project_id", "language"):
        self._client.create_payload_index(
            collection_name=self._collection,
            field_name=field,
            field_schema=models.PayloadSchemaType.KEYWORD,
        )
    return True

upsert_chunks(project_id, chunks, vectors, embedding_model)

Write chunks with the Overview §7 payload. text is stored so search snippets and the M4 reranker can read chunk content without re-opening files.

Source code in src/noesis/core/vectorstore.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def upsert_chunks(
    self,
    project_id: str,
    chunks: list[_ChunkLike],
    vectors: list[list[float]],
    embedding_model: str,
) -> None:
    """Write chunks with the Overview §7 payload. ``text`` is stored so
    ``search`` snippets and the M4 reranker can read chunk content
    without re-opening files."""
    if len(chunks) != len(vectors):
        raise ValueError(f"got {len(chunks)} chunks but {len(vectors)} vectors")
    if not chunks:
        return
    points = [
        models.PointStruct(
            id=chunk_point_id(
                project_id, chunk.file_path, chunk.start_line, chunk.file_hash
            ),
            vector={
                DENSE_VECTOR_NAME: vector,
                # TF encoding runs client-side (fastembed) inside the
                # qdrant-client; IDF weighting is applied server-side
                # via Modifier.IDF. Nothing leaves the machine.
                SPARSE_VECTOR_NAME: models.Document(
                    text=chunk.text, model=BM25_MODEL_ID
                ),
            },
            payload={
                "project_id": project_id,
                "file_path": chunk.file_path,
                "start_line": chunk.start_line,
                "end_line": chunk.end_line,
                "language": chunk.language,
                "node_type": chunk.node_type,
                "symbol_name": chunk.symbol_name,
                "file_hash": chunk.file_hash,
                "embedding_model": embedding_model,
                "text": chunk.text,
            },
        )
        for chunk, vector in zip(chunks, vectors)
    ]
    # index_client, never a pooled query connection (ADR-83): this is
    # the only write-path call that builds a models.Document, so it must
    # not share inference state with a concurrent search, and keeping it
    # off the pool means an index run can never consume a query slot.
    # Its lock guards it against ITSELF too — two different projects'
    # runs can reach here at once, since the launch guard is per
    # project_id — and, in the single-client configuration, it is the
    # very same lock the query path takes, which is what keeps that
    # configuration correct.
    with self._lock_for(self._index_client):
        self._index_client.upsert(
            collection_name=self._collection, points=points, wait=True
        )

delete_file_chunks(project_id, file_paths, *, exclude_file_hash=None)

Delete every point for the given files within one project.

exclude_file_hash spares points carrying that hash — the indexer upserts a file's new chunks first, then prunes the old ones, so a failure never leaves a file with zero searchable chunks.

Source code in src/noesis/core/vectorstore.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def delete_file_chunks(
    self,
    project_id: str,
    file_paths: Iterable[str],
    *,
    exclude_file_hash: str | None = None,
) -> None:
    """Delete every point for the given files within one project.

    ``exclude_file_hash`` spares points carrying that hash — the indexer
    upserts a file's new chunks first, then prunes the old ones, so a
    failure never leaves a file with zero searchable chunks."""
    paths = list(file_paths)
    if not paths:
        return
    query_filter = models.Filter(
        must=[
            models.FieldCondition(
                key="project_id",
                match=models.MatchValue(value=project_id),
            ),
            models.FieldCondition(
                key="file_path", match=models.MatchAny(any=paths)
            ),
        ],
        must_not=(
            [
                models.FieldCondition(
                    key="file_hash",
                    match=models.MatchValue(value=exclude_file_hash),
                )
            ]
            if exclude_file_hash is not None
            else None
        ),
    )
    self._client.delete(
        collection_name=self._collection,
        points_selector=models.FilterSelector(filter=query_filter),
        wait=True,
    )

delete_project_points(project_id)

Delete every point belonging to a project (ADR-43 project deletion). Filter-only — never touches other projects' points.

Source code in src/noesis/core/vectorstore.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
def delete_project_points(self, project_id: str) -> None:
    """Delete every point belonging to a project (ADR-43 project
    deletion). Filter-only — never touches other projects' points."""
    self._client.delete(
        collection_name=self._collection,
        points_selector=models.FilterSelector(
            filter=models.Filter(
                must=[
                    models.FieldCondition(
                        key="project_id",
                        match=models.MatchValue(value=project_id),
                    )
                ]
            )
        ),
        wait=True,
    )

count_project_points(project_id)

Exact number of points stored for one project.

Drift gate for the indexer: compared against the state DB's expected chunk total to detect a vector store that lost data (an externally dropped/recreated collection) while state still reports files as indexed. Same filtered count(exact=True) path as delete_orphan_points.

Source code in src/noesis/core/vectorstore.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
def count_project_points(self, project_id: str) -> int:
    """Exact number of points stored for one project.

    Drift gate for the indexer: compared against the state DB's expected
    chunk total to detect a vector store that lost data (an externally
    dropped/recreated collection) while state still reports files as
    indexed. Same filtered ``count(exact=True)`` path as
    delete_orphan_points."""
    return self._client.count(
        collection_name=self._collection,
        count_filter=models.Filter(
            must=[
                models.FieldCondition(
                    key="project_id",
                    match=models.MatchValue(value=project_id),
                )
            ]
        ),
        exact=True,
    ).count

per_file_point_counts(project_id)

Point count per file_path for one project, via payload-only scroll.

Only called after count_project_points has already detected drift, so the full-project scroll is paid for only on genuine divergence. file_path has no payload index, so this scans rather than filters on it — acceptable at recovery time, not per query.

Source code in src/noesis/core/vectorstore.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
def per_file_point_counts(self, project_id: str) -> dict[str, int]:
    """Point count per ``file_path`` for one project, via payload-only
    scroll.

    Only called after count_project_points has already detected drift,
    so the full-project scroll is paid for only on genuine divergence.
    ``file_path`` has no payload index, so this scans rather than
    filters on it — acceptable at recovery time, not per query."""
    counts: Counter[str] = Counter()
    offset = None
    while True:
        points, offset = self._client.scroll(
            collection_name=self._collection,
            scroll_filter=models.Filter(
                must=[
                    models.FieldCondition(
                        key="project_id",
                        match=models.MatchValue(value=project_id),
                    )
                ]
            ),
            with_payload=["file_path"],
            with_vectors=False,
            limit=1000,
            offset=offset,
        )
        for point in points:
            path = (point.payload or {}).get("file_path")
            if path is not None:
                counts[str(path)] += 1
        if offset is None:
            break
    return dict(counts)

delete_orphan_points(live_project_ids)

Delete points whose project_id is not in live_project_ids, and return how many went. Startup-only crash recovery for the collection — the Qdrant-side counterpart of state.fail_orphaned_runs, and the catch-all for orphans no wipe could have prevented: a process killed mid-run, a delete that raced an in-flight write, a run whose upsert outlived the event loop.

REFUSES to sweep when live_project_ids is empty. An empty project table cannot be told apart from a state DB that resolved to the wrong path — the exact misconfiguration the 2026-07-11 hunt found (a cwd-relative db_path silently opening a fresh, empty DB) — and this operation is destructive: on the wrong DB, "no live projects" would read as "delete the entire collection". A sweep skipped here costs a few dead points until a project exists; a sweep run there costs the whole index. Safe under the dual-transport deployment: a project row is committed before its first point is ever written, so a project another process is mid-indexing is never mistaken for an orphan.

Source code in src/noesis/core/vectorstore.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def delete_orphan_points(self, live_project_ids: Iterable[str]) -> int:
    """Delete points whose project_id is not in *live_project_ids*, and
    return how many went. Startup-only crash recovery for the collection —
    the Qdrant-side counterpart of state.fail_orphaned_runs, and the
    catch-all for orphans no wipe could have prevented: a process killed
    mid-run, a delete that raced an in-flight write, a run whose upsert
    outlived the event loop.

    REFUSES to sweep when *live_project_ids* is empty. An empty project
    table cannot be told apart from a state DB that resolved to the wrong
    path — the exact misconfiguration the 2026-07-11 hunt found (a
    cwd-relative db_path silently opening a fresh, empty DB) — and this
    operation is destructive: on the wrong DB, "no live projects" would
    read as "delete the entire collection". A sweep skipped here costs a
    few dead points until a project exists; a sweep run there costs the
    whole index. Safe under the dual-transport deployment: a project row
    is committed before its first point is ever written, so a project
    another process is mid-indexing is never mistaken for an orphan.
    """
    live = list(live_project_ids)
    if not live:
        return 0
    # must_not(project_id in live) — the complement of the live set, so a
    # project registered but never indexed simply matches nothing.
    orphans = models.Filter(
        must_not=[
            models.FieldCondition(
                key="project_id", match=models.MatchAny(any=live)
            )
        ]
    )
    # Counted before the delete: Qdrant's delete result carries no count,
    # and a silent destructive startup step is exactly what an operator
    # needs to see in the log.
    count = self._client.count(
        collection_name=self._collection, count_filter=orphans, exact=True
    ).count
    if count:
        self._client.delete(
            collection_name=self._collection,
            points_selector=models.FilterSelector(filter=orphans),
            wait=True,
        )
    return count

search(project_id, *, dense_vector=None, query_text=None, top_k=10, language=None, channel='hybrid', prefetch_limit=50, with_text=False)

Search one project's chunks over the requested channel (§3.3).

hybrid (default) runs dense + BM25 prefetches of prefetch_limit each and fuses server-side with RRF; dense and sparse query a single channel — kept first-class because the M3 eval gate compares hybrid against exactly those baselines. The payload filter is applied inside each prefetch so both candidate lists are project-scoped before fusion.

Returns span dicts per §3.3; snippet is the first ~200 chars of the stored chunk text. with_text=True additionally returns the full stored chunk text — the M4 reranker scores (query, chunk_text) pairs from the payload instead of re-opening files; the retriever strips it before results leave core. No path_prefix yet — see the module docstring.

Source code in src/noesis/core/vectorstore.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
def search(
    self,
    project_id: str,
    *,
    dense_vector: list[float] | None = None,
    query_text: str | None = None,
    top_k: int = 10,
    language: str | None = None,
    channel: SearchChannel = "hybrid",
    prefetch_limit: int = 50,
    with_text: bool = False,
) -> list[dict[str, Any]]:
    """Search one project's chunks over the requested channel (§3.3).

    ``hybrid`` (default) runs dense + BM25 prefetches of
    ``prefetch_limit`` each and fuses server-side with RRF; ``dense``
    and ``sparse`` query a single channel — kept first-class because
    the M3 eval gate compares hybrid against exactly those baselines.
    The payload filter is applied inside each prefetch so both
    candidate lists are project-scoped before fusion.

    Returns span dicts per §3.3; ``snippet`` is the first ~200 chars
    of the stored chunk text. ``with_text=True`` additionally returns
    the full stored chunk ``text`` — the M4 reranker scores (query,
    chunk_text) pairs from the payload instead of re-opening files; the
    retriever strips it before results leave core. No ``path_prefix``
    yet — see the module docstring."""
    must: list[models.FieldCondition] = [
        models.FieldCondition(
            key="project_id", match=models.MatchValue(value=project_id)
        )
    ]
    if language is not None:
        must.append(
            models.FieldCondition(
                key="language", match=models.MatchValue(value=language)
            )
        )
    query_filter = models.Filter(must=must)

    if channel in ("dense", "hybrid") and dense_vector is None:
        raise ValueError(f"channel {channel!r} requires dense_vector")
    if channel in ("sparse", "hybrid") and query_text is None:
        raise ValueError(f"channel {channel!r} requires query_text")

    if channel == "dense":
        # No models.Document anywhere on this path, so it touches no
        # per-client inference state and needs neither a pooled
        # connection nor a lock (ADR-83; verified by instrumenting
        # ModelEmbedder — zero accumulate/drain calls for dense).
        # Deliberately left on ``client`` so a dense-only caller (the
        # eval harness's baseline channels) never contends for a
        # CONNECTION. It does still take an executor slot: the gate wraps
        # every channel, and that is correct — a dense query is a real
        # round trip to a co-resident Qdrant and belongs inside the bound.
        # An earlier wording here said "slot" and seeded a false claim in
        # the architecture doc (PR #50 round-7 review).
        response = self._client.query_points(
            collection_name=self._collection,
            query=dense_vector,
            using=DENSE_VECTOR_NAME,
            query_filter=query_filter,
            limit=top_k,
            with_payload=True,
        )
    elif channel == "sparse":
        with self._checked_out_query_client() as qc:
            response = qc.query_points(
                collection_name=self._collection,
                query=models.Document(text=query_text, model=BM25_MODEL_ID),
                using=SPARSE_VECTOR_NAME,
                query_filter=query_filter,
                limit=top_k,
                with_payload=True,
            )
    else:
        effective_prefetch = max(prefetch_limit, top_k)
        with self._checked_out_query_client() as qc:
            response = qc.query_points(
                collection_name=self._collection,
                prefetch=[
                    models.Prefetch(
                        query=dense_vector,
                        using=DENSE_VECTOR_NAME,
                        filter=query_filter,
                        limit=effective_prefetch,
                    ),
                    models.Prefetch(
                        query=models.Document(
                            text=query_text, model=BM25_MODEL_ID
                        ),
                        using=SPARSE_VECTOR_NAME,
                        filter=query_filter,
                        limit=effective_prefetch,
                    ),
                ],
                query=models.FusionQuery(fusion=models.Fusion.RRF),
                limit=top_k,
                with_payload=True,
            )
    results: list[dict[str, Any]] = []
    for point in response.points:
        payload = point.payload or {}
        result = {
            "chunk_id": str(point.id),
            "file_path": payload.get("file_path"),
            "start_line": payload.get("start_line"),
            "end_line": payload.get("end_line"),
            "language": payload.get("language"),
            "symbol_name": payload.get("symbol_name"),
            "score": point.score,
            "snippet": (payload.get("text") or "")[:_SNIPPET_CHARS],
        }
        if with_text:
            result["text"] = payload.get("text") or ""
        results.append(result)
    return results

get_chunk(chunk_id)

Fetch one stored chunk by its point id (M6 get_chunk tool).

chunk_id values come from search hits — the deterministic UUIDv5 point ids. Returns the exact stored span with full chunk content (the payload text), or None for an unknown id. Content is the indexed snapshot, not ground truth — callers read the live file before acting (§3.3).

Source code in src/noesis/core/vectorstore.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
def get_chunk(self, chunk_id: str) -> dict[str, Any] | None:
    """Fetch one stored chunk by its point id (M6 ``get_chunk`` tool).

    ``chunk_id`` values come from search hits — the deterministic
    UUIDv5 point ids. Returns the exact stored span with full chunk
    ``content`` (the payload ``text``), or None for an unknown id.
    Content is the *indexed* snapshot, not ground truth — callers read
    the live file before acting (§3.3)."""
    try:
        points = self._client.retrieve(
            collection_name=self._collection,
            ids=[chunk_id],
            with_payload=True,
        )
    except UnexpectedResponse as exc:
        # A remote server rejects malformed point ids (non-UUID strings)
        # with 400 — same meaning as unknown. Anything else (connection
        # down, 5xx) must propagate, not masquerade as "unknown chunk_id".
        if exc.status_code == 400:
            return None
        raise
    except ValueError:
        # Local (in-process) Qdrant raises ValueError on a malformed
        # (non-UUID) point id where a remote server answers 400 — both
        # mean "no such chunk". Keeps the contract transport-independent.
        return None
    if not points:
        return None
    payload = points[0].payload or {}
    return {
        "chunk_id": str(points[0].id),
        "project_id": payload.get("project_id"),
        "file_path": payload.get("file_path"),
        "start_line": payload.get("start_line"),
        "end_line": payload.get("end_line"),
        "language": payload.get("language"),
        "symbol_name": payload.get("symbol_name"),
        "content": payload.get("text") or "",
    }

chunk_point_id(project_id, file_path, start_line, file_hash)

Deterministic point id — re-runs over unchanged content are idempotent.

Source code in src/noesis/core/vectorstore.py
78
79
80
81
82
83
84
85
86
def chunk_point_id(
    project_id: str, file_path: str, start_line: int, file_hash: str
) -> str:
    """Deterministic point id — re-runs over unchanged content are idempotent."""
    return str(
        uuid.uuid5(
            CHUNK_NAMESPACE, f"{project_id}:{file_path}:{start_line}:{file_hash}"
        )
    )

noesis.core.structural

Structural search over live files via ast-grep (§3.5, ADR-21/22).

Bypasses Qdrant, SQLite chunk state, and the embedder entirely (Finding 5): results are pattern matches against the filesystem as it is right now, so they are never stale by construction. It reuses exactly two core surfaces — the project registry (project_id → root_path) and the discovery filter — so structural search can never surface a file that indexing would have excluded (.gitignore, secret skip-list, size caps). Search only: ast-grep's rewrite capability is never exposed (ADR-22).

The scan is blocking I/O plus native Rust compute, so structural_search runs it via run_in_executor on the default thread pool — never on the embedder/reranker workers, which must not queue behind a scan (§3.5).

logger = logging.getLogger(__name__) module-attribute

StructuralMatch

Bases: TypedDict

file_path instance-attribute

start_line instance-attribute

end_line instance-attribute

matched_text instance-attribute

meta_vars instance-attribute

StructuralResult

Bases: TypedDict

matches instance-attribute

scanned_files instance-attribute

truncated instance-attribute

timed_out instance-attribute

StructuralSearchError(error_type, message)

Bases: Exception

Structured, adapter-mappable failure. error_type is one of unknown_project / unsupported_language / pattern_error / invalid_path; message carries the diagnostic (for pattern errors, ast-grep's own — agents iterate on patterns, keep that cheap).

Source code in src/noesis/core/structural.py
65
66
67
68
def __init__(self, error_type: str, message: str) -> None:
    super().__init__(message)
    self.error_type = error_type
    self.message = message

error_type = error_type instance-attribute

message = message instance-attribute

Pattern-match ASTs of live, discovery-filtered files (§3.5).

max_results is clamped to the configured cap; paths optionally restricts the scan to project-relative subtrees.

Source code in src/noesis/core/structural.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
async def structural_search(
    conn: Connection,
    project_id: str,
    pattern: str,
    language: str,
    *,
    paths: list[str] | None = None,
    max_results: int | None = None,
    settings: StructuralSettings | None = None,
) -> StructuralResult:
    """Pattern-match ASTs of live, discovery-filtered files (§3.5).

    *max_results* is clamped to the configured cap; *paths* optionally
    restricts the scan to project-relative subtrees.
    """
    cfg = settings or StructuralSettings()
    project = state.get_project(conn, project_id)
    if project is None:
        raise StructuralSearchError(
            "unknown_project", f"unknown project_id {project_id!r}"
        )
    cfg_discovery = discovery_config_for_project(conn, project_id)
    if language not in LANGUAGE_MAP:
        raise StructuralSearchError(
            "unsupported_language",
            f"{language!r} is not supported for structural search; "
            f"supported: {', '.join(sorted(LANGUAGE_MAP))}",
        )
    _validate_pattern(pattern, LANGUAGE_MAP[language].ast_grep)
    norm_paths = _normalize_paths(paths)
    # Requests may lower the configured cap, never raise it; a non-positive
    # value (REST validates ge=1, but core has other callers — MCP in M6)
    # clamps to 1 rather than silently returning nothing.
    limit = (
        cfg.max_results if max_results is None else min(max_results, cfg.max_results)
    )
    limit = max(1, limit)

    return await asyncio.get_running_loop().run_in_executor(
        None,
        _scan_sync,
        project["root_path"],
        pattern,
        language,
        norm_paths,
        limit,
        cfg.timeout_s,
        cfg_discovery,
    )