Skip to content

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
async def build_runtime_context(cfg: Settings) -> AppContext:
    """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."""
    # Same persistent fastembed cache default as noesis.prefetch —
    # without it, the BM25 assets land in the system tmp dir and
    # get re-fetched after a reboot (runtime network, ADR-25-adjacent).
    import logging
    import os

    from noesis.prefetch import FASTEMBED_CACHE_ENV, default_fastembed_cache

    os.environ.setdefault(FASTEMBED_CACHE_ENV, default_fastembed_cache())
    # Log the resolved DB so a divergence between the HTTP and stdio
    # transports (each logs its own path at startup) is visible, not silent.
    logging.getLogger(__name__).info("state db: %s", cfg.db_path)
    conn = state.connect(cfg.db_path)
    state.init_db(conn)
    # Crash recovery: mark runs whose owning process is dead as failed, so a
    # leftover 'running' row can't jam the launch guard forever. Owner-gated
    # (M7) so a co-running process's live run is never mislabelled.
    orphaned = state.fail_orphaned_runs(conn)
    if orphaned:
        import logging

        logging.getLogger(__name__).warning(
            "marked %d orphaned 'running' index run(s) as failed (interrupted)",
            orphaned,
        )
    # Device precedence (ADR-40): an explicit config.toml pin wins (operator
    # config is never second-guessed by UI state); otherwise the dashboard's
    # persisted app_settings choice; otherwise auto-detect (None).
    stored_device = state.get_setting(conn, "compute_device")
    if stored_device == "auto":
        stored_device = None
    embedder_device = cfg.embedder.device or stored_device
    reranker_device = cfg.reranker.device or stored_device
    embedder = LocalSTEmbedder(
        model_id=cfg.embedder.model,
        dim=cfg.embedder.dim,
        batch_size=cfg.embedder.batch_size,
        device=embedder_device,
    )
    log = logging.getLogger(__name__)
    # Resolved here, not at the use site, so one log line tells an operator
    # what the machine actually got — a derived value nobody can see is a
    # value nobody can debug (ADR-83/84).
    query_connections = derive_query_connections(cfg.qdrant.query_connections)
    query_queue_depth = derive_query_queue_depth(
        query_connections, cfg.qdrant.query_queue_depth
    )
    log.info(
        "search concurrency: %d query connections, queue depth %d (cpus=%d, %s)",
        query_connections,
        query_queue_depth,
        available_cpus(),
        "configured"
        if cfg.qdrant.query_connections is not None
        else "derived — set [qdrant] query_connections to override",
    )
    # A silent hang here (Qdrant down/unreachable) is a common false "bug"
    # report — name what we're waiting on before the blocking round-trips.
    log.info(
        "connecting to Qdrant at %s (%d query + 1 index + 1 admin connections, ADR-83)",
        cfg.qdrant.url,
        query_connections,
    )
    # Three roles, deliberately distinct objects (ADR-83):
    #   admin  — deletes, counts, scroll, retrieve, collection setup. None of
    #            these build a models.Document, so they need no pool slot and
    #            must never take one from a query.
    #   index  — upsert_chunks only, so an index run cannot consume a query
    #            connection however long its batch runs.
    #   query  — the pool, one checked out per sparse/hybrid search.
    store = VectorStore(
        QdrantClient(url=cfg.qdrant.url),
        collection_name=cfg.qdrant.collection,
        index_client=QdrantClient(url=cfg.qdrant.url),
        query_clients=[
            QdrantClient(url=cfg.qdrant.url) for _ in range(query_connections)
        ],
    )
    created = store.ensure_collection(embedder)
    if created:
        tracked = state.indexed_file_total(conn)
        if tracked > 0:
            log.warning(
                "Qdrant collection %s was MISSING at startup but the state DB "
                "already tracks %d indexed file(s) — signature of an external "
                "collection wipe: points are gone while state still reports "
                "files as indexed. Search will return empty for affected "
                "projects until a full reindex, which now self-heals by "
                "re-embedding drifted files. Nothing was deleted by this "
                "process.",
                cfg.qdrant.collection,
                tracked,
            )
    log.info("Qdrant collection %s ready", cfg.qdrant.collection)
    # The Qdrant-side half of the crash recovery above: fail_orphaned_runs
    # cleans SQLite rows a dead process left behind, this cleans the points
    # one left behind. Startup is the only safe moment — no run of ours is in
    # flight yet, and a project row is always committed before its first point
    # is written, so a project another transport is mid-indexing cannot look
    # like an orphan. Skipped on an empty project table (see the method).
    swept = await asyncio.to_thread(
        store.delete_orphan_points, [row["id"] for row in state.list_projects(conn)]
    )
    if swept:
        log.warning(
            "swept %d orphaned point(s) belonging to no registered project", swept
        )
    reranker: LocalCrossEncoderReranker | None = None
    if cfg.reranker.enabled:
        reranker = LocalCrossEncoderReranker(
            model_id=cfg.reranker.model,
            batch_size=cfg.reranker.batch_size,
            device=reranker_device,
        )
        if cfg.reranker.preload:
            # preload() forces the ~2.3GB model load now; embedder/reranker
            # loads log their own start/ready lines (core.embedder/reranker).
            log.info("preloading reranker model (may take a while)")
            await reranker.preload()
    ctx = AppContext(
        conn=conn,
        store=store,
        embedder=embedder,
        reranker=reranker,
        # Sized from the SAME derived value as the store's query pool above:
        # a slot and a connection must be 1:1, or a checked-out search waits
        # on a connection that no thread is holding, or vice versa (ADR-84).
        search_gate=SearchGate(query_connections, query_queue_depth),
        rerank_candidates=cfg.reranker.candidates,
        embed_batch_size=cfg.embedder.batch_size,
        structural=cfg.structural,
        git_fast_path=cfg.git.fast_path,
        indexing=cfg.indexing,
        config_device_pin=cfg.embedder.device,
        config_reranker_device_pin=cfg.reranker.device,
    )

    async def _warm_up_embedder() -> None:
        # ADR-77 (issue #47): not awaited here — this coroutine runs as a
        # background task instead, so a multi-minute cold download overlaps
        # the agent's own setup time rather than delaying the
        # FastMCP/FastAPI lifespan, which must finish before the server
        # answers `initialize` (blocking it here would look like a server
        # that failed to start). Both transports share this function, since
        # both share build_runtime_context.
        try:
            await ctx.embedder.preload()
            log.info("embedder warm-up complete")
        except Exception:
            log.exception(
                "embedder warm-up failed — will load lazily on first use instead"
            )

    ctx.embedder_warmup = asyncio.create_task(_warm_up_embedder())

    async def _warm_up_reranker(model: LocalCrossEncoderReranker) -> None:
        # Issue #52: ADR-77's argument applies unchanged to the reranker, only
        # more so — its weights are ~2.3 GB against the embedder's ~550 MB
        # (measured off a real HF cache: 2,271,071,852 and 546,938,168 bytes;
        # decimal GB/MB, the convention download sizes are quoted in), and
        # with `reranker.enabled=true` every search reranks by default
        # (ADR-34), so the first search pays that load in full.
        #
        # Queued BEHIND the embedder's warm-up rather than beside it: the
        # embedder gates every search, the reranker only scores hits a search
        # already produced, so two concurrent cold loads would slow the one
        # that is actually on the critical path (and, on a small GPU, contend
        # for the memory both are claiming). This is a trade, not a free
        # lunch: it delays reranker readiness by whatever is left of the
        # embedder's load, so a first reranked search arriving in that window
        # waits longer than it would have with both loading at once. That is
        # the cost we choose — a slow first SEARCH is worse than a slow first
        # RERANK, and the reranker is the optional half.
        #
        # `asyncio.wait` rather than `await task`: it waits for completion
        # without adopting the other task's outcome, so a warm-up that failed
        # (it logs and swallows its own errors) still lets this one run, and
        # cancelling THIS task at teardown does not reach in and cancel the
        # embedder's. A CancelledError delivered here propagates on purpose.
        if ctx.embedder_warmup is not None:
            await asyncio.wait([ctx.embedder_warmup])
        try:
            await model.preload()
            log.info("reranker warm-up complete")
        except Exception:
            log.exception(
                "reranker warm-up failed — will load lazily on first use instead"
            )

    # Nothing to warm when the kill switch is off, and nothing left to warm
    # when `reranker.preload=true` already awaited the load above. The model
    # is passed in rather than closed over so its type is the concrete
    # reranker, not the `| None` the enclosing scope carries — the guard
    # below is what makes it non-None, and a type checker cannot see that
    # through a closure.
    if reranker is not None and not cfg.reranker.preload:
        ctx.reranker_warmup = asyncio.create_task(_warm_up_reranker(reranker))
    log.info("runtime ready")
    return ctx

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
async def close_runtime_context(ctx: AppContext) -> None:
    """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."""
    import logging

    log = logging.getLogger(__name__)
    tasks = [t for t in ctx.jobs.values() if not t.done()]
    for warmup in (ctx.embedder_warmup, ctx.reranker_warmup, ctx.prefetch_task):
        if warmup is not None and not warmup.done():
            tasks.append(warmup)
    for task in tasks:
        task.cancel()
    if tasks:
        await asyncio.gather(*tasks, return_exceptions=True)
    # search_gate first: it may still be running a search that holds one of
    # the store's query connections, and closing the store under it would
    # pull the connection out from beneath an in-flight call.
    for resource in (ctx.search_gate, ctx.embedder, ctx.reranker, ctx.store):
        close = getattr(resource, "close", None)
        if close is not None:
            # Each close() joins a worker thread with a 5s bound. Bounded is
            # not the same as free: run it off the loop, or teardown blocks
            # every other task (including the MCP session manager's own
            # shutdown in the combined lifespan) for up to 5s per resource.
            try:
                await asyncio.to_thread(close)
            except Exception:
                log.exception("error closing %r during teardown", resource)
    # Same reason, and it must happen here rather than at process exit: the
    # writer holds its own handle to the state DB, which would otherwise
    # outlive ctx.conn and survive a DB-file removal. Scoped to this context's
    # own writer (ADR-59) — it was process-wide, so a second live context's
    # teardown used to discard rows this one had just enqueued.
    await asyncio.to_thread(ctx.telemetry.close)
    ctx.conn.close()

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
def create_app(
    settings: Settings | None = None, ctx: AppContext | None = None
) -> FastAPI:
    """Build the app. Tests pass a pre-built *ctx* (fake embedder,
    in-memory Qdrant); production builds one from settings."""
    # Configure logging before any runtime work so startup/model-load/index
    # lines are actually emitted (the noesis loggers have no handler otherwise
    # and default to WARNING — see noesis.logging_config). Idempotent.
    configure_logging()
    cfg = settings or load_settings()

    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        if ctx is not None:
            app.state.ctx = ctx
        else:
            app.state.ctx = await build_runtime_context(cfg)
        # Watcher lives in the lifespan for prod and test contexts alike —
        # the Observer thread is lazy (spawns on the first scheduled watch),
        # so apps with no watched projects pay one asyncio task, nothing more.
        from noesis.core.watcher import WatcherManager

        app.state.ctx.watcher = WatcherManager(
            app.state.ctx, poll_interval_s=cfg.watcher.poll_interval_s
        )
        app.state.ctx.watcher.start()
        try:
            yield
        finally:
            await app.state.ctx.watcher.stop()
            if ctx is None:
                await close_runtime_context(app.state.ctx)
            else:
                # Test-supplied ctx owns its own conn/embedder teardown, but
                # still await the cancelled index tasks so their run rows are
                # marked failed before the fixture tears the ctx down (H5).
                tasks = [t for t in app.state.ctx.jobs.values() if not t.done()]
                for task in tasks:
                    task.cancel()
                if tasks:
                    await asyncio.gather(*tasks, return_exceptions=True)

    # MCP tools resolve the context lazily (per call) from this app's
    # state — the closure is late-bound, and tools can only run after the
    # combined lifespan has set app.state.ctx.
    mcp = build_mcp(lambda: app.state.ctx)
    mcp_app = mcp.http_app(path="/")

    app = FastAPI(
        title="noesis", lifespan=combine_lifespans(lifespan, mcp_app.lifespan)
    )
    # DNS-rebinding guard (PR #10 security review): binding 127.0.0.1 stops
    # remote hosts, but a browser on this machine visiting a page whose
    # domain re-resolves to 127.0.0.1 would reach the mutation endpoints
    # with readable responses. Rejecting foreign Host headers closes that
    # class; "testserver" is Starlette's TestClient default.
    from starlette.middleware.trustedhost import TrustedHostMiddleware

    app.add_middleware(
        TrustedHostMiddleware,
        allowed_hosts=["127.0.0.1", "localhost", "testserver"],
    )
    app.include_router(router)
    app.include_router(dashboard_router)
    from fastapi.staticfiles import StaticFiles

    app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
    app.mount("/mcp", mcp_app)
    return app

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
async def build_runtime_context(cfg: Settings) -> AppContext:
    """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."""
    # Same persistent fastembed cache default as noesis.prefetch —
    # without it, the BM25 assets land in the system tmp dir and
    # get re-fetched after a reboot (runtime network, ADR-25-adjacent).
    import logging
    import os

    from noesis.prefetch import FASTEMBED_CACHE_ENV, default_fastembed_cache

    os.environ.setdefault(FASTEMBED_CACHE_ENV, default_fastembed_cache())
    # Log the resolved DB so a divergence between the HTTP and stdio
    # transports (each logs its own path at startup) is visible, not silent.
    logging.getLogger(__name__).info("state db: %s", cfg.db_path)
    conn = state.connect(cfg.db_path)
    state.init_db(conn)
    # Crash recovery: mark runs whose owning process is dead as failed, so a
    # leftover 'running' row can't jam the launch guard forever. Owner-gated
    # (M7) so a co-running process's live run is never mislabelled.
    orphaned = state.fail_orphaned_runs(conn)
    if orphaned:
        import logging

        logging.getLogger(__name__).warning(
            "marked %d orphaned 'running' index run(s) as failed (interrupted)",
            orphaned,
        )
    # Device precedence (ADR-40): an explicit config.toml pin wins (operator
    # config is never second-guessed by UI state); otherwise the dashboard's
    # persisted app_settings choice; otherwise auto-detect (None).
    stored_device = state.get_setting(conn, "compute_device")
    if stored_device == "auto":
        stored_device = None
    embedder_device = cfg.embedder.device or stored_device
    reranker_device = cfg.reranker.device or stored_device
    embedder = LocalSTEmbedder(
        model_id=cfg.embedder.model,
        dim=cfg.embedder.dim,
        batch_size=cfg.embedder.batch_size,
        device=embedder_device,
    )
    log = logging.getLogger(__name__)
    # Resolved here, not at the use site, so one log line tells an operator
    # what the machine actually got — a derived value nobody can see is a
    # value nobody can debug (ADR-83/84).
    query_connections = derive_query_connections(cfg.qdrant.query_connections)
    query_queue_depth = derive_query_queue_depth(
        query_connections, cfg.qdrant.query_queue_depth
    )
    log.info(
        "search concurrency: %d query connections, queue depth %d (cpus=%d, %s)",
        query_connections,
        query_queue_depth,
        available_cpus(),
        "configured"
        if cfg.qdrant.query_connections is not None
        else "derived — set [qdrant] query_connections to override",
    )
    # A silent hang here (Qdrant down/unreachable) is a common false "bug"
    # report — name what we're waiting on before the blocking round-trips.
    log.info(
        "connecting to Qdrant at %s (%d query + 1 index + 1 admin connections, ADR-83)",
        cfg.qdrant.url,
        query_connections,
    )
    # Three roles, deliberately distinct objects (ADR-83):
    #   admin  — deletes, counts, scroll, retrieve, collection setup. None of
    #            these build a models.Document, so they need no pool slot and
    #            must never take one from a query.
    #   index  — upsert_chunks only, so an index run cannot consume a query
    #            connection however long its batch runs.
    #   query  — the pool, one checked out per sparse/hybrid search.
    store = VectorStore(
        QdrantClient(url=cfg.qdrant.url),
        collection_name=cfg.qdrant.collection,
        index_client=QdrantClient(url=cfg.qdrant.url),
        query_clients=[
            QdrantClient(url=cfg.qdrant.url) for _ in range(query_connections)
        ],
    )
    created = store.ensure_collection(embedder)
    if created:
        tracked = state.indexed_file_total(conn)
        if tracked > 0:
            log.warning(
                "Qdrant collection %s was MISSING at startup but the state DB "
                "already tracks %d indexed file(s) — signature of an external "
                "collection wipe: points are gone while state still reports "
                "files as indexed. Search will return empty for affected "
                "projects until a full reindex, which now self-heals by "
                "re-embedding drifted files. Nothing was deleted by this "
                "process.",
                cfg.qdrant.collection,
                tracked,
            )
    log.info("Qdrant collection %s ready", cfg.qdrant.collection)
    # The Qdrant-side half of the crash recovery above: fail_orphaned_runs
    # cleans SQLite rows a dead process left behind, this cleans the points
    # one left behind. Startup is the only safe moment — no run of ours is in
    # flight yet, and a project row is always committed before its first point
    # is written, so a project another transport is mid-indexing cannot look
    # like an orphan. Skipped on an empty project table (see the method).
    swept = await asyncio.to_thread(
        store.delete_orphan_points, [row["id"] for row in state.list_projects(conn)]
    )
    if swept:
        log.warning(
            "swept %d orphaned point(s) belonging to no registered project", swept
        )
    reranker: LocalCrossEncoderReranker | None = None
    if cfg.reranker.enabled:
        reranker = LocalCrossEncoderReranker(
            model_id=cfg.reranker.model,
            batch_size=cfg.reranker.batch_size,
            device=reranker_device,
        )
        if cfg.reranker.preload:
            # preload() forces the ~2.3GB model load now; embedder/reranker
            # loads log their own start/ready lines (core.embedder/reranker).
            log.info("preloading reranker model (may take a while)")
            await reranker.preload()
    ctx = AppContext(
        conn=conn,
        store=store,
        embedder=embedder,
        reranker=reranker,
        # Sized from the SAME derived value as the store's query pool above:
        # a slot and a connection must be 1:1, or a checked-out search waits
        # on a connection that no thread is holding, or vice versa (ADR-84).
        search_gate=SearchGate(query_connections, query_queue_depth),
        rerank_candidates=cfg.reranker.candidates,
        embed_batch_size=cfg.embedder.batch_size,
        structural=cfg.structural,
        git_fast_path=cfg.git.fast_path,
        indexing=cfg.indexing,
        config_device_pin=cfg.embedder.device,
        config_reranker_device_pin=cfg.reranker.device,
    )

    async def _warm_up_embedder() -> None:
        # ADR-77 (issue #47): not awaited here — this coroutine runs as a
        # background task instead, so a multi-minute cold download overlaps
        # the agent's own setup time rather than delaying the
        # FastMCP/FastAPI lifespan, which must finish before the server
        # answers `initialize` (blocking it here would look like a server
        # that failed to start). Both transports share this function, since
        # both share build_runtime_context.
        try:
            await ctx.embedder.preload()
            log.info("embedder warm-up complete")
        except Exception:
            log.exception(
                "embedder warm-up failed — will load lazily on first use instead"
            )

    ctx.embedder_warmup = asyncio.create_task(_warm_up_embedder())

    async def _warm_up_reranker(model: LocalCrossEncoderReranker) -> None:
        # Issue #52: ADR-77's argument applies unchanged to the reranker, only
        # more so — its weights are ~2.3 GB against the embedder's ~550 MB
        # (measured off a real HF cache: 2,271,071,852 and 546,938,168 bytes;
        # decimal GB/MB, the convention download sizes are quoted in), and
        # with `reranker.enabled=true` every search reranks by default
        # (ADR-34), so the first search pays that load in full.
        #
        # Queued BEHIND the embedder's warm-up rather than beside it: the
        # embedder gates every search, the reranker only scores hits a search
        # already produced, so two concurrent cold loads would slow the one
        # that is actually on the critical path (and, on a small GPU, contend
        # for the memory both are claiming). This is a trade, not a free
        # lunch: it delays reranker readiness by whatever is left of the
        # embedder's load, so a first reranked search arriving in that window
        # waits longer than it would have with both loading at once. That is
        # the cost we choose — a slow first SEARCH is worse than a slow first
        # RERANK, and the reranker is the optional half.
        #
        # `asyncio.wait` rather than `await task`: it waits for completion
        # without adopting the other task's outcome, so a warm-up that failed
        # (it logs and swallows its own errors) still lets this one run, and
        # cancelling THIS task at teardown does not reach in and cancel the
        # embedder's. A CancelledError delivered here propagates on purpose.
        if ctx.embedder_warmup is not None:
            await asyncio.wait([ctx.embedder_warmup])
        try:
            await model.preload()
            log.info("reranker warm-up complete")
        except Exception:
            log.exception(
                "reranker warm-up failed — will load lazily on first use instead"
            )

    # Nothing to warm when the kill switch is off, and nothing left to warm
    # when `reranker.preload=true` already awaited the load above. The model
    # is passed in rather than closed over so its type is the concrete
    # reranker, not the `| None` the enclosing scope carries — the guard
    # below is what makes it non-None, and a type checker cannot see that
    # through a closure.
    if reranker is not None and not cfg.reranker.preload:
        ctx.reranker_warmup = asyncio.create_task(_warm_up_reranker(reranker))
    log.info("runtime ready")
    return ctx

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
async def close_runtime_context(ctx: AppContext) -> None:
    """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."""
    import logging

    log = logging.getLogger(__name__)
    tasks = [t for t in ctx.jobs.values() if not t.done()]
    for warmup in (ctx.embedder_warmup, ctx.reranker_warmup, ctx.prefetch_task):
        if warmup is not None and not warmup.done():
            tasks.append(warmup)
    for task in tasks:
        task.cancel()
    if tasks:
        await asyncio.gather(*tasks, return_exceptions=True)
    # search_gate first: it may still be running a search that holds one of
    # the store's query connections, and closing the store under it would
    # pull the connection out from beneath an in-flight call.
    for resource in (ctx.search_gate, ctx.embedder, ctx.reranker, ctx.store):
        close = getattr(resource, "close", None)
        if close is not None:
            # Each close() joins a worker thread with a 5s bound. Bounded is
            # not the same as free: run it off the loop, or teardown blocks
            # every other task (including the MCP session manager's own
            # shutdown in the combined lifespan) for up to 5s per resource.
            try:
                await asyncio.to_thread(close)
            except Exception:
                log.exception("error closing %r during teardown", resource)
    # Same reason, and it must happen here rather than at process exit: the
    # writer holds its own handle to the state DB, which would otherwise
    # outlive ctx.conn and survive a DB-file removal. Scoped to this context's
    # own writer (ADR-59) — it was process-wide, so a second live context's
    # teardown used to discard rows this one had just enqueued.
    await asyncio.to_thread(ctx.telemetry.close)
    ctx.conn.close()

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
def default_fastembed_cache() -> str:
    """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."""
    base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
    return str(Path(base).expanduser() / "noesis" / "fastembed")

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.json alone reported ready after a download interrupted between metadata and weights (ADR-79).
  • tokenizer — a file carrying an actual VOCABULARY, taken from each family's own vocab_files_names rather than guessed: a fast tokenizer's tokenizer.json; sentencepiece's sentencepiece.bpe.model (XLM-R), spiece.model (T5/ALBERT) or tokenizer.model (Llama); wordpiece's vocab.txt; or byte-level BPE's vocab.json AND merges.txt, which is the one family whose vocabulary is two files (GPT2Tokenizer declares both) and so is the one entry checked as a pair. Deliberately NOT tokenizer_config.json or special_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 only config.json + model.safetensors left in a real BAAI/bge-reranker-v2-m3 cache and HF_HUB_OFFLINE=1, CrossEncoder(...) did not raise — it built an XLMRobertaTokenizer with vocab_size 5 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
