ModelSaar

Managed model lifecycle

Rendered from docs/lifecycle.md at commit 813abb1662f7. The repository file is authoritative.

By default ModelSaar cooperates with inference servers that the user manages: it observes what is loaded and never loads, unloads or downloads anything. This page describes the optional managed mode. It exists for operators who want to preload a model before a session, or free memory explicitly, through the gateway's own admission rules instead of talking to the runtime behind its back.

backends:
  - id: ollama
    type: ollama
    base_url: http://127.0.0.1:11434
    resource_pool: gpu
    lifecycle:
      managed: true        # default false: without this the gateway refuses every lifecycle operation (403)
      keep_alive_s: 1800   # keep_alive sent with an explicit load (omit = the runtime's default)
      load_timeout_s: 300
      max_lease_s: 3600
modelsaar lifecycle status
modelsaar lifecycle load ollama/qwen3.8:latest --hold 900   # load, and hold a 15-minute lease
modelsaar lifecycle unload ollama/qwen3.8:latest
modelsaar lifecycle release lease_ab12cd34ef56

The CLI talks to the running gateway (GET /admin/lifecycle, POST /admin/lifecycle/{load,unload,release}, admin key). By default there is no automatic eviction, no background unloading and no model download: every operation is an explicit administrator action on an explicitly managed backend. Two further switches, each off by default, are described at the end of this page: automatic eviction of idle models and model downloads from an allowlist.

Rules

rule behaviour
explicit scope only backends with lifecycle.managed: true; anything else → 403 backend_not_managed, nothing is sent to the runtime
locks one lifecycle operation at a time per deployment; a concurrent load/unload waits for the running one
implicit leases a deployment with an in-flight or uncertain reservation is never unloaded → 409 deployment_busy. There is no force option
explicit leases load … --hold N records a lease (bounded by max_lease_s) and sends keep_alive ≥ N; while it is live, unload → 409 deployment_leased; release or expiry ends it
no race with dispatch during an unload the deployment is draining: admission admits no new request for it (the request is refused with the reason, not queued behind the unload)
budgets a load passes the same atomic admission as an inference request (slots, pool memory_gb); a load that does not fit → 503 admission_rejected. It never evicts another model unless the backend opted into auto_evict (below; unreleased)
observation residency is re-read from the runtime after every operation; the answer reports loaded_observed. After 0.2.0 an unload also reports absence_confirmed — true only when a listing taken after the call shows the model gone on every backend that knows it — and outcome: unconfirmed otherwise; an unconfirmed unload keeps the model counted against its pool
one model, several names (after 0.2.0) busy, queued-for and lease checks, the lock and the draining state apply to the physical model (endpoint + model name), so unload a/m is refused while b/m — the same model on the same server — is in use or leased

What a lease does not do: it cannot stop the runtime's own keep-alive expiry, an ollama stop typed by someone else, or another client that talks to the runtime directly. The runtime stays authoritative.

Runtimes

backend path load unload how
Ollama yes (generative models) yes the documented prompt-less POST /api/generate (keep_alive: 0 unloads). No prompt text is sent
llama-swap (detected by GET /running on an openai_compatible backend) no — llama-swap starts a model on its first request yes, per model (POST /api/models/unload/<model>) residency comes from /running, so routing sees which model is up and swap costs are visible in ranking and in the pool's memory accounting
vLLM, llama.cpp, other OpenAI-compatible servers no no 501 lifecycle_unsupported

Composing with llama-swap

Point an openai_compatible backend at llama-swap's /v1 and declare its models (context lengths are not discoverable through the proxy). Give the backend a resource_pool with max_concurrent: 1 when llama-swap runs one model at a time, so the gateway queues instead of forcing swaps mid-stream. With /running observed, the router's residency preference keeps a conversation on the model that is already up; set lifecycle.managed: true only if the gateway should also be allowed to unload a model on request.

Evidence

tests/test_lifecycle.py (10 cases, real HTTP, fixture backends emulating Ollama's /api/generate load/unload and llama-swap's /running and unload): unmanaged refusal, load/unload, lease block/expiry/ release, active-model protection, draining, memory-budget refusal, serialised concurrent operations, the CLI, llama-swap residency and per-model unload. On the GX10, real Ollama protected a leased model from unload, and llama-swap v279 started a real llama.cpp model on demand and confirmed its unload. Live evidence.

Opt-in automatic eviction (unreleased; after 0.2.0)

Off by default, and a second switch on top of managed:

backends:
  - id: ollama
    lifecycle:
      managed: true
      auto_evict: true               # default false
      max_evictions_per_request: 1   # 1..8
      evict_min_idle_s: 0            # a model used more recently than this is not evicted

