mirror of
https://github.com/mudler/LocalAI.git
synced 2026-06-12 10:47:23 -04:00
* fix(galleryop): self-evict terminal ops from OpCache.GetStatus The processingBackends map (the UI 'reinstalling' spinner source) only cleared an op when a client polled /api/backends/job/:uid. The Manage-page Reinstall and Upgrade buttons never poll, so completed installs leaked into processingBackends forever and the backend card spun 'reinstalling' even though the install had finished. Evict terminal ops on the list read instead; DeleteUUID already broadcasts the eviction so peer replicas converge. Reproduced on a live 5-node distributed cluster: 5 backends sat in processingBackends with underlying jobs reporting completed:true,progress:100. Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(nodes): clear pending backend ops behind offline/draining nodes ListDuePendingBackendOps filters status=healthy, so a backend op queued against a node that went offline (stale heartbeat) or draining (admin action) was never retried, aged out, or deleted - it leaked forever and kept the UI operation spinning. Add DeleteStalePendingBackendOps and run it each reconcile pass: draining nodes are cleared immediately (model rows already purged), offline nodes once their heartbeat is older than a grace window (blip protection). Reproduced on a live cluster: orphaned llama-cpp install rows targeting an offline (nvidia-thor) and a draining (mac-mini-m4) node sat at attempts=0 indefinitely. Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(nodes): stream per-node progress during backend upgrade The install dispatch subscribed to a per-op progress subject and streamed per-node download ticks; the upgrade dispatch did a bare 15-minute blocking NATS round-trip with no subscription, so the UI showed progress:0 the whole time (the 'reinstalling but nothing happens' report on a slow node). Thread the op ID through BackendManager.UpgradeBackend -> the distributed manager -> the adapter, and have the adapter subscribe to the per-op progress subject before the request (extracted into a shared subscribeProgress helper reused by install/upgrade/force-fallback). The worker's upgradeBackend now creates the same DebouncedInstallProgressPublisher installBackend uses. An upgrade is a force-reinstall, so it reuses SubjectNodeBackendInstallProgress rather than minting a new subject - no new NATS permission, no new rolling-update compat surface. Reconciler-driven retries pass empty opID/onProgress and stay on the silent path. Reproduced on a live cluster: upgrade of llama-cpp-development on agx-orin-slow sat at progress:0 for 4+ minutes with no per-node feedback. Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(galleryop): persist cancellation + periodically reap orphaned ops Two distributed gaps surfaced when a replica was killed mid-upgrade on a live cluster, leaving the backend stuck 'processing' in the UI forever: 1. CancelOperation flipped the in-memory status to cancelled and broadcast a NATS event but never persisted the terminal status. On the next replica restart the still-active row re-hydrated straight back into processingBackends and the UI spun again. It now calls store.Cancel(id) so the cancel survives a restart. 2. CleanStale (which marks abandoned active ops failed) only ran once on startup, so an op orphaned AFTER startup - its owning replica's foreground handler goroutine gone - was never reaped until the next restart. Add GalleryService.ReapStaleOperations and run it on a 15m ticker (CleanStale now returns the reaped count for observability). Neither is covered by the OpCache self-evict fix: an orphaned op never reaches Processed, so it would never self-evict. Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(review): address self-review findings on the distributed install fixes Three findings from an adversarial review of this branch: 1. CRITICAL - OpCache.GetStatus crashed under concurrent load. m.Map() returns the live internal map by reference, so deleting from it on the read path was an unsynchronized write to a map four HTTP handlers poll every ~1s -> a 'concurrent map writes' fatal. Rewritten to iterate a Keys() snapshot, build a fresh result map, and apply evictions via the locked DeleteUUID after the loop. Added a -race concurrency regression guard. 2. HIGH - GetStatus evicted failed ops too, hiding them from /api/operations and breaking the dismiss-failed-op flow (the panel keeps Error != nil ops so the admin can read the error and click Dismiss). Eviction now fires only for terminal ops with Error == nil (success/cancelled); failures are retained. 3. MEDIUM - DeleteStalePendingBackendOps missed StatusUnhealthy nodes. A node marked unhealthy on a NATS ErrNoResponders never transitions to offline (health.go skips re-marking it), so its pending ops leaked exactly like the offline case. Unhealthy is now reaped via the same stale-heartbeat grace path (a fresh-heartbeat node is recovering and keeps its op). Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(review-2): don't evict the still-installing soft-path; don't spin on failed ops Second review pass found two issues: 1. MEDIUM (Go) - OpCache.GetStatus evicted the ErrWorkerStillInstalling soft-path op. That op is deliberately Processed=true with no error to show a yellow in-progress state when a worker timed out the NATS round-trip but is still installing in the background; the reconciler confirms the real outcome later. Evicting it (and broadcasting OpEnd + marking the DB completed) hid an install that may still fail. Eviction is now scoped to a clean success (progress 100 + 'completed', matching the job-poll's historical condition) or a cancellation - the soft-path (progress != 100) and failures are kept. 2. MEDIUM (React) - the Backends gallery card rendered ANY operation as an 'Installing...' spinner, so a failed op (now intentionally kept in the list for the OperationsBar error + Dismiss) spun forever. Exclude errored ops from the card spinner, mirroring Models.jsx (isInstalling already excludes op.error). The error + Dismiss still surface in the global OperationsBar. Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> * fix(ui): refresh Manage backends table when an operation settles The Manage backends table fetched installed backends only on mount/after delete and checked upgrades only on tab activation. After a reinstall/upgrade completed neither re-ran, so the installed-version cell and the 'update available' badge stayed stale until the user switched tabs - the op looked like it 'did nothing'. Watch the operations list (via useOperations) and re-fetch installed backends + available upgrades whenever the count settles, mirroring the operations.length watch Backends.jsx already uses. Consolidates the prior tab-activation upgrades check into the same effect. Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Ettore Di Giacinto <mudler@localai.io> --------- Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
213 lines
7.4 KiB
Go
213 lines
7.4 KiB
Go
package galleryop
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/mudler/LocalAI/core/config"
|
|
"github.com/mudler/LocalAI/core/gallery"
|
|
"github.com/mudler/LocalAI/core/services/messaging"
|
|
"github.com/mudler/LocalAI/pkg/downloader"
|
|
"github.com/mudler/LocalAI/pkg/model"
|
|
"github.com/mudler/LocalAI/pkg/system"
|
|
|
|
"github.com/mudler/LocalAI/pkg/utils"
|
|
"github.com/mudler/xlog"
|
|
)
|
|
|
|
func (g *GalleryService) backendHandler(op *ManagementOp[gallery.GalleryBackend, any], systemState *system.SystemState) error {
|
|
utils.ResetDownloadTimers()
|
|
|
|
// Dedup check in distributed mode — skip if another instance is already processing this element
|
|
if g.galleryStore != nil && op.GalleryElementName != "" {
|
|
dup, err := g.galleryStore.FindDuplicate(op.GalleryElementName)
|
|
if err == nil && dup != nil && dup.ID != op.ID {
|
|
g.UpdateStatus(op.ID, &OpStatus{
|
|
Processed: true,
|
|
Message: fmt.Sprintf("already being processed by another instance (op %s)", dup.ID),
|
|
})
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// Check if already cancelled
|
|
if op.Context != nil {
|
|
select {
|
|
case <-op.Context.Done():
|
|
g.UpdateStatus(op.ID, &OpStatus{
|
|
Cancelled: true,
|
|
Processed: true,
|
|
Message: "cancelled",
|
|
GalleryElementName: op.GalleryElementName,
|
|
})
|
|
return op.Context.Err()
|
|
default:
|
|
}
|
|
}
|
|
|
|
g.UpdateStatus(op.ID, &OpStatus{Message: fmt.Sprintf("processing backend: %s", op.GalleryElementName), Progress: 0, Cancellable: true})
|
|
|
|
// displayDownload displays the download progress
|
|
progressCallback := func(fileName string, current string, total string, percentage float64) {
|
|
// Check for cancellation during progress updates
|
|
if op.Context != nil {
|
|
select {
|
|
case <-op.Context.Done():
|
|
return
|
|
default:
|
|
}
|
|
}
|
|
g.UpdateStatus(op.ID, &OpStatus{Message: fmt.Sprintf(processingMessage, fileName, total, current), FileName: fileName, Progress: percentage, TotalFileSize: total, DownloadedFileSize: current, Cancellable: true})
|
|
utils.DisplayDownloadFunction(fileName, current, total, percentage)
|
|
}
|
|
|
|
ctx := op.Context
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
|
|
var err error
|
|
if op.Upgrade {
|
|
err = g.backendManager.UpgradeBackend(ctx, op.ID, op.GalleryElementName, progressCallback)
|
|
} else if op.Delete {
|
|
err = g.backendManager.DeleteBackend(op.GalleryElementName)
|
|
} else {
|
|
err = g.backendManager.InstallBackend(ctx, op, progressCallback)
|
|
// Update GalleryElementName for status tracking if a name was derived
|
|
if op.ExternalName != "" {
|
|
op.GalleryElementName = op.ExternalName
|
|
}
|
|
}
|
|
if err != nil {
|
|
// Check if error is due to cancellation
|
|
if op.Context != nil && errors.Is(err, op.Context.Err()) {
|
|
g.UpdateStatus(op.ID, &OpStatus{
|
|
Cancelled: true,
|
|
Processed: true,
|
|
Message: "cancelled",
|
|
GalleryElementName: op.GalleryElementName,
|
|
})
|
|
return err
|
|
}
|
|
if errors.Is(err, ErrWorkerStillInstalling) {
|
|
// Soft failure: at least one worker timed out replying but is
|
|
// still running the install in the background. Mark the op as
|
|
// processed with a non-error message so the admin UI shows a
|
|
// yellow in-progress state rather than red. The reconciler's
|
|
// next pass will reconcile the actual outcome via backend.list.
|
|
xlog.Info("worker still installing in background", "backend", op.GalleryElementName, "error", err)
|
|
g.UpdateStatus(op.ID, &OpStatus{
|
|
Processed: true,
|
|
GalleryElementName: op.GalleryElementName,
|
|
Message: fmt.Sprintf("backend %s: worker still installing in background; reconciler will confirm completion (%v)", op.GalleryElementName, err),
|
|
Cancellable: false,
|
|
})
|
|
return nil
|
|
}
|
|
xlog.Error("error installing backend", "error", err, "backend", op.GalleryElementName)
|
|
if !op.Delete {
|
|
// If we didn't install the backend, we need to make sure we don't have a leftover directory
|
|
gallery.DeleteBackendFromSystem(systemState, op.GalleryElementName)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// Tell peer replicas that the backend set has changed. UpgradeChecker
|
|
// caches upgrade-available bits for 6 hours, so without this peers would
|
|
// keep advertising an upgrade for a backend that already moved.
|
|
opName := "install"
|
|
switch {
|
|
case op.Delete:
|
|
opName = "delete"
|
|
case op.Upgrade:
|
|
opName = "upgrade"
|
|
}
|
|
g.publishCacheInvalidate(messaging.SubjectCacheInvalidateBackends, messaging.CacheInvalidateEvent{
|
|
Element: op.GalleryElementName,
|
|
Op: opName,
|
|
})
|
|
|
|
g.UpdateStatus(op.ID,
|
|
&OpStatus{
|
|
Deletion: op.Delete,
|
|
Processed: true,
|
|
GalleryElementName: op.GalleryElementName,
|
|
Message: "completed",
|
|
Progress: 100,
|
|
Cancellable: false})
|
|
return nil
|
|
}
|
|
|
|
// InstallExternalBackend installs a backend from an external source (OCI image, URL, or path).
|
|
// This method contains the logic to detect the input type and call the appropriate installation function.
|
|
// It can be used by both CLI and Web UI for installing backends from external sources.
|
|
func InstallExternalBackend(ctx context.Context, galleries []config.Gallery, systemState *system.SystemState, modelLoader *model.ModelLoader, downloadStatus func(string, string, string, float64), backend, name, alias string, requireIntegrity bool) error {
|
|
uri := downloader.URI(backend)
|
|
switch {
|
|
case uri.LooksLikeDir():
|
|
if name == "" { // infer it from the path
|
|
name = filepath.Base(backend)
|
|
}
|
|
xlog.Info("Installing backend from path", "backend", backend, "name", name)
|
|
if err := gallery.InstallBackend(ctx, systemState, modelLoader, &gallery.GalleryBackend{
|
|
Metadata: gallery.Metadata{
|
|
Name: name,
|
|
},
|
|
Alias: alias,
|
|
URI: backend,
|
|
}, downloadStatus, requireIntegrity); err != nil {
|
|
return fmt.Errorf("error installing backend %s: %w", backend, err)
|
|
}
|
|
case uri.LooksLikeOCI() && !uri.LooksLikeOCIFile():
|
|
if name == "" {
|
|
return fmt.Errorf("specifying a name is required for OCI images")
|
|
}
|
|
xlog.Info("Installing backend from OCI image", "backend", backend, "name", name)
|
|
if err := gallery.InstallBackend(ctx, systemState, modelLoader, &gallery.GalleryBackend{
|
|
Metadata: gallery.Metadata{
|
|
Name: name,
|
|
},
|
|
Alias: alias,
|
|
URI: backend,
|
|
}, downloadStatus, requireIntegrity); err != nil {
|
|
return fmt.Errorf("error installing backend %s: %w", backend, err)
|
|
}
|
|
case uri.LooksLikeOCIFile():
|
|
derivedName, err := uri.FilenameFromUrl()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get filename from URL: %w", err)
|
|
}
|
|
// strip extension if any
|
|
derivedName = strings.TrimSuffix(derivedName, filepath.Ext(derivedName))
|
|
// Use provided name if available, otherwise use derived name
|
|
if name == "" {
|
|
name = derivedName
|
|
}
|
|
|
|
xlog.Info("Installing backend from OCI image", "backend", backend, "name", name)
|
|
if err := gallery.InstallBackend(ctx, systemState, modelLoader, &gallery.GalleryBackend{
|
|
Metadata: gallery.Metadata{
|
|
Name: name,
|
|
},
|
|
Alias: alias,
|
|
URI: backend,
|
|
}, downloadStatus, requireIntegrity); err != nil {
|
|
return fmt.Errorf("error installing backend %s: %w", backend, err)
|
|
}
|
|
default:
|
|
// Treat as gallery backend name
|
|
if name != "" || alias != "" {
|
|
return fmt.Errorf("specifying a name or alias is not supported for gallery backends")
|
|
}
|
|
err := gallery.InstallBackendFromGallery(ctx, galleries, systemState, modelLoader, backend, downloadStatus, true, requireIntegrity)
|
|
if err != nil {
|
|
return fmt.Errorf("error installing backend %s: %w", backend, err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|