App & runtime¶
Process assembly: the FastAPI application, the shared runtime context used by both transports, asset prefetch, and logging.
noesis.app
¶
FastAPI application factory (Overview §4.2, expanded §3.1).
One process, localhost-only (CLAUDE.md rule 2 — run with
uvicorn noesis.app:app --host 127.0.0.1; never a wildcard bind). The
lifespan owns every core resource: SQLite connection, Qdrant client, the
Embedder. The FastMCP server (M6) mounts at /mcp via the Draft's
verified pattern — mcp.http_app(path="/") combined into this app's
lifespan with combine_lifespans so the MCP session manager's task
group is initialized alongside our resources.
__all__ = ['AppContext', 'build_runtime_context', 'close_runtime_context', 'create_app', 'app']
module-attribute
¶
app = create_app()
module-attribute
¶
AppContext(conn, store, embedder, reranker=None, rerank_candidates=50, embed_batch_size=32, structural=StructuralSettings(), git_fast_path=True, indexing=IndexingSettings(), telemetry=QueryTelemetry(), search_gate=_default_search_gate(), jobs=dict(), progress=dict(), watcher=None, config_device_pin=None, config_reranker_device_pin=None, embedder_warmup=None, reranker_warmup=None, prefetch_job=None, prefetch_task=None)
dataclass
¶
Core resources shared by all adapters. reranker is None when
reranker.enabled=false — the kill switch (§3.3) removes the model
entirely; rerank_candidates is the fused-candidate depth reranked
per request (config reranker.candidates).
conn
instance-attribute
¶
store
instance-attribute
¶
embedder
instance-attribute
¶
reranker = None
class-attribute
instance-attribute
¶
rerank_candidates = 50
class-attribute
instance-attribute
¶
embed_batch_size = 32
class-attribute
instance-attribute
¶
structural = field(default_factory=StructuralSettings)
class-attribute
instance-attribute
¶
git_fast_path = True
class-attribute
instance-attribute
¶
indexing = field(default_factory=IndexingSettings)
class-attribute
instance-attribute
¶
telemetry = field(default_factory=QueryTelemetry)
class-attribute
instance-attribute
¶
search_gate = field(default_factory=_default_search_gate)
class-attribute
instance-attribute
¶
jobs = field(default_factory=dict)
class-attribute
instance-attribute
¶
progress = field(default_factory=dict)
class-attribute
instance-attribute
¶
watcher = None
class-attribute
instance-attribute
¶
config_device_pin = None
class-attribute
instance-attribute
¶
config_reranker_device_pin = None
class-attribute
instance-attribute
¶
embedder_warmup = None
class-attribute
instance-attribute
¶
reranker_warmup = None
class-attribute
instance-attribute
¶
prefetch_job = None
class-attribute
instance-attribute
¶
prefetch_task = None
class-attribute
instance-attribute
¶
build_runtime_context(cfg)
async
¶
Construct production core resources from settings. Shared by the FastAPI lifespan and the stdio MCP entry point (noesis.mcp.main) — one build path, so the two transports cannot diverge on wiring.
Source code in src/noesis/runtime.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 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 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 295 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 | |
close_runtime_context(ctx)
async
¶
Tear down what build_runtime_context created.
Cancelling a task only schedules CancelledError; the cancelled
execute_run still has to resume and run its except BaseException
handler, which calls state.finish_run to mark the run failed. So we
must AWAIT the tasks' unwind before closing anything they touch — closing
conn first would make that final write raise ProgrammingError and
leave the run row stuck running (H5). Order: cancel → await → stop
model workers → close the Qdrant client(s) → stop the telemetry writer →
close SQLite. ctx.store.close() (ADR-76) closes a pre-existing gap:
the QdrantClient(s) were never explicitly closed before, single or
split. Each resource's close() is isolated (PR #50 round-3 review): one
raising is logged and must not skip the rest, or the telemetry/conn
cleanup after them.
Source code in src/noesis/runtime.py
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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
create_app(settings=None, ctx=None)
¶
Build the app. Tests pass a pre-built ctx (fake embedder, in-memory Qdrant); production builds one from settings.
Source code in src/noesis/app.py
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 | |
noesis.runtime
¶
Core runtime context — construction and teardown, no web framework.
Split out of noesis.app (L3) so the stdio MCP entry point
(python -m noesis.mcp) can build/tear down core resources without
importing noesis.app, whose module body calls create_app() and would
otherwise build an entire unused FastAPI app (second FastMCP instance, static
mount, config read) at import — any failure there killing the stdio server
before main() runs. Nothing here has an import-time side effect.
AppContext(conn, store, embedder, reranker=None, rerank_candidates=50, embed_batch_size=32, structural=StructuralSettings(), git_fast_path=True, indexing=IndexingSettings(), telemetry=QueryTelemetry(), search_gate=_default_search_gate(), jobs=dict(), progress=dict(), watcher=None, config_device_pin=None, config_reranker_device_pin=None, embedder_warmup=None, reranker_warmup=None, prefetch_job=None, prefetch_task=None)
dataclass
¶
Core resources shared by all adapters. reranker is None when
reranker.enabled=false — the kill switch (§3.3) removes the model
entirely; rerank_candidates is the fused-candidate depth reranked
per request (config reranker.candidates).
conn
instance-attribute
¶
store
instance-attribute
¶
embedder
instance-attribute
¶
reranker = None
class-attribute
instance-attribute
¶
rerank_candidates = 50
class-attribute
instance-attribute
¶
embed_batch_size = 32
class-attribute
instance-attribute
¶
structural = field(default_factory=StructuralSettings)
class-attribute
instance-attribute
¶
git_fast_path = True
class-attribute
instance-attribute
¶
indexing = field(default_factory=IndexingSettings)
class-attribute
instance-attribute
¶
telemetry = field(default_factory=QueryTelemetry)
class-attribute
instance-attribute
¶
search_gate = field(default_factory=_default_search_gate)
class-attribute
instance-attribute
¶
jobs = field(default_factory=dict)
class-attribute
instance-attribute
¶
progress = field(default_factory=dict)
class-attribute
instance-attribute
¶
watcher = None
class-attribute
instance-attribute
¶
config_device_pin = None
class-attribute
instance-attribute
¶
config_reranker_device_pin = None
class-attribute
instance-attribute
¶
embedder_warmup = None
class-attribute
instance-attribute
¶
reranker_warmup = None
class-attribute
instance-attribute
¶
prefetch_job = None
class-attribute
instance-attribute
¶
prefetch_task = None
class-attribute
instance-attribute
¶
build_runtime_context(cfg)
async
¶
Construct production core resources from settings. Shared by the FastAPI lifespan and the stdio MCP entry point (noesis.mcp.main) — one build path, so the two transports cannot diverge on wiring.
Source code in src/noesis/runtime.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 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 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 295 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 | |
close_runtime_context(ctx)
async
¶
Tear down what build_runtime_context created.
Cancelling a task only schedules CancelledError; the cancelled
execute_run still has to resume and run its except BaseException
handler, which calls state.finish_run to mark the run failed. So we
must AWAIT the tasks' unwind before closing anything they touch — closing
conn first would make that final write raise ProgrammingError and
leave the run row stuck running (H5). Order: cancel → await → stop
model workers → close the Qdrant client(s) → stop the telemetry writer →
close SQLite. ctx.store.close() (ADR-76) closes a pre-existing gap:
the QdrantClient(s) were never explicitly closed before, single or
split. Each resource's close() is isolated (PR #50 round-3 review): one
raising is logged and must not skip the rest, or the telemetry/conn
cleanup after them.
Source code in src/noesis/runtime.py
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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
noesis.prefetch
¶
Install-time asset prefetch — uv run python -m noesis.prefetch.
Downloads every network-fetched asset the service needs (decision rows 30
and 32, doc §3.8): tree-sitter grammars for all canonical languages (the
1.12.x language pack fetches each grammar over HTTP on first
get_parser), the embedding model weights, the M4 reranker weights
(skippable — the reranker is optional, config reranker.enabled), and
the BM25 tokenizer assets fastembed fetches on first sparse encode
(~100 KB of stopwords and stemmer config — same asset class as the model
weights, no code or query leaves the machine). Run once after uv sync;
afterwards the service makes zero outbound calls at runtime. Deliberately
lives outside core/ — this is the only module whose job is to trigger
downloads.
logger = logging.getLogger(__name__)
module-attribute
¶
FASTEMBED_CACHE_ENV = 'FASTEMBED_CACHE_PATH'
module-attribute
¶
UNKNOWN_RERANKER = _UnknownReranker()
module-attribute
¶
PREFETCH_STEPS = ('grammars', 'bm25', 'model', 'reranker')
module-attribute
¶
default_fastembed_cache()
¶
Absolute, cwd-independent default cache dir for fastembed's BM25
assets (M8). The previous data/fastembed_cache default was resolved
against the current working directory, so prefetch (run from the repo)
and the stdio MCP server (spawned with the agent host's cwd) landed on
DIFFERENT caches — the first sparse search then re-downloaded assets at
runtime, or failed offline. Anchoring to the user cache dir makes every
process on the machine resolve one path regardless of cwd.
Source code in src/noesis/prefetch.py
36 37 38 39 40 41 42 43 44 45 | |
model_assets_ready(model_id)
¶
Best-effort, no-network check: is model_id fully cached in the
local HF cache (ADR-78 addendum, issue #47 finding 4, PR #50 review)?
Asked of BOTH model boundaries (issue #52): the embedder's
SentenceTransformer and the reranker's CrossEncoder resolve the
same HF cache and need the same three kinds of file. Hence the neutral
name: it was embedder_assets_ready while the embedder was the only
caller.
Requires config.json, at least one weight file, AND at least one
tokenizer file:
- weights — a single-file checkpoint (
model.safetensors/pytorch_model.bin) or a sharded one's index manifest (*.index.json).config.jsonalone reportedreadyafter a download interrupted between metadata and weights (ADR-79). - tokenizer — a file carrying an actual VOCABULARY, taken from each
family's own
vocab_files_namesrather than guessed: a fast tokenizer'stokenizer.json; sentencepiece'ssentencepiece.bpe.model(XLM-R),spiece.model(T5/ALBERT) ortokenizer.model(Llama); wordpiece'svocab.txt; or byte-level BPE'svocab.jsonANDmerges.txt, which is the one family whose vocabulary is two files (GPT2Tokenizerdeclares both) and so is the one entry checked as a pair. Deliberately NOTtokenizer_config.jsonorspecial_tokens_map.json, which are metadata: they name the tokenizer class and its special tokens and hold no vocabulary, so a cache with only those is the same broken state as no tokenizer at all (issue #52 review round 4). Weights without a vocabulary are not a working model, and the failure is quieter than a stall: with onlyconfig.json+model.safetensorsleft in a realBAAI/bge-reranker-v2-m3cache andHF_HUB_OFFLINE=1,CrossEncoder(...)did not raise — it built anXLMRobertaTokenizerwithvocab_size5 that tokenized every word to<unk>and still returned a plausible-looking score (measured, ADR-90). A "ready" that means "will silently rank noise" is worse than one that means "will stall".
ANY member of a family satisfies it, never a specific filename: the two
default models differ (BAAI/bge-reranker-v2-m3 ships
sentencepiece.bpe.model, nomic-ai/CodeRankEmbed ships
vocab.txt; both ship tokenizer.json), and requiring one spelling
would report a false "missing" for the other. Only the pytorch-backend
filenames are checked, not the whole repo tree: neither LocalSTEmbedder
nor LocalCrossEncoderReranker requests backend="onnx", so an
onnx/openvino variant shipped alongside pytorch weights in the same repo
must not cause a false "missing".
try_to_load_from_cache returns a sentinel object — not None — for
a filename HF has already probed and confirmed absent from the repo
(e.g. a single-file checkpoint's sharded-index name, probed once by a
prior load's fallback logic and cached negative; verified against a live
cache). isinstance(result, str) treats that sentinel as absent, same
as a filename that was never probed at all — is not None would not.
All lookups happen in the default HF cache location (HF_HOME /
~/.cache/huggingface/hub), the same resolution sentence_transformers
itself uses, so this asks exactly what the real load will find.
Source code in src/noesis/prefetch.py
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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
model_readiness(model)
async
¶
Shared (assets, ready) computation behind /healthz (ADR rows
78/79) and jobs.index_status (ADR row 81) — PR #50 round-5 review.
Previously pasted verbatim in both call sites: they agreed only because
the text was identical and one test compared the two endpoints' output,
not because there was one implementation: a future edit to either copy
(e.g. a "warming" state, a different n/a rule) had nothing stopping it
from landing on one side only. model is duck-typed — model_id
required, resolved_device optional — so this has no dependency on a
specific Embedder or Reranker implementation and stays outside core/
like the rest of this module (module docstring).
resolved_device is the load signal, not a device-selection record:
both boundaries assign it only after the model constructor returns
(ADR-79 for the embedder; issue #52 for the reranker, which had the same
premature assignment until this signal started reading it). So False
here means "assets may be cached, but the model is not loaded yet — the
next call pays the load", and "n/a" means the implementation does not
report a device at all (a test double).
Source code in src/noesis/prefetch.py
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
reranker_readiness(reranker)
async
¶
(reranker_assets, reranker_ready) for the health surfaces (issue
52). None is the reranker.enabled=false kill switch (§3.3, the¶
shipped default), which is a different answer from "enabled but its
weights are missing" — reporting "missing" for a feature nobody turned
on would send an operator to fetch 2.3GB they do not need, and omitting
the fields entirely would leave a caller unable to tell "off" from "this
server does not report it". So the kill switch gets its own value and no
HF-cache lookup happens at all.
:data:UNKNOWN_RERANKER is the third case: a duck-typed context (a test
or an adapter) that carries no reranker attribute has not told us the
switch is off, so it reports "unknown" — the value both surfaces
already use for "cannot tell".
Lives here, next to the embedder half, rather than at the two call sites: ADR-82 had to unwind exactly that duplication once already.
Source code in src/noesis/prefetch.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
prefetch_grammars()
¶
Source code in src/noesis/prefetch.py
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
prefetch_model(model_id)
¶
Source code in src/noesis/prefetch.py
294 295 296 297 298 299 300 301 302 303 304 | |
prefetch_reranker(model_id)
¶
Source code in src/noesis/prefetch.py
307 308 309 310 311 312 313 314 315 316 317 318 | |
prefetch_bm25()
¶
Source code in src/noesis/prefetch.py
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | |
configured_model_ids()
¶
(embedder model, reranker model) the SERVICE will actually load, or
None if the config cannot be read.
Read from the same config resolution the service uses (NOESIS_CONFIG
→ ./config.toml → XDG, ADR-44), because prefetching a model nobody
loads fixes nothing: with a non-default [embedder] model or
[reranker] model, the hardcoded repo ids this replaces downloaded
multi-GB weights the service never opens, while /healthz and the
plugin's healthcheck.py — whose remedy is literally "run prefetch" —
kept reporting missing (issue #52 review). Run prefetch with the same
NOESIS_CONFIG the service gets, or from the same directory, for the
two to agree.
Reads the model IDS only, deliberately not reranker.enabled: a default
config (enabled = false) still prefetches the reranker's weights, which
is bandwidth for a model the service will not load. That is tracked as
issue #58 and was left alone on purpose — unlike a wrong model id it breaks
nothing (with reranking off the health fields read "disabled" and never
complain), --skip-reranker already exists, and changing what a
documented install command downloads belongs in its own change (ADR-91).
A MISSING config is not a failure — load_settings answers with the
shipped defaults, which is exactly right for a fresh install. A config
that exists but will not parse is different: it means the operator
configured something and we cannot see what, so None comes back and
the caller skips the model downloads rather than fetching ~2.9 GB of
defaults the service may never load (ADR-90). The config-independent
assets — grammars, BM25 — still come down.
Source code in src/noesis/prefetch.py
346 347 348 349 350 351 352 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 | |
job_status(ctx)
¶
Dashboard read model for the prefetch progress bar — the same shape whether or not a job has ever run, so the template/JS never special-case "no job yet" versus "one finished a while ago".
percent is None (indeterminate — ADR-79's "no smoothing
pretence", same as jobs.run_progress) while a job is actively running:
prefetch's functions report no sub-step progress (deliberately —
reusing them without touching their internals is the whole point, see
the module docstring above), so the honest signal is "step N of M is in
flight", not a fabricated percentage. Once the job stops running,
percent becomes the fraction of applicable steps that finished
done — 100 on success, partial on a failure part-way through.
"Skipped" steps (config unreadable, ADR-91) are excluded from both the
numerator and denominator, matching main()'s own "skipped is not the
same as failed" distinction.
Source code in src/noesis/prefetch.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
start_job(ctx)
¶
Dashboard action: kick off the background job above. Returns the 202-style acceptance body the REST route forwards verbatim.
Only one job runs at a time — a second click while one is in flight
returns already_running rather than launching a concurrent download
(mirrors jobs.launch_index_run's identical guard for index runs, for
the identical reason: two overlapping downloads into the same HF cache
directory buy nothing and only contend for bandwidth/disk).
No atomic-transaction dance here unlike launch_index_run — that one
guards against two processes (HTTP + stdio MCP) racing the same
SQLite-backed launch; this job is REST-only (issue #51 gave it no MCP
tool) and the check-then-launch below runs to completion on one event
loop before any await, so there is no window for a second call to see a
stale "not running" state.
Source code in src/noesis/prefetch.py
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 | |
main()
¶
Source code in src/noesis/prefetch.py
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 630 631 632 633 634 635 636 637 638 | |
noesis.logging_config
¶
Central logging configuration for Noesis (local-only, stderr-only).
Called once at each entry point (noesis.app.create_app and
noesis.mcp.__main__.main) before any runtime work. Configures the
noesis logger namespace with a single stderr handler at
NOESIS_LOG_LEVEL (default INFO). Prior to this the noesis loggers had
no handler and the stdlib lastResort handler is WARNING-level, so every
logger.info(...) in the package printed nothing — the runtime looked like
a black box even though the log calls existed.
Design constraints:
- stderr only. stdout carries the stdio MCP JSON-RPC stream; a log line on
stdout corrupts it (CLAUDE.md rule 2, noesis.mcp.__main__). We pin
sys.stderr explicitly rather than relying on the implicit default.
- No new runtime deps (CLAUDE.md rule 3): stdlib logging + json.
- propagate defaults True on the noesis logger so pytest's
caplog (a handler on the root logger) still captures records — the
existing tests/test_reranker.py caplog assertions depend on this. The
stdio MCP entry point passes propagate=False so records can never reach
a root handler bound to stdout and corrupt its JSON-RPC stream.
- This module only sets up transport/format. The content rule (ADR-25: never
log query text or file contents) is enforced at the individual call sites.
LEVEL_ENV = 'NOESIS_LOG_LEVEL'
module-attribute
¶
FORMAT_ENV = 'NOESIS_LOG_FORMAT'
module-attribute
¶
LOGGER_NAME = 'noesis'
module-attribute
¶
configure_logging(propagate=True)
¶
Idempotently configure the noesis logger. Safe to call repeatedly:
the level, formatter, and propagation are refreshed from the environment /
arguments on every call, but at most one handler is ever attached.
propagate controls whether records also bubble to the root logger.
The default (True) is required for the HTTP app and the test suite, where
pytest's caplog handler sits on the root logger. The stdio MCP entry
point (noesis.mcp.__main__) passes propagate=False: its own
stderr handler still emits every line, but a root handler bound to
stdout (e.g. a host's bootstrap/sitecustomize handler) would otherwise
receive these records too and corrupt the JSON-RPC stream that shares
stdout. stderr-only is the whole point in that process.
Source code in src/noesis/logging_config.py
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 | |