Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
67c9fcd
fix(upgraderun): answer pending, not started, when a single start tim…
mudler Nov 24, 2026
f9de46d
fix(addons): keep the recorded upgrade operation with the run item
mudler Nov 24, 2026
2f6088e
fix(gallery): report a failed restore after a cancel as a failure
mudler Nov 24, 2026
1f5fc01
fix(gallery): never delete a previous build that a failed restore kept
mudler Nov 24, 2026
9bb6a2d
fix(nodes): do not read an old worker's answer as a missing route
mudler Nov 24, 2026
a02b0c7
fix(backendlib): run every library install through one guarded job ru…
mudler Nov 24, 2026
3632357
fix(upgraderun): follow a live operation when a run is taken over
mudler Nov 24, 2026
e35a578
fix(upgraderun): take the lock of a new run before its row exists
mudler Nov 24, 2026
35adedc
fix(model): keep the start check process out of the watchdog
mudler Nov 24, 2026
c4f617f
fix(sanitize): redact prefixed keys and token shapes, drop format cha…
mudler Nov 24, 2026
c922fe3
fix(model): sanitize the output and the error of a start check
mudler Nov 24, 2026
273840e
fix(updates): show an item the server still checks as busy
mudler Nov 24, 2026
7daa6ca
fix(updates): drop run answers older than the one the page shows
mudler Nov 24, 2026
82c415c
fix(upgraderun): check a followed item whose status stops changing
mudler Nov 24, 2026
59ca958
fix(application): register the run observers before the sweep starts
mudler Nov 24, 2026
debe9dc
fix(upgraderun): wait in Close for the start, cancel and check gorout…
mudler Nov 24, 2026
94ea6bd
fix(updatenotify): put the name in the body of a run's end on one line
mudler Nov 24, 2026
91ced71
fix(gallery): refuse a backend name that ends like a swap directory
mudler Nov 24, 2026
454852a
fix(updates): say once why a review could not load
mudler Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions .agents/distributed-seams.md
Original file line number Diff line number Diff line change
Expand Up @@ -432,10 +432,13 @@ is `ErrNoRoute`, whether a wait that ran out means that the worker may still be
installing (`waitExpired`), whether a missing acknowledgement of `backend.stop`
may be read as an older worker (`acknowledgementMissing`: true only for NATS), and
how the carrier is named in a log line. An HTTP link never reads silence as a
stop that was done. A 404 is a worker that does not serve the verb. It becomes
`ErrNoRoute` only for `backend.upgrade`: the worker is older than the verb, and
the upgrade fails on it. There is no fallback to a forced install; an old worker
must be upgraded with the frontend. A 404 is a plain error for every other verb.
stop that was done. A 404 is a worker that does not serve the verb. For
`backend.upgrade` it becomes `nodes.ErrWorkerTooOld`: the worker is older than
the verb, and the upgrade fails on it. It is the worker's own answer, never
`ErrNoRoute`: the node is not marked unhealthy, and its pending upgrade waits
without counting a failed attempt. There is no fallback to a forced install; an
old worker must be upgraded with the frontend. A 404 is a plain error for every
other verb.

## Agent RPC

Expand Down Expand Up @@ -605,8 +608,8 @@ grace, and nothing but `PresenceGone` may be read as absence.

On `ErrNoRoute` the only change to the node's own state is the status-only
`MarkUnhealthy`, which the next heartbeat reverses. A caller may also route
around the node (the scheduler skips it, and an upgrade falls back to the older
install subject). Never delete `node_models` rows on it. Timeouts are not
around the node (the scheduler skips it). An upgrade has no fallback: it fails
on that node. Never delete `node_models` rows on it. Timeouts are not
`ErrNoRoute`.

A pending backend op that fails with `ErrNoRoute` is still recorded as a failed
Expand Down
38 changes: 32 additions & 6 deletions core/application/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,13 @@ type Application struct {
addonAdminCheck func(context.Context, contract.Actor) error
librarySnap librarySnapshot
backendLibrary *backendlib.Installer
addonManager *addons.Manager
addonHostOps *addonruntime.HostOps
// libraryJobs runs every library install of this node under one guard;
// see LibraryJobs.
libraryJobsMu sync.Mutex
libraryJobs *backendlib.JobRunner
libraryJobsFor *backendlib.Installer
addonManager *addons.Manager
addonHostOps *addonruntime.HostOps
// hostAuthority answers what each add-on may call; see addonAuthority.
hostAuthority hostops.Authority
addonAuthorityOnce sync.Once
Expand Down Expand Up @@ -285,7 +290,7 @@ type Application struct {
// upgradeRuns owns the server-owned upgrade runs; nil when they could not
// start. upgradeRunsStop stops its sweep and runners and closes a
// database opened for it. See upgrade_runs.go.
upgradeRuns *upgraderun.Service
upgradeRuns atomic.Pointer[upgraderun.Service]
upgradeRunsStop func()
addonRunUpgrader *addonendpoints.QueuedUpgrader
// upgradeRunTweak changes the options of the service before it starts;
Expand Down Expand Up @@ -987,7 +992,7 @@ func (a *Application) start() (startErr error) {
return a.studioVisionModel("")
}
if a.backendLibrary != nil {
assistantClient.BackendLibrary = libraryInstallNoProgress{a.backendLibrary}
assistantClient.BackendLibrary = libraryInstallNoProgress{in: a.backendLibrary, jobs: a.LibraryJobs}
}
assistantClient.UpdatesChecker = func() localaiInproc.BackendUpdatesSource {
if a.upgradeChecker == nil {
Expand Down Expand Up @@ -1103,6 +1108,23 @@ func (a *Application) AddonManager() *addons.Manager { return a.addonManager }
// It is nil unless this instance owns the add-on libraries.
func (a *Application) BackendLibrary() *backendlib.Installer { return a.backendLibrary }

// LibraryJobs runs the library installs of this node: the install route, the
// library items of upgrade runs and the Assistant's install all go through it,
// so one install of a backend name runs at a time. nil without a backend
// library.
func (a *Application) LibraryJobs() *backendlib.JobRunner {
lib := a.BackendLibrary()
if lib == nil {
return nil
}
a.libraryJobsMu.Lock()
defer a.libraryJobsMu.Unlock()
if a.libraryJobs == nil || a.libraryJobsFor != lib {
a.libraryJobs, a.libraryJobsFor = &backendlib.JobRunner{Install: lib.Install}, lib
}
return a.libraryJobs
}

// AddonSources exposes owner-only source administration and explicit live refresh.
// Forwarders never load source configuration or perform catalog I/O.
func (a *Application) AddonSources() *catalog.Sources { return a.addonSources }
Expand Down Expand Up @@ -1321,10 +1343,14 @@ func startLibraryRefresh(ctx context.Context, refresh func(context.Context) erro

// libraryInstallNoProgress adapts the library installer to the assistant's
// installer interface, which does not report progress.
type libraryInstallNoProgress struct{ in *backendlib.Installer }
// The install runs under the guard of every library install of this node.
type libraryInstallNoProgress struct {
in *backendlib.Installer
jobs func() *backendlib.JobRunner
}

func (l libraryInstallNoProgress) Install(ctx context.Context, sourceID, backend, version string) error {
return l.in.Install(ctx, sourceID, backend, version, backendlib.Progress{})
return l.jobs().Run(ctx, backendlib.Job{SourceID: sourceID, Backend: backend, Version: version})
}

func (l libraryInstallNoProgress) Updates(ctx context.Context) ([]localaitools.BackendLibraryUpdate, error) {
Expand Down
45 changes: 22 additions & 23 deletions core/application/upgrade_runs.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"github.com/mudler/LocalAI/core/services/modelupdates"
"github.com/mudler/LocalAI/core/services/updatenotify"
"github.com/mudler/LocalAI/core/services/upgraderun"
"github.com/mudler/LocalAI/pkg/addons/contract"
"github.com/mudler/xlog"
)

Expand All @@ -32,7 +31,7 @@ const upgradeRunsDBFile = "upgrade_runs.db"
// UpgradeRuns returns the service of the server-owned upgrade runs, or nil
// when it could not start (no database to keep the runs in). The routes that
// update one item fall back to their direct path then.
func (a *Application) UpgradeRuns() *upgraderun.Service { return a.upgradeRuns }
func (a *Application) UpgradeRuns() *upgraderun.Service { return a.upgradeRuns.Load() }

// AddonRunUpgrader starts the add-on items of upgrade runs; the add-on upgrade
// route hands its recorded upgrade to it. Never nil.
Expand Down Expand Up @@ -112,6 +111,14 @@ func (a *Application) startUpgradeRuns() {
store, closeDB = s, closer
}
opts := a.upgradeRunOptions(store, bus, toucher)
// The observers are part of the options, so they hear the first change
// of a run that the sweep takes over as soon as the service runs: one
// live row and one end row for each run in the inbox of each
// administrator, written by the frontend that runs the run, and the
// drop of an add-on upgrade that a run recorded and never started.
opts.Observers = append(opts.Observers,
&updatenotify.RunNotifier{Emitter: a.updateEmitter(), Context: a.applicationConfig.Context},
a.addonRunUpgrader)
if a.upgradeRunTweak != nil {
a.upgradeRunTweak(&opts)
}
Expand All @@ -121,16 +128,13 @@ func (a *Application) startUpgradeRuns() {
xlog.Warn("Upgrade runs are not available", "error", err)
return
}
a.upgradeRuns.Store(svc)
ctx, stop := context.WithCancel(a.applicationConfig.Context)
done := make(chan struct{})
go func() {
defer close(done)
svc.Run(ctx)
}()
// One live row and one end row for each run in the inbox of each
// administrator, written by the frontend that runs the run.
svc.AddObserver(&updatenotify.RunNotifier{Emitter: a.updateEmitter(), Context: a.applicationConfig.Context})
a.upgradeRuns = svc
a.upgradeRunsStop = func() {
stop()
<-done
Expand Down Expand Up @@ -172,8 +176,8 @@ func (a *Application) upgradeRunOptions(store *distributed.UpgradeRunStore, bus
opCache: a.operationCache,
},
}
if lib := a.BackendLibrary(); lib != nil {
starters[upgraderun.KindLibrary] = libraryRunStarter{installer: lib, status: gs}
if a.BackendLibrary() != nil {
starters[upgraderun.KindLibrary] = libraryRunStarter{jobs: a.LibraryJobs, status: gs}
}
checkers := []upgraderun.Checker{
upgraderun.BackendChecker{Snapshots: backendSnapshots{a}},
Expand Down Expand Up @@ -280,27 +284,22 @@ func (m modelSnapshots) CheckNow(ctx context.Context) modelupdates.Snapshot {

// libraryRunStarter installs a library backend for the actor of the run: on a
// frontend the add-on owner resolves the entry and checks that actor, as it
// does for POST /backends/library/install.
// does for POST /backends/library/install. It uses the job runner of the
// route, so the run and the route never install one backend name at once.
type libraryRunStarter struct {
installer upgraderun.LibraryInstaller
status upgraderun.StatusWriter
jobs func() *backendlib.JobRunner
status backendlib.JobStatus
}

func (s libraryRunStarter) Start(ctx context.Context, actor string, it upgraderun.Item) (string, error) {
in := s.installer
if a, _, ok := addonendpoints.DecodeRunActor(actor); ok {
in = actorInstaller{in: s.installer, actor: a}
ctx = library.WithActor(ctx, a)
}
return upgraderun.LibraryStarter{Installer: in, Status: s.status}.Start(ctx, actor, it)
}

type actorInstaller struct {
in upgraderun.LibraryInstaller
actor contract.Actor
}

func (i actorInstaller) Install(ctx context.Context, sourceID, backend, version string, progress backendlib.Progress) error {
return i.in.Install(library.WithActor(ctx, i.actor), sourceID, backend, version, progress)
var jobs upgraderun.LibraryJobs
if r := s.jobs(); r != nil {
jobs = r
}
return upgraderun.LibraryStarter{Jobs: jobs, Status: s.status}.Start(ctx, actor, it)
}

// autoUpgrader is the add-on owner for the automatic upgrade, or nil.
Expand Down
60 changes: 59 additions & 1 deletion core/application/upgrade_runs_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,60 @@ var _ = Describe("Upgrade run wiring", func() {
a.stopUpgradeRuns()
})

It("tells its observers the first change of a run it takes over at start", func() {
dir := GinkgoT().TempDir()
db, err := upgraderuntest.OpenSQLite(dir)
Expect(err).NotTo(HaveOccurred())
store, err := distributed.NewUpgradeRunStore(db)
Expect(err).NotTo(HaveOccurred())
// A run that a frontend which went away left running, with an
// item whose operation has no status any more.
Expect(store.Create(&distributed.UpgradeRunRecord{ID: "left", Source: "manual", Actor: "admin", State: "running", Runner: "gone", CreatedAt: time.Now()},
[]distributed.UpgradeRunItemRecord{{Key: "gallery:kokoro", Kind: "gallery", Name: "kokoro", Phase: "running", JobID: "lost-job"}})).To(Succeed())
a := runApp(ctx, "", "frontend-a")
a.distributed = &DistributedServices{Broadcaster: testutil.NewFakeBus(), DistStores: &distributed.Stores{UpgradeRuns: store}}
seen := make(chan upgraderun.Change, 64)
a.upgradeRunTweak = func(o *upgraderun.Options) {
o.Jobs = upgraderuntest.NewJobs()
o.Checkers = []upgraderun.Checker{upgraderuntest.NewChecker(upgraderun.KindGallery)}
o.Observers = append(o.Observers, upgraderun.ObserverFunc(func(c upgraderun.Change) {
select {
case seen <- c:
default:
}
}))
}
a.startUpgradeRuns()
DeferCleanup(a.stopUpgradeRuns)
var first upgraderun.Change
Eventually(seen, 5*time.Second).Should(Receive(&first))
Expect(first.Run.ID).To(Equal("left"))
Expect(first.Local).To(BeTrue())
Expect(first.Run.Item("gallery:kokoro").Phase).To(Equal(upgraderun.PhaseUnconfirmed), "the takeover itself is the first change")
})

It("publishes the service so that readers on other goroutines never race its start", func() {
a := runApp(ctx, GinkgoT().TempDir(), "")
stop := make(chan struct{})
read := make(chan struct{})
go func() {
defer close(read)
for {
select {
case <-stop:
return
default:
_ = a.UpgradeRuns()
}
}
}()
a.startUpgradeRuns()
close(stop)
<-read
Expect(a.UpgradeRuns()).NotTo(BeNil())
a.stopUpgradeRuns()
})

It("does not start without a database or a data path, and the routes fall back", func() {
a := runApp(ctx, "", "")
a.startUpgradeRuns()
Expand Down Expand Up @@ -83,6 +137,9 @@ var _ = Describe("Upgrade run wiring", func() {
o.Starters = map[upgraderun.Kind]upgraderun.Starter{upgraderun.KindGallery: starter}
o.Checkers = []upgraderun.Checker{backends}
o.PollInterval, o.SweepInterval = 10*time.Millisecond, 20*time.Millisecond
// The fake status table keeps A's last status after A stops,
// as the other frontends keep it when A dies.
o.RecoveredIdleAfter = 200 * time.Millisecond
}
a.startUpgradeRuns()
Expect(a.UpgradeRuns()).NotTo(BeNil())
Expand All @@ -102,7 +159,8 @@ var _ = Describe("Upgrade run wiring", func() {
Expect(b.UpgradeRuns().Local()).To(BeEmpty())

// Frontend A stops while the backend item runs, and the update had
// applied: B's sweep takes the run over and its check confirms it.
// applied: B's sweep takes the run over, follows the operation, and
// once its status shows no change its check confirms it.
Eventually(func() string { return starter.Job("gallery:kokoro") }).ShouldNot(BeEmpty())
backends.Remove("gallery:kokoro")
a.stopUpgradeRuns()
Expand Down
4 changes: 4 additions & 0 deletions core/gallery/backend_name.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ func ValidateBackendName(name string) error {
return fmt.Errorf("%w: %q has \"..\"", ErrInvalidBackendName, name)
case strings.HasPrefix(name, "."):
return fmt.Errorf("%w: %q starts with a dot", ErrInvalidBackendName, name)
case isSwapDir(name):
// The listing skips such a directory and a swap would take it for
// the backup or the staging of another backend.
return fmt.Errorf("%w: %q ends like a directory of an install or an upgrade", ErrInvalidBackendName, name)
}
return nil
}
Expand Down
7 changes: 7 additions & 0 deletions core/gallery/backend_name_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ var _ = Describe("The backend name used to build a path", func() {
Entry("leading dot", ".hidden", false),
Entry("absolute", "/etc", false),
Entry("nul", "a\x00b", false),
// A name that ends like a directory of a swap would be read as one.
Entry("backup suffix", "llama-cpp.backup", false),
Entry("install backup suffix", "llama-cpp.install-backup", false),
Entry("upgrade staging suffix", "llama-cpp.upgrade-tmp", false),
Entry("install staging suffix", "llama-cpp.install-tmp", false),
Entry("failed suffix", "llama-cpp.failed", false),
Entry("kept previous build", "llama-cpp.backup.kept-20260101T000000", false),
)

Describe("in an upgrade", func() {
Expand Down
22 changes: 17 additions & 5 deletions core/gallery/backends.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,10 +380,13 @@ func InstallBackend(ctx context.Context, systemState *system.SystemState, modelL
// Mirrors the atomic-swap UpgradeBackend already performs.
stagingPath := backendPath + ".install-tmp"
backupPath := backendPath + ".install-backup"
// Clean any stale staging/backup dirs from a prior interrupted attempt
// (best-effort; a missing dir is the common case).
// Clean a stale staging dir from a prior interrupted attempt
// (best-effort; a missing dir is the common case). A stale backup can be
// the last build that worked, so it is moved aside, never deleted.
_ = os.RemoveAll(stagingPath)
_ = os.RemoveAll(backupPath)
if err := keepPreviousBuild(backupPath); err != nil {
return err
}
if err := os.MkdirAll(stagingPath, 0750); err != nil {
return fmt.Errorf("failed to create staging path: %v", err)
}
Expand Down Expand Up @@ -567,10 +570,16 @@ func InstallBackend(ctx context.Context, systemState *system.SystemState, modelL
if replaced && options.startCheck != nil {
return rollbackSwap(ctx, systemState, modelLoader, UpgradeFailureSwap, fmt.Errorf("failed to register backends after install: %w", err), backendPath, backupPath)
}
_ = os.RemoveAll(backupPath)
// The new build is in place but not registered: the replaced one
// stays at backupPath, where the next install moves it aside.
if replaced {
xlog.Warn("Keeping the replaced build after a failed registration", "path", filepath.Base(backupPath))
}
return err
}
_ = os.RemoveAll(backupPath)
if err := os.RemoveAll(backupPath); err != nil {
xlog.Warn("Could not remove the replaced build after the install", "path", filepath.Base(backupPath), "error", err)
}
return nil
}

Expand Down Expand Up @@ -829,6 +838,9 @@ func collectRoot(basePath string, isSystem, lenient bool) (map[string]collectedB
var swapDirSuffixes = []string{".upgrade-tmp", ".backup", ".install-tmp", ".install-backup", failedSuffix}

func isSwapDir(name string) bool {
if isKeptDir(name) {
return true
}
for _, suffix := range swapDirSuffixes {
if strings.HasSuffix(name, suffix) && len(name) > len(suffix) {
return true
Expand Down
Loading
Loading