Files
lemonade/test/cpp/test_cloud_rows.cpp
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

150 lines
5.3 KiB
C++

// The cloud rows in a store: what a refresh reseeds, what it refuses to overwrite, and
// what an evict leaves alone. The provider is a callable, so no server is involved.
#include <lemon/model_manager.h>
#include <lemon/models/alias_manager.h>
#include <lemon/models/cloud_rows.h>
#include <lemon/models/store.h>
#include <lemon/models/store_snapshot.h>
#include <algorithm>
#include <cstdio>
#include <map>
#include <memory>
#include <string>
#include <vector>
using lemon::ModelInfo;
using lemon::models::CloudRows;
using lemon::models::ModelStore;
static int g_failures = 0;
static void check(const std::string& name, bool ok) {
std::printf("[%s] %s\n", ok ? "PASS" : "FAIL", name.c_str());
if (!ok) ++g_failures;
}
static ModelInfo listed(const std::string& name, const std::string& provider) {
ModelInfo info;
info.model_name = name;
info.recipe = "cloud";
info.cloud_provider = provider;
return info;
}
// Publish `rows`, as a build would have.
static void publish(ModelStore& store, std::map<std::string, ModelInfo> rows) {
ModelStore::Build build(store);
build.commit(std::move(rows), nullptr, {});
}
static std::vector<std::string> names_of(const ModelStore& store) {
std::vector<std::string> names;
for (const auto& [name, info] : store.read()->models) {
names.push_back(name);
}
return names;
}
static void test_refresh_reseeds_one_provider() {
std::vector<std::vector<ModelInfo>> listings{{listed("alpha", "p1"), listed("beta", "p1")},
{listed("beta", "p1")}};
size_t calls = 0;
lemon::models::AliasManager aliases{""};
ModelStore store{aliases};
CloudRows rows(store, [&listings, &calls](const std::string&) {
return listings[std::min(calls++, listings.size() - 1)];
});
check("a refresh puts the provider's listing in the store",
rows.refresh("p1") == 2 && names_of(store).size() == 2);
check("and counting reads the same rows", rows.count("p1") == 2);
// The second listing no longer carries alpha.
check("a refresh drops what the provider stopped listing", rows.refresh("p1") == 1);
check("the stopped model is gone rather than stale",
store.read()->find("alpha") == nullptr && store.read()->find("beta") != nullptr);
}
static void test_refresh_leaves_everyone_else_alone() {
lemon::models::AliasManager aliases{""};
ModelStore store{aliases};
publish(store, {
{"alpha", listed("alpha", "p1")},
{"other", listed("other", "p2")},
{"local", [] { ModelInfo info; info.model_name = "local"; info.recipe = "llamacpp"; return info; }()},
});
CloudRows rows(store, [](const std::string&) { return std::vector<ModelInfo>{}; });
check("a provider that lists nothing reseeds to none", rows.refresh("p1") == 0);
check("another provider's rows survive it", store.read()->find("other") != nullptr);
check("and so does a local model's", store.read()->find("local") != nullptr);
}
static void test_refresh_does_not_take_a_held_name() {
lemon::models::AliasManager aliases{""};
ModelStore store{aliases};
publish(store, {{"shared", [] {
ModelInfo info;
info.model_name = "shared";
info.recipe = "llamacpp";
return info;
}()}});
CloudRows rows(store, [](const std::string&) {
return std::vector<ModelInfo>{listed("shared", "p1")};
});
check("a name another source holds is not overwritten", rows.refresh("p1") == 0);
check("the holder keeps its recipe", store.read()->find("shared")->recipe == "llamacpp");
}
static void test_rows_a_listing_left_undressed() {
lemon::models::AliasManager aliases{""};
ModelStore store{aliases};
CloudRows rows(store, [](const std::string&) {
return std::vector<ModelInfo>{listed("bare", "p1")};
});
rows.refresh("p1");
const ModelInfo* added = store.read()->find("bare");
check("a row with no options still gets the recipe's own so Router can build it",
added != nullptr && added->recipe_options.get_recipe() == "cloud");
}
static void test_evict_and_the_empty_ask() {
lemon::models::AliasManager aliases{""};
ModelStore store{aliases};
publish(store, {
{"alpha", listed("alpha", "p1")},
{"beta", listed("beta", "p1")},
{"other", listed("other", "p2")},
});
CloudRows rows(store, [](const std::string&) { return std::vector<ModelInfo>{}; });
check("an evict takes one provider and reports how many", rows.evict("p1") == 2);
check("the other provider is untouched",
store.read()->find("other") != nullptr && rows.count("p2") == 1);
check("evicting nobody answers nothing and changes nothing",
rows.evict("nope") == 0 && rows.evict("") == 0);
check("an empty provider name never asks the provider", rows.refresh("") == 0);
check("and a provider with no way to list is not an error",
CloudRows(store, nullptr).refresh("p1") == 0);
}
int main() {
test_refresh_reseeds_one_provider();
test_refresh_leaves_everyone_else_alone();
test_refresh_does_not_take_a_held_name();
test_rows_a_listing_left_undressed();
test_evict_and_the_empty_ask();
if (g_failures != 0) {
std::printf("\n%d check(s) failed\n", g_failures);
return 1;
}
std::printf("\nAll cloud row checks passed\n");
return 0;
}