def model_assets_ready(model_id: str) -> bool:
    """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.json`` alone reported ``ready`` after a
      download interrupted between metadata and weights (ADR-79).
    * tokenizer — a file carrying an actual VOCABULARY, taken from each
      family's own ``vocab_files_names`` rather than guessed: a fast
      tokenizer's ``tokenizer.json``; sentencepiece's ``sentencepiece.bpe.model``
      (XLM-R), ``spiece.model`` (T5/ALBERT) or ``tokenizer.model`` (Llama);
      wordpiece's ``vocab.txt``; or byte-level BPE's ``vocab.json`` AND
      ``merges.txt``, which is the one family whose vocabulary is two files
      (``GPT2Tokenizer`` declares both) and so is the one entry checked as a
      pair. Deliberately NOT ``tokenizer_config.json`` or
      ``special_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 only
      ``config.json`` + ``model.safetensors`` left in a real
      ``BAAI/bge-reranker-v2-m3`` cache and ``HF_HUB_OFFLINE=1``,
      ``CrossEncoder(...)`` did not raise — it built an ``XLMRobertaTokenizer``
      with ``vocab_size`` 5 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."""
    from huggingface_hub import try_to_load_from_cache
    from huggingface_hub.errors import HFValidationError

    def cached(filename: str) -> bool:
        return isinstance(try_to_load_from_cache(model_id, filename), str)

    # ``[embedder] model`` (and ``[reranker] model``) is free text, and
    # sentence-transformers accepts a local directory as readily as a hub repo
    # id. The filesystem is asked FIRST because that is what the loader itself
    # does: with an incomplete ``./BAAI/bge-reranker-v2-m3/`` in the working
    # directory beside a fully cached copy of that hub repo, ``CrossEncoder``
    # failed on the LOCAL one (measured) — the directory wins.
    #
    # Ordering by the exception instead was wrong for a whole class of pins:
    # ``models/bge-reranker`` is a valid hub repo id AND a relative directory,
    # so it never reached the fallback and answered "missing" forever while the
    # model loaded fine from disk — which, now that a missing reranker exits 1
    # from the plugin healthcheck, is a permanent red whose remedy (run
    # prefetch) can never clear it (issue #52 review round 8).
    #
    # Either way the CONTRACT is the same: config, weights and a vocabulary.
    # Only the lookup changes. An unparseable id that is also not a directory
    # falls through to "missing", the fail-safe direction ADR-79 chose: a false
    # "missing" costs a redundant prefetch, a false "ready" is the bug.
    # A blank pin is malformed, not "the current directory" — but
    # ``Path("").is_dir()`` IS True (it means cwd), and ``load_settings``
    # does not reject an empty ``[embedder]``/``[reranker] model``. Left
    # unguarded, a fresh install run from inside a model directory (or any
    # cwd that happens to hold matching filenames) reported "ready" for a pin
    # that was never actually set — probing the service's cwd instead of
    # answering "missing" (issue #52 review round 12). An empty repo id is
    # also rejected by ``huggingface_hub``'s own validation
    # (``HFValidationError``), so "missing" is the same verdict the hub-lookup
    # path below would give if this didn't intercept first.
    if isinstance(model_id, str) and not model_id.strip():
        return False
    try:
        # The LITERAL string, deliberately not ``expanduser()``'d: the loaders
        # test the pin as written, so ``CrossEncoder("~/models/m")`` raises
        # ``FileNotFoundError: Path ~/models/m not found`` even when that
        # directory exists and is complete (measured). Expanding here reported
        # "ready" for a pin that cannot load — a false READY, the one direction
        # this check must never get wrong (issue #52 review round 11).
        directory = Path(model_id)
        if directory.is_dir():
            return _has_required_files(lambda name: (directory / name).is_file())
    except (OSError, TypeError):
        # The pin is unusable, not merely absent: a segment past NAME_MAX
        # raises OSError(ENAMETOOLONG) from is_dir, and a non-string pin
        # (`[embedder] model = 123`, which load_settings does not type-check)
        # raises TypeError from Path() itself — neither of which pathlib
        # swallows. (RuntimeError sat here for `~nosuchuser/...`, which
        # expanduser raised; dropping the expansion dropped that source with
        # it — such a pin is now simply not a directory.) Escaping here means
        # /healthz, GET /projects/{id}/status and get_index_status all 500 on a
        # typo'd pin, which is the failure ADR-79's guard exists to prevent
        # (issue #52 review round 9). "missing" is the answer: nothing readable
        # is there, and no hub id can be built from it either.
        return False
    try:
        return _has_required_files(cached)
    except HFValidationError:
        return False

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
async def model_readiness(model: object) -> tuple[str, bool | str]:
    """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)."""
    ready = await asyncio.to_thread(model_assets_ready, model.model_id)
    assets = "ready" if ready else "missing"
    resolved_device = getattr(model, "resolved_device", "n/a")
    model_ready = "n/a" if resolved_device == "n/a" else bool(resolved_device)
    return assets, model_ready

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
async def reranker_readiness(reranker: object | None) -> tuple[str, bool | str]:
    """``(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."""
    if reranker is UNKNOWN_RERANKER:
        return "unknown", "unknown"
    if reranker is None:
        return "disabled", "disabled"
    return await model_readiness(reranker)