Without it nothing changes: a request or an admin load that does not fit the pool's memory_gb is refused. With it, when the candidate does not fit, the gateway may unload idle models to make room and then serve the request. The figures are the pool's memory accounting (docs/routing.md, "Memory budgets"): resident models at what the runtime reports, the candidate at its cold figure.

rule detail
who can be evicted a registry deployment that is resident in the same pool, on a backend that itself set managed and auto_evict and can unload
one model, several names two backends[] entries can point at the same server, so one resident model can be a/m and b/m. Every rule here is applied to the physical model (endpoint + model name): it is evictable only if every name's backend opted in and nothing protects it under any name
never evicted a model with an in-flight or uncertain request, a request queued for it, an explicit lease, or a load or unload in progress — under any of its names; one used less than evict_min_idle_s ago; the candidate itself; a resident model the registry does not know (it is counted, not touched)
order and amount least recently used first (a model never used through this gateway counts as oldest); as few as needed; at most max_evictions_per_request; if the admissible set cannot free enough, nothing is unloaded and the request is refused
how the ordinary guarded unload (same 409 rules); all names of the model drain in one step and stay draining until the outcome is known
when memory counts as free only on confirmed absence: a successful residency listing taken after the unload call, from every backend that knows the model, without the model in it. The unload call's own answer is not evidence
failure an unload the runtime refuses, a listing that fails, is missing or predates the call, or a model the runtime still lists: the eviction stops, the model stays counted (unconfirmed in the history), and the request is refused
audit the decision record lists evictions; /admin/lifecycle history has an evict entry per victim with the request's deployment

What it is not: a scheduler (it reacts to one request), a guarantee against out-of-memory (the budget is still a budget), or protection against thrash — two workloads that alternate between models that do not fit together will swap on every switch; evict_min_idle_s turns that into refusals instead. The runtime may also evict on its own (Ollama's keep-alive); the gateway only sees that at the next residency refresh.

Hardware validation covered two aliases of one real Ollama deployment. A lease taken under either name protected the resident model. Releasing the lease allowed eviction and dispatch of its replacement. Live evidence.

Opt-in model downloads (unreleased; after 0.2.0)

Off by default, and a separate switch from auto_evict. With it an administrator can ask a managed backend's runtime to download a model that the operator has named on that backend's allowlist.

backends:
  - id: ollama
    lifecycle:
      managed: true
      allow_pull: true                  # default false
      pull_allowlist:                   # exact names with their tag, as the runtime lists them
        - model: gemma3:4b
          digest: sha256:a2af6cc3eb7f…  # optional pin: 64 hex characters as `ollama list --digests` / /api/tags show
          size_gb: 3.4                  # declared download size (1e9 bytes); required with a store budget
        - qwen3:8b                      # a bare name = no pin, no declared size
      pull_store_budget_gb: 200         # optional; listed sizes + declared size must fit, checked before any transfer
      pull_timeout_s: 7200
      pull_stall_timeout_s: 300         # a pull that reports nothing for this long is cancelled
modelsaar lifecycle pull ollama gemma3:4b --wait    # backend id, exact model name; --wait follows it to the end
modelsaar lifecycle status                          # progress, allowlist, withheld models, history
modelsaar lifecycle pull-cancel ollama

(POST /admin/lifecycle/pull {"backend", "model"} → 202 with the job, or 200 when the model is already there; POST /admin/lifecycle/pull-cancel {"backend"}; progress in GET /admin/lifecycle.)

rule detail
who can start a download the admin key, through the CLI or the admin API. Nothing else: a request for an absent model is an ordinary 404 model_not_found; no alias, probe, evaluation, eviction or scheduled task pulls anything
what can be downloaded only a name on that backend's pull_allowlist, matched exactly, tag included (gemma3 does not match gemma3:4b); anything else is 403 pull_not_allowed
who connects where the runtime downloads from its own registry. The gateway sends the model's name to the runtime (POST /api/pull) and reads status objects back; it never fetches model data, never contacts a registry, and never sends the runtime's insecure option
pinned digest a name with a digest is registered for routing only while the runtime lists it at exactly that digest — checked at every discovery, whoever installed the model and whenever it appeared. Otherwise it is withheld (pull.withheld in the status)
a pull that ends at another digest state digest_mismatch; the model is withheld from routing, including after restart. Ollama deletes by mutable name. An administrator can inspect and clean up the store; the gateway cannot establish exclusive ownership of a tag
a model already in the store nothing is transferred (200). At another digest than the pin: 409 digest_mismatch, nothing transferred or removed — the gateway does not replace or delete a model it did not create
store budget with pull_store_budget_gb, the sizes the runtime lists plus the entry's declared size_gb must fit, before any transfer (507 pull_over_budget, including if a listed size is unknown). While a transfer runs, layer totals above the declared size (+5 %) cancel it (over_size)
one at a time one pull per runtime endpoint, including through another backend alias; a second is 409 pull_in_progress
cancel closes the connection to the runtime, which is how a pull is cancelled; the terminal state is then read from the runtime's listing. If the runtime finishes despite cancellation, the model stays withheld until an administrator repeats the request and verifies its digest and size
every terminal state comes from the listing ok means the runtime lists the model (at the pin, if any) — not that the transfer said success. failed, cancelled, over_size, digest_mismatch each say whether the model is present and whether routing has accepted it
restart the job record is kept in the state database. A pull that was running when the gateway stopped reads interrupted; lifecycle pull again resumes it (Ollama resumes a cancelled pull from where it left off), pull-cancel clears it
audit /admin/lifecycle history has a pull entry per job with its outcome

What the gateway cannot do, and does not pretend to:

Runtimes: Ollama (/api/tags, /api/pull). Other backend types answer 501.

Tests cover authentication, the opt-in switch, concurrent requests, cancellation before transfer and during verification, budget accounting, digest checks, and recovery after restart. The real Ollama trial also checked cancellation and retry using a separate store with two small models.

Place a verified model on a worker

On the development branch, an administrator can select an identical model on any of a set of configured workers. List the backend IDs in routing.cluster_workers. Each eligible backend needs lifecycle.managed: true, support for managed loading and a resource pool with a memory budget. An empty worker list disables placement.

modelsaar lifecycle place gpu-a/my-model:latest --hold 120

The deployment ID identifies the desired weights and role. Other workers must supply the same verified identity. The gateway refreshes residency, checks locality and health, and excludes pools with unknown or insufficient capacity. Among workers that fit, it prefers a resident model, then lower occupancy, then more spare memory. A placement never downloads a missing model. Admission checks the selected worker again before submitting the load.

The admin API is POST /admin/lifecycle/place with {"deployment": "gpu-a/my-model:latest", "hold_s": 120}. A confirmed result is HTTP 200 and names the worker, selected deployment and projected pool usage. HTTP 202 means the runtime accepted the load but its residency listing did not confirm it. A supplied hold uses the existing residency lease and can be released with modelsaar lifecycle release <lease-id>. A placement lease protects weights from gateway eviction. Job execution and ownership are a separate part of the scheduler.

Cluster inference jobs

Enable routing.cluster_workers and run a gateway with its regular persistent state database. Send a non-streaming chat-completions body to POST /v1/cluster/jobs with the usual API key and a unique Idempotency-Key (1–128 letters, digits, dots, underscores, colons or hyphens). Choose auto for worker selection. Explicit deployments, session pins, tool round trips and reasoning continuity retain their routing constraints. Jobs use single-stage inference; requests selecting a cascade or streaming receive a validation error. The ordinary chat and Responses APIs retain their existing retry policy.

The scheduler ranks eligible configured workers with the same model identity and role by occupancy, then residency and deployment ID. It acquires admission against the selected worker and pool, checks health while queued, and checks the selected deployment again before inference. If a queued worker disappears, or a connection provably fails before transmission, the scheduler can move the job to another eligible replica. Immediately before dispatch it writes a durable submission marker. If the worker stops after that boundary and its result cannot be determined, the client receives 503 worker_outcome_unknown. The scheduler will not execute that job again.

The submitting request receives the completion, X-ModelSaar-Job-Id and a Location for GET /v1/cluster/jobs/{id}. A repeated identical POST with the same caller and key returns its receipt (202 while active, 200 after a known terminal outcome, 503 on uncertain submission). A changed payload or routing headers under an existing key returns 409. Receipts contain the state, selected worker deployment, request ID and outcome; answer text and prompts are not stored. A caller can read only its own receipts. Use a unique key per intended inference and preserve it across retries.

Ownership renews during execution (routing.cluster_job_lease_s, default 30 seconds). After a gateway restart the caller can repeat the original input to reclaim an expired queued job. An expired submitted job becomes uncertain. A fresh owner token fences out the old claimant. Keys remain in the local SQLite database, which must be preserved for retries across restarts. A ledger at its configured capacity refuses new keys; it retains old keys for deduplication. Defaults are 10,000 records per caller and 100,000 total (cluster_max_jobs_per_key and cluster_max_job_records under routing). One gateway manages admission across its configured backend machines. Separate gateways with separate state folders cannot deduplicate one another's work.