diff --git a/.agents/distributed-seams.md b/.agents/distributed-seams.md index 6f85278c038c..c7150e9fb856 100644 --- a/.agents/distributed-seams.md +++ b/.agents/distributed-seams.md @@ -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 @@ -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 diff --git a/core/application/application.go b/core/application/application.go index 457c33b7e7f6..4ec557a6c8f4 100644 --- a/core/application/application.go +++ b/core/application/application.go @@ -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 @@ -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; @@ -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 { @@ -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 } @@ -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) { diff --git a/core/application/upgrade_runs.go b/core/application/upgrade_runs.go index 2a4171f67acc..c06959a85605 100644 --- a/core/application/upgrade_runs.go +++ b/core/application/upgrade_runs.go @@ -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" ) @@ -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. @@ -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) } @@ -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 @@ -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}}, @@ -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. diff --git a/core/application/upgrade_runs_internal_test.go b/core/application/upgrade_runs_internal_test.go index e8559f7e8bd0..8336c0e1f67e 100644 --- a/core/application/upgrade_runs_internal_test.go +++ b/core/application/upgrade_runs_internal_test.go @@ -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() @@ -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()) @@ -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() diff --git a/core/gallery/backend_name.go b/core/gallery/backend_name.go index 04cd0394b5c8..72d12eb2cbe5 100644 --- a/core/gallery/backend_name.go +++ b/core/gallery/backend_name.go @@ -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 } diff --git a/core/gallery/backend_name_test.go b/core/gallery/backend_name_test.go index 8a3c64f53a97..c7e72858a933 100644 --- a/core/gallery/backend_name_test.go +++ b/core/gallery/backend_name_test.go @@ -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() { diff --git a/core/gallery/backends.go b/core/gallery/backends.go index 48a313735365..dde00cbe9ac8 100644 --- a/core/gallery/backends.go +++ b/core/gallery/backends.go @@ -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) } @@ -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 } @@ -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 diff --git a/core/gallery/leftovers.go b/core/gallery/leftovers.go index 7c6aaf5a3dfb..6fd0f325a941 100644 --- a/core/gallery/leftovers.go +++ b/core/gallery/leftovers.go @@ -2,9 +2,11 @@ package gallery import ( "errors" + "fmt" "os" "path/filepath" "strings" + "time" "github.com/mudler/LocalAI/pkg/system" "github.com/mudler/xlog" @@ -22,6 +24,9 @@ import ( // it is left alone, and logged: the backend in place may be a new build // whose start check never ran, and only a person can tell which to keep. // - A build moved aside because it did not start (".failed") is left alone. +// - A previous build that a later install or upgrade moved aside +// (".backup.kept-