models

package
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
const (
	OriginOperator = "operator"
	OriginMesh     = "mesh"
)

Origins for cache entries.

View Source
const PartialMaxAge = 7 * 24 * time.Hour

PartialMaxAge is how long an abandoned .partial download survives before GCPartials removes it.

Variables

View Source
var ErrInvalidID = errors.New("models: invalid model id")

ErrInvalidID rejects a model id that is unsafe to use as a path component.

View Source
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.

View Source
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 LocalArtifactPath

func LocalArtifactPath(artifactURL string) (string, bool)

LocalArtifactPath reports whether an artifact_url points at a file already on this machine, and returns its filesystem path. Both `file:///abs/path` and a bare absolute path are accepted — operators writing a local catalog by hand reach for the latter.

This is how a node serves an existing GGUF collection (LM Studio, ollama, hand-built quants) without re-downloading gigabytes it already has.

func ValidateID added in v0.2.0

func ValidateID(id string) error

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 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

func LoadCatalog(ctx context.Context, path, url string, client *http.Client) (*Catalog, error)

LoadCatalog reads a catalog from a local path or URL (one must be set; path wins).

func ParseCatalog

func ParseCatalog(raw []byte) (*Catalog, error)

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.

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"`
}

CatalogModel is one curated model entry.

func (CatalogModel) Spec

func (m CatalogModel) Spec() *typesv1.ModelSpec

Spec converts a catalog entry to the proto ModelSpec.

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"`
	// 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.
	Path string `json:"path,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 currently loaded in a runtime;
	// retention never evicts a loaded model. Nil = nothing is loaded.
	IsLoaded func(id string) bool
	// contains filtered or unexported fields
}

Manager owns <data_dir>/models: downloads, verification, pins and LRU eviction under the disk budget.

func NewManager

func NewManager(dir string, maxDiskMB int64, log *slog.Logger) (*Manager, error)

NewManager loads (or initializes) the cache state.

func (*Manager) DownloadProgress added in v0.3.0

func (m *Manager) DownloadProgress(id string) (Progress, bool)

DownloadProgress reports live byte progress for an in-flight download.

func (*Manager) Ensure

func (m *Manager) Ensure(ctx context.Context, spec *typesv1.ModelSpec) (string, error)

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) 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

func (m *Manager) GCPartials(maxAge time.Duration) []string

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

func (m *Manager) Has(id string) bool

Has reports whether id is on disk, complete and verified (a `cached` candidate: loadable without a download).

func (*Manager) List

func (m *Manager) List() []Info

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) MaxDiskMB

func (m *Manager) MaxDiskMB() int64

MaxDiskMB is the live disk budget (0 = unlimited).

func (*Manager) Origin added in v0.3.0

func (m *Manager) Origin(id string) string

Origin reports who owns a cached model ("" when not cached).

func (*Manager) Path

func (m *Manager) Path(id string) string

Path returns where a model artifact lives locally.

func (*Manager) Pin

func (m *Manager) Pin(id string, pinned bool) error

Pin marks a model exempt from eviction; unpin re-allows it.

func (*Manager) Reconcile added in v0.4.0

func (m *Manager) Reconcile(cat *Catalog) []string

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. Anything else is logged and left alone. Returns the adopted ids.

func (*Manager) Remove

func (m *Manager) Remove(id string) error

Remove deletes a model from the cache.

func (*Manager) Retain added in v0.4.0

func (m *Manager) Retain() []string

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

func (m *Manager) RetentionDays() int

RetentionDays is the live retention window (0 = never evict on age).

func (*Manager) RunHousekeeping added in v0.4.0

func (m *Manager) RunHousekeeping(ctx context.Context)

RunHousekeeping GCs stale partials and applies retention on start and then hourly, until ctx ends.

func (*Manager) SetMaxDiskMB added in v0.4.0

func (m *Manager) SetMaxDiskMB(mb int64)

SetMaxDiskMB changes the disk budget live (PUT /api/v1/limits). It does not evict immediately; the next fetch does.

func (*Manager) SetRetentionDays added in v0.4.0

func (m *Manager) SetRetentionDays(days int)

SetRetentionDays changes the retention window live; Retain applies it.

func (*Manager) Stats added in v0.4.0

func (m *Manager) Stats() DiskStats

Stats sizes the store: real files, not the index.

func (*Manager) Touch

func (m *Manager) Touch(id string)

Touch refreshes LRU recency (called when a model serves a request).

func (*Manager) Verify

func (m *Manager) Verify(id string) error

Verify re-hashes a cached artifact against its recorded SHA. Serving paths call this before loading a model into the runtime.

type Progress added in v0.3.0

type Progress struct {
	ReceivedBytes int64 `json:"received_bytes"`
	TotalBytes    int64 `json:"total_bytes"`
}

Progress is live byte progress for an in-flight download.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL