Documentation
¶
Overview ¶
Package models manages the local model cache: catalog manifests (teraflock/models format), resumable GGUF downloads with SHA256 verification, and LRU eviction under the operator's disk budget.
Index ¶
- Constants
- Variables
- func CompositeSHA256(partHashes []string) string
- func FetchCatalog(ctx context.Context, path, url string, client *http.Client, prev CatalogStamp) (*Catalog, CatalogStamp, error)
- func LocalArtifactPath(artifactURL string) (string, bool)
- func LocalArtifactURL(path string) string
- func ManifestIDOf(id, quant string) string
- func ValidateID(id string) error
- type Artifact
- type Catalog
- type CatalogModel
- type CatalogPart
- type CatalogStamp
- type DiskStats
- type Info
- type Manager
- func (m *Manager) CancelDownload(id string) bool
- func (m *Manager) DownloadProgress(id string) (Progress, bool)
- func (m *Manager) Ensure(ctx context.Context, spec *typesv1.ModelSpec) (string, error)
- func (m *Manager) EnsureArtifact(ctx context.Context, spec *typesv1.ModelSpec, origin string) (Artifact, error)
- func (m *Manager) EnsureOrigin(ctx context.Context, spec *typesv1.ModelSpec, origin string) (string, error)
- func (m *Manager) GCPartials(maxAge time.Duration) []string
- func (m *Manager) Has(id string) bool
- func (m *Manager) List() []Info
- func (m *Manager) MaxDiskMB() int64
- func (m *Manager) Origin(id string) string
- func (m *Manager) Path(id string) string
- func (m *Manager) Pin(id string, pinned bool) error
- func (m *Manager) Placement(id string) string
- func (m *Manager) Reconcile(cat *Catalog) []string
- func (m *Manager) Remove(id string) error
- func (m *Manager) Retain() []string
- func (m *Manager) RetentionDays() int
- func (m *Manager) RunHousekeeping(ctx context.Context)
- func (m *Manager) SetMaxDiskMB(mb int64)
- func (m *Manager) SetPlacement(id, reason string)
- func (m *Manager) SetRetentionDays(days int)
- func (m *Manager) Stats() DiskStats
- func (m *Manager) Touch(id string)
- func (m *Manager) Verify(id string) error
- type Progress
Constants ¶
const ( StateDownloading = "downloading" StateReady = "ready" // StateMissing is reported (never stored) for a ready entry whose file // is gone from disk: the index knows the model, the operator or // something else deleted the artifact. It does not count against the // budget; the next load re-downloads it. StateMissing = "missing" )
States a cache entry moves through.
const ( OriginOperator = "operator" OriginMesh = "mesh" )
Origins for cache entries.
const PartialMaxAge = 7 * 24 * time.Hour
PartialMaxAge is how long an abandoned .partial download survives before GCPartials removes it.
Variables ¶
var ErrCatalogNotModified = errors.New("models: catalog not modified")
ErrCatalogNotModified is returned by FetchCatalog when the server says the catalog still matches the stamp it was given.
var ErrInvalidID = errors.New("models: invalid model id")
ErrInvalidID rejects a model id that is unsafe to use as a path component.
var ErrNoArtifact = errors.New("no artifact in spec")
ErrNoArtifact means a ModelSpec names neither an artifact_url nor parts: there is nothing to download. A daemon that predates multi-part specs sees every sharded assignment this way, and reports it `failed` with this reason so the coordinator backs off (proto design note 2026-09-08-sharded-artifacts).
var ErrOverBudget = errors.New("models: cannot fit")
ErrOverBudget means a model cannot fit inside max_disk_mb even after evicting everything eviction is allowed to touch.
var ErrSHAMismatch = errors.New("models: sha256 mismatch")
ErrSHAMismatch means a downloaded artifact failed verification. The daemon refuses to serve hash-mismatched files (SPEC §6).
Functions ¶
func CompositeSHA256 ¶ added in v0.6.0
CompositeSHA256 is the single "quant sha" of a multi-part artifact: the hex sha256 over the concatenation of the lowercase-hex part hashes in series order, no separators. The catalog emitter, the control-plane registry and the daemon all derive the same value, so a sharded spec's sha256 keeps meaning for DispatchRequest.quant_sha256 pinning. It is never a file hash: files are verified against their own part hash.
func FetchCatalog ¶ added in v0.7.2
func FetchCatalog(ctx context.Context, path, url string, client *http.Client, prev CatalogStamp) (*Catalog, CatalogStamp, error)
FetchCatalog is LoadCatalog with conditional requests. prev is the stamp of the copy the caller already holds (zero = unconditional); when the server answers 304 the error is ErrCatalogNotModified and the caller keeps its copy. A local path is always re-read.
func LocalArtifactPath ¶
LocalArtifactPath reports whether an artifact_url points at a file already on this machine, and returns its filesystem path. Accepted forms:
file:///models/a.gguf /models/a.gguf ~/models/a.gguf (everywhere) file:///C:/models/a.gguf C:\models\a.gguf C:/models/a.gguf (Windows) file://C:\models\a.gguf \\nas\share\a.gguf file://nas/share/a.gguf
Operators writing a local catalog by hand reach for the bare path. On Windows a rooted POSIX path (/models/a.gguf) is accepted too and, as with any Windows API, resolves against the current drive; a catalog written on one platform is usable on the other. Percent-escapes in a file:// URL are decoded (file:///models/my%20model.gguf).
This is how a node serves an existing GGUF collection (LM Studio, ollama, hand-built quants) without re-downloading gigabytes it already has.
func LocalArtifactURL ¶ added in v0.6.0
LocalArtifactURL is the inverse: the file:// URL for a filesystem path, in the form every platform's LocalArtifactPath accepts (file:///C:/x on Windows, file:///x elsewhere, file://nas/share/x for a UNC path). Build artifact_url values with this rather than "file://" + path: that yields file://C:\x on Windows, which LocalArtifactPath tolerates but nothing else does.
func ManifestIDOf ¶ added in v0.7.2
ManifestIDOf is ManifestID for an id and quant held separately.
func ValidateID ¶ added in v0.2.0
ValidateID rejects ids that must never reach filepath.Join. Catalog entries arrive over the network (models.manifest_url is a remote default), so an id such as "../../etc/cron.d/evil" would otherwise escape Dir and let a compromised catalog write anywhere the daemon can.
Types ¶
type Artifact ¶ added in v0.6.0
type Artifact struct {
// Path is the GGUF to load: the file, or part 1 of a sharded set.
Path string
// MmprojPath is the vision projector sidecar for --mmproj; "" when none.
MmprojPath string
// SizeBytes is what the whole set occupies on disk (0 = unknown).
SizeBytes int64
}
Artifact is a model's files as the runtime needs them.
type Catalog ¶
type Catalog struct {
Models []CatalogModel `yaml:"models" json:"models"`
}
Catalog is the manifest format of the teraflock/models repo (catalog/*.yaml). JSON is accepted too.
func LoadCatalog ¶
LoadCatalog reads a catalog from a local path or URL (one must be set; path wins).
func ParseCatalog ¶
ParseCatalog decodes YAML or JSON manifest bytes.
func (*Catalog) Find ¶
func (c *Catalog) Find(id string) (CatalogModel, bool)
Find returns the entry with the given id.
func (*Catalog) Quants ¶ added in v0.7.2
func (c *Catalog) Quants(manifestID string) []CatalogModel
Quants returns the entries emitted from one manifest, in catalog order: the first is the manifest's first quant, which is what the mesh gateway's `flock/<manifest id>` alias serves.
type CatalogModel ¶
type CatalogModel struct {
ID string `yaml:"id" json:"id"`
// DisplayName is the human-readable name (incl. quant) UIs show —
// ids are ambiguous now that model lines carry point versions
// (qwen3-8b vs qwen3.8-27b). Empty in pre-field catalogs.
DisplayName string `yaml:"display_name" json:"display_name"`
Family string `yaml:"family" json:"family"`
ParamsB float64 `yaml:"params_b" json:"params_b"`
Quant string `yaml:"quant" json:"quant"`
SHA256 string `yaml:"sha256" json:"sha256"`
MinVRAMMB uint64 `yaml:"min_vram_mb" json:"min_vram_mb"`
MinRAMMB uint64 `yaml:"min_ram_mb" json:"min_ram_mb"`
License string `yaml:"license" json:"license"`
ArtifactURL string `yaml:"artifact_url" json:"artifact_url"`
SizeBytes uint64 `yaml:"size_bytes" json:"size_bytes"`
PayoutClass string `yaml:"payout_class" json:"payout_class"`
ContextLength uint32 `yaml:"context_length" json:"context_length"`
Embeddings bool `yaml:"embeddings" json:"embeddings"`
// Decision marks a typed decision model (served for /v1/systemone,
// never for chat). Mutually exclusive with Embeddings; absent (false)
// in catalogs that predate the field.
Decision bool `yaml:"decision" json:"decision"`
// Parts lists the shards of a sharded GGUF in series order
// (<name>-00001-of-0000N.gguf ...), each with its own hash. Empty for a
// single-file model. When set, ArtifactURL is empty, SizeBytes is the
// total across parts and SHA256 is the composite id (CompositeSHA256),
// never a file hash.
Parts []CatalogPart `yaml:"parts" json:"parts,omitempty"`
// Mmproj is the optional vision projector sidecar (mmproj-*.gguf)
// llama-server takes via --mmproj; verified and stored like a part,
// not counted in SizeBytes.
Mmproj *CatalogPart `yaml:"mmproj" json:"mmproj,omitempty"`
}
CatalogModel is one curated model entry.
func (CatalogModel) ManifestID ¶ added in v0.7.2
func (m CatalogModel) ManifestID() string
ManifestID is the catalog manifest a flat entry was emitted from: flat ids are `<manifest id>-<quant lowercased>` (models repo, tools/validate EmitFlat), and the manifest id is what the public `flock/<id>` alias names. "" when the id does not have that shape (an operator's own model).
func (CatalogModel) Spec ¶
func (m CatalogModel) Spec() *typesv1.ModelSpec
Spec converts a catalog entry to the proto ModelSpec.
type CatalogPart ¶ added in v0.6.0
type CatalogPart struct {
URL string `yaml:"url" json:"url"`
SHA256 string `yaml:"sha256" json:"sha256"`
SizeBytes uint64 `yaml:"size_bytes" json:"size_bytes"`
}
CatalogPart is one pinned file of a multi-file artifact: a GGUF shard or the mmproj sidecar. Same three names as the proto ArtifactPart and the catalog YAML so nothing is renamed between them.
type CatalogStamp ¶ added in v0.7.2
CatalogStamp is the HTTP validators of a fetched catalog (ETag and Last-Modified). Handing the last stamp back to FetchCatalog makes the request conditional, so a periodic refresh of an unchanged catalog costs a 304 instead of the whole document.
type DiskStats ¶ added in v0.4.0
type DiskStats struct {
// ModelsBytes counts complete artifacts that are actually on disk.
ModelsBytes int64
// PartialBytes counts resumable .partial downloads (live and abandoned).
PartialBytes int64
// BudgetBytes is max_disk_mb (0 = unlimited).
BudgetBytes int64
// FreeBytes is free space on the volume holding Dir.
FreeBytes int64
Dir string
}
DiskStats is the aggregate store view for /api/v1/status.
type Info ¶
type Info struct {
ID string `json:"id"`
SizeBytes int64 `json:"size_bytes"`
Pinned bool `json:"pinned"`
LastUsed time.Time `json:"last_used"`
State string `json:"state"`
// Origin is "operator" or "mesh" (who installed it).
Origin string `json:"origin"`
// Placement is why the mesh placed it (floor, demand, warm, stage);
// "" when unknown.
Placement string `json:"placement,omitempty"`
// ReceivedBytes is live progress, present only while downloading.
ReceivedBytes int64 `json:"received_bytes,omitempty"`
// Path is the artifact's absolute path; empty unless the file exists.
// For a multi-file entry it is the first shard (see Manager.Path).
Path string `json:"path,omitempty"`
// PartsTotal is the number of files in a multi-file artifact (shards
// plus the mmproj sidecar); 0 for a plain single-file model.
PartsTotal int `json:"parts_total,omitempty"`
// PartsDone is how many of them are verified and in place; equal to
// PartsTotal once ready.
PartsDone int `json:"parts_done,omitempty"`
}
Info is a local cache listing row.
type Manager ¶
type Manager struct {
Dir string
Client *http.Client
Log *slog.Logger
// OnProgress, when set, receives byte progress during downloads
// (throttled). total is 0 when the server sent no length and the
// catalog carries no size.
OnProgress func(id string, received, total int64)
// Activity receives store events (downloads, evictions, missing
// files). May be nil.
Activity *activity.Ring
// IsLoaded reports whether a model is in a runtime right now — loaded,
// serving a request, or on its way in (download, admission, runtime
// start). Neither retention nor disk-budget eviction ever takes such a
// model: deleting the weights under a live llama-server (which mmaps
// them) is a crash or a silently wrong answer, never a freed budget.
// Nil = nothing is loaded.
IsLoaded func(id string) bool
// DownloadMaxAttempts, DownloadBackoffMin/Max bound the retry schedule
// for a transient download failure (rate limiting, a flaky upstream).
// NewManager sets the package defaults; tests lower them to keep a
// simulated failure fast.
DownloadMaxAttempts int
DownloadBackoffMin, DownloadBackoffMax time.Duration
// contains filtered or unexported fields
}
Manager owns <data_dir>/models: downloads, verification, pins and LRU eviction under the disk budget.
func NewManager ¶
NewManager loads (or initializes) the cache state.
func (*Manager) CancelDownload ¶ added in v0.8.3
CancelDownload stops the download of id whoever started it, waits for it to wind down (files closed, entry gone), and reports whether there was one. The .partial stays for a later resume; Remove deletes it. Never call it with m.mu held: the transfer needs the lock to finish.
func (*Manager) DownloadProgress ¶ added in v0.3.0
DownloadProgress reports live byte progress for an in-flight download.
func (*Manager) Ensure ¶
Ensure makes the model available locally: verified cache hit, resumed partial download, or full download. Returns the local path. The entry is operator-owned; see EnsureOrigin.
func (*Manager) EnsureArtifact ¶ added in v0.6.0
func (m *Manager) EnsureArtifact(ctx context.Context, spec *typesv1.ModelSpec, origin string) (Artifact, error)
EnsureArtifact is EnsureOrigin returning every path the runtime needs (the mmproj sidecar has no place in a single string).
A sharded spec (parts) is fetched one part at a time, each through the same resumable, hash-verified download as a single file, into <Dir>/<id>/ under the upstream names; a shard that verified once is never fetched again, and progress is the sum over the whole set.
func (*Manager) EnsureOrigin ¶ added in v0.3.0
func (m *Manager) EnsureOrigin(ctx context.Context, spec *typesv1.ModelSpec, origin string) (string, error)
EnsureOrigin is Ensure with ownership: a mesh-origin fetch may only evict other mesh-origin models to make room (the operator's models are off limits to the coordinator), and a model the operator already has is never re-labelled as the mesh's.
func (*Manager) GCPartials ¶ added in v0.4.0
GCPartials removes .partial files whose last write is older than maxAge and that no download is currently writing. An abandoned resume otherwise leaks its bytes forever. Returns the ids cleaned up.
func (*Manager) Has ¶ added in v0.4.0
Has reports whether id is on disk, complete and verified (a `cached` candidate: loadable without a download).
func (*Manager) List ¶
List returns cache contents sorted by id. Every ready entry is stat'd: a file deleted underneath the daemon shows as StateMissing rather than a phantom `ready` that still counts against the budget.
func (*Manager) Origin ¶ added in v0.3.0
Origin reports who owns a cached model ("" when not cached).
func (*Manager) Path ¶
Path returns where a model artifact lives locally: <Dir>/<id>.gguf, or for a multi-file entry the first shard inside <Dir>/<id>/ (llama-server discovers the sibling shards from it). An id the cache does not know is assumed single-file.
func (*Manager) Placement ¶ added in v0.9.0
Placement reports why the mesh placed a cached model ("" when unknown or not cached); see cacheEntry.Placement.
func (*Manager) Reconcile ¶ added in v0.4.0
Reconcile adopts artifacts that are in Dir but not in the index — a models.json lost or rolled back, a file copied in by hand — as operator-origin entries when their name is a known catalog id, their size matches the catalog, and (when the catalog states a real hash) their sha256 verifies. Hash pinning is what lets the mesh trust what a node serves (SPEC §6), so a file that merely has the right name and size is not enough; the hash is computed outside the lock, once per distinct file. A multi-file set (<id>/ holding the catalog's shards and mmproj) is adopted only when every file is present and verifies. Anything else is logged and left alone. Returns the adopted ids.
func (*Manager) Retain ¶ added in v0.4.0
Retain evicts unpinned, unloaded models that have not served a request for longer than the retention window (RetentionDays; 0 = never). Mesh and operator models alike: the operator opted in by setting it. Returns the evicted ids.
func (*Manager) RetentionDays ¶ added in v0.4.0
RetentionDays is the live retention window (0 = never evict on age).
func (*Manager) RunHousekeeping ¶ added in v0.4.0
RunHousekeeping GCs stale partials and applies retention on start and then hourly, until ctx ends.
func (*Manager) SetMaxDiskMB ¶ added in v0.4.0
SetMaxDiskMB changes the disk budget live (PUT /api/v1/limits). It does not evict immediately; the next fetch does.
func (*Manager) SetPlacement ¶ added in v0.9.0
SetPlacement records why the mesh asked for a cached model, replacing an earlier reason (a warm of a cached copy is a new placement). A model the cache does not know is ignored.
func (*Manager) SetRetentionDays ¶ added in v0.4.0
SetRetentionDays changes the retention window live; Retain applies it.