mirror of
https://github.com/mudler/LocalAI.git
synced 2026-07-30 18:09:05 -04:00
* fix(worker): reap deleted backends and stop models that live on a worker
Three related backend-lifecycle defects, all reachable from the same
production incident on a Jetson/Thor worker: a deleted backend's gRPC
process survived ~40 minutes with its directory removed from disk, a later
model load was routed to that orphan and failed with a certifi path pointing
into the deleted directory, and the admin could not stop the model because
the frontend reported it as not loaded.
1. backend.delete orphaned the process it claimed to delete
------------------------------------------------------------
s.processes is keyed by `modelID#replicaIndex` (buildProcessKey), so the
backend name never appeared in a key and was recorded nowhere on the
process. backend.delete resolved its target via isRunning/stopBackend, whose
prefix path only matches a bare *modelID* - a delete keyed on a backend name
resolved to zero keys, the stop silently no-op'd, and the files were removed
out from under a live process.
The install fast path then handed that orphan back out: it returns any live
process for the (model, replica) slot without checking which backend started
it, so a reinstalled variant inherited the deleted backend's port.
- Record backendName on backendProcess, threaded installBackend ->
startBackend.
- Add resolveProcessKeysForBackend, matching the recorded name and resolving
alias <-> concrete via ListSystemBackends *before* DeleteBackendFromSystem
erases the metadata that carries the alias. Alias resolution failure
degrades to name-only matching so a delete never fails on it.
- backend.stop goes through resolveStopTargets, which accepts a backend
name, a model name, or an exact modelID#replica key. Its payload field is
named "backend" but is published with all three meanings: the admin UI
sends a backend name, UnloadRemoteModel sends a model name, and the
router's abandoned-load reap (#10948) sends an exact replica key.
Narrowing it to backend names alone would strand the latter two.
backend.delete stays strict - its identifier is unambiguously a backend.
- Gate the install fast path on processMatchesBackend so a slot held by a
different backend is restarted rather than reused. Processes with no
recorded name (pre-upgrade) are accepted, so rollout does not restart
every running backend.
- stopBackendExact reports a real stop failure - the process still being
alive afterwards, which is precisely what finishBackendStop already
detects to keep the entry and its port reserved - and backend.delete no
longer replies success when it knew about a process and could not kill it.
"No process was running" stays a success but is logged, so the orphan case
is visible rather than silent.
2. /backend/shutdown reported a running model as missing
---------------------------------------------------------
ModelLoader.deleteProcess short-circuits on a miss in this replica's
in-memory store. In distributed mode the authoritative record of "is this
model loaded" is the shared node registry: a frontend replica that never
served the model itself (load balancer picked a peer, or the replica
restarted) has no local entry. The remote unload path that pkg/model
documents ("when ShutdownModel is called for a model with no local process,
UnloadRemoteModel is called") sat behind that short-circuit, unreachable in
exactly the case it exists for. #10865 reworked this function but kept the
short-circuit at the top, so the gap survived that refactor.
- deleteProcess consults the remote unloader on a local-store miss, via a
shared unloadRemote helper so this branch and the existing
no-local-process branch both prefer #10865's RemoteModelContextUnloader,
preserving force propagation across the distributed boundary.
- UnloadRemoteModelContext reports ErrRemoteModelNotLoaded when no node has
the model; it previously returned nil, making a no-op stop
indistinguishable from a real one. The converse case (nodes have it, none
could be stopped) already errors since #10865 joined the per-node
failures, so that half of the original fix was dropped as redundant.
- Only when the model is absent locally AND cluster-wide does the endpoint
report not-found, now 404 naming both scopes rather than a bare 500.
- modelNotFoundErr becomes the exported ErrModelNotFound so the HTTP layer
can map it without string matching; watchdog's identity comparison becomes
errors.Is.
3. Coverage for the bounded Free() that #10865 shipped untested
----------------------------------------------------------------
The original branch also bounded the pre-stop Free(), but #10865 landed that
fix first (workerBackendFreeTimeout, applied in both stopBackendExact and
handleModelUnload). That production change is therefore DROPPED here as
superseded - master's version is strictly better, since it also releases the
supervisor mutex across the call and keeps the port reserved until
termination completes.
What #10865 did not ship is a test, and the bound is load-bearing: the
router-side reap in #10948 sends backend.stop for an abandoned load, and
against a wedged backend an unbounded Free would swallow that stop before it
reached the process. Nothing failed if the bound regressed.
The spec stands up a real gRPC backend server whose Free handler never
returns - what a Python backend looks like when its single worker thread
(PYTHON_GRPC_MAX_WORKERS=1 on 37 backends) is occupied by a stuck LoadModel.
A stub socket is not sufficient and was tried first: without a completed
HTTP/2 handshake, gRPC's own ~20s connect timeout ends the call, so that
version passed against the very bug it targets. With the connection READY,
only the caller's deadline can end it, so the spec hangs to its 60s limit if
the timeout is removed and passes with it.
Its fixture process is deliberately never started. go-processmanager v0.1.1
writes Process.pid from readPID() without synchronization, so a live process
races its own monitor goroutine under -race - reproducible with a bare
Run()+Stop() and unrelated to this spec. Since
scripts/model-lifecycle-conformance.sh runs this package with -race and is
fail-closed, starting one would turn that gate red on an upstream defect. An
unstarted process still proves the point: the stop is reached and the slot
released, which is exactly what an unbounded Free prevents.
Verified: make lint (new-from-merge-base origin/master) reports 0 issues;
scripts/model-lifecycle-conformance.sh passes all three stages including the
FizzBee liveness check (1458 states, IsLive: true).
Assisted-by: Claude:claude-opus-4-8 golangci-lint
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
* fix(distributed): keep remote unload idempotent, ask presence separately
2035a4d25 made UnloadRemoteModel return ErrRemoteModelNotLoaded when no node
holds the model, so ShutdownModel could answer 404 instead of a misleading
500. That narrowed a shared adapter contract to serve one caller and broke
the documented idempotent-unload guarantee, which CI caught on PR #10956:
[FAIL] Node Backend Lifecycle (NATS-driven) > NATS backend.stop events
should be no-op for models not on any node [Distributed]
Expected success, but got: model not loaded on any node
The spec name states the contract outright. The matching unit assertion was
updated in that commit; this e2e one was missed because it lives under
tests/e2e/ with no build tags and does not run in package-scoped test runs.
Caller audit - who breaks when an idempotent unload becomes an error:
- pkg/model/watchdog.go:902 (LRU memory reclaimer) is the serious one. It
untracks a model ONLY when shutdown returns nil or ErrModelNotFound. A new
error type means the model is never untracked, so the reclaimer keeps
re-selecting the same entry and never reclaims - a live wedge whenever a
local store entry outlives the remote model.
- core/services/galleryop/managers_local.go:43 (DeleteModel) would warn on
every deletion of an already-unloaded model.
- core/services/modeladmin/{state,config,remote_sync}.go stop instances
best-effort against models that are frequently not loaded.
- deleteProcess itself: the no-local-process branch returns the unload result
directly, so a stale local entry for a model no longer on any node turned a
previously-successful cleanup into a failure.
Only ShutdownModel wants the distinction, and only on the local-store-miss
path. So the distinction moves to the caller instead of the contract:
- UnloadRemoteModel/UnloadRemoteModelContext return nil again when no node
has the model, and ErrRemoteModelNotLoaded is removed.
- New optional RemoteModelPresenceChecker (HasRemoteModel) answers the
question directly. deleteProcess consults it BEFORE unloading, because an
idempotent unload cannot report afterwards whether anything was stopped.
Absent locally AND cluster-wide is the only case that reports 404.
- A failed registry lookup is surfaced rather than reported as absence: an
unreachable registry is not evidence a model is gone, and answering a
confident 404 off a failed lookup is how an operator gets told a running
model does not exist.
- Unloaders that predate the extension keep working - deleteProcess attempts
the unload rather than refusing it - and compile-time assertions in the
nodes package now pin all three optional interfaces, since both are
consumed by runtime type assertion where drift degrades behavior silently
instead of failing the build.
The contract is now pinned at both levels that disagreed, each spec pointing
at the other: "with no nodes returns nil" in unloader_test.go and "should be
no-op for models not on any node" in node_lifecycle_test.go.
Verified: full distributed e2e suite 233 passed / 0 failed (the suite that
failed 232/1 in CI); pkg/model and core/services/nodes green; make lint
new-from-merge-base reports 0 issues.
Assisted-by: Claude:claude-opus-4-8 golangci-lint
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
* fix(distributed): drop replica rows when a worker stops a backend
A worker returns a stopped backend's gRPC port to its allocator as soon as
the process is confirmed dead, and hands it to the next backend that starts.
The controller's NodeModel row for the old address survives, and both
SmartRouter.probeHealth and the HealthMonitor per-model probe verify
liveness, not identity, so once an unrelated backend binds the recycled port
the stale row passes every check and the request is served by the wrong
backend instead of failing.
backend.delete is newly able to trigger this: before #10956 a delete never
actually stopped a process, so it never recycled a port. backend.upgrade has
the identical gap and always did — upgradeBackend force-stops every process
using the binary and starts none back up, while
DistributedBackendManager.UpgradeBackend never removes rows. model.unload is
the one path that gets this right today: it calls RemoveAllNodeModelReplicas
straight after StopBackend.
Report the process keys the worker terminated on the delete and upgrade
replies, and drop the matching rows in RemoteUnloaderAdapter, which already
holds a ModelLocator with RemoveNodeModel. All three call sites funnel
through that adapter, so no new interface, DB migration, or proto change is
needed. A key is reported only once its process is confirmed gone, so the
list stays trustworthy on the partial-failure replies too.
Old workers never populate the new fields. ReportsStoppedProcesses tells
"stopped nothing" apart from "does not report", so an old worker's silence
falls back to the pre-existing probe-based staleness recovery instead of
being mistaken for a completed cleanup.
Quarantine released ports for a short window as an interlock covering the
NATS round-trip between the worker freeing the port and the controller
dropping the row. It is deliberately not derived from HealthCheckInterval:
that cadence is operator-tunable and the per-model reaper can be disabled
outright, so coupling a worker-local constant to it would be silently wrong
on some clusters. Eager row removal is the fix; the delay only closes the
handoff gap.
Identity verification in probeHealth was considered and rejected: Health and
Status carry no backend identity, so it needs a proto change plus an
implementation in 36 Python and 4 C++ Health servicers, it is fail-open for
any backend not yet rebuilt, and the probeCache short-circuit means it would
not even execute during the 30s window where the misroute happens.
Fixes #10952
Refs #10954, #10956
Assisted-by: Claude:claude-opus-4-8 golangci-lint
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
* chore(deps): bump go-processmanager, assert real backend termination
go-processmanager wrote Process.PID from readPID() with no synchronization
while its own monitor goroutine cleared the same field on exit, so a bare
Run()+Stop() tripped the race detector without any concurrent access from
the caller. LocalAI hit this on every backend stop.
Upstream fixed it in a94e2b7 by guarding PID with a mutex and adding
CurrentPID() as a race-safe accessor. The exported field was kept to avoid
a breaking change but is now deprecated: a direct read still races the
monitor. No tag carries the fix yet, so pin the pseudo-version.
GetGRPCPID reads through CurrentPID() instead of the field. The accessor
returns the same string under an RLock, so the empty-PID and strconv error
paths are unchanged; it is the only direct field read in the tree.
With the race gone, the Free-timeout spec no longer has to leave its
fixture process unstarted. It now runs a real child and asserts the child
genuinely exits, which is exactly what the earlier workaround gave up: the
spec could show the stop was reached and the slot released, but not that
SIGTERM ever landed. Termination is observed through Done(), which closes
only once the library has waited on the child. The pidfile-based liveness
helpers cannot serve here, because Stop() deletes the pidfile while
releasing the handle and so reports "not alive" even if no signal was sent.
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
Assisted-by: Claude Code:claude-opus-4-8[1m] [Read] [Edit] [Bash]
---------
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
676 lines
23 KiB
Go
676 lines
23 KiB
Go
package model
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
pb "github.com/mudler/LocalAI/pkg/grpc/proto"
|
|
"github.com/mudler/LocalAI/pkg/system"
|
|
"github.com/mudler/LocalAI/pkg/utils"
|
|
|
|
"github.com/mudler/xlog"
|
|
)
|
|
|
|
// new idea: what if we declare a struct of these here, and use a loop to check?
|
|
|
|
// TODO: Split ModelLoader and TemplateLoader? Just to keep things more organized. Left together to share a mutex until I look into that. Would split if we separate directories for .bin/.yaml and .tmpl
|
|
// ModelUnloadHook is called when a model is about to be unloaded.
|
|
// The model name is passed as the argument.
|
|
type ModelUnloadHook func(modelName string)
|
|
|
|
// RemoteModelUnloader handles unloading models from remote backend nodes.
|
|
// In distributed mode, this is implemented by the SmartRouter.
|
|
// When ShutdownModel is called for a model with no local process,
|
|
// RemoteModelUnloader.UnloadRemoteModel is called to tell the remote node to free it.
|
|
type RemoteModelUnloader interface {
|
|
UnloadRemoteModel(modelName string) error
|
|
}
|
|
|
|
// RemoteModelContextUnloader is the optional cancellation/force extension used
|
|
// by distributed workers. Keeping it separate preserves compatibility with
|
|
// existing RemoteModelUnloader implementations.
|
|
type RemoteModelContextUnloader interface {
|
|
UnloadRemoteModelContext(ctx context.Context, modelName string, force bool) error
|
|
}
|
|
|
|
// RemoteModelPresenceChecker reports whether any node in the cluster currently
|
|
// holds the model.
|
|
//
|
|
// Unloading is deliberately idempotent: UnloadRemoteModel succeeds when no node
|
|
// has the model, because cleanup paths (model deletion, config edits, watchdog
|
|
// eviction) legitimately run against an already-unloaded model and must not
|
|
// fail. That makes the unload result unable to distinguish "stopped it" from
|
|
// "there was nothing to stop", so the one caller that needs the distinction —
|
|
// ShutdownModel, which must report 404 rather than a misleading success for a
|
|
// model loaded nowhere — asks separately, before unloading.
|
|
type RemoteModelPresenceChecker interface {
|
|
HasRemoteModel(ctx context.Context, modelName string) (bool, error)
|
|
}
|
|
|
|
// ModelRouter is a callback that routes model loading to a remote node
|
|
// instead of starting a local process. When set on the ModelLoader,
|
|
// grpcModel() will delegate to this function before attempting local loading.
|
|
type ModelRouter func(ctx context.Context, backend, modelID, modelName, modelFile string,
|
|
opts *pb.ModelOptions, parallel bool) (*Model, error)
|
|
|
|
// BackendLoadEvent describes one actual backend load attempt: a backend
|
|
// process spawn (or remote-address attach) followed by its LoadModel RPC.
|
|
// Cache hits and loads coalesced onto another goroutine's in-flight attempt
|
|
// never produce an event, so observers see real loads only. Distributed-mode
|
|
// routing is excluded too: there grpcModel runs per inference request and the
|
|
// worker node owns the actual load.
|
|
type BackendLoadEvent struct {
|
|
ModelID string
|
|
ModelName string
|
|
// Backend is the alias-resolved backend string (e.g. "parakeet-cpp").
|
|
Backend string
|
|
// BackendURI is the resolved runtime serving the load: the installed
|
|
// backend's launcher path (which names the variant directory) or a
|
|
// remote gRPC address. This is what identifies WHICH build served the
|
|
// model — a stale installed backend is invisible in the model config
|
|
// but obvious here.
|
|
BackendURI string
|
|
Duration time.Duration
|
|
Err error
|
|
}
|
|
|
|
type ModelLoader struct {
|
|
ModelPath string
|
|
mu sync.Mutex
|
|
store ModelStore
|
|
loading map[string]chan struct{} // tracks models currently being loaded
|
|
operations *modelOperationLocks
|
|
wd *WatchDog
|
|
externalBackends map[string]string
|
|
lruEvictionMaxRetries int // Maximum number of retries when waiting for busy models
|
|
lruEvictionRetryInterval time.Duration // Interval between retries when waiting for busy models
|
|
onUnloadHooks []ModelUnloadHook
|
|
loadObserver func(BackendLoadEvent)
|
|
remoteUnloader RemoteModelUnloader
|
|
modelRouter ModelRouter // distributed mode: route to remote node
|
|
backendLogs *BackendLogStore
|
|
backendLoggingEnabled atomic.Bool
|
|
// stoppingProcs marks backend processes that LocalAI is stopping on
|
|
// purpose (model unload / graceful shutdown), keyed by the
|
|
// *process.Process pointer. The exit-watcher goroutine in startProcess
|
|
// consults it to decide whether an exit is an expected stop or a crash —
|
|
// the exit code can't, since a child killed by our own SIGTERM/SIGKILL
|
|
// reports -1, indistinguishable from a signal-induced crash.
|
|
stoppingProcs sync.Map
|
|
// loadFailures records, per modelID, the cooldown window applied after a
|
|
// failed load so that a client repeatedly polling a broken model does not
|
|
// spawn (and leak) a fresh backend process on every request. Guarded by mu.
|
|
loadFailures map[string]*loadFailureState
|
|
loadFailureBaseCooldown time.Duration // first cooldown after a failure
|
|
loadFailureMaxCooldown time.Duration // cap for the exponential backoff
|
|
}
|
|
|
|
// loadFailureState tracks consecutive load failures for a single modelID and
|
|
// the instant at which its cooldown window expires.
|
|
type loadFailureState struct {
|
|
consecutive int
|
|
cooldownUntil time.Time
|
|
}
|
|
|
|
// ModelLoadCooldownError is returned when a model load is skipped because a
|
|
// recent attempt failed and the per-model cooldown window has not yet elapsed.
|
|
// The HTTP layer maps it to 503 with a Retry-After header so a polling client
|
|
// backs off instead of triggering a fresh backend start on every request.
|
|
type ModelLoadCooldownError struct {
|
|
ModelID string
|
|
RetryAfter time.Duration
|
|
}
|
|
|
|
func (e *ModelLoadCooldownError) Error() string {
|
|
return fmt.Sprintf("model %q load is in cooldown after a recent failure; retry after %s",
|
|
e.ModelID, e.RetryAfter.Round(time.Second))
|
|
}
|
|
|
|
// NewModelLoader creates a new ModelLoader instance.
|
|
// LRU eviction is now managed through the WatchDog component.
|
|
func NewModelLoader(system *system.SystemState) *ModelLoader {
|
|
nml := &ModelLoader{
|
|
ModelPath: system.Model.ModelsPath,
|
|
store: NewInMemoryModelStore(),
|
|
loading: make(map[string]chan struct{}),
|
|
operations: newModelOperationLocks(),
|
|
externalBackends: make(map[string]string),
|
|
lruEvictionMaxRetries: 30, // Default: 30 retries
|
|
lruEvictionRetryInterval: 1 * time.Second, // Default: 1 second
|
|
backendLogs: NewBackendLogStore(1000),
|
|
loadFailures: make(map[string]*loadFailureState),
|
|
loadFailureBaseCooldown: 10 * time.Second, // Default: 10s after the first failure
|
|
loadFailureMaxCooldown: 5 * time.Minute, // Default cap for the backoff
|
|
}
|
|
|
|
return nml
|
|
}
|
|
|
|
// SetLoadFailureCooldown configures the per-model load-failure backoff. base is
|
|
// the cooldown applied after the first failure; it doubles on each consecutive
|
|
// failure up to max. base is authoritative (base <= 0 disables the cooldown
|
|
// entirely); max only overrides the current cap when > 0.
|
|
func (ml *ModelLoader) SetLoadFailureCooldown(base, max time.Duration) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
if base < 0 {
|
|
base = 0
|
|
}
|
|
ml.loadFailureBaseCooldown = base
|
|
if max > 0 {
|
|
ml.loadFailureMaxCooldown = max
|
|
}
|
|
if ml.loadFailureMaxCooldown < ml.loadFailureBaseCooldown {
|
|
ml.loadFailureMaxCooldown = ml.loadFailureBaseCooldown
|
|
}
|
|
}
|
|
|
|
// cooldownRemaining returns how long the modelID's load cooldown still has to
|
|
// run, or 0 if there is none. Callers must hold ml.mu.
|
|
func (ml *ModelLoader) cooldownRemaining(modelID string) time.Duration {
|
|
st := ml.loadFailures[modelID]
|
|
if st == nil {
|
|
return 0
|
|
}
|
|
if remaining := time.Until(st.cooldownUntil); remaining > 0 {
|
|
return remaining
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// recordLoadFailure grows the modelID's consecutive-failure count and arms the
|
|
// next cooldown window using exponential backoff capped at loadFailureMaxCooldown.
|
|
func (ml *ModelLoader) recordLoadFailure(modelID string) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
if ml.loadFailureBaseCooldown <= 0 {
|
|
return // cooldown disabled
|
|
}
|
|
st := ml.loadFailures[modelID]
|
|
if st == nil {
|
|
st = &loadFailureState{}
|
|
ml.loadFailures[modelID] = st
|
|
}
|
|
st.consecutive++
|
|
// base * 2^(consecutive-1), clamped. Cap the shift to avoid overflowing
|
|
// the Duration; anything past the cap collapses to loadFailureMaxCooldown.
|
|
shift := st.consecutive - 1
|
|
if shift > 20 {
|
|
shift = 20
|
|
}
|
|
backoff := ml.loadFailureBaseCooldown * (1 << shift)
|
|
if backoff <= 0 || backoff > ml.loadFailureMaxCooldown {
|
|
backoff = ml.loadFailureMaxCooldown
|
|
}
|
|
st.cooldownUntil = time.Now().Add(backoff)
|
|
}
|
|
|
|
// clearLoadFailure resets the modelID's failure state after a successful load.
|
|
// Callers must hold ml.mu.
|
|
func (ml *ModelLoader) clearLoadFailure(modelID string) {
|
|
delete(ml.loadFailures, modelID)
|
|
}
|
|
|
|
// GetLoadingCount returns the number of models currently being loaded
|
|
func (ml *ModelLoader) GetLoadingCount() int {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
return len(ml.loading)
|
|
}
|
|
|
|
// OnModelUnload registers a hook that is called when a model is unloaded.
|
|
func (ml *ModelLoader) OnModelUnload(hook ModelUnloadHook) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
ml.onUnloadHooks = append(ml.onUnloadHooks, hook)
|
|
}
|
|
|
|
func (ml *ModelLoader) SetWatchDog(wd *WatchDog) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
ml.wd = wd
|
|
}
|
|
|
|
// SetLoadObserver registers a callback fired after every actual backend load
|
|
// attempt, successful or not. See BackendLoadEvent for what counts as one.
|
|
func (ml *ModelLoader) SetLoadObserver(obs func(BackendLoadEvent)) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
ml.loadObserver = obs
|
|
}
|
|
|
|
func (ml *ModelLoader) notifyLoadObserver(ev BackendLoadEvent) {
|
|
ml.mu.Lock()
|
|
obs := ml.loadObserver
|
|
ml.mu.Unlock()
|
|
if obs != nil {
|
|
obs(ev)
|
|
}
|
|
}
|
|
|
|
// SetRemoteUnloader sets the handler for unloading models on remote nodes.
|
|
// In distributed mode, this should be set to the SmartRouter adapter.
|
|
func (ml *ModelLoader) SetRemoteUnloader(u RemoteModelUnloader) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
ml.remoteUnloader = u
|
|
}
|
|
|
|
// SetModelRouter sets the distributed model router callback.
|
|
// When set, grpcModel() will delegate to this function before attempting local loading.
|
|
func (ml *ModelLoader) SetModelRouter(r ModelRouter) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
ml.modelRouter = r
|
|
}
|
|
|
|
// SetModelStore replaces the default in-memory model store.
|
|
// In distributed mode this is called with a DistributedModelStore.
|
|
func (ml *ModelLoader) SetModelStore(s ModelStore) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
ml.store = s
|
|
}
|
|
|
|
func (ml *ModelLoader) GetWatchDog() *WatchDog {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
return ml.wd
|
|
}
|
|
|
|
func (ml *ModelLoader) BackendLogs() *BackendLogStore {
|
|
return ml.backendLogs
|
|
}
|
|
|
|
func (ml *ModelLoader) SetBackendLoggingEnabled(enabled bool) {
|
|
ml.backendLoggingEnabled.Store(enabled)
|
|
}
|
|
|
|
func (ml *ModelLoader) BackendLoggingEnabled() bool {
|
|
return ml.backendLoggingEnabled.Load()
|
|
}
|
|
|
|
// SetLRUEvictionRetrySettings updates the LRU eviction retry settings
|
|
func (ml *ModelLoader) SetLRUEvictionRetrySettings(maxRetries int, retryInterval time.Duration) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
ml.lruEvictionMaxRetries = maxRetries
|
|
ml.lruEvictionRetryInterval = retryInterval
|
|
}
|
|
|
|
func (ml *ModelLoader) ExistsInModelPath(s string) bool {
|
|
return utils.ExistsInPath(ml.ModelPath, s)
|
|
}
|
|
|
|
func (ml *ModelLoader) SetExternalBackend(name, uri string) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
ml.externalBackends[name] = uri
|
|
}
|
|
|
|
func (ml *ModelLoader) DeleteExternalBackend(name string) {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
delete(ml.externalBackends, name)
|
|
}
|
|
|
|
func (ml *ModelLoader) GetExternalBackend(name string) string {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
return ml.externalBackends[name]
|
|
}
|
|
|
|
func (ml *ModelLoader) GetAllExternalBackends(o *Options) map[string]string {
|
|
ml.mu.Lock()
|
|
defer ml.mu.Unlock()
|
|
backends := make(map[string]string)
|
|
maps.Copy(backends, ml.externalBackends)
|
|
if o != nil {
|
|
maps.Copy(backends, o.externalBackends)
|
|
}
|
|
return backends
|
|
}
|
|
|
|
var knownFilesToSkip []string = []string{
|
|
"MODEL_CARD",
|
|
"README",
|
|
"README.md",
|
|
}
|
|
|
|
var knownModelsNameSuffixToSkip []string = []string{
|
|
".tmpl",
|
|
".keep",
|
|
".yaml",
|
|
".yml",
|
|
".json",
|
|
".txt",
|
|
".pt",
|
|
".onnx",
|
|
".md",
|
|
".ds_store",
|
|
".",
|
|
".safetensors",
|
|
".bin",
|
|
".gguf",
|
|
".ggml",
|
|
".ckpt",
|
|
".zip",
|
|
".tag",
|
|
".bak",
|
|
".partial",
|
|
".tar.gz",
|
|
}
|
|
|
|
func (ml *ModelLoader) ListFilesInModelPath() ([]string, error) {
|
|
files, err := os.ReadDir(ml.ModelPath)
|
|
if err != nil {
|
|
return []string{}, err
|
|
}
|
|
|
|
models := []string{}
|
|
FILE:
|
|
for _, file := range files {
|
|
|
|
for _, skip := range knownFilesToSkip {
|
|
if strings.EqualFold(file.Name(), skip) {
|
|
continue FILE
|
|
}
|
|
}
|
|
|
|
// Skip templates, YAML, .keep, .json, .DS_Store, and other non-model files.
|
|
// Use case-insensitive matching so e.g. CACHEDIR.TAG is caught by ".tag".
|
|
lowerName := strings.ToLower(file.Name())
|
|
for _, skip := range knownModelsNameSuffixToSkip {
|
|
if strings.HasSuffix(lowerName, skip) {
|
|
continue FILE
|
|
}
|
|
}
|
|
// Skip backup files created by LocalAI or huggingface_hub (e.g. model.yaml.bak-pre-gpumem072).
|
|
if strings.Contains(lowerName, ".bak") {
|
|
continue FILE
|
|
}
|
|
|
|
// Skip directories
|
|
if file.IsDir() {
|
|
continue
|
|
}
|
|
|
|
models = append(models, file.Name())
|
|
}
|
|
|
|
return models, nil
|
|
}
|
|
|
|
func (ml *ModelLoader) ListLoadedModels() []*Model {
|
|
ml.mu.Lock()
|
|
store := ml.store
|
|
ml.mu.Unlock()
|
|
|
|
models := []*Model{}
|
|
store.Range(func(_ string, m *Model) bool {
|
|
models = append(models, m)
|
|
return true
|
|
})
|
|
|
|
return models
|
|
}
|
|
|
|
func (ml *ModelLoader) LoadModel(modelID, modelName string, loader func(string, string, string) (*Model, error)) (*Model, error) {
|
|
return ml.LoadModelWithFile(modelID, modelName, modelName, loader)
|
|
}
|
|
|
|
func (ml *ModelLoader) LoadModelWithFile(modelID, modelName, modelFileName string, loader func(string, string, string) (*Model, error)) (*Model, error) {
|
|
if modelFileName == "" {
|
|
modelFileName = modelName
|
|
}
|
|
release := ml.operations.acquire(modelID, false)
|
|
defer release()
|
|
return ml.loadModel(modelID, modelName, modelFileName, loader, true)
|
|
}
|
|
|
|
// loadModel is the implementation behind LoadModelWithFile. checkCooldown gates fresh,
|
|
// independent load triggers behind the per-model failure cooldown; it is set to
|
|
// false for the coalesced retry of an in-flight burst (a follower whose leader
|
|
// just failed), which is not a new trigger and should still get its one retry.
|
|
func (ml *ModelLoader) loadModel(modelID, modelName, modelFileName string, loader func(string, string, string) (*Model, error), checkCooldown bool) (*Model, error) {
|
|
ml.mu.Lock()
|
|
distributed := ml.modelRouter != nil
|
|
ml.mu.Unlock()
|
|
|
|
if distributed {
|
|
// Distributed mode: SmartRouter must run per inference request so
|
|
// PickBestReplica (core/services/nodes/replicapicker.go) picks the
|
|
// least-loaded replica each time. The cached *Model returned from a
|
|
// previous call holds a client wrapper bound to one (nodeID,
|
|
// replicaIndex), so reusing it pins every subsequent request to the
|
|
// node that won the very first pick — defeating per-replica load
|
|
// balancing. Bypass the cache and the loading-coalesce map; the
|
|
// router does its own coalescing for first-time loads (advisory DB
|
|
// lock + singleflight on backend.install RPC), so concurrent first
|
|
// requests still produce a single worker-side install.
|
|
//
|
|
// TODO(distributed-cache): if profiling shows the per-request
|
|
// FindAndLockNodeWithModel SELECT FOR UPDATE becomes a hot path
|
|
// under burst load, replace this branch with a per-modelID cache
|
|
// that holds a *list* of replicas (refreshed every ~5s in
|
|
// background) and picks per call via PickBestReplica against
|
|
// locally-tracked in-flight counters. Same policy, no DB round-trip
|
|
// per inference. Trade-off: cross-frontend in-flight visibility
|
|
// becomes eventually consistent, acceptable for 1-3 frontend
|
|
// deployments.
|
|
modelFile := filepath.Join(ml.ModelPath, modelFileName)
|
|
model, err := loader(modelID, modelName, modelFile)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to route model with internal loader: %s", err)
|
|
}
|
|
if model == nil {
|
|
return nil, fmt.Errorf("loader didn't return a model")
|
|
}
|
|
// Record the latest mapping so DistributedModelStore.Range, shutdown,
|
|
// and listing endpoints see a representative entry. The DB is the
|
|
// source of truth for cluster-wide state; the local store is just a
|
|
// stub for in-process callers.
|
|
ml.mu.Lock()
|
|
ml.store.Set(modelID, model)
|
|
ml.mu.Unlock()
|
|
return model, nil
|
|
}
|
|
|
|
// Check if we already have a loaded model
|
|
if model := ml.checkIsLoaded(modelID); model != nil {
|
|
return model, nil
|
|
}
|
|
|
|
ml.mu.Lock()
|
|
// A concurrent leader can publish its model between the health check above
|
|
// and this lock acquisition. It is fresh by definition, so avoid starting a
|
|
// duplicate load without performing another network probe under ml.mu.
|
|
if model, ok := ml.store.Get(modelID); ok {
|
|
ml.mu.Unlock()
|
|
return model, nil
|
|
}
|
|
|
|
// If a recent load attempt for this model failed, short-circuit fresh load
|
|
// triggers until the cooldown elapses. This stops a client that keeps
|
|
// polling a broken model from spawning (and leaking) a new backend process
|
|
// on every request. The coalesced follower-retry below passes
|
|
// checkCooldown=false so an in-flight burst still gets its one retry.
|
|
if checkCooldown {
|
|
if retryAfter := ml.cooldownRemaining(modelID); retryAfter > 0 {
|
|
ml.mu.Unlock()
|
|
xlog.Debug("Model load in cooldown after a recent failure", "modelID", modelID, "retryAfter", retryAfter)
|
|
return nil, &ModelLoadCooldownError{ModelID: modelID, RetryAfter: retryAfter}
|
|
}
|
|
}
|
|
|
|
// Check if another goroutine is already loading this model
|
|
if loadingChan, isLoading := ml.loading[modelID]; isLoading {
|
|
ml.mu.Unlock()
|
|
// Wait for the other goroutine to finish loading
|
|
xlog.Debug("Waiting for model to be loaded by another request", "modelID", modelID)
|
|
<-loadingChan
|
|
// Now check if the model is loaded
|
|
model := ml.checkIsLoaded(modelID)
|
|
if model != nil {
|
|
return model, nil
|
|
}
|
|
// If still not loaded, the other goroutine failed. Retry once as part of
|
|
// this burst, bypassing the cooldown gate (we are not a new trigger).
|
|
return ml.loadModel(modelID, modelName, modelFileName, loader, false)
|
|
}
|
|
|
|
// Mark this model as loading (create a channel that will be closed when done)
|
|
loadingChan := make(chan struct{})
|
|
ml.loading[modelID] = loadingChan
|
|
ml.mu.Unlock()
|
|
|
|
// Ensure we clean up the loading state when done
|
|
defer func() {
|
|
ml.mu.Lock()
|
|
delete(ml.loading, modelID)
|
|
close(loadingChan)
|
|
ml.mu.Unlock()
|
|
}()
|
|
|
|
// Load the model (this can take a long time, no lock held)
|
|
modelFile := filepath.Join(ml.ModelPath, modelFileName)
|
|
xlog.Debug("Loading model in memory from file", "file", modelFile)
|
|
|
|
model, err := loader(modelID, modelName, modelFile)
|
|
if err != nil {
|
|
ml.recordLoadFailure(modelID)
|
|
return nil, fmt.Errorf("failed to load model with internal loader: %s", err)
|
|
}
|
|
|
|
if model == nil {
|
|
ml.recordLoadFailure(modelID)
|
|
return nil, fmt.Errorf("loader didn't return a model")
|
|
}
|
|
|
|
// Add to models map and reset any prior failure cooldown for this model.
|
|
ml.mu.Lock()
|
|
ml.clearLoadFailure(modelID)
|
|
ml.store.Set(modelID, model)
|
|
ml.mu.Unlock()
|
|
|
|
return model, nil
|
|
}
|
|
|
|
func (ml *ModelLoader) ShutdownModel(modelName string) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), gracefulShutdownTimeout)
|
|
defer cancel()
|
|
err := ml.shutdownModel(ctx, modelName, false)
|
|
if errors.Is(err, ErrModelBusy) && forceBackendShutdown {
|
|
xlog.Warn("Model remained busy until the graceful shutdown deadline; forcing shutdown", "model", modelName)
|
|
return ml.ShutdownModelForce(modelName)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// ShutdownModelForce stops a backend without waiting for an in-flight gRPC
|
|
// call to finish first. It is used by the watchdog's busy-killer, which only
|
|
// fires once a backend has been stuck on a call past the busy timeout — the
|
|
// graceful ShutdownModel intentionally waits for active calls until its
|
|
// bounded deadline. See deleteProcess.
|
|
func (ml *ModelLoader) ShutdownModelForce(modelName string) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), forcedShutdownTimeout)
|
|
defer cancel()
|
|
return ml.shutdownModel(ctx, modelName, true)
|
|
}
|
|
|
|
// ShutdownModelContext is the cancellation-aware lifecycle primitive used by
|
|
// both graceful and forced shutdown wrappers.
|
|
func (ml *ModelLoader) ShutdownModelContext(ctx context.Context, modelName string, force bool) error {
|
|
return ml.shutdownModel(ctx, modelName, force)
|
|
}
|
|
|
|
func (ml *ModelLoader) shutdownModel(ctx context.Context, modelName string, force bool) error {
|
|
release, err := ml.operations.acquireContext(ctx, modelName, true)
|
|
if err != nil {
|
|
return fmt.Errorf("waiting to shut down model %q: %w", modelName, err)
|
|
}
|
|
defer release()
|
|
return ml.deleteProcess(ctx, modelName, force)
|
|
}
|
|
|
|
func (ml *ModelLoader) CheckIsLoaded(s string) *Model {
|
|
release := ml.operations.acquire(s, false)
|
|
defer release()
|
|
return ml.checkIsLoaded(s)
|
|
}
|
|
|
|
func (ml *ModelLoader) checkIsLoaded(s string) *Model {
|
|
ml.mu.Lock()
|
|
store := ml.store
|
|
wd := ml.wd
|
|
ml.mu.Unlock()
|
|
|
|
m, ok := store.Get(s)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
// Health checks are per model. Serializing them here prevents a cold health
|
|
// cache from generating a burst of identical probes without blocking any
|
|
// other model's lifecycle.
|
|
m.healthMu.Lock()
|
|
defer m.healthMu.Unlock()
|
|
|
|
xlog.Debug("Model already loaded in memory", "model", s)
|
|
|
|
// Skip the gRPC health check if the model was recently verified.
|
|
// This avoids serializing concurrent requests behind ml.mu while each
|
|
// one does a network round-trip (especially costly in distributed mode).
|
|
if m.IsRecentlyHealthy() {
|
|
xlog.Debug("Model health check cached, skipping gRPC probe", "model", s)
|
|
return m
|
|
}
|
|
|
|
client := m.GRPC(false, wd)
|
|
|
|
xlog.Debug("Checking model availability", "model", s)
|
|
cTimeout, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
|
|
alive, err := client.HealthCheck(cTimeout)
|
|
if !alive {
|
|
xlog.Warn("GRPC Model not responding", "error", err)
|
|
xlog.Warn("Deleting the process in order to recreate it")
|
|
process := m.Process()
|
|
if process == nil {
|
|
// Remote/distributed model — no local process to check.
|
|
// Only evict on definitive connection errors (node is down).
|
|
// Timeouts may mean the node is busy, so keep the model cached.
|
|
if isConnectionError(err) {
|
|
xlog.Warn("Remote model unreachable (connection error), removing from cache", "model", s, "error", err)
|
|
if delErr := ml.deleteProcess(cTimeout, s, false); delErr != nil {
|
|
xlog.Error("error cleaning up remote model", "error", delErr, "model", s)
|
|
}
|
|
return nil
|
|
}
|
|
xlog.Warn("Remote model health check failed (possible timeout), keeping cached", "model", s, "error", err)
|
|
return m
|
|
}
|
|
if !process.IsAlive() {
|
|
xlog.Debug("GRPC Process is not responding", "model", s)
|
|
// stop and delete the process, this forces to re-load the model and re-create again the service
|
|
err := ml.deleteProcess(cTimeout, s, true)
|
|
if err != nil {
|
|
xlog.Error("error stopping process", "error", err, "process", s)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
m.MarkHealthy()
|
|
return m
|
|
}
|