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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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
¶
StructuralResult
¶
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 | |
structural_search(conn, project_id, pattern, language, *, paths=None, max_results=None, settings=None)
async
¶
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 | |