Commit Graph
9 Commits
Author SHA1 Message Date
Iswarya AlexandClaude b771b4fcc6 RAI 1.9.0 Upgrade (#4188)
* Move ryzenai-llm to ryzenai-server v1.9.0

- Pin ryzenai-llm npu to v1.9.0
- Rebuild the NPU catalog from the 42 amd/*_rai_1.9.0_npu checkpoints
- Drop 12 NPU models with no RAI 1.9 build
- Update the custom-model placeholder checkpoint

* Drop ryzenai-1.7 hybrid models; test hybrid suite on a 1.9 NPU model

* RAI 1.9: NPU-only catalog matching the 1.9.0 collection; test ryzenai on npu only

* test: use a Qwen NPU model for ryzenai tool-call tests

* test(ryzenai): add image/audio tests, fix tool-call failure message, shared media helpers

- Extract _solid_color_png_data_uri into test/utils/media.py so omni and
  llm tests share one copy
- Add test_013b/c/d for image input, streaming image input, and audio
  input (skipped when the backend lacks image_input/audio_input support)
- Register Gemma-4-E2B-it-NPU as the multimodal test model for ryzenai
- tool_calls assertion now prints model content on failure so the next
  flake explains itself

Co-Authored-By: Claude <[email protected]>

* chore: pin ryzenai-server v1.9.0 zip sha256

Co-Authored-By: Claude <[email protected]>

* fix(ryzenai): switch tool-call test model to Llama-3.2-1B-Instruct-NPU

Qwen2.5-3B 1.9 NPU checkpoint produces garbage output after the first
token on STX Halo runners. Llama-3.2-1B-Instruct decodes cleanly and
ryzenai-server now parses its bare-JSON tool-call format.

Co-Authored-By: Claude <[email protected]>

* chore: add hot label to Gemma-4-E4B-it-NPU; remove stale comment

Co-Authored-By: Claude <[email protected]>

* refactor: revert out-of-scope test changes from 1.9 upgrade branch

Remove image/audio tests from server_llm.py — the ryzenai backend does
not declare image_input/audio_input support so they never ran.
Restore server_omni.py to main (PNG helper refactor was unrelated).
Remove dead capabilities.py multimodal model entry.

Co-Authored-By: Claude <[email protected]>

* chore: update ryzenai-server v1.9.0 zip sha256

Rebuilt from 8008518 (Llama 3.2 tool-call parser).

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
2026-11-18 17:07:53 +00:00
Satya Devineni d397a6e8fa Add SystemOne decision models: /v1/systemone, GGUF zero-shot on /v1/classify, and the systemone router classifier (#3956)
* main into zero shot, post refactoring

* cleanup

* cleanup

* CR feedback: fixed the residency document clarification bug

* cr feedback: fake tests with propoer assertions

* stacks on the zero shot work in 3952

* pr feedback: better policy checks and logging for backend failures

* pr feedback: adding on_truncation

* pr feedback: adding the truncation support for classifier and fixing documentation issues

* CI fix and doc enhancement

* pr feedback: fixed edge cases

* added check for 0.3.7 truncated verification

* pr feedback: router validation and argument handling

* Added the example lfm2 ONNX model

* pr feedback: added max-length and 3 flag truncate flags

* pin bump to 0.4.0 and more tests for zero-shot

* CI fix

* pr feedback: model level filtering

* PR Feedback: CR feedback

* restricting decision models based on model family. 8k context limit by default for encoder decision models

* checks at router level to reject wrongly labeled systemone models with 400

* pr feedback: default set to 4k, limits passed down by llama-server, truncated  is added to systemone

* truncated documentation

* pr feedback: checks the token count instead of the template
2026-11-04 05:34:34 +00:00
Satya Devineni f9004ca0a8 Adding zero-shot classifier support (#3952)
* main into zero shot, post refactoring

* cleanup

* cleanup

* CR feedback: fixed the residency document clarification bug

* cr feedback: fake tests with propoer assertions

* pr feedback: better policy checks and logging for backend failures

* pr feedback: adding on_truncation

* pr feedback: adding the truncation support for classifier and fixing documentation issues

* CI fix and doc enhancement

* pr feedback: fixed edge cases

* added check for 0.3.7 truncated verification

* Added the example lfm2 ONNX model

* pr feedback: added max-length and 3 flag truncate flags

* pin bump to 0.4.0 and more tests for zero-shot

* CI fix

* pr feedback: clarified on the PII detector
2026-10-29 17:21:53 +00:00
Michele Balistreriandfl0rianr fb8935641c Model Manager refactoring (#3828)
* draft model manager refactoring

* draft model management spec

* address review comments

* remove eol

* remove some non-relevant comments

* step 0: tests

* step 1: move recipe option store

* step 2: locator

* step 3: artifact transfer

* step 4a: store_builder

* step 4b: store_snapshot

* step 4c: catalog

* step 5: change notifier, generation on the snapshot

- ModelChangeNotifier with two signals and one subscriber each; ModelManager
  owns it and Server registers both routing subscribers on it
- StoreSnapshot::helper_models computed at publish by collect_helper_models();
  Server::active_policy_helper_models() and the startup seed block are gone
- notify_models_changed fires the snapshot generation; notify_generation_ and
  next_notify_generation() deleted
- fix: build_cache no longer mints a generation on a read that changes nothing,
  which had made generation-based coalescing impossible
- fix: set_model_update_available_for_test wrote the cache without publishing
- test_change_notifier: 16 checks, CI ON

* step 6a: RegistryId and the registry descriptor table

- RegistryId (string, no enum) plus RegistryDescriptor holding the per-host
  spellings, display name, scheme prefix, cache-dir prefix and default revision
- model_registry.cpp vocabulary and cache-dir naming read the table; the enum
  no longer carries facts of its own
- registry_id_from() yields nullopt for an unknown host, the primitive behind
  the spec's warn-and-skip delta (not wired to the load path yet)
- fix: descriptor_for() returned a pointer into a by-value vector
- registry_id.cpp compiled into the CLI as well; it does not link core
- test_registry_identity: 18 checks, CI ON

* step 6b: remove RemoteRegistrySource; registries are strings

- model_registry.h exposes models::RegistryId; the enum is deleted
- function names unchanged, only the carried type: parse/name/display/scheme/
  is_remote/detect_url/search/cache_dir_name/model_registry/ModelRegistry::source
- require_descriptor() throws when a caller invents an id
- test/app/app-regression/registrySearch.test.cjs slices model_registry.cpp by
  literal text; updated to match, and added to the standing gate list
- Locator now carries optional<RegistryId>

* test: pin the unknown-registry load-path delta

A persisted entry naming an unregistered host warns naming model and id,
contributes no entry, and leaves the rest of the catalog loading. That is
already the behavior via parse_model_source_fields throwing inside the
per-entry catch in build_cache; this pins it so a later step cannot regress it.

Test-only: ctest 81/81, app regression 136/136.

* step 6c': backends stop naming hosts

6b renamed the hf/modelscope dichotomy instead of removing it. Backends may
handle a source differently, but not by splitting the world in two hosts.

- vLLM quant probe: the identity test became an endpoint fact, the URL is built
  from the descriptor, and the hand-rolled "models--" + $HOME cache naming uses
  hf_cache::repo_id_to_cache_dir_name() + get_hf_cache_dir(). Passing the repo id
  rather than the raw checkpoint also fixes a latent miss for repo:variant ids.
- RegistryDescriptor gains endpoint_default; empty for ModelScope, which serves
  files through its API, preserving today's never-fetch behavior.
- FLM no longer guesses Hugging Face when the model manager is absent; both sites
  throw, as vLLM already did.
- dropped two unused default args that asserted a host.

Remaining sites for step 7 (vllm snapshot branch, flm --modelscope argv, whisper
resolve URL) need a port fact and are recorded in the plan.

Gates: ctest 81/81, cli2 73 OK, endpoints 171 OK, llm/vulkan 31 OK.

* step 6c: ArtifactSource, FetchableRepository, registration macro

- ArtifactRef names a checkpoint; from_locator carries the path for bytes that
  came from no host, so two files never share a ref
- ArtifactSource answers resolve/present/acquisition/deletion for one checkpoint
- FetchableRepository layers the pullable role on it; the whole interface is
  implementable from the value types alone
- LEMONADE_REGISTER_ARTIFACT_REPOSITORY is now the single writer of the
  descriptor table: seeded deque (pointer stability, not vector), replace on same
  id, first factory kept with duplicate claims reported rather than link-ordered
- RepositoryDescriptor and descriptor() deliberately absent; the spec lets step 12
  add them with a default

test/cpp/test_artifact_source.cpp, CI ON, 20 checks, mutation-checked twice.

Gates: ctest 82/82, app regression 136/136, cli2 73 OK, endpoints 171 OK,
llm/vulkan 31 OK.

* step 7a: artifact_resolver

* step 7b: fetchable_repository

* step 13: scancatalog

* step 7c: artifact_resolver

* move npu download

* step 7f: vllm/flm download

* reduce comment slop

* step 14: ListedCatalog per provider, and locality leaves the design

Cloud listing becomes one catalog per installed provider, so an
unreachable provider costs only its own entries.
CloudServer::discover_provider_models() owns the credential and
plaintext-endpoint guards for every caller of a listing, which deletes
the duplicated guard block in refresh_cloud_models() and orphans
CloudOps::discover_models().

CatalogDescriptor replaces the id()/required() overrides and carries
{id, required} only. Locality is deleted from the design rather than
introduced: every minter already distinguishes itself in the name it
emits (provider id leading a listing name, -FLM for discovery, the
parent-directory qualifier for the scan), nothing splits a name on '.',
and no persisted format ever carried a middle segment. Registering
user.<provider>.NAME is therefore settled by precedence, documented,
not by a vocabulary guard. The startup duplicate-claim check goes with
it: with no minter minting a locality it could only fire on a false
positive, and its remedy was to drop a provider's whole model set.

Gates: ctest 86/86, app regression 136/136, cli2 73 OK/2 skip,
endpoints 171 OK/3 skip (mock-provider cases ran), llm/vulkan 31 OK/2 skip.

* step 15: json_catalog

* step 15b:  registry documents

* cleanup

* step 8a: update scan

* step 8b: model sync

* fix ci tests

* step 9a: delete plan

* 9b: artifact store

* 9c: download policy

* 9d: npu_cache

* 9e: ingest

* 16: labels

* merge fix

* step 17-i: delete shards

* step 17-ii: fix and enable tests

* step 10a-b: alias manager + resolve()

* step 10c: every surface resolves through the manager.

* step 10d: fixes

* step 11: ModelManagerConfig

* step 12a: docs

* step 12b: model catalogs

* step 18a: start build cache work

* step 18b: catalogsetdeps

* step 19: catalog_locator

* step 19b: http catalog locator

* step 19c: configurable model catalogs

* step 20a: read capability hints only from the keys that carry them

* step 20b: a rebuild stops re-fetching a catalog it just read

* step 20c: a fetched catalog has a size limit and its cache an owner

* step 21a: a read stops taking the model store lock

* step 21b: the store lock covers the commit, not the composition

* step 21b-i: a commit stops walking the filesystem

* step 21c-i: publishing derives the name tables

* step 21c-ii: a write seeds a draft and the publish moves it out

* step 22: a filter test states the machine it means

* step 23: the update flag a scan publishes gets a gate

* step 26+27: the machine probe and the name tables leave the facade

* remove excessive comment

* step 28: modelstore

* step 29: CloudRows

* step 30: move build_cache

* step 31: store patches

* step 31 followup

* port PR #3882

* probes

* P0: the facade-shape gate reads both include spellings and one-way budgets

* P1: the dependency graph points one way

Every file under src/cpp/server/models/ included the facade header, so the
DAG read bottom-up: the layer existed in directories but not in reality. The
reason was structural. ModelInfo — the value object that crosses the whole
server by value — lived in the facade header, so anything that took a
ModelInfo had to name the orchestrator to spell its arguments.

ModelInfo, ModelFileInfo, and GgufMetadata move to models/model_info.h;
UnknownModelError and InvalidModelDefinitionError move to
models/model_errors.h. The facade now includes the leaves, never the other
way: the ratchet pins the models layer's facade-header count at zero, and
the include-graph grep confirms it. Consumers of the moved types got the
explicit include they were borrowing through the facade, including auto_tune.h,
which named no model header at all and worked by accident.

The same inversion hid inside ArtifactRef. A ref is an address — repo,
revision, variant — and two refs that compare equal name the same bytes; but
it also carried `const ArtifactLayout* layout` and a sibling path, so the
resolver had to mutate the address before handing it to a repository, and
placement — which is a property of where the bytes land — became part of what
an address is. Placement moves out: the resolver answers a SourcePlacement
beside the ref, create_repository takes it, FetchableRepository holds it,
and ArtifactRef is back to a value that can travel alone. The
sibling-layout tests now assert the binding where it lives, on the source.

Three headers are public, and the spec's Source Layout section says so:
model_manager.h (behavior), model_info.h (the value object), store_snapshot.h
(the read-only set a consumer holds). A fourth consumer, server.cpp, reads only
the snapshot, so it left the escape whitelist; auto_tune.h joins the sanctioned
side by naming model_info.h. The line budget travels 1103 -> 1105 for the two
includes model_manager.cpp took on to stop borrowing them transitively.

Gate: cpp-ci 114/114; endpoints 178 OK / 3 skip; llm/vulkan 31 OK / 2 skip;
whisper 12 OK / 2 skip; cli2 73 OK / 2 skip; app 136. Mutation-checked: the
facade-header ratchet at zero, a private models header reaching a consumer in
both include spellings, a sanctioned include passing unflagged, and a retired
whitelist name demanding deletion.

* P2a: the token stops bytes, and credentials stay on their origin

Cancellation had no parameter. A download noticed a cancel only when a
progress report happened to return false, so a stalled transfer with no bytes
and no reports could not be cancelled at all, and every caller that wanted to
stop one had to smuggle the request through the reporting channel.
utils::RequestCancelToken already existed for inference; it lived in
utils/http_client.h, out of reach of a transfer seam that must not know about
HTTP. The token moves to its own leaf, utils/cancel_token.h, as
utils::CancelToken — the same currency for inference and for model transfers —
and download_file, download_attempt, ArtifactTransfer::execute and
FileTransfer::transfer all take it. ByteProgress returns void: it reports
bytes, nothing else. A DownloadProgressCallback that returns false now closes
the update channel instead of secretly cancelling, and the only message that
stops a plan is the token, checked before each file and on every curl tick.

The second owed defect was credential scope. Rule 2 of Transfer And Layout
says a repository's auth_headers() travel only while the origin still matches
the origin that minted them, at every hop. libcurl re-sends custom headers to
any host a Location names, so the download no longer lets libcurl follow: it
walks the hops one request at a time, drops the header list at a cross-origin
boundary and never restores it, enforces the policy's scheme set on every
target itself, and refuses a 3xx body into the partial file. Production
behavior is unchanged — ExternalHttpsOnly is still the default policy — and
HttpFileTransfer gained the policy seam the fixture has been asking for in a
comment since it was written.

The token is wired where cancels are born: the download job hands the worker a
flag its cancel endpoints set, so a cancel stops bytes on the next socket tick
rather than at the next progress report; the legacy streaming path answers from
socket death; the pull chain carries it from the facade through ingest and the
BackendOpsContext down to the transfer.

Gate: cpp-ci 115/115 including the new FileTransferTest (the spec's
test_file_transfer, 21 checks over two loopback origins: credential kept
direct and on a same-origin redirect, stripped cross-origin, never restored
after a strip, disallowed redirect scheme refused before bytes, one mixed
scheme plan one progress total, a file://-only plan, mid-transfer cancel with
the partial preserved); endpoints 178 OK / 3 skip; llm/vulkan 31 OK / 2 skip;
whisper 12 OK / 2 skip; cli2 73 OK / 2 skip; app 136; a real 174 MB Hugging
Face pull in 3.2 s through the manual-hop engine. Mutations by exit code:
token check removed, cancel dies mid-transfer; strip disabled, the cross-origin
check fails; strip unconditional, the same-origin check fails; progress-false
made cancel again, the mute test dies. M1 is what surfaced the redundancy the
mutation was meant to prove: two channels watched the token in the tick; the
wrapper's copy is gone and the HTTP client's is the one place. Restores
verified, grep MUT zero.

* P2b: the main pull plans through the repository seam

Every checkpoint of a pull is an ArtifactRef bound to one FetchableRepository;
the file set is registry_download_plan's, auth headers come from the source, and
no ModelRegistry survives in the download path. The reuse merge, manifest,
pinning and provenance stay where the spec puts them.

test_pull_registry drives the whole ModelManager against scripted sources:
exact URL plan, snapshot placement, pins, manifest lifecycle, refusal words,
and a pre-set cancel token that leaves no artifact.

Facade ceiling 1106 -> 1107 for the repository_for wiring line.

* P2c: the update scan asks sources, not registries

Each (source, repository) group opens a FetchableRepository, honors
can_go_stale() before opening its mouth, lists latest and previous through
list(), and takes its headers from the source. registry_for and its legacy
ModelRegistry& are gone from UpdateScanDeps and the facade config; the
artifact-aware refinement stays in registry_files, composed as before.

test_update_available ports to StubRepository and gains three checks for the
frozen-source rule: never listed, reports nothing, moves no flag.

Facade unchanged at 1107 lines.

* P2d: the registry class lives with its adapters, nowhere else

model_registry.h moved out of the public include path into src/cpp/server/,
and only model_registry.cpp and models/registry_repository.cpp may name it --
the facade-shape gate now enforces that named set. Wire facts (file trees,
search rows, provider names, cache-dir naming) moved to
lemon/models/registry_types.h, a public leaf: they persist on disk, so their
shape is public by design. RepoListing carries the host's raw_metadata.

Search became a source answer: FetchableRepository::search with the
supports_search() gate, exposed through ModelManager::search_registry so the
API layer keeps talking to the facade. hf_variants reads variants through
create_repository.

Standing acceptance rule: store, sync, ingest, scan and the facade pair carry
zero provider string literals; only the adapter pair names the legacy header.
Both mutation-proven this phase.

Facade 1107 -> 1124 lines for search_registry.

* P3: provenance learns which checkpoint landed where

v1 files read forever, verbatim. A v2 write keeps the v1 sentence in the main
repository's file and adds checkpoints[type] = {selection, snapshot_id}; an
auxiliary repository -- which v1 refused to let speak at all -- now records
only its own checkpoint under version 2, so a shared side cache can name every
model that filled it without any of them claiming the whole.

The pull commit loop names the slot per repository. RegistryProvenanceTest
pins v1 read, v2 shapes, the shared aux file and moved-snapshot bookkeeping;
PullRegistryTest pins them after a real pull.

Mutation-proven: the v1 answer, the aux guard and the slot routing each have
a check that dies without them.

* F4 trim: a locator reads, it does not probe

CatalogLocator::changed() had no production caller -- invalidation is event
driven (watcher, settings write, ingest) and fetched bodies are windowed
(fresh_for plus conditional GET), so a standalone HEAD round trip was dead
weight with a live cost. It, both implementations, and HttpClient::head are
gone; the spec's staleness rows now describe what the read observes rather
than a probe nobody runs.

CatalogState stays: it is what read() hands back so the next read asks
conditionally. CatalogLocatorTest keeps the read-side truth, minus the probe.

* P4a: the store owns its build and its patches

ensure_current holds the compose retry loop -- the facade's build_cache is one
line now. StorePatches is gone: patch_download, patch_removed and patch_options
are ModelStore methods, the artifacts store arriving per call so the store
keeps no dependency of its own. The bodies moved verbatim; the tests moved
with them and lost nothing.

Facade 1124 -> 1097: the one-way ceiling pays a refund this phase.
Mutation-proven by test_compose_retry (attempts 1 -> both retry checks die).

* the repository seam is explained once, where it is filled in

Three structs restated which source answers for a checkpoint. ModelManagerConfig
is the origin -- ingest and update scan take it by assignment -- so it keeps the
explanation and the plumbed copies just point at it.

* callback bags shrink where the collaborator was restyled, not tested around

UpdateScanDeps stops restyling the artifact cache as three lambdas - the
disk baseline and the processed-snapshot fast path now read the
ModelArtifactStore itself, and the registry-source rule collapses to the
one free function that already owned it. ModelIngest drops its pin and
patch_downloaded wrappers and calls the registries and store it already
holds.

Read paths stop copying the world to answer one question: the facade
publishes snapshot(), and model_get, model suggestions on a miss, the
register echo, and the two MCP 'find a local model' walks read rows
instead of cloning maps. The echo regains an assertion in
test_000a, which the mutation check proved it needed.

* the facade declares no test hooks and holds no override members

The four hooks existed because substitutions had nowhere else to live.
They have somewhere else now:

- test_extra_model_discovery drives ScanCatalog directly; the device
  rule for the operator's directory moved onto the catalog itself.
- test_model_sync_and_auto_update drives SyncService with its own deps
  - canned scan, download recorder, phase bus - so the queue state
  machine is tested at the queue, not through eight ModelManagers with
  their real behavior patched out. The stale-flag case now proves the
  stronger thing: a set flag never downloads a model on its own when
  the fresh check fails.
- the phase callback and both override members are deleted with their
  setters; FacadeShapeTest's four-name whitelist becomes two zero
  assertions - no _for_test anywhere under src/cpp, no *_override_
  member in the facade header - and a probe hook planted in an
  unrelated product file trips the gate by name.

Facade: 1088 -> 1076 lines; header sheds 33.

* options are a read and a write, named as the spec names them

The facade spoke about options in six verbs; the spec knows two. GET,
POST dry-run, DELETE, the load-time save and the load-time tombstone
layer now share one read - options(name[, changes]) returns the entry,
the layering beneath it, and what changes would resolve to - and two
writes: set_options merges, replace_options replaces. preview_saved was
the clearest smell: what-a-write-would-produce is a read, so it lives
in the read.

FacadeShape grows honest ceilings: facade lines 1082, header method
declarations 71, members 15 - all one-way, so shrinking owes no edit
and growing names itself. The counters earn their numbers: planted
declarations and members are counted and refused.

* the facade locks twice and waits never

Both direct locks are the options file's write ordering, documented
where they sit; publishing has exactly one road, StoreWrite. Ratcheted
so a third lock has to argue for itself.

* check_updates and sync_status, the names the spec uses

Two renames onto the facade surface the spec already spells; nothing
else moved. Live proof: update-models --check and the update/sync
endpoints pass against a fresh server.

* checkpoint_status[] on the wire, and the spec says what the code does

Every checkpoint of every listed model now answers for itself - type,
present, required, registry, path - from the same ArtifactSources a pull
would open. Building that read exposed a real seam gap: source_for
never threaded ModelManagerConfig.repository_for, so a fixture host was
obeyed by pull and scan but bypassed by status; it now reaches every
consumer, and test_pull_registry pins the whole answer, honest scripted
presence included.

The wire contract earns its pins: /v1/models rows carry a present,
required, path-bearing main entry for a downloaded model and a boolean
update_available; docs/api shows both fields with their entries; the
app refuses to export checkpoint_status into a portable file, because
its paths belong to one machine.

Spec reconciliation, the CODE->SPEC list closed: the facade section
describes the shipped surface - snapshot reads, the options read/write
pair, config-as-the-only-door with the zero-hook gate named - and says
outright there is no ModelView and no generated model-object pass, with
the drift guards that actually exist in its place. Source Layout lists
the four public models headers and the private registry header;
staleness item 5 reads as event-plus-window, CatalogLocator::changed()
dead; test_update_available names repository_for; ModelSyncServiceTest
is no longer an aspiration - the suite is renamed to it.

Facade ceiling 1109 with checkpoint_status; declaration ceiling 72.

* S1: the spec describes shipped code, not the design it preceded

docs/dev/specs/model-management.md had drifted from what the tree does in ten
places. Each was checked against the implementation before being rewritten:

- Catalogs are objects built per store build by `product_catalogs()`, not
  singletons; the six shipped ones are named with their rank, claim, and the
  three input shapes (pinned document, `CatalogLocator`, callable).
- Locators: `file_catalog_locator` and `http_catalog_locator` are the two that
  ship, with their read policy, cache pair (`<id>.json`, `<id>.json.validators`,
  body written first), and the 8 MB body cap. No resource locator: the built-in
  registry arrives already read via `RegistryDocuments`.
- Store: `resolve()` returns `ResolvedModel`; there is no `model_path()`, no
  `ModelView`. `StoreWrite` is the composition's write type; it is still public
  on the facade, which is recorded as a known gap rather than a rule.
- `checkpoint_status[]` reads presence from `ArtifactSource::present()`, so it
  can disagree with `downloaded` on an interrupted pull. Documented as shipped.
- SyncService is `src/cpp/server/models/sync_service.{h,cpp}` with the real
  enqueue/wait/cancel surface; `models_changed` carries a `reason` and a
  generation that changes on catalog mutations only.
- Docs section: the real descriptor structs (`RegistryDescriptor`, `DocEntry`,
  `CatalogDescriptor`), the real region markers and region names, and the
  host_specific rule that keeps a machine-dependent row out of a committed page.

Removed the probe-and-detector table row, which described a mechanism deleted
before this spec section was last touched.

No code changed; generators and cpp-ci are unaffected (119/119 re-verified).

* S2b: SyncService started its worker before stop_ existed, and no test had a bound

ModelSyncServiceTest hung often enough to be killed by hand. Tracing the
worker's transitions showed the cause in product code: sync_service.h declared
`std::thread worker_;` before `bool stop_ = false;`. Members initialize in
declaration order and constructing the thread starts it, so run_worker()'s
first act -- waiting on `stop_ || is_sync_running` -- read stop_ before its
initializer ran, with no synchronization. Memory that happens to read non-zero
makes the worker believe it was already asked to stop, so it returns at once:
the service is dead on arrival, is_sync_running stays true, and
wait_until_idle()/wait_for() block forever. That fits every observation --
intermittent, load-sensitive, and blocked at 0% CPU with every thread in
futex_wait.

Fix: move the stop flag into State, where it initializes with the rest of the
guarded state and lives under the mutex the worker waits on, and leave worker_
declared last so the invariant is visible at the declaration. Router and
JobManager use the same wait idiom in the correct order; SyncService was the
only instance. As a backstop, both waits now also wake when the worker has
exited and log a warning instead of waiting for a transition that can no longer
happen, so a future dead worker costs a wrong status rather than a hung request
thread.

test_model_sync_service.cpp also had a real use-after-free of its own: every
parking scenario declared the SyncService before the state the worker parked on,
so ~SyncService joined after those locals were freed, while bus.sink still
captured them by reference and was never cleared. One PhaseGate now owns the
park, is declared before the service, takes itself off the bus in its
destructor, and bounds both directions of the rendezvous, so a missed phase is a
named FAIL instead of a hang.

New regression test constructs 200 services in a row and requires each to run
its first generation within a deadline; forcing the worker to stop on entry
makes it fail on attempt 0 in all three runs.

Every test now carries a ctest TIMEOUT (default 120s, 300s for the two whose
runtime is defined by waiting on a timeout constant) so a stuck test is one red
line instead of an unattended run: 143 at 120s, 2 at 300s, measured against a
suite whose slowest test is 14s and 115 of 119 finish under 0.3s.

cpp-ci 119/119; 960 sync-test runs at 16-way concurrency with no stall and no
failure, against 5 stalls in the first 32 runs before the fix.

* S2: the shape gate now counts what it claims, and measures what was unmeasured

Four rules in test_facade_shape were reporting something other than the truth.

Members (G1): the count was lines ending `_;`, so `cloud_registry_ = nullptr;` and the
two-line `catalog_fetch_clock_ = std::make_shared<...>()` were invisible and a new member
written with an initializer would never trip the ceiling. Members are now counted by
declaration: comments stripped, statements split on `;`, class-body indentation, angle
depth tracked so `std::function<std::string()> x_;` is a member while `void f();` is not.
Honest count is 18 -- the review that opened this step said 17 and was itself one short,
missing `default_model_source_provider_`, whose type contains the `()` that hid it from the
grep the count was based on.

Substrings (G3): `find_in(file, "model_registry.h")` counted a sentence naming the header,
and an include someone commented out counted too. Includes are now parsed from lines whose
first non-blank character is `#`, over comment-stripped text.

Direct-only includes (G2): the escaping whitelist saw `#include <lemon/models/...>` but not
the relative spelling, and it missed the more serious fact that a whitelisted *header* hands
models types to everything that includes it. A new named set lists the headers allowed to
re-export the models layer -- five of them -- and a failure prints what each one drags in.
Whitelisting `backend_ops.h` for `ArtifactFetchService` really does reach every backend that
includes it, and that is now visible instead of implied.

Shrink-punishing ratchets (G4): every "at most" needle failed when the count went *down*
with "ceiling is stale", which is exactly the churn the refactor wants. They now fail only
over the ceiling and print a note asking for it to be tightened.

Three rules that did not exist, all needed by later steps: the facade header's reach
(29 product files, one-way -- three include spellings, and the bare `#include
"model_manager.h"` used by the backend tree accounts for 7 of them), `StoreWrite` confined
to the facade, and in-flight markers (`.download_manifest.json`, `.partial`) confined to the
eight files that can currently decide presence. That last one is the shape of D2/R1: presence
has two authorities today, and the list is what S5 has to shrink.

Eleven mutations, all as required. Two caught defects in the new code rather than confirming
the old: may_only_shrink reported "unexpected" and then still passed when every whitelisted
name happened to be present, and the member counter returned 1 until the statement splitter
was fixed. kRulesVersion prints with the results so a binary older than the tree is visible
in the output rather than inferred from an impossible failure.

cpp-ci 119/119.

* S2b: nothing any more stops a cpp test from dialing out or forking

The hermeticity audit came back clean -- no C++ test needs external HTTP or a
running lemond, so none was deleted -- and an audit is worth exactly as much as
the rule that keeps it true. Two checks, both seeded at the honest zero.

A non-loopback host *name* is not the thing to ban: test_model_registry.cpp,
test_cloud_provider_registry_config.cpp and test_config_default_source.cpp pass
huggingface.co, api.fireworks.ai and friends to pure functions to check URL
building and endpoint classification, and a blanket ban would tax the tests that
verify URL handling. The rule is a non-loopback host and a request on the same
line, over comment-stripped text.

Only the named test spawns a process, with test_process_manager.cpp on the list
because process management is its subject. A test that spawned lemond would also
make one test's server another test's interference: ctest runs these in parallel.

Three mutations: a real HttpClient against huggingface.co fails, the same line
commented out passes (so the rule reads code, not prose), and a popen added to
another test fails. The gate caught itself on the first run -- it holds the token
tables as data and matched its own patterns -- so it is excluded from the two
scans over test/cpp, which costs nothing since it neither dials out nor forks.

Why the count is zero is written in the gate's comment: every create_repository()
call in test/cpp stops at resolve()/acquisition(), a plan and a path with no
request, and test_update_available.cpp injects config.repository_for. A reader
can then tell a rule that holds from a rule nobody ever checked.

cpp-ci 119/119.

* S3: declaration order is initialization order, and the declaration ceiling was fiction

ModelManager declared registries_, recipe_options_, architecture_defaults_ above config_
while its init list wrote config_ first. Actual construction follows the declarations, so
alias_manager_(config_.cache_dir) ran after config_ only by luck of where the members
happened to sit: registries_ and recipe_options_ build from static helpers and read no
member. Give that file a member that reads config_ in its initializer, placed above
config_, and it reads an object that does not exist yet -- which is not a hypothetical, it
is how SyncService hung. Declarations now run config_, extra_models_dir_, alias_manager_,
registries_, recipe_options_, and the init list already matched.

Found by asking for -Wreorder explicitly, which the build never does: no -Wall anywhere,
so this defect class is invisible otherwise. The same warning fired on WrappedServer, whose
init list wrote last_backend_activity_ before instance_id_ while declaring them the other
way round; both initializers are independent, so it was cosmetic, and it is aligned too.

recipes_all_models_filtered_snapshot() had exactly one caller, a test, and differed from the
public recipes_with_all_models_filtered() by a build_cache(). Deleted: the concurrent reader
now uses manager.snapshot()->empty_recipes(), a public non-rebuilding const read that already
existed, so the side-table exposure goes away without weakening what the test stresses.

Also, the header declaration ceiling measured nothing. It counted `);` occurrences across the
whole file -- missing every method ending `) const;`, counting doc comments -- and reported 71
against a ceiling of 72 while ModelManager's own brace depth holds 87 function declarations.
It now counts declarations at class scope, nested type bodies excluded, and the ceiling says
87; adding one method fails, which the old counter could not do. S8's real starting surface is
87 declarations across 29 includers. The re-export detail dump printed on every run including
passes, where it read like a failure; it prints on failure now.

cpp-ci 119/119, cli2 73 tests OK, gate green, comment gate 0.

* S4: a recipe is policy, so it stops riding in an address

ArtifactRef carried `recipe` while operator== ignored it. That is a field which changes what
a plan contains and asserts nothing about identity: two refs equal as addresses produced
different downloads. It is what lets the shared plan builder reach for a recipe at all, since
the only way registry_download_plan could ask which files a model wants was through the ref
handed to it.

Moved to SourcePlacement, beside the layout and sibling it already travelled with, and read
back through repository.recipe() where the plan is built. Placement is resolver output, was
already threaded through create_repository, RepositoryFactory, both registration macros and
the FetchableRepository constructor, so this is a field move and a getter rather than a new
channel. The four mint sites stopped setting it; placement_for() and the host-scheme branch
set it; ingest builds one placement per pull, because every checkpoint of a pull belongs to
the same model and so to the same recipe; update_scan does the same for its probe.

checkpoint_type stays, and the header now says why the two are treated differently: which
checkpoint is a question about bytes, which recipe is a question about what to do with them.
The probes in hf_variants and search_registry needed no change -- they list and search and
never build a plan, so an empty recipe was already the right answer for them.

The new layout test asks the question the field used to make unanswerable: the same ref under
two placements yields plans that differ only in the files the policy selected and agree on the
destination. Moonshine was the natural second policy and throws when a listing has no folder
by that name; ThinkSound wants a fixed set of audio files and finds none in the fixture, which
says the same thing without an exception.

cpp-ci 119/119, whisper 12 OK (2 skipped), generators --check, comment gate 0. Whisper needs
XDG_RUNTIME_DIR pointing somewhere writable in the server's environment before it will load
anything; recorded because the error it produces otherwise reads like a model-load failure.

* S5: presence gets one implementation, and it takes a path rather than a source

downloaded and checkpoint_status[].present were computed twice, differently. The store
applied existence, in-flight markers and backend validation; LocalPathArtifactSource applied
existence plus validation; a registry checkpoint applied existence alone. An interrupted
download reported downloaded:false beside present:true, and a repository holding an HTML error
page named .gguf reported present:true.

The three checks now live in one function, checkpoint_bytes_present(path, validator), and the
marker half in models/download_markers.{h,cpp} -- interrupted_download() names
.download_manifest.json and .partial nowhere else. Both sources and the store's complete()
call it, so no caller can hold a different opinion about the same bytes. The registry source
validates with the ops of the recipe in its SourcePlacement, which is why S4 came first.

The plan said to make complete() a loop over sources. That was tried and it is wrong:
adopt_extra_cache() asks complete() whether a row would be whole, and the row it asks has no
provenance yet -- the resolver reads a bare org/repo checkpoint as a registry checkpoint, the
registry source looks only in the managed cache, and a model whose bytes sit complete in the
extra models directory is refused adoption and then loses its resolved path too, because
compose only resolves rows it believes are downloaded. The store decides which path a
checkpoint resolves to -- adopted caches, shard families resolved to the one file the engine
opens -- so the authority is a function over that path. Asking a source derives the location a
second time from provenance, which is the second opinion this step exists to remove.

Finding, from failing to see the bug first: checkpoint_status reports present:false with no
reason when a source cannot even be built, and the wire carries no reason field. Every
registry case in test_model_download_state was therefore false/false -- agreeing, vacuously.
A bare ModelManager wires no default model source, so no registry source can be built for an
org/repo checkpoint; production always does (RuntimeConfig::default_model_source). Five test
binaries now share one helper that takes the name from parse_remote_registry_source("")
instead of repeating the literal.

The characterization test was wrong too, and the mutation caught it. It asserted the two
answers agreed; deleting the marker check from the helper then broke just one of three marker
cases, because with no markers both authorities wrongly answer present and still agree. Each
case now pins the absolute answer. Re-run: M-A trips all three, M-B (registry stops
validating) trips the .gguf-of-HTML case alone, M-C (optional checkpoints ignored) trips the
whisper side cache alone.

One divergence is left and now documented rather than hidden: a row that adopted an
extra-directory cache reads downloaded:true beside present:false, because the registry source
answers for the managed cache only. Both fixes cost something -- reading the extra roots from
the source risks writing refs/main into a directory lemonade does not own, and recording the
adoption on the row changes the source the API reports and which rows the update scan visits.
That is a step of its own, not a smuggled-in extra.

cpp-ci 119/119, cli2 73 OK, endpoints 178 OK, whisper 12 OK, app regression 136, generators
--check, comment gate 0.

* S6: invalidation invalidates; it does not rebuild or publish

The write path published twice for every model change. `Write` publishes in its destructor,
and `invalidate_cache()` published a draft that is only a copy of what is already published --
so an invalidation announced a snapshot that says nothing changed, and the rebuild that follows
announces the change. Deleting the publish from the invalidation is the whole step, and it
needs the flag write to take the writer lock, since a reader can now hold the shared lock for
the whole read instead of a copy.

`invalidate_models_cache()`, `catalog_set_changed()`, the `DirectoryWatcher` callback and
`deps.persist_size` -- "content changed" and "the cache might be stale", the two ways a model
write used to end -- point at `ModelStore::invalidate()`. `persist_size` takes the size off the
published snapshot rather than opening a write to get a draft. `StoreWrite` scopes in the
facade 7 -> 3: two options patches and the download self-heal S7 renames. Live, one touch in
the extra models directory produces exactly one `Cache built`, and a burst of two produces one.

`test_generation_survives_a_rebuild` asserted the opposite -- "invalidating publishes, so a
lock-free reader sees it" -- which was the intended behavior written as a test of the old one.
It is replaced by `test_invalidation_publishes_nothing` in the store, and the notifier gains
`test_invalidation_marks_stale_without_publishing` and `test_an_invalidation_announces_nothing`.

Two things the plan had wrong: `Write::invalidate_cache()` has four callers left, not two; and
`StoreSnapshot::valid` is copied from `cache_valid_` at publish, so an invalidated store still
hands out a snapshot reading `valid: true`. Safe while `patch_download` is its only reader --
that path is guarded by `Write::cache_valid()` -- and worth reconciling if S7 touches either.

Verification: ctest -L cpp-ci 119/119; the comment gate is clean; both doc generators
report no drift; endpoints 178 tests OK (3 skipped) and whisper 12 OK (2 skipped). cli2 stops
at `test_092`, which fails the same way with this commit stashed and passes when run alone:
its shared repository is also `USER_MODEL_TE_CHECKPOINT`'s, and earlier cli2 tests register and
download the model that claims it. A fixture collision, not a delete regression.

* tests: the dummy model's text encoder gets a repository of its own

`test_092_delete_preserves_cross_repo_dependency` asserts the shared repository
directory is gone once the last model that uses it is deleted. `user.Dummy-Model`,
registered and pulled by earlier tests in the same persistent suite, resolved its
text encoder inside that same repository, so the delete correctly kept the bytes and
the assertion failed. The fixture already warns about this in two comments -- "only
holds while nothing else claims it" -- and the rule is stated for the main checkpoint
but was never applied to the text encoder.

Moved to a ~11 MB quant of `mradermacher/Tiny-LLM-GGUF`, a repository no other fixture
touches. Both consumers of the constant compare the checkpoint string, so nothing else
changes.

Why it hid: the repository held an unclaimed orphan file, and deleting a model whose
bytes nobody else claims removes the directory over it. Once the cache was cleared and
the suite re-downloaded Dummy-Model through the server, the ownership claim was written
and the collision became visible.

Verification: cli2 73 OK (2 skipped) -- previously 40 run, failfast at test_092 -- and
endpoints 178 OK (3 skipped), which exercises the constant in both directions.

* S7: the store answers reads, so collaborators stop reaching back into the facade

ModelStore took the read side the spec assigns it -- current(), resolve, exists, info,
resolve_name, public_name_for, rejection_reason, supported_models(), downloaded_models(),
resolved_paths_for, is_downloaded -- plus the one AliasManager resolution needs and the
composer its owner installs, because composing reads catalogs, registries, the machine
probe and saved options and none of that belongs to the store. A store with no composer
answers from what it published and never builds, which is what a test that patches rows
directly wants; the eleven sites that default-constructed one now name an in-memory
AliasManager.

ModelIngest::Deps lost seven read lambdas and three signal ones: models_changed and
model_updated became one ModelChangeNotifier*, persist_size moved into ingest (it needed
only the registries and the store it already held), and SyncService::Deps lost three and
gained a ModelStore*. Fields across the deps and hooks bags: 41 -> 27. make_ingest_deps()
is 34 lines, then 13. The facade's read verbs are one-line delegations; the file went
1096 lines -> 904 and its header 87 declarations -> 85, with both ceilings tightened.
wait_for_sync() was dead with no caller anywhere and is gone, and
remove_model_from_cache() -- a wrapper for one store call -- is inlined into the delete.

Three things the plan prescribed are not what shipped, and the spec now says why.
exists_unfiltered is not a store verb: it asks the registries about rows the host filter
removed, so the published set cannot answer it, and ModelIngest computes it from the
RegistryDocuments it holds -- a store method would be a second registry reader for one
caller. resolved_paths_for moved to ModelStore rather than ModelArtifactStore, because it
reads one published row's recorded paths, which is a snapshot question; the plan called it
the opposite. info() throws for a name nothing answers, since that is the contract the
facade's get_model_info has always had and every caller depended on; the nullable question
is read()->find(), and rule 6's wording distinguishes them.

A pinned contract caught a regression mid-step. Delegating resolved_paths_for through
current() turned a pure read into a compose-path call, which queues behind an in-flight
patch, and "a read answers while a writer holds the store" failed. Which verbs ensure and
which never wait is now written in the header, in the spec, and in that test.

Moving the self-heal changed behavior. The facade corrected a missing-bytes row with a
hand-rolled write that flipped that one row; the store verb routes through patch_download,
which also settles the collections routing through the model. A collection whose
component's bytes vanished no longer reports itself downloaded. Nothing pinned the old
narrow behavior, so this is a change to notice rather than one to assume.

Mutation checks. Dropping the alias fallback from ModelStore::resolve fails
NameResolutionTest, which covers the six steps end to end. test_model_alias does not catch
it and cannot: it exercises AliasManager alone, which is the point of the spec's rule that
aliases are consulted at resolution time and never folded into the snapshot. Dropping the
exists guard in ingest's pull fails PullRegistryTest, not the endpoints test_000a the plan
predicted.

Verification: ctest -L cpp-ci 119/119 after touching every source and rebuilding; app
regression 136 passed; both doc generators report no drift; the comment gate in CI form is
clean. Integration ran green against this code with comment-only edits still to come --
cli2 73 OK (2 skipped), whisper 12 OK (2 skipped), endpoints 178 OK (3 skipped) -- and the
repeat of that battery could not finish: this machine lost network egress partway (server
log full of "Could not resolve hostname", curl to huggingface.co returning 000), and the
one cli2 failure, test_044's config set, followed test_043 rebinding the listen host.
Re-run cli2, whisper and endpoints before relying on this commit end to end.

* S8: no header includes the facade header

A header that includes model_manager.h hands the whole models layer to
everyone behind it. Three of them did — backend_manager.h, wrapped_server.h
and backends/backend_ops.h, each included by 53-58 files — so editing the
facade recompiled 75 of the tree's product files. It now reaches 22, all of
them translation units that call it.

model_manager_types.h declares ModelManager and ModelInfo for the headers
that name the orchestrator without calling it; the alternative, writing the
pair out in each header, duplicates the struct/class kind MSVC warns about
and buys ~1 TU per header where the fan-out is small. Headers that read
models facts name the leaf for each fact instead: download_progress.h,
model_info.h, registry_types.h, artifact_fetch.h.

FacadeShapeTest now ratchets transitive reach rather than the direct-include
count, which a cosmetic edit could satisfy, and fails if any header includes
the facade at all. allowed_reexporters is compared as a set — it was failing
on ordering, not membership. download_progress.h joins the public read side.

Verified: cpp-ci 119/119, cli2 73 OK, endpoints 178 OK, whisper 12 OK, app
regression 136 passed, both doc generators --check clean.

* S9a: three facade helpers stop being public

forget_registered_model, save_model_options and start_directory_watcher were public, and every
product call to them comes from inside model_manager.cpp. The two tests that drove
save_model_options drive the public replace_options verb, which performs the same file-plus-cache
write, so no seam is lost by closing them.

download_from_huggingface_engine has no caller in the tree and stays: its comment says it is a
source-compatibility alias for integrations built against the original API, and an in-repo scan
cannot see those callers.

StoreWrite stays public for one reason - test_model_manager_shim holds a writer while a reader
runs, and with no read-only accessor for the facade's ModelStore that is the only way to express
the test. The comment names the blocker: give ModelManager a const store() seam and re-home the
writer hold, and the token becomes private.

FacadeShapeTest's direct-includer ceiling drops to its honest value of 22, so an added includer
fails instead of being absorbed by slack. cpp-ci 119/119.

* An invalidation landing mid-compose is no longer silently discarded

S6 moved invalidation off the write path: invalidate() takes the writer lock, clears
cache_valid_, and publishes nothing. That removed the only signal a compose in flight had.
Build::commit() refused a candidate by comparing generation_, which an invalidation no longer
moves, so a compose racing a persist would land a set built from catalogs enumerated before
that persist and set cache_valid_ = true on top of it. The stale set was then current: the
model that just finished downloading stayed missing until something else invalidated.

An invalidation now bumps invalidations_, a counter no client watches, and Build records it
beside the generation. Bumping generation itself was rejected: it is the signal that a set was
published, and an invalidation publishes nothing.

ComposeRetryTest caught this by accident. It had been simulating the racing writer with a raw
StoreWrite, whose destructor publishes, so it exercised the pre-S6 mechanism and passed; pointed
at the verb product code actually calls, it failed. test_store now pins the same case one level
down, where the store owns the race.

Also in this commit, the rest of S9b:
- ModelManager gains const store(), the read seam. A write scope needs a non-const ModelStore,
  so no caller of it can hold the facade's writer, which is what let StoreWrite go private.
- The reader-not-blocked-by-a-writer check moves from test_model_manager_shim to test_store,
  where the store is the thing under test; the shim test no longer needs write access.
- FacadeShapeTest gains "only the models layer and the facade open a store write scope": ingest,
  cloud_rows and update_scan write, gateways and backends cannot.

cpp-ci 119/119, cli2 73 OK, endpoints 178 OK.

* S9c: four facade verbs with no product caller go away

generation(), all_models(), has_alias() and checkpoints_complete() were one-line pass-throughs
that nothing in the product called. The store already answers the first two through the read
seam added last commit, so the tests now say manager.store().generation() and
store().read()->models -- which is also what the read migration will leave the gateways saying.

checkpoints_complete() asked ModelArtifactStore::complete() about a row, and the thirteen tests
that used it were handing it rows that are not in any store. complete() needs nothing from the
manager but the row, so test_model_download_state now holds its own artifact store: the checks
are about a row and the bytes on disk, and that is the pair they name.

has_alias() turned out to have no callers at all - the three hits the caller census counted are
AliasManager's own method, called on an AliasManager. A receiver type is part of a caller count.

FacadeShapeTest's budgets re-struck to their honest values: 86 -> 82 header declarations,
904 -> 889 lines. cpp-ci 119/119.

* S9c: resolved_paths_for leaves the facade

Nothing in the product called it. The two callers the caller census counted are inside ingest,
where they already go to the store directly - the same receiver-type mistake as has_alias last
commit. The store's own version is const, so the shim test reads it off the store seam.

Budgets: 879 lines, 81 header declarations.

* spec: the facade's read verbs stay, and why

Plan item 2b said to delete the one-line read delegations once the store answered reads. That
cannot be done: a facade read composes, composing publishes, and publishing takes the writer. A
ModelStore& handed to server.cpp to save a delegation is a store write scope waiting to happen in
a file that has no business holding one.

Rule 6b records the shape that is actually safe: the read verbs stay on the facade, and
ModelManager::store() is const, offering only what answers from the published snapshot without
waiting on a writer - read(), generation(), descriptors(), resolved_paths_for().

* spec: the facade sketch becomes the shipped surface

The sketch ended its alias group in "..." and stood for thirty-five verbs that ship. It now lists
them, grouped by what they are asked for, and the name-set diff between header and sketch is
empty in both directions.

Two corrections it forced. wait_for_sync() never shipped - the verb is wait_until_sync_idle().
resolve_model_name() was missing from the reads group. download_from_huggingface_engine() is
written down with the reason it survives an empty caller list: source compatibility for
integrations built against the original API, whose callers this repo cannot see.

* S10: the resolver mints refs and opens every repository

Pull and update scan each re-implemented selection: assembling ArtifactRefs from checkpoint
strings, filtering the lazy checkpoints, parsing repo_id and variant. Three copies of rules that
decide what a pull downloads, each able to drift from the others.

ArtifactSourceResolver gains refs_for(info) and repository_for(ref, placement).
download_from_registry takes both; the update scan, hf_variants' pull listing and
search_registry take repository_for. ingest and update_scan lose their repository_for Deps
lambda: the injected host now reaches them through the resolver's hook, which is where
ModelManager wires ModelManagerConfig::repository_for, so a stubbed pull stubs one thing.

The facade builds one resolver at construction. It used to build hooks and a resolver inside
every source_for() call, which is once per checkpoint.

FacadeShapeTest now refuses `create_repository(` anywhere but the resolver, the factory that
declares it, and the facade's one wiring line. That is "one site binds a checkpoint to a source"
taken literally.

Two divergences are deliberate and now written into spec rule 7: the pull keeps its own list() +
registry_download_plan() rather than acquisition() (one listing serves three decisions), and the
update check keeps group_aux_checkpoint_variants because a malformed auxiliary checkpoint is
skipped silently by a check and refused loudly by a pull.

test_update_scan had been reaching the real factory through an unset seam and relying on it to
throw; it now installs a stub that answers "can go stale" and fails on the tree, which is the
shape it was always pretending to test.

cpp-ci 119/119, cli2 73 OK, whisper 12 OK, endpoints 178 OK; /pull/variants returns 12 variants
for a live repo through the new seam.

* S11 (part): fold checkpoint_grammar and definition_labels into the headers that own them

checkpoint_grammar was two functions parsing a ref's own parts; they now sit with ArtifactRef,
which is what the grammar describes. definition_labels was row policy -- the label set a
registration derives -- and json_catalog is where a row is parsed, so it moved there and took its
backend-descriptor include with it. Two .cpp link units gone, two headers fewer.

The other six candidates in the S11 table do not survive the step's own rule, and each reason is
now written next to the row it refutes:

- catalog_fetch_clock: four owners (catalog_set deps, configured_catalog, model_manager member,
  the locator), not "its only user". Folding into any one makes three peers depend on a sibling
  for a type all four share.
- registry_documents: holds a mutex and publishes immutable snapshots. The step excludes anything
  with a mutex, and this row contradicts that.
- routing_parse_options: three parse sites build their tiers differently; that is the point of it.
  No host owns the concept.
- recipe_option_layers -> recipe_options_store.h: the store is one rung of the ladder the folder
  builds. Making the rung own the ladder inverts it, and the store has three mutexes.
- fetchable_repository.cpp -> registry_id.cpp: the registration table maps ids to repository
  factories. Inside registry_id.cpp the id type would depend on every repository, which is the
  dependency the factory exists to invert.

* S12: one StoreWrite binary for the store's write side; 3 CMake blocks become 1

test_store, test_store_build and test_store_patches all asked the same question of the same
object -- what a writer does to the published snapshot, and what a reader sees while it
happens -- so they are one process now, with each file's helpers kept in its own namespace
rather than renamed until they stopped colliding. 73 check() call sites in, 73 PASS lines out.

StorePatchesTest was listed here as "targets a class deleted in P4a". It does not: it exercises
patch_download and patch_removed, both live, so it merged on its actual surface instead of being
deleted. Deleting it would have dropped five checks over store writes that nothing else covers.

StoreSnapshot stays separate. It is the read side, and merging a read-side binary into a
write-side one would leave a binary named for half of what it tests.

Also removes a third copy of the saved-options rationale; composition.h owns that sentence.

* S13a: repository bookkeeping leaves artifact_store.cpp into its own unit

A repository cache's snapshot pointer and its processed-model ledger were six methods at the end
of a 1176-line file, beside download cleanup that has nothing to do with either. They move to
repository_provenance.{h,cpp} and the class forwards, so callers are untouched. The store is now
1055 lines; the extracted rules are 171, and RegistryProvenanceTest already covered them without
needing a new fixture.

* S13b: collections leave ingest.cpp into their own unit

Fetching a manifest, registering the components it names, deciding whether a collection may be
registered at all, and refilling a slim entry from a cached manifest: four methods plus three
helpers that only they used, 469 lines out of a 1471-line file. They share one input — the
manifest — which is why they belong together and not spread across the ingest.

ModelIngest keeps its public validate_collection() and populate_from_cached_manifest() and
forwards, so no caller changed; register_components and resolve_from_manifest were already private
and are now the collection unit's. The back-pointer to the ingest is there because a collection
pulls its components through the same path a plain model does rather than owning a second copy of
the download code. The destructor moves out-of-line for the unique_ptr.

ingest.cpp is 1058 lines. cli2 73 OK, endpoints 178 OK, whisper 12 OK, both doc generators
current, ctest 117/117.

* S14 items 1 and 2: delegated delete gets its fixture; a mistyped config value stops emptying the model set

Two carried defects, both about absence.

Delegated delete had no fixture. The path is real -- flm's descriptor declares self_manages_downloads,
so its source answers Deletion::Kind::Delegate, ownership_of records the recipe, and remove_self_managed_model
does the removal -- but nothing pinned it, so nothing said which side of that chain a change had broken.
The new case registers an flm row, deletes it, and requires the request to reach the backend: with no flm
executable the delegate refuses, and the refusal is the evidence. A CacheDir branch completes silently and
looks like success, which is why mutating `kind == Delegate` to false now fails two checks instead of none.
It needs disable_model_filtering for the same reason test_model_delete_shared_repo.cpp does -- flm is a
system package the test host will not have, and filtering would drop the row before the delete reached it.

backend_string/bool/int/double read config_[section][key].get<T>() after checking only that the key exists.
config.json is hand-edited, so a value of the wrong type throws type_error.302 out of recipe detection,
where it is caught and logged -- leaving `recipes` absent, which the router reads as "no recipe is
available" and filters every model on the machine. One bad key cost the whole set. All four now read
through one lookup that treats absence and mismatch alike, so a mistyped value costs at most the setting
it holds. Pinned by feeding build_recipes_info a document whose llamacpp.backend is a number: before, the
test binary aborted with the exception; after, the table survives with the recipe in it.

Top-level keys were already validated at construction, so they are untouched -- this was specific to the
per-backend readers, which had no validation behind them.

ctest 117/117.

* S15 (part): budgets struck to what they measure, and printed where a shrink will show

Three of the five facade budgets sat exactly at their ceiling with nothing saying so, which is the
same drift the ceilings exist to catch -- one line added somewhere else would have failed for a
reason unrelated to the line. All five now read the measured value: 876 lines, 82 declarations,
19 members, 22 direct and 22 transitive includers. The closure equaling the direct count is not a
coincidence to tidy; it holds because no header propagates the facade, and that has its own check.

Adds one summary line to FacadeShapeTest's output listing each budget against its ceiling. A
ceiling only says "not worse"; without the measured number a shrink is invisible unless someone
goes looking, and the reason to notice a shrink is to tighten the ceiling before something backfills it.

Also records S14 item 3 as investigated-and-left rather than open. validate_checkpoint_file() was
offered as the hook that already answers "may this file complete this checkpoint", and it does not:
it returns "" for a non-.gguf path, skipping magic-number validation rather than rejecting the file,
so routing the three literals through it refuses models that load today. Each site is written up
where the next reader will look instead of reopening the question.

* S15: the store's forwarding declarations point at the provenance rules instead of restating them

Splitting a unit copies its doc comments along with its signatures, and six of them ended up
describing the same behavior twice -- once where it is decided, once where it is forwarded. A pair
like that goes stale on the first change to either side. The header keeps one line saying what the
group is and where the rules live; the parameter note stays only where the default is not visible.

* S15: one sentence describes the provenance group, at its own header

The forwarding block restated in different words what repository_provenance.h already says about
the same five functions. A pointer is enough from a file that decides nothing.

* S15: registry_source_of moves to the header that owns registry names

It normalized ModelInfo::registry_source from artifact_store.h, where it sat beside the cache layout
it has nothing to do with. It is now declared next to parse_remote_registry_source() and
remote_registry_source_name(), the two calls it composes, and defined in the same file as them. The row type
does not take on registry parsing to get this: the function takes a row, which keeps the dependency one-way.

Ten call sites dropped their models:: qualifier, since lemon::models sees lemon:: by lookup -- the
qualified spellings were only ever correct because the declaration happened to be in the models layer.

Resolves the question S7 left open about this function's home. ctest 117/117, facade budgets unchanged.

* review: a store snapshot lives as long as the loop that reads it

* review: an NPU cache already on disk is not fetched again by an auto-load

* review: a planned name cannot place bytes outside its own directory

* review: load_optional_json looks for the UTF-8 path it was given

* review: the POSIX safe_* answer instead of throwing

* review: the snapshot golden compares one separator, not the native one

* review: the re-exporter diff compares the lists it prints

* review: the reader threads run before the writer stops them

* review: a re-pull proves it wrote no bytes; the empty if goes

* docs: a Hugging Face snapshot directory is the commit SHA

* gate: the directory-settings needles move with discovery into ScanCatalog

* build: test_auto_tune links json, and the gate asks reachability not naming

* models: a row borrowed from a published set outlives it; find() aliases the set

* api: checkpoint_status[].path is opt-in with ?include_paths=true

* aliases: a save holds the lock from snapshot through rename

* paths: one grammar for a component, and no writing through a symlink

* models: a delegate's checkpoint answers with the row's own fact

* comments: cut the essays this branch wrote

* comments: drop a same-pattern pointer in the collection ingest

* docs: the include_paths link names the heading that exists

* pull: a snapshot id the layout refuses throws instead of planning nothing

* transfer: a file name passes the grammar, not only containment

* docs: the spec names the consumers that exist after the merge

The merge moved every caller into route classes, so the spec's file names and its claim that the model-object field list is hand-kept both went stale in the same change. Records the merge in the plan: what moved where, the three silent losses the port recovered, the ceilings re-struck to measurement, and which suites did not run here.

* store: a collection's state settles under the writer lock

Two components of one collection finishing at once each computed the dependent
collection states from the set they had read, so each saw the other still
absent and both published the collection as not here with everything
installed. The recompute is a scan over rows and touches no filesystem, so
moving it inside the Write scope costs nothing it could not pay under a lock,
and the draft it reads is the one this writer just patched. A component the
draft no longer holds counts as absent rather than as just landed, so a delete
landing between the read and the commit cannot complete a collection on a row
that is gone.

The test starts both writers at once and repeats the round, because the window
they must both be inside is filesystem work wide: it fails on the ordering this
replaces and passes on this one.

* allow deleting models with all checkpoints shared

* relax symlink rules when they are within the repo

* address review comments

* address review feedback

* reduce test footprint

* fix shared-repository deletion with HF symlinks

* restore resume validation

* fix resume via proxy

* fix regressions

* address more review comments

---------

Co-authored-by: fl0rianr <[email protected]>
2026-10-27 19:57:39 +00:00
f2208e49ed test: isolate every C++ test from the real config dir (#3612)
* test: isolate every C++ test from the real config dir

user_models.json and friends moved from the cache dir to the config dir in
#3028, but the tests that isolate themselves only via set_cache_dir() were not
updated. Since then, running the suite locally writes fixtures straight into
the developer's ~/.config/lemonade/user_models.json: one run of
test_model_manager_collection_validation registers 8 router/classifier models
there, and test_model_registry adds 2 more. CI never notices because a fresh
runner has no registry worth corrupting.

Rather than add the missing call to each test, make isolation automatic.
add_cpp_ci_test() is already the only supported way to declare a test, so it
now links lemonade-test-isolation into the test executable, which points both
dirs at a throwaway directory before main() runs. A test with its own layout to
exercise (test_config_dir_migration) still overrides it by calling the setters
itself, so there is no opt-out list to maintain.

Drops the per-test temp-dir scaffolding that existed only for this, and roots
the fixture dirs that are still needed at the isolated state dir.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(cmake): guard the test isolation library the way every test block does

Two defects in the previous commit, both caught by CI:

The .dockerignore excludes test/ entirely, so the Docker build configures a
tree with no test sources at all. Every test block already guards on
EXISTS "${_FOO_TEST_SRC}" for that reason; add_library() for the isolation TU
did not, and failed the configure with "Cannot find source file". Guard it the
same way. A tree that carries tests but not the isolation source is a
contradiction rather than a case to tolerate, so add_cpp_ci_test() now fails
loudly instead of silently linking nothing.

Only 52 of the 81 test executables link lemonade-server-core, and
get_config_dir() lives there. Linking the isolation TU into the other 29 left
set_cache_dir/set_config_dir undefined at link time. Those tests also cannot
reach the real config dir at all, so that link condition is the exact set that
needs redirecting, not an approximation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test: harden C++ state isolation

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Florian Reinle <[email protected]>
2026-10-14 12:53:47 +00:00
Salah Eddine Bekhouche 3986f979c4 fix(routing): don't drop the whole router policy over one hardware-filtered classifier (#3414)
* fix(routing): don't drop the whole router policy over one hardware-filtered classifier

ModelManager::build_cache()'s routing-policy resolver only consulted the
post-filter models_cache_, so a classifier component whose backend needs
hardware this host lacks (no NPU, insufficient memory, not yet downloaded)
was indistinguishable from a name that isn't a model at all. The parser
threw "unresolvable type" and the entire policy was dropped, including
unrelated deterministic rules that had nothing to do with the unavailable
classifier.

Snapshot every model's type before filter_models_by_backend() removes some
of them, and fall back to that snapshot in the resolver. A filtered
classifier's type is still known, so the policy still parses; that specific
classifier now fails only at evaluate() time, where its own on_error
already applies -- the existing, correct mechanism for an unavailable
backend, just no longer bypassed by a parse-time abort.

Fixes #2748 (the two confirmed bugs: build_cache's no-fallback resolver,
and the "policy silently dropped" consequence of its asymmetry with
validate_collection_request's inline-model fallback). The lower-priority
"worth a look" items from that issue are unrelated to this fix: one
(display inconsistency across ollama_api.cpp/CLI) was already resolved as
a side effect of #3099; the other (telemetry for silent classifier
fail-open) is untouched here.

* fix(routing): also fall back component alias resolution for a filtered model

The type fallback alone wasn't enough: public_model_aliases_ is rebuilt
from models_cache_ (post-filter) too, so a filtered model's bare-name alias
(e.g. npu-clf -> user.npu-clf) disappears the same way its type did. A
classifier authored against the bare name, or against components declared
in the opposite form, failed the declared-component check before
get_model_type() was ever reached -- the same whole-policy-drop as #2748,
just via a different resolver.

Snapshot a pre-filter bare-name -> canonical alias map alongside the type
snapshot, and fall back to it in resolve_component the same way. Added a
second regression test with the canonical id in `components` and the bare
name on the classifier, the opposite pairing from the existing test, which
alone didn't exercise this path. Also trimmed the surrounding comments into
one explanation instead of one per lambda.

* fix(routing): use full alias precedence for the pre-filter resolver, not first-seen

The bare-alias fallback added last commit used first-seen-wins, not the
Registered > Imported > Builtin precedence rebuild_public_model_aliases_locked()
applies. If a higher-precedence model (e.g. a user override) normally wins a
bare name but gets hardware-filtered while a lower-precedence model with the
same bare name survives, the policy resolver would silently rebind the
classifier to that survivor instead -- worse than the original bug, since it
fails silently rather than loudly.

Extract the precedence computation from rebuild_public_model_aliases_locked()
into compute_bare_name_precedence(), reusable against the pre-filter model
set. The routing-policy resolver now checks this precedence-correct pre-filter
map first, falling back to the post-filter public_model_aliases_ only for
what the map doesn't cover (e.g. an extra_models_dir input_alias).

Also: both #2748 regression tests now assert their NPU-backed model was
actually filtered before checking the policy still parses, so they can't go
vacuously green on a future NPU-capable CI runner.

* fix(routing): make the pre-filter alias resolver share the real alias algorithm

The precedence fix still only reproduced the bare-name half of what
rebuild_public_model_aliases_locked() computes: builtin.<X> and
ModelInfo::input_aliases are separate alias forms that pass never ran
against the pre-filter set. A router referencing a filtered builtin as
builtin.<X> still failed resolve_component's declared-component check and
dropped the whole policy again.

Extracted rebuild_public_model_aliases_locked()'s full algorithm into
compute_model_alias_maps(), a pure function of an arbitrary model map. It
now runs against models_cache_ (post-filter, for the real member state) and
against all_models (pre-filter, for the routing resolver's snapshot) --
one implementation, so the two can't drift apart again. Since the pre-filter
set is a strict superset of the post-filter one, the resolver no longer
needs a separate fallback to public_model_aliases_ at all.

Added a third regression test for the builtin.<X> case, using a real builtin
(ryzenai-llm) so no fixture registration is needed to exercise it.

* fix(routing): share one component resolver between the two policy parse sites

Extracts the resolution shape both collection.router parse sites use --
alias first, then a type lookup with one fallback tier -- so the two can
no longer drift the way #2748 did. Each site supplies only its own tiers.

A classifier component that only the pre-filter tier can resolve is
unavailable on this host and will take its on_error path on every request;
warn once per collection so the degraded routing is visible. The pre-filter
snapshots are now skipped entirely when no router collection is registered.

The regression tests evaluate the parsed policy instead of only asserting
it parsed: the unrelated keyword rule must still route while the filtered
classifier's rule falls back.
2026-09-09 15:29:22 +00:00
Jeremy FowersandClaude Opus 5 f9865cde78 feat(models): add an explicit chat label (#3099)
* feat(models): add an explicit `chat` label

Chat-ness was inferred in five inconsistent places: an allow-list in
get_model_type_from_labels plus three copy-pasted "non-chat label"
denylists. FastFlowLM has no chat marker at all -- 10 of its chat models
report no labels and only worked via a silent LLM fallback.

Make `chat` a first-class deployment label, stamped at every ingest
boundary that cannot declare it, and collapse the five inference sites
to one label test.

Also removes the deprecated `Lite Collection` / `Ultra Collection`
registry entries.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(models): derive the deployment label from the backend descriptor

Each backend descriptor now declares a `default_classification`, and a single
`ensure_deployment_label(labels, recipe)` stamps it at every ingest path when a
model's own labels name no deployment mode. This replaces the recipe-blind
`ensure_chat_label`, which labeled a bare sd-cpp or whispercpp user model as
`chat`.

- Add the missing `chat` label to Muse-Glimmer-30B-GGUF.
- Check the registry invariant in CI (test/test_server_models_labels.py): every
  model declares exactly one modality, and it agrees with its recipe.
- Classify FastFlowLM models by checkpoint name, since `flm list --json` reports
  input modalities rather than a deployment mode (ROCm/FastFlowLM#668).
- Split get_model_type_from_labels() into find_deployment_mode() plus the
  LLM-fallback wrapper, so callers can tell "declares chat" from "declares
  nothing"; share one has_label() helper across the four ad-hoc idioms.
- Document all nine deployment labels and the recipe-default fallback.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(models): drop the descriptor-outranks-labels guard

The guard existed because `vision` / `reasoning` / `tool-calling` used to imply
chat, so an sd-cpp model labeled `vision` or an onnxruntime model labeled
`reasoning` typed as LLM and slipped past classifier-capability validation. With
`chat` as the sole chat marker and the recipe's classification stamped at ingest,
the only labels this could still override are ones a user typed by hand.

The `classification` fixup stays, since /v1/classify is served only by
onnxruntime; it now names that backend through its descriptor instead of relying
on the removed branch to have returned first.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(models): treat `chat-transcription` as a capability, not a mode

`chat-transcription` means a chat model takes audio in a chat turn and
transcribes it as part of its answer, so it sits with `vision` and
`tool-calling` rather than naming the LLM deployment mode — `chat` does
that. A model carrying only capability labels now falls through to its
recipe's default label.

Also: warn at cache build for any model that reaches a client with no
deployment label; restore the array/element type guards when reading
`labels` off a `/v1/models` response; describe the FLM discovery
workaround in terms of the actual `flm list --json` catalog; and correct
the deployment-label docs to match `get_deployment_model_type()`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(models): declare each backend's supported deployment modes

Each backend descriptor now lists every deployment mode it can serve, most
default first, replacing `default_labels`, `default_classification` and the
editorial `modality` string. A model's labels are reconciled against that list
at ingest, so a label can no longer claim a mode its backend would reject at
inference time.

- `POST /pull` returns 400 and registers nothing when a definition names an
  unservable mode, via `labels` or the `embedding`/`reranking` parameters;
  collection imports reject the same definition before any component registers
- Naming no mode stays valid: the recipe's default is stamped, so an LLM always
  carries `chat` and clients can test one label instead of inferring from
  absence
- Deleted `get_deployment_model_type()`; label normalization runs on every
  ingest path, including the built-in cache build, so labels and ModelType
  cannot disagree
- `/system-info` derives `modality` from the declared modes, and `bench` reads
  them directly instead of parsing the display string back into a ModelType,
  which also fixes llamacpp embedding and reranking benchmarks
- `BackendModeContractTest` fails the build when a descriptor's declared modes
  disagree with the capability interfaces its server class implements

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(models): drop FastFlowLM's reranking claim

FLM serves no /v1/rerank route (v0.9.46 registers only chat/completions,
completions, embeddings, audio/transcriptions, models, version) and its
catalog has no reranking model, so `IRerankingServer` made the descriptor
advertise a mode nothing could satisfy.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(models): refuse an illegal set of mode labels instead of repairing it

A label set either describes a model the backend can deploy or describes no
model at all: a mode the recipe cannot serve, or two different modes, is now
refused rather than normalized down to a winner. Two servable modes were the
gap — llama-server is spawned with --embeddings for an embedding model only, so
`["chat", "embeddings"]` advertised an endpoint the subprocess never had.

/pull answers 400 and registers nothing; a stored entry that predates the rule
is skipped at startup with an error naming it, leaving user_models.json untouched
so it can be corrected by hand. Dropping the repair also removes the question of
which mode wins, so labels and ModelType agree by construction.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-14 20:39:44 +00:00
41ef688dab Wire collection.router classifiers to Router::classify + validate model capability at parse time (#2727)
* Wire routing classifier services to Router::classify for ModelType::CLASSIFICATION

run_classifier previously always called chat_completion, so a
collection.router classifier condition could never actually reach an
onnxruntime-backed model (WrappedServer's default chat_completion() is
an unsupported-capability error for backends that don't implement it).
Add classify/get_model_type callbacks (both optional, defaulting to
the prior chat-completion-only behavior) and route to Router::classify
when the target model is tagged ModelType::CLASSIFICATION.

Verified live: a collection.router policy using an onnxruntime
classifier now produces real per-request scores and routes benign vs.
flagged input differently, instead of always falling through to
on_error regardless of input.

* Validate classifier/semantic_similarity model capability at policy-parse time

routing.classifiers[].model was only checked for existence (via
resolve_component + require_declared), never for capability. A
"classifier" entry pointing at, say, an embedding or image model would
register successfully and only fail at request time with a generic
router error. Add an optional get_model_type resolver to
RoutingPolicyParseOptions and validate: "classifier" needs LLM (chat-
completion-based) or CLASSIFICATION (/v1/classify); "semantic_similarity"
needs EMBEDDING. Wired at both production parse sites (build_cache's
routing-policy parse and validate_collection_request's registration-time
compile-check); left unset in existing parser unit tests, which keeps
their behavior unchanged.

Verified live: registering a policy whose classifier model is an
embedding model is now rejected immediately with a clear error instead
of silently succeeding.

* Fix ModelType fallback ambiguity for unresolvable/inline components

RoutingModelTypeResolver returned a bare ModelType, defaulting to LLM
whenever a component couldn't be resolved (e.g. an inline collection
component not registered yet). Since LLM is an accepted classifier
type, this was asymmetric and registration-order-dependent: a valid
inline semantic_similarity + inline embedding model was rejected
("type llm, needs embedding"), while an invalid inline classifier +
inline image/embedding model was silently accepted.

Change the resolver to return std::optional<ModelType>; the parser
now throws a clear "unresolvable type" error instead of guessing.
validate_collection_request derives the type from the matching inline
`models[]` definition's labels when the component isn't registered
yet (reusing the existing find_inline_def matching), only falling
back to nullopt when genuinely nothing is known. build_cache's
resolver simplifies to nullopt on a cache miss, since everything real
is already present by that point.

Addresses fl0rianr's review on #2727.

* Preserve throw-before-load ordering in run_classifier

ensure_model now ran unconditionally before checking whether
chat_completion_call was configured, so a caller relying on
"missing chat_completion call throws before any load side effect"
would observe a different order than before the classify-routing
change. Check whether the classify path will be used first (a pure
function of the model's type, no side effects), then validate
chat_completion_call is configured before calling ensure_model when
falling back to it.

Nit from ramkrishna2910's review on #2727.

* Add unit tests for classify routing and capability validation

- run_classifier: a ModelType::CLASSIFICATION model routes through
  classify (not chat_completion); a non-CLASSIFICATION model falls
  back to the chat-completion path as before.
- Parser capability check: classifier accepts LLM/CLASSIFICATION and
  rejects EMBEDDING; semantic_similarity accepts EMBEDDING and rejects
  LLM; an unresolvable (nullopt) type is a hard error, not a silent
  pass.
- The exact regression pair from fl0rianr's review: an inline
  semantic_similarity condition backed by an inline embedding
  definition must pass, and an inline classifier condition backed by
  that same embedding definition must fail.

Requested by ramkrishna2910's review on #2727.

* Fix collection.router validation rejecting label-less inline models

validate_collection_request's get_model_type lambda only derived a type
from an inline models[] definition when it had a "labels" array, and
returned nullopt otherwise - even when the definition existed. An inline
model with no labels (a plain chat/completion model, the common case)
was thus treated as unresolvable and rejected as an invalid classifier
target, even though get_model_type_from_labels() would correctly default
it to ModelType::LLM. Now nullopt is only returned when no inline
definition is found at all.

Caught by CI: test_model_manager_collection_validation exercises exactly
this via valid_router_collection()'s label-less "pii-detector" fixture.

* Load model before resolving type in run_classifier (cold start)

Router::get_model_type() reports ModelType::LLM until the backend is loaded and
alive, so resolving the type before ensure_model() made the first request after
startup/eviction/restart pick the chat path for a classify-only model —
recreating the unsupported-capability / on_error failure this routing exists to
avoid. Resolve the type after loading; move the chat_completion-configured guard
onto the chat branch.

Adds a regression test simulating the cold-start transition (get_model_type
returns LLM before ensure_loaded, CLASSIFICATION after) — it fails on the old
ordering and passes now.

Addresses the second blocker in fl0rianr's review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Centralize inline model-type derivation for collection.router validation

validate_collection_request() derived an unregistered inline component's type
from its explicit `labels` only, while register_user_model() also applies legacy
capability flags (embedding/reranking/vision/reasoning) and the backend
descriptor's default_labels. So a label-less sd-cpp model validated as LLM
(accepted as a classifier) but registered as IMAGE, and a legacy `embedding:true`
model was rejected for semantic_similarity though it registers as an embedder —
both recreating the runtime capability mismatch this PR prevents.

Extract normalized_definition_labels() and use it in both places so validation
and registration cannot drift. Adds ModelManagerCollectionValidationTest cases
(against the real resolver, not a fake): label-less sd-cpp as classifier fails,
legacy embedding:true for semantic_similarity passes, label-less llamacpp still
defaults to LLM.

Addresses fl0rianr's third review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Make routing model-type backend-capability-aware (chat-indicator bypass)

get_model_type_from_labels() gives chat-indicator labels (reasoning/vision/
tools/chat-transcription) priority, so a non-chat backend plus a stray
chat-indicator label typed as LLM at BOTH validation and runtime
(router.cpp sets the runtime type from model_info.type). An onnxruntime model
with reasoning:true, or an sd-cpp model with vision:true, was therefore accepted
as a classifier and — for onnxruntime — sent down run_classifier's chat path,
which OnnxRuntimeServer cannot serve (IClassificationServer only): the original
unsupported-capability / on_error fail-open, back again.

Add get_deployment_model_type(recipe, labels): the backend descriptor's default
labels declare a definitive non-LLM deployment (onnxruntime->classification,
sd-cpp->image, whispercpp->transcription, ...), which wins over chat-indicator
labels because those backends do not implement chat_completion. Use it at every
ModelInfo::type derivation site (fixing runtime) and in the inline validation
resolver (fixing parse-time). Only affects models with a contradictory
chat-indicator label on a non-chat backend, so real catalog models are unchanged.

Tests: onnxruntime+reasoning is CLASSIFICATION (accepted, routes to classify);
sd-cpp+vision is IMAGE (rejected as classifier).

Addresses fl0rianr's fourth review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Declare kokoro's TTS default label so it can't be typed as a classifier

kokoro is the only non-chat backend with empty default_labels, so a label-less
kokoro model still typed LLM and slipped past classifier-capability validation
into run_classifier's chat path (which KokoroServer cannot serve). Give the
descriptor its true default label ("tts") so get_deployment_model_type() pins it
to TTS. Catalog kokoro models already carry "tts" explicitly, so they are
unaffected. Adds a label-less-kokoro-as-classifier rejection test.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Don't type a chat backend CLASSIFICATION from a spurious label

/v1/classify (IClassificationServer) is implemented only by the onnxruntime
backend. A `classification`/`classifier` label on a chat backend (llamacpp/flm/
ryzenai/vllm/cloud) previously typed the model CLASSIFICATION, so run_classifier
called Router::classify() and hit an unsupported-capability error — the inverse
of the chat-indicator bypass, and the same on_error fail-open.

get_deployment_model_type() now drops a classification claim once it has fallen
through to a backend with no definitive non-LLM deployment (onnxruntime already
returns CLASSIFICATION via its default label before this point), so such a model
stays LLM and is served via the chat-classifier path, never Router::classify.

Test: llamacpp + labels:["classification"] stays LLM and is accepted as a
classifier via the chat path.

Addresses fl0rianr's fifth review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: QuManu <[email protected]>
Co-authored-by: ramkrishna2910 <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-07-20 08:29:07 +00:00
eddierichter-amd 3cebf6bcd0 Router/2383 policy parser hot reload (#2519)
* feat(router): add policy parser and hot-reload store

* feat(router): preserve collection routing metadata

* test(router): cover policy loading in CI

* fix(router): align pull validation with policy compilation

* fix(router): reject duplicate policy model names

* fix(router): harden policy store file handling
2026-07-06 18:54:53 +00:00