prefetch_grammars()

Source code in src/noesis/prefetch.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def prefetch_grammars() -> list[str]:
    from tree_sitter_language_pack import get_parser

    from noesis.core.languages import EXT_TO_LANGUAGE

    failed: list[str] = []
    for language in sorted(set(EXT_TO_LANGUAGE.values())):
        try:
            get_parser(language)  # type: ignore[arg-type]
            print(f"grammar ok: {language}")
        except Exception as exc:
            # Missing grammar is degraded (line-chunk fallback), not fatal.
            print(f"grammar FAILED: {language}: {exc}", file=sys.stderr)
            failed.append(language)
    return failed

prefetch_model(model_id)

Source code in src/noesis/prefetch.py
294
295
296
297
298
299
300
301
302
303
304
def prefetch_model(model_id: str) -> None:
    # Through the Embedder boundary — rule 1 forbids importing
    # sentence_transformers anywhere else; one embed forces the weight
    # download inside LocalSTEmbedder's worker.
    import asyncio

    from noesis.core.embedder import LocalSTEmbedder

    embedder = LocalSTEmbedder(model_id=model_id)
    vector = asyncio.run(embedder.embed_query("prefetch"))
    print(f"model ok: {model_id} (dim {len(vector)})")

prefetch_reranker(model_id)

