Skip to content

Latest commit

 

History

History
210 lines (186 loc) · 14.6 KB

model-revisions.md

File metadata and controls

210 lines (186 loc) · 14.6 KB

Model artifact revisions

Last updated: 2026-10-09

An existing model can acquire new weights without changing its model ID or releasing another provider binary. Publishers upload an immutable revision and promote it; providers that support model_revisions_v1 prepare the new bytes while the old revision serves, then switch at a model-scoped idle boundary. The revision runbook covers operation and rollback.

Context

The original prefetch shortcut treated an advertised or loaded model ID as already available. desired_models identified builds by ID, so a new manifest under the same ID did not invalidate that shortcut. Promotion also replaced the coordinator's one expected hash, making still-running older weights fail routing and attestation before their replacements were ready.

Gemma's external MTP assistant already used a useful lifecycle: prepare while serving, fence new admissions, drain accepted requests, then install or reopen the original engine. ModelIdleUpgrade is now the shared lifecycle primitive. Target updates use it for every supported model; assistant resolution and verification remain owned by SpecDecArtifactFunnel.

Mechanism

flowchart TD
  P["publish-model-revision.py: hash complete local revision"] --> R["reserve R2 prefix for exact manifest identity"]
  R --> U["upload files; upload manifest last"]
  U --> V["handlePublishModelRevision: validate manifest and file sizes"]
  V --> S["SetExistingModelVersion; PromoteModelVersion; SyncModelCatalog"]
  S --> D["desired_models: model ID, version, aggregate SHA-256"]
  D --> B["prepareModelRevision: resume, reuse, verify hidden snapshot"]
  B --> J["serve old revision during rollout jitter"]
  J --> F["beginModelRevisionDrain: close new admission for this model"]
  F --> I{"accepted work idle?"}
  I -->|"timeout or cancellation"| O["reopen old revision; retry with backoff"]
  I -->|yes| C["commitModelRevisionIfIdle"]
  C --> L["if warm: unload old; validate and load new through normal admission"]
  L --> A["atomically select refs/main; advertise exact new hash"]
  L -->|failure| X["restoreModelRevision: restore old selection and reload"]
  X -->|success| O
  X -->|failure| E["keep model admission closed; retry"]
Loading

The coordinator sends revision fields only to providers advertising the model_revisions_v1 protocol capability. It includes already-advertised concrete models without aliases, and continues to use alias lineage for build-ID swaps. An emitted alias target suppresses competing targets for its previous/retired members. If the provider cannot acquire that alias target, its eligible old build still receives same-ID revision updates. A new hash or version changes the desired-state deduplication key. Reconnects receive the latest state, so a provider can skip revisions published offline. Older providers keep the ID-only protocol and need one provider upgrade to gain revision reconciliation.

A revision can specify hugging_face_artifact with its own pinned public repo, commit and optional subdirectory. The publisher exposes --hf-repo-id, --hf-revision and --hf-path-prefix; the API records that locator on the version row. Providers verify the same manifest checksums from HF and R2, with HF first and R2 fallback. The upstream/feed hugging_face_id is unchanged. For a new version, omission selects R2-only. An identical publish-revision retry uses SetExistingModelVersion to preserve the stored locator, including any deliberate mirror edit made since the first attempt. Normal registration through SetModelVersion continues to support adding, changing or clearing this transport metadata without changing the immutable file identity.

ModelDownloader retains its foreground parallel scheduler and background sequential scheduler. They share manifest validation, checksum/resume transport, immutable publication, file reuse and a cancellable process-shared writer lease. Files copied from the active snapshot are independently owned and reverified. The implementation uses copies, not a deduplicating blob store; disk must fit both retained and incoming revisions. A storage failure preserves the selection. ModelArtifactWriteLease.openDescriptor keeps persistent lock files under the selected cache root's .artifact-writer-locks directory, outside each removable model directory. ModelDownloader.remove acquires the same lease without waiting and refuses removal while a download or update owns it. Keeping the lock inode through removal prevents another process from acquiring a second lock on a recreated model tree; the operating system releases a crashed process's lease.

After prefetch and catalog prewarming, protectPreparedModelRevision reacquires that lease and revalidates the replacement against its manifest and the selected rollback snapshot against the live hash. It derives the replacement's model metadata from those protected files, then rechecks desired state and the serving selection after the hash work. Missing, corrupt or superseded snapshots abort preparation before admission draining or engine unloading begins; the successful attempt retains the lease through activation or recovery.

Completed snapshots live at snapshots/.revision-<identity_sha256>. The snapshot key hashes the model ID, version, R2 prefix, aggregate hash and path-sorted file entries; creation timestamps and download mirrors do not affect it. The wire aggregate alone cannot identify a layout because it combines file digests without hashing their paths. Reconciliation also reads the selected manifest receipt's version, so equal-content versions still converge to the requested layout. Hidden staging and completed-but-unselected snapshots are excluded from discovery. ModelScanner.findLatestSnapshot honors refs/main; modification times cannot undo a rollback. Legacy caches without a ref retain modification-time discovery. The provider never deletes retained revisions automatically.

The selected receipt must match the requested version/hash, have valid manifest metadata and identify its canonical snapshot directory. Receipt checks do not hash weights during reconciliation. When reusing a snapshot, verifyRevisionAndRepairReceipt first checks that the complete integrity-file inventory from ModelScanner.collectWeightFiles matches the manifest, then verifies its bytes under the writer lease and atomically restores a missing, malformed or mismatched receipt. Extra templates, tokenizer files or weights are rejected on reuse and before first publication from staging; unrelated notes and hidden receipts remain outside the integrity surface. Corrupt weights are rejected without rewriting the receipt. Canonical parent comparison also lets activation and rollback use resolved paths beneath a valid linked model directory while rejecting snapshots outside that model's store.

For an activation-enabled first download with no usable selected snapshot, ModelArtifactRevision.publishRevision writes the refs/main intent before atomically moving the verified staging directory into its final snapshot path. A crash before that move leaves no discoverable model; a crash afterward leaves the complete verified snapshot discoverable without another download. A retry may replace an intent whose target is still absent. Existing managed or legacy snapshots retain their selection until activateRevision; preparation with activate: false never writes the initial intent.

The monitor runs one revision attempt at a time and retries with jittered, exponential backoff capped at 300 seconds. A new desired identity resets that backoff and cancels the superseded attempt. Each attempt rechecks current desired state before activation and after each suspending publication step. Publication returns success before activation consumes alias lineage; a superseded or cancelled attempt restores the previous selection and leaves the current alias drop pending for retry. A provisional advertisement is not treated as converged while activation is in progress. The drain waits at most 120 half-second checks for accepted work; loading and recovery occur afterward and are not included in that wait bound. Other resident models remain available. Cold loads serialize behind activation so another load cannot consume the space reserved by unloading the old target. A warm replacement is loaded from its explicit snapshot path before refs/main changes, so a crash during validation boots the old snapshot.

Normal memory admission, engine compatibility, template checks, hash identity and prefix-cache rules still apply. The update path does not allocate two full target models simultaneously. A single-provider model can have a loading gap; random rollout jitter is not a fleet availability guarantee.

Invariants

  1. A published version cannot change identity. SetModelVersion rejects different hashes, prefixes, sizes, file counts or file manifests for an existing (model_id, version). An identical retry preserves the original uploader and upload timestamp. The publisher's conditional R2 reservation rejects competing different content before uploading. R2 supports the conditional PutObject used for that reservation (Cloudflare API contract).
  2. Selection follows verification. ModelArtifactRevision.publishRevision records the manifest beside verified bytes. activateRevision atomically changes the ref; no in-place snapshot replacement is used for manifest models.
  3. Promoting a revision does not revoke previous approved bytes. ModelRegistryRecord.ServingVersions contains previously promoted ready revisions. Routing, models_update, drained inventory replacement and challenge validation accept only the desired or explicitly retained hashes for that same model. Unpromoted hashes are excluded. Existing legacy omission semantics are unchanged.
  4. Revocation is explicit. RetireModelVersion removes an inactive revision from the accepted set. It refuses the active version and invalidates the store cache. Retirement is not automatic fleet cleanup. Idempotent registration preserves retired status even when a subsequent promotion fails. Retired versions cannot be promoted again; new approval requires a new version.
  5. Accepted requests keep their engine until idle. beginModelRevisionDrain uses the same admission fence as MTP upgrades. commitModelRevisionIfIdle checks coordinator requests, local reservations, engine work and load/unload ownership before changing the slot.
  6. A failed rollback is not reported as recovery. restoreModelRevision returns failure on a ref or reload error; finishModelRevisionDrain leaves that model fenced until a later attempt can recover it. Shutdown cancels and joins revision work.

Failure modes

Condition Result
Incomplete upload or invalid manifest Publishing is rejected; desired revision stays unchanged
Catalog/alias refresh or provider desired-state send fails after promotion API returns retryable 503; retry the same version and source fields. Alias read failures retain the last alias map and suppress fan-out until refresh succeeds; already-applied hash policy remains in effect
Network interruption or insufficient disk Old revision serves; partial downloads can resume
Removal while a writer owns the model lease Removal returns a busy error; retry after download or update completes
Process exits after first activation-enabled snapshot publication Prewritten ref selects the complete verified snapshot on restart
Desired revision changes during preparation or publication Old attempt is cancelled; publication restores the previous selection and preserves pending alias cleanup; completed bytes may remain for reuse
Explicit external snapshot override The provider respects the override and does not replace it through the cache
Busy accepted requests outlast drain wait New admission reopens on old revision; retry later
New engine fails to load Restore old ref and attempt to reload old engine
Ref restoration or old reload fails Model remains fenced; other models continue
Provider has not received the supporting binary Retained approved revision remains valid; no automatic same-ID update
Operator retires a still-used revision Its hash is no longer accepted; those providers can lose routing/trust

Code map

Concern Implementation
Publisher and immutable R2 reservation scripts/publish-model-revision.py (reserve_revision, publish_files)
Update and retirement API coordinator/api/catalog/model_revision_handlers.go
Persistent acceptance and immutable versions coordinator/store/model_revision.go, postgres_model_revisions.go, postgres_model_registry.go; CachedStore overrides
Desired state and routing hash admission coordinator/registry/model_commands.go, model_revisions.go, model_catalog.go
Drained inventory hash validation coordinator/registry/provider_models_replace.go (ReplaceProviderModels)
Immutable files and atomic selection provider-swift/Sources/ProviderCore/Models/ModelArtifactRevision.swift, ModelArtifactWriteLease.swift
Verified local receipt recovery provider-swift/Sources/ProviderCore/Models/ModelArtifactReceipt.swift (verifyRevisionAndRepairReceipt)
Reconciliation and backoff provider-swift/Sources/ProviderCore/ProviderLoop+ModelRevisions.swift
Snapshot revalidation before draining provider-swift/Sources/ProviderCore/ProviderLoop+ModelRevisionPreparation.swift (protectPreparedModelRevision)
Guarded inventory publication provider-swift/Sources/ProviderCore/ProviderLoop+PrefetchPublication.swift (publishVerifiedPrefetch)
Activation and recovery provider-swift/Sources/ProviderCore/ProviderLoop+ModelRevisionActivation.swift, ProviderLoop+ModelRevisionRecovery.swift
Shared target/assistant drain lifecycle provider-swift/Sources/ProviderCore/Models/ModelIdleUpgrade.swift

Related