Source code in src/noesis/prefetch.py
307
308
309
310
311
312
313
314
315
316
317
318
def prefetch_reranker(model_id: str) -> None:
    # Through the Reranker boundary — rule 1 (as amended by ADR-33) allows
    # sentence_transformers only in the two model-loading modules; a preload
    # forces the weight download inside the reranker's worker.
    import asyncio

    from noesis.core.reranker import LocalCrossEncoderReranker

    reranker = LocalCrossEncoderReranker(model_id=model_id)
    asyncio.run(reranker.preload())
    reranker.close()
    print(f"reranker ok: {model_id}")

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
def prefetch_bm25() -> None:
    # Through the same client-side inference path the vector store uses at
    # runtime, so exactly the assets qdrant-client will look for get cached.
    from qdrant_client import QdrantClient, models

    from noesis.core.vectorstore import BM25_MODEL_ID

    client = QdrantClient(":memory:")
    client.create_collection(
        "prefetch_probe",
        vectors_config={},
        sparse_vectors_config={"bm25": models.SparseVectorParams()},
    )
    client.upsert(
        "prefetch_probe",
        points=[
            models.PointStruct(
                id=1,
                vector={"bm25": models.Document(text="prefetch", model=BM25_MODEL_ID)},
            )
        ],
    )
    print(f"bm25 ok: {BM25_MODEL_ID}")

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
def configured_model_ids() -> tuple[str, str] | None:
    """``(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."""
    from noesis.core.config import load_settings

    try:
        cfg = load_settings()
    except Exception as exc:  # noqa: BLE001 — any config error, same answer
        print(f"could not read config: {exc}", file=sys.stderr)
        return None
    return cfg.embedder.model, cfg.reranker.model

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
def job_status(ctx: Any) -> dict[str, Any]:
    """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."""
    job = getattr(ctx, "prefetch_job", None)
    if job is None:
        return {
            "status": "idle",
            "started_at": None,
            "finished_at": None,
            "error": None,
            "percent": None,
            "steps": _idle_steps(),
        }
    steps = {name: dict(job["steps"][name]) for name in PREFETCH_STEPS}
    percent = None
    if job["status"] != "running":
        applicable = [s for s in steps.values() if s["status"] != "skipped"]
        if applicable:
            done = sum(1 for s in applicable if s["status"] == "done")
            percent = round(done / len(applicable) * 100.0, 1)
    return {
        "status": job["status"],
        "started_at": job["started_at"],
        "finished_at": job["finished_at"],
        "error": job["error"],
        "percent": percent,
        "steps": steps,
    }

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
def start_job(ctx: Any) -> dict[str, Any]:
    """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."""
    existing = getattr(ctx, "prefetch_job", None)
    if existing is not None and existing["status"] == "running":
        return {"status": "already_running"}
    job: dict[str, Any] = {
        "status": "running",
        "started_at": datetime.now(timezone.utc).isoformat(),
        "finished_at": None,
        "error": None,
        "steps": _idle_steps(),
    }
    ctx.prefetch_job = job
    # Reference retained on ctx (not just fired-and-forgotten): an
    # unreferenced asyncio.Task can be garbage-collected mid-flight, and
    # close_runtime_context needs it to cancel/await this job at teardown
    # like the embedder/reranker warm-ups (runtime.py).
    ctx.prefetch_task = asyncio.create_task(_run_job(ctx, job))
    return {"status": "accepted"}

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
def main() -> int:
    os.environ.setdefault(FASTEMBED_CACHE_ENV, default_fastembed_cache())
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--skip-model", action="store_true", help="grammars only, no model weights"
    )
    parser.add_argument(
        "--model",
        default=None,
        help="embedding model to fetch (default: whatever config.toml names)",
    )
    parser.add_argument(
        "--skip-reranker",
        action="store_true",
        help="skip the ~2.3 GB reranker weights (only needed if reranker.enabled)",
    )
    parser.add_argument(
        "--reranker-model",
        default=None,
        help="reranker model to fetch (default: whatever config.toml names)",
    )
    args = parser.parse_args()

    # Resolved AFTER parsing, and only when a step actually needs an id: the
    # config was read before argparse ran, so `--help` printed a config-parse
    # error above the usage text, and `--skip-model` complained about a file it
    # was never going to consult (issue #52 review round 6). `None` survives
    # here when the config cannot be read, and the steps below skip.
    wants_embedder = not args.skip_model and args.model is None
    wants_reranker = (
        not (args.skip_model or args.skip_reranker) and args.reranker_model is None
    )
    if wants_embedder or wants_reranker:
        configured = configured_model_ids()
        if configured is not None:
            if args.model is None:
                args.model = configured[0]
            if args.reranker_model is None:
                args.reranker_model = configured[1]

    failed = prefetch_grammars()
    prefetch_bm25()
    # An unresolved model id means the config did not parse and no flag named
    # one. Skipping is the point (see configured_model_ids), but it is a
    # non-zero exit: the prefetch did not do the job it was asked to do, and a
    # CI step or an install script must not read that as success.
    unresolved: list[str] = []
    if not args.skip_model:
        if args.model is None:
            unresolved.append("--model")
        else:
            prefetch_model(args.model)
    if not (args.skip_model or args.skip_reranker):
        if args.reranker_model is None:
            unresolved.append("--reranker-model")
        else:
            prefetch_reranker(args.reranker_model)
    if failed:
        print(f"{len(failed)} grammar(s) failed: {', '.join(failed)}", file=sys.stderr)
    if unresolved:
        print(
            "skipped model weights: the config could not be read, so the model "
            f"ids are unknown — fix config.toml, or pass {' and '.join(unresolved)}",
            file=sys.stderr,
        )
    if failed or unresolved:
        return 1
    print("prefetch complete")
    return 0

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
def configure_logging(propagate: bool = True) -> logging.Logger:
    """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.
    """
    logger = logging.getLogger(LOGGER_NAME)
    logger.setLevel(_resolve_level(os.environ.get(LEVEL_ENV)))
    # Set on every call, before the idempotent early-return, so a later
    # configure_logging(propagate=False) can still flip an already-configured
    # logger (the stdio entry point runs after app import may have configured
    # it with the default True).
    logger.propagate = propagate
    formatter = _make_formatter()

    for handler in logger.handlers:
        if getattr(handler, "_noesis_tag", None) == _HANDLER_TAG:
            handler.setFormatter(formatter)  # env may have changed (tests)
            return logger

    handler = logging.StreamHandler(sys.stderr)
    handler._noesis_tag = _HANDLER_TAG  # type: ignore[attr-defined]
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger