From 67c9fcdec0db8d0ca132b70cc1e6016f662d1ecf Mon Sep 17 00:00:00 2001 From: Ettore Di Giacinto Date: Tue, 24 Nov 2026 15:43:49 +0000 Subject: [PATCH 01/19] fix(upgraderun): answer pending, not started, when a single start times out StartOne returns after its wait with the state of the item. When the operation was not accepted yet, the item has no job and is not terminal. The single upgrade routes and the Assistant only handled a terminal item, so they answered "started" with an empty job ID. SingleOutcome maps the item to a job, a refusal or a pending start, and every caller of StartOne uses it: the two backend upgrade routes, the model upgrade route, the add-on upgrade route and the in-process client. A pending start answers 202 with code pending, the run ID and the run. The Assistant gets an error that names the run to follow, never a job. The HTTP client of the tools reads the same 202 answer. Assisted-by: Claude:claude-opus-5-5 --- core/http/endpoints/addons/updates.go | 21 +++-- core/http/endpoints/addons/upgrade_run.go | 45 ++++++----- .../http/endpoints/addons/upgrade_run_test.go | 63 +++++++++++++++ core/http/endpoints/localai/backend.go | 2 + core/http/endpoints/localai/model_updates.go | 13 ++-- .../endpoints/localai/model_updates_test.go | 18 +++++ core/http/endpoints/localai/upgrade_runs.go | 34 +++++++-- .../endpoints/localai/upgrade_runs_test.go | 25 ++++++ core/services/localaitools/httpapi/client.go | 28 ++++++- .../localaitools/httpapi/client_test.go | 21 +++++ .../localaitools/inproc/upgrade_runs.go | 11 ++- .../localaitools/inproc/upgrade_runs_test.go | 14 ++++ core/services/upgraderun/fakes_test.go | 21 ++++- core/services/upgraderun/single.go | 76 +++++++++++++++++++ core/services/upgraderun/single_test.go | 68 +++++++++++++++++ .../upgraderun/upgraderuntest/fakes.go | 21 ++++- docs/content/models/upgrade-runs.md | 11 ++- swagger/docs.go | 42 ++++++++++ swagger/swagger.json | 42 ++++++++++ swagger/swagger.yaml | 33 ++++++++ 20 files changed, 560 insertions(+), 49 deletions(-) create mode 100644 core/services/upgraderun/single_test.go diff --git a/core/http/endpoints/addons/updates.go b/core/http/endpoints/addons/updates.go index 3cccb2bbfca7..b3d3a9b5e8cb 100644 --- a/core/http/endpoints/addons/updates.go +++ b/core/http/endpoints/addons/updates.go @@ -71,8 +71,9 @@ func updateCall(c echo.Context, g *gateway.Gateway, a contract.Actor, id, opID, } return c.JSON(code, AddonErrorResponse{Error: AddonError{Type: env.Error.Type, Message: env.Error.Message, Code: code}}) } + status := http.StatusOK if after != nil { - data, e := after(c, a, id, opID, env.Data) + data, st, e := after(c, a, id, opID, env.Data) var refusal *afterRefusal if errors.As(e, &refusal) { return c.JSON(refusal.status, AddonErrorResponse{Error: AddonError{Type: refusal.kind, Message: refusal.message, Code: refusal.status}}) @@ -81,13 +82,16 @@ func updateCall(c echo.Context, g *gateway.Gateway, a contract.Actor, id, opID, return failure(c, 503, "Addons unavailable") } env.Data = data + if st != 0 { + status = st + } } if wrap { // The answer of a lifecycle action is the operation status in a // result, as every other lifecycle route gives it. - return c.JSON(200, contract.Result{Payload: env.Data}) + return c.JSON(status, contract.Result{Payload: env.Data}) } - return c.Blob(200, echo.MIMEApplicationJSON, env.Data) + return c.Blob(status, echo.MIMEApplicationJSON, env.Data) } // GetUpdate reads the update status of an add-on. @@ -133,8 +137,9 @@ func updateMutation(g *gateway.Gateway, db *gorm.DB, opts []Option, action strin } // afterUpdate rewrites the data of a successful update action before it is -// answered; nil answers it as the owner gave it. -type afterUpdate func(c echo.Context, a contract.Actor, id, opID string, data json.RawMessage) (json.RawMessage, error) +// answered, with the HTTP status of the answer (zero is 200); nil answers it +// as the owner gave it. +type afterUpdate func(c echo.Context, a contract.Actor, id, opID string, data json.RawMessage) (json.RawMessage, int, error) func updateMutationWith(g *gateway.Gateway, db *gorm.DB, opts []Option, action string, wrap bool, body func() any, opOf func(any) string, argsOf func(any) (uint64, any), after afterUpdate) echo.HandlerFunc { s := resolve(opts) @@ -205,6 +210,7 @@ func CheckUpdate(g *gateway.Gateway, db *gorm.DB, opts ...Option) echo.HandlerFu // @Param id path string true "Add-on ID" // @Param request body UpgradeRequest true "Operation and the pinned digests" // @Success 200 {object} contract.Result "Operation accepted; the payload is the operation status" +// @Success 202 {object} contract.Result "Operation accepted and handed to an upgrade run that did not start it within the wait; the payload has run and runId but no jobId, and the run starts the recorded operation later" // @Failure 400 {object} AddonErrorResponse "Malformed request" // @Failure 401 {object} AddonErrorResponse "Named authentication required" // @Failure 403 {object} AddonErrorResponse "Feature, administration or browser session denied" @@ -219,13 +225,14 @@ func UpgradeAddon(g *gateway.Gateway, db *gorm.DB, opts ...Option) echo.HandlerF func() any { return &UpgradeRequest{} }, func(v any) string { return v.(*UpgradeRequest).OperationID }, upgradeArgs, - func(c echo.Context, a contract.Actor, id, opID string, status json.RawMessage) (json.RawMessage, error) { + func(c echo.Context, a contract.Actor, id, opID string, status json.RawMessage) (json.RawMessage, int, error) { if s.runs != nil && s.upgrader != nil { if svc := s.runs(); svc != nil { return runUpgrade(c, g, s, svc, a, id, opID, status) } } - return queueUpgrade(g, s, a, id, opID, status) + data, err := queueUpgrade(g, s, a, id, opID, status) + return data, 0, err }) } return updateMutation(g, db, opts, gateway.ActionUpdateUpgrade, true, diff --git a/core/http/endpoints/addons/upgrade_run.go b/core/http/endpoints/addons/upgrade_run.go index 278c3a80dd4d..d36bf243dec2 100644 --- a/core/http/endpoints/addons/upgrade_run.go +++ b/core/http/endpoints/addons/upgrade_run.go @@ -250,19 +250,20 @@ const ctxUpdateRequest = "addon.update.request" // operation ID to a run of one item, and answers as queueUpgrade does, with // the run added. A run that cannot start drops the record, so the add-on is // free again. -func runUpgrade(c echo.Context, g *gateway.Gateway, s settings, svc *upgraderun.Service, a contract.Actor, id, opID string, status json.RawMessage) (json.RawMessage, error) { +func runUpgrade(c echo.Context, g *gateway.Gateway, s settings, svc *upgraderun.Service, a contract.Actor, id, opID string, status json.RawMessage) (json.RawMessage, int, error) { var view map[string]any if json.Unmarshal(status, &view) != nil { - return nil, errors.New("unreadable operation status") + return nil, 0, errors.New("unreadable operation status") } // A repeated request answers the recorded operation and queues nothing. if phase, _ := view["Phase"].(string); phase != "accepted" { - return status, nil + return status, 0, nil } ctx := c.Request().Context() req, _ := c.Get(ctxUpdateRequest).(*UpgradeRequest) if req == nil { - return queueUpgrade(g, s, a, id, opID, status) + data, err := queueUpgrade(g, s, a, id, opID, status) + return data, 0, err } key := recordedKey(a, id, req.ExpectedDigest, req.CandidateDigest) s.upgrader.expect(key, opID) @@ -275,33 +276,39 @@ func runUpgrade(c echo.Context, g *gateway.Gateway, s settings, svc *upgraderun. case "": case upgraderun.CodeRunActive: drop() - return nil, &afterRefusal{status: http.StatusConflict, kind: upgraderun.CodeRunActive, message: "Another upgrade run is running. Wait for it to end, or cancel it, and upgrade again"} + return nil, 0, &afterRefusal{status: http.StatusConflict, kind: upgraderun.CodeRunActive, message: "Another upgrade run is running. Wait for it to end, or cancel it, and upgrade again"} case upgraderun.CodeNoUpdate, upgraderun.CodeSourceUnchecked, upgraderun.CodeStale: // The run's check does not list the add-on as the owner just did // (the check is older, or this frontend does not list add-ons): the // owner accepted the upgrade, so queue it as before. s.upgrader.take(key) - return queueUpgrade(g, s, a, id, opID, status) + data, err := queueUpgrade(g, s, a, id, opID, status) + return data, 0, err default: drop() - return nil, err + return nil, 0, err + } + out := upgraderun.SingleOutcome(run, item) + answer := http.StatusOK + switch out.State { + case upgraderun.SingleRefused: + drop() + return nil, 0, &afterRefusal{status: http.StatusConflict, kind: out.ErrorKey, message: out.Error} + case upgraderun.SingleStarted: + view["jobId"] = out.JobID + case upgraderun.SinglePending: + // The run keeps the recorded operation and starts it later: the + // answer has the run to follow and no job yet. + answer = http.StatusAccepted } // The actor names the user only; the credential reference it carries // stays on the server. + run = out.Run run.Actor = RunActorUser(run.Actor) view["run"] = run - switch { - case item.JobID != "": - view["jobId"] = item.JobID - case item.Phase.Terminal(): - drop() - kind := item.ErrorKey - if kind == "" { - kind = upgraderun.ErrKeyUpgradeFailed - } - return nil, &afterRefusal{status: http.StatusConflict, kind: kind, message: item.Error} - } - return json.Marshal(view) + view["runId"] = run.ID + data, err := json.Marshal(view) + return data, answer, err } // GatewayUpdateChecker lists the add-ons with an update for upgrade runs diff --git a/core/http/endpoints/addons/upgrade_run_test.go b/core/http/endpoints/addons/upgrade_run_test.go index 0ad61540a92c..961b97cb230e 100644 --- a/core/http/endpoints/addons/upgrade_run_test.go +++ b/core/http/endpoints/addons/upgrade_run_test.go @@ -223,6 +223,69 @@ var _ = Describe("add-on items of upgrade runs", Label("updates"), func() { }) }) +// gatedStarter holds the start of an item until its gate is closed. +type gatedStarter struct { + inner upgraderun.Starter + gate chan struct{} +} + +func (g gatedStarter) Start(ctx context.Context, actor string, it upgraderun.Item) (string, error) { + select { + case <-g.gate: + case <-ctx.Done(): + return "", ctx.Err() + } + return g.inner.Start(ctx, actor, it) +} + +var _ = Describe("the add-on upgrade route when its run is slow to start", Label("updates"), func() { + It("answers 202 with the run and no job, and the run later runs the caller's recorded operation", func() { + s := newUpdatesStack() + gs := galleryop.NewGalleryService(&config.ApplicationConfig{}, nil) + qctx, stop := context.WithCancel(context.Background()) + DeferCleanup(stop) + Expect(gs.Start(qctx, nil, nil)).To(Succeed()) + up := &QueuedUpgrader{Gateway: func() *gateway.Gateway { return s.gateway }, Queue: func() *galleryop.GalleryService { return gs }} + gate := make(chan struct{}) + h, err := upgraderuntest.NewHarness(GinkgoT().TempDir(), upgraderuntest.Options{ + Jobs: gs, + Starters: map[upgraderun.Kind]upgraderun.Starter{upgraderun.KindAddon: gatedStarter{inner: upgraderun.AddonStarter{Upgrader: up}, gate: gate}}, + }) + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(h.Service.Close) + old := runStartWait + runStartWait = 200 * time.Millisecond + DeferCleanup(func() { runStartWait = old }) + + e := echo.New() + e.Use(auth.Middleware(s.db, s.cfg)) + group := e.Group("/api/addons", auth.RequireFeature(s.db, auth.FeatureAddons), auth.CSRFMiddleware(), BrowserProtection()) + group.POST("/dispatch", Dispatch(s.gateway, s.db, WithOwnership(s.mode))) + group.POST("/:id/upgrade", UpgradeAddon(s.gateway, s.db, WithOwnership(s.mode), WithOperationQueue(gs, nil), + WithUpgradeRuns(func() *upgraderun.Service { return h.Service }, up))) + alice := func(op string) func(*http.Request) { return humanTab(s.cookies["alice"], op) } + + before := s.installedDigest() + next := s.publish("build-2", catalog.Requirements{}) + Expect(send(s.frontends["owner"], "POST", "/api/addons/notes/update/check", `{"operationId":"c"}`, alice("c")).code).To(Equal(200)) + h.Addons.Add(upgraderun.Candidate{Kind: upgraderun.KindAddon, Name: "notes", From: before, To: next.Digest, + Extra: map[string]string{upgraderun.ExtraExpectedDigest: before, upgraderun.ExtraCandidateDigest: next.Digest}}) + + res := send(e, "POST", "/api/addons/notes/upgrade", + fmt.Sprintf(`{"operationId":"p-1","expectedDigest":%q,"candidateDigest":%q}`, before, next.Digest), alice("p-1")) + Expect(res.code).To(Equal(http.StatusAccepted), fmt.Sprint(res.body)) + payload := res.body["payload"].(map[string]any) + Expect(payload).NotTo(HaveKey("jobId")) + Expect(payload).To(HaveKeyWithValue("Phase", "accepted")) + runView := payload["run"].(map[string]any) + Expect(payload).To(HaveKeyWithValue("runId", runView["id"])) + + close(gate) + Expect(awaitLifecycle(e, "notes", "p-1", alice("p-1"))).To(HaveKeyWithValue("Phase", "completed")) + Expect(s.generation()).To(Equal(uint64(2))) + }) +}) + var _ = Describe("add-on items of upgrade runs on a frontend that is not the owner", Label("updates"), func() { var ( s *updatesStack diff --git a/core/http/endpoints/localai/backend.go b/core/http/endpoints/localai/backend.go index 0546653ac57c..db4c9c121b4c 100644 --- a/core/http/endpoints/localai/backend.go +++ b/core/http/endpoints/localai/backend.go @@ -141,6 +141,7 @@ func (mgs *BackendEndpointService) GetAllStatusEndpoint() echo.HandlerFunc { // @Tags backends // @Param request body GalleryBackend true "query params" // @Success 200 {object} schema.BackendResponse "Response" +// @Success 202 {object} SingleUpgradePending "An upgrade run took the request and did not get the operation accepted in time; it starts it later (code pending)" // @Failure 403 {object} map[string]interface{} "Backend installation is disabled on this server (code backend_install_disabled)" // @Failure 409 {object} map[string]interface{} "Hardware-specific build in distributed mode (code concrete_backend_requires_target)" // @Router /backends/apply [post] @@ -343,6 +344,7 @@ func (mgs *BackendEndpointService) UpgradeGuard() *BackendUpgradeGuard { // @Param name path string true "Backend name" // @Param expected_to query string false "The version or digest the caller wants; refused with code stale when it is no longer the available one" // @Success 200 {object} schema.BackendResponse "Response" +// @Success 202 {object} SingleUpgradePending "An upgrade run took the request and did not get the operation accepted in time; it starts it later (code pending)" // @Failure 403 {object} map[string]interface{} "Backend installation is disabled on this server (code backend_install_disabled)" // @Failure 404 {object} map[string]interface{} "The backend is not installed (code not_installed)" // @Failure 409 {object} map[string]interface{} "The backend has no pending upgrade (code no_update) or the requested build is no longer the available one (code stale)" diff --git a/core/http/endpoints/localai/model_updates.go b/core/http/endpoints/localai/model_updates.go index 7bedefcaf6a8..f2bb867bca3a 100644 --- a/core/http/endpoints/localai/model_updates.go +++ b/core/http/endpoints/localai/model_updates.go @@ -92,6 +92,7 @@ type ModelUpgradeRunResponse struct { // @Param name path string true "Installed model name" // @Param request body schema.ModelUpgradeRequest false "Options" // @Success 200 {object} ModelUpgradeRunResponse "Operation, and the run when one started it" +// @Success 202 {object} SingleUpgradePending "The run did not get the operation accepted in time; it starts it later (code pending)" // @Failure 404 {object} schema.ModelUpgradeError "Not installed" // @Failure 409 {object} schema.ModelUpgradeError "Running, held, edited keys need a choice, or another upgrade run runs (code run_active)" // @Failure 422 {object} schema.ModelUpgradeError "Not installed from a gallery with a recorded origin" @@ -210,12 +211,12 @@ func upgradeModelViaRun(c echo.Context, d ModelUpgradeDeps, svc *upgraderun.Serv } return true, modelUpgradeError(c, err) } - if item.JobID == "" && item.Phase.Terminal() { - code := item.ErrorKey - if code == "" { - code = upgraderun.ErrKeyUnknown - } - return true, c.JSON(http.StatusConflict, schema.ModelUpgradeError{Error: item.Error, Code: code}) + out := upgraderun.SingleOutcome(run, item) + switch out.State { + case upgraderun.SingleRefused: + return true, c.JSON(http.StatusConflict, schema.ModelUpgradeError{Error: out.Error, Code: out.ErrorKey}) + case upgraderun.SinglePending: + return true, singlePending(c, out) } run = publicRun(run) return true, c.JSON(http.StatusOK, ModelUpgradeRunResponse{ diff --git a/core/http/endpoints/localai/model_updates_test.go b/core/http/endpoints/localai/model_updates_test.go index b997e41eb774..07ed1b7ce373 100644 --- a/core/http/endpoints/localai/model_updates_test.go +++ b/core/http/endpoints/localai/model_updates_test.go @@ -175,6 +175,24 @@ var _ = Describe("Model update routes", func() { Consistently(rec.done, 100*time.Millisecond).ShouldNot(Receive(), "the run's starter queued it, not the route") }) + It("answers 202 with the run, and no job, when the operation is not accepted within the wait", func() { + gate := make(chan struct{}) + DeferCleanup(func() { close(gate) }) + h.Starter.Block(gate) + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + req := httptest.NewRequest(http.MethodPost, "/api/models/upgrade/tiny", nil).WithContext(ctx) + w := httptest.NewRecorder() + e.ServeHTTP(w, req) + Expect(w.Code).To(Equal(http.StatusAccepted), w.Body.String()) + var body SingleUpgradePending + Expect(json.Unmarshal(w.Body.Bytes(), &body)).To(Succeed()) + Expect(body.Code).To(Equal("pending")) + Expect(body.RunID).NotTo(BeEmpty()) + Expect(w.Body.String()).NotTo(ContainSubstring("Upgrade started")) + Expect(w.Body.String()).NotTo(ContainSubstring(`"jobID"`)) + }) + It("answers 409 run_active while another run runs", func() { Expect(do(http.MethodPost, "/api/models/upgrade/tiny", "").Code).To(Equal(http.StatusOK)) w := do(http.MethodPost, "/api/models/upgrade/tiny", "") diff --git a/core/http/endpoints/localai/upgrade_runs.go b/core/http/endpoints/localai/upgrade_runs.go index 72e78de23f94..80eb61b66c46 100644 --- a/core/http/endpoints/localai/upgrade_runs.go +++ b/core/http/endpoints/localai/upgrade_runs.go @@ -424,6 +424,26 @@ type SingleUpgradeAnswer func(c echo.Context, jobID string, run upgraderun.Run) // singleRefusal is the refusal of a single upgrade route that a run answered: // the error text the route always had, with a stable code. +// SingleUpgradePending is the answer of a single upgrade route whose run did +// not get the operation accepted within the wait (202). The run goes on and +// starts the item; follow it at GET /api/updates/runs/{run_id}. +type SingleUpgradePending struct { + // Code is always "pending". + Code string `json:"code"` + Message string `json:"message"` + RunID string `json:"run_id"` + Run *upgraderun.Run `json:"run,omitempty"` +} + +// singlePending answers a run of one item that has no operation yet. +func singlePending(c echo.Context, out upgraderun.SingleResult) error { + run := publicRun(out.Run) + return c.JSON(http.StatusAccepted, SingleUpgradePending{ + Code: string(upgraderun.SinglePending), RunID: out.RunID, Run: &run, + Message: "the upgrade waits in an upgrade run and has no operation yet; follow the run", + }) +} + func singleRefusal(c echo.Context, status int, code, msg string) error { return c.JSON(status, map[string]any{"error": msg, "code": code}) } @@ -477,14 +497,14 @@ func BackendUpgradeViaRun(d UpgradeRunDeps, guard *BackendUpgradeGuard, legacy e default: return runRefusal(c, err) } - if item.JobID == "" && item.Phase.Terminal() { - code := item.ErrorKey - if code == "" { - code = upgraderun.ErrKeyUnknown - } - return singleRefusal(c, http.StatusConflict, code, item.Error) + out := upgraderun.SingleOutcome(run, item) + switch out.State { + case upgraderun.SingleRefused: + return singleRefusal(c, http.StatusConflict, out.ErrorKey, out.Error) + case upgraderun.SinglePending: + return singlePending(c, out) } - return answer(c, item.JobID, publicRun(run)) + return answer(c, out.JobID, publicRun(out.Run)) } } diff --git a/core/http/endpoints/localai/upgrade_runs_test.go b/core/http/endpoints/localai/upgrade_runs_test.go index fe976d8f3ac3..c97700db6946 100644 --- a/core/http/endpoints/localai/upgrade_runs_test.go +++ b/core/http/endpoints/localai/upgrade_runs_test.go @@ -488,6 +488,31 @@ var _ = Describe("Single upgrade routes as runs of one item", func() { Expect(legacyBody).To(ContainSubstring(`"expected_to":"v5"`), "the guard leaves the body readable for the handler") }) + DescribeTable("answers 202 with the run, and no job, when the operation is not accepted within the wait", + func(path string) { + gate := make(chan struct{}) + DeferCleanup(func() { close(gate) }) + h.Starter.Block(gate) + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + req := httptest.NewRequest(http.MethodPost, path, nil).WithContext(ctx) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + Expect(rec.Code).To(Equal(http.StatusAccepted), rec.Body.String()) + var body SingleUpgradePending + Expect(json.Unmarshal(rec.Body.Bytes(), &body)).To(Succeed()) + Expect(body.Code).To(Equal("pending")) + Expect(body.RunID).NotTo(BeEmpty()) + Expect(body.Run).NotTo(BeNil()) + Expect(body.Run.ID).To(Equal(body.RunID)) + Expect(rec.Body.String()).NotTo(ContainSubstring("started")) + Expect(rec.Body.String()).NotTo(ContainSubstring(`"jobID"`)) + Expect(legacy).To(BeZero()) + }, + Entry("POST /api/backends/upgrade/{name}", "/api/backends/upgrade/kokoro"), + Entry("POST /backends/upgrade/{name}", "/backends/upgrade/kokoro"), + ) + It("answers 409 with the error key when the item could not start", func() { h.Starter.SetErr(&upgraderun.StartError{ErrorKey: "download", Err: errors.New("registry down")}) rec := doJSON(e, http.MethodPost, "/api/backends/upgrade/kokoro", nil) diff --git a/core/services/localaitools/httpapi/client.go b/core/services/localaitools/httpapi/client.go index 5815d4d5149b..1801a61e5aa4 100644 --- a/core/services/localaitools/httpapi/client.go +++ b/core/services/localaitools/httpapi/client.go @@ -24,6 +24,7 @@ import ( localaitools "github.com/mudler/LocalAI/core/services/localaitools" "github.com/mudler/LocalAI/core/services/modeladmin" "github.com/mudler/LocalAI/core/services/modelupdates" + "github.com/mudler/LocalAI/core/services/upgraderun" "github.com/mudler/LocalAI/pkg/httpclient" "github.com/mudler/LocalAI/pkg/modelsearch" "github.com/mudler/LocalAI/pkg/vram" @@ -549,13 +550,32 @@ func (c *Client) InstallLibraryBackend(ctx context.Context, req localaitools.Ins func (c *Client) UpgradeBackend(ctx context.Context, name string) (string, error) { var resp struct { ID string `json:"uuid"` + singlePending } if err := c.do(ctx, http.MethodPost, routeBackendUpgrade(name), nil, &resp); err != nil { return "", err } + if err := resp.err("gallery:" + name); err != nil { + return "", err + } return resp.ID, nil } +// singlePending reads the 202 answer of a single upgrade that an upgrade run +// did not start in time (code pending): there is no job to report, only the +// run that starts it later. +type singlePending struct { + Code string `json:"code"` + RunID string `json:"run_id"` +} + +func (p singlePending) err(key string) error { + if p.Code != string(upgraderun.SinglePending) { + return nil + } + return &upgraderun.PendingError{RunID: p.RunID, Key: key} +} + // ---- Upgrade runs ---- func (c *Client) StartUpgradeRun(ctx context.Context, req localaitools.UpgradeRunStartRequest) (*localaitools.UpgradeRun, error) { @@ -627,11 +647,17 @@ func (c *Client) UpgradeModel(ctx context.Context, name string, configOnly bool, if name == "" { return "", errors.New("name is required") } - var resp schema.ModelUpgradeResponse + var resp struct { + schema.ModelUpgradeResponse + singlePending + } body := schema.ModelUpgradeRequest{ConfigOnly: configOnly, Choices: choices} if err := c.do(ctx, http.MethodPost, routeModelUpgrade(name), body, &resp); err != nil { return "", err } + if err := resp.err("model:" + name); err != nil { + return "", err + } return resp.JobID, nil } diff --git a/core/services/localaitools/httpapi/client_test.go b/core/services/localaitools/httpapi/client_test.go index 3fae165d70e4..ab0107a393a2 100644 --- a/core/services/localaitools/httpapi/client_test.go +++ b/core/services/localaitools/httpapi/client_test.go @@ -14,6 +14,7 @@ import ( "github.com/mudler/LocalAI/core/schema" localaitools "github.com/mudler/LocalAI/core/services/localaitools" + "github.com/mudler/LocalAI/core/services/upgraderun" ) // fakeLocalAI is a minimal HTTP server that mimics the relevant LocalAI @@ -164,6 +165,26 @@ var _ = Describe("httpapi.Client against the LocalAI admin REST surface", func() }) }) + Describe("a single upgrade that an upgrade run did not start in time", func() { + It("answers with the run, never a job, for a backend and a model", func() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte(`{"code":"pending","message":"waits","run_id":"run-7","run":{"id":"run-7"}}`)) + })) + defer srv.Close() + cl := New(srv.URL, "") + job, err := cl.UpgradeBackend(ctx, "kokoro") + Expect(job).To(BeEmpty()) + var pending *upgraderun.PendingError + Expect(errors.As(err, &pending)).To(BeTrue(), "%v", err) + Expect(pending.RunID).To(Equal("run-7")) + job, err = cl.UpgradeModel(ctx, "tiny", false, nil) + Expect(job).To(BeEmpty()) + Expect(errors.As(err, &pending)).To(BeTrue(), "%v", err) + }) + }) + Describe("SearchModels", func() { It("sends the query and parses the response", func() { var got url.Values diff --git a/core/services/localaitools/inproc/upgrade_runs.go b/core/services/localaitools/inproc/upgrade_runs.go index 4f8738a95bcc..09dce41caa15 100644 --- a/core/services/localaitools/inproc/upgrade_runs.go +++ b/core/services/localaitools/inproc/upgrade_runs.go @@ -3,7 +3,6 @@ package inproc import ( "context" "errors" - "fmt" "time" "github.com/mudler/LocalAI/core/services/backendupdates" @@ -150,7 +149,7 @@ func (c *Client) upgradeOneViaRun(ctx context.Context, kind upgraderun.Kind, nam if svc == nil { return "", false, nil } - _, item, err := svc.StartOne(ctx, c.runActor(ctx), upgraderun.StartItem{Kind: kind, Name: name}, upgraderun.SourceManual, 0) + run, item, err := svc.StartOne(ctx, c.runActor(ctx), upgraderun.StartItem{Kind: kind, Name: name}, upgraderun.SourceManual, 0) switch upgraderun.CodeOf(err) { case "": case upgraderun.CodeNoUpdate, upgraderun.CodeSourceUnchecked, upgraderun.CodeStale: @@ -158,8 +157,8 @@ func (c *Client) upgradeOneViaRun(ctx context.Context, kind upgraderun.Kind, nam default: return "", true, err } - if item.JobID == "" && item.Phase.Terminal() { - return "", true, fmt.Errorf("%s: %s", item.ErrorKey, item.Error) - } - return item.JobID, true, nil + out := upgraderun.SingleOutcome(run, item) + // A pending start has no job yet: the error names the run to follow, so + // the Assistant never says the upgrade started. + return out.JobID, true, out.Err() } diff --git a/core/services/localaitools/inproc/upgrade_runs_test.go b/core/services/localaitools/inproc/upgrade_runs_test.go index df0d89ea01d9..0c1b158014e4 100644 --- a/core/services/localaitools/inproc/upgrade_runs_test.go +++ b/core/services/localaitools/inproc/upgrade_runs_test.go @@ -79,6 +79,20 @@ var _ = Describe("Upgrade runs through the in-process client", func() { Expect(upgraderun.CodeOf(err)).To(Equal(upgraderun.CodeRunActive)) }) + It("never says started without a job: a start that waits out answers with the run", func() { + gate := make(chan struct{}) + DeferCleanup(func() { close(gate) }) + h.Starter.Block(gate) + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + job, err := c.UpgradeBackend(ctx, "kokoro") + Expect(job).To(BeEmpty()) + var pending *upgraderun.PendingError + Expect(errors.As(err, &pending)).To(BeTrue(), "%v", err) + Expect(pending.RunID).NotTo(BeEmpty()) + Expect(err.Error()).To(ContainSubstring(pending.RunID)) + }) + It("never upgrades directly beside a run: a backend the run does not list, a model with options, a model retry", func() { _, err := c.UpgradeBackend(context.Background(), "kokoro") Expect(err).NotTo(HaveOccurred()) diff --git a/core/services/upgraderun/fakes_test.go b/core/services/upgraderun/fakes_test.go index 81ac6af4acb6..53920823f1b7 100644 --- a/core/services/upgraderun/fakes_test.go +++ b/core/services/upgraderun/fakes_test.go @@ -92,13 +92,32 @@ type fakeStarter struct { order []string actors []string err error + // gate, when set, holds every start until it is closed. + gate chan struct{} +} + +// block holds every later start until gate is closed. +func (s *fakeStarter) block(gate chan struct{}) { + s.mu.Lock() + defer s.mu.Unlock() + s.gate = gate } func newFakeStarter(jobs *fakeJobs) *fakeStarter { return &fakeStarter{jobs: jobs, byKey: map[string]string{}} } -func (s *fakeStarter) Start(_ context.Context, actor string, it Item) (string, error) { +func (s *fakeStarter) Start(ctx context.Context, actor string, it Item) (string, error) { + s.mu.Lock() + gate := s.gate + s.mu.Unlock() + if gate != nil { + select { + case <-gate: + case <-ctx.Done(): + return "", ctx.Err() + } + } s.mu.Lock() defer s.mu.Unlock() if s.err != nil { diff --git a/core/services/upgraderun/single.go b/core/services/upgraderun/single.go index 6084a2cec547..88fed93e4474 100644 --- a/core/services/upgraderun/single.go +++ b/core/services/upgraderun/single.go @@ -2,6 +2,7 @@ package upgraderun import ( "context" + "fmt" "time" ) @@ -59,3 +60,78 @@ func (s *Service) itemOf(ctx context.Context, run Run, key string) (Run, Item, e } return run, Item{Key: key}, nil } + +// SingleState is what the caller of StartOne answers for its item. +type SingleState string + +const ( + // SingleStarted: the operation of the item was accepted; JobID is set. + SingleStarted SingleState = "started" + // SingleRefused: the item ended without an operation (its start was + // refused or skipped). + SingleRefused SingleState = "refused" + // SinglePending: the wait ended before the operation was accepted. The + // run goes on and starts the item later; the caller answers with the run. + SinglePending SingleState = "pending" +) + +// SingleResult is the outcome of a run of one item, as the routes and the +// Assistant answer it. +type SingleResult struct { + State SingleState + Run Run + Item Item + RunID string + JobID string + // ErrorKey and Error describe a refusal. + ErrorKey string + Error string +} + +// SingleOutcome maps the run and the item StartOne returned to a job, a +// refusal or a pending start. Every caller of StartOne uses it, so none of +// them answers "started" without a job. +func SingleOutcome(run Run, it Item) SingleResult { + out := SingleResult{Run: run, Item: it, RunID: run.ID} + switch { + case it.JobID != "": + out.State, out.JobID = SingleStarted, it.JobID + case it.Phase.Terminal(): + out.State, out.ErrorKey, out.Error = SingleRefused, orUnknown(it.ErrorKey), it.Error + default: + out.State = SinglePending + } + return out +} + +// Err is nil for a started item, a *RefusedError for a refused one and a +// *PendingError for a pending one. +func (r SingleResult) Err() error { + switch r.State { + case SingleStarted: + return nil + case SingleRefused: + return &RefusedError{Key: r.Item.Key, ErrorKey: r.ErrorKey, Message: r.Error} + } + return &PendingError{RunID: r.RunID, Key: r.Item.Key} +} + +// RefusedError is an item of a run of one that ended without an operation. +type RefusedError struct { + Key string + ErrorKey string + Message string +} + +func (e *RefusedError) Error() string { return e.ErrorKey + ": " + e.Message } + +// PendingError is an item of a run of one whose operation was not accepted +// within the wait. The run keeps it and starts it later. +type PendingError struct { + RunID string + Key string +} + +func (e *PendingError) Error() string { + return fmt.Sprintf("the update of %s waits in upgrade run %s and has no operation yet; follow the run", e.Key, e.RunID) +} diff --git a/core/services/upgraderun/single_test.go b/core/services/upgraderun/single_test.go new file mode 100644 index 000000000000..93b28b69c618 --- /dev/null +++ b/core/services/upgraderun/single_test.go @@ -0,0 +1,68 @@ +package upgraderun_test + +import ( + "context" + "errors" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + . "github.com/mudler/LocalAI/core/services/upgraderun" +) + +var _ = Describe("The outcome of a run of one item", func() { + run := Run{ID: "run-1", State: RunRunning} + + It("is started when the item has a job", func() { + out := SingleOutcome(run, Item{Key: "gallery:a", Phase: PhaseRunning, JobID: "job-1"}) + Expect(out.State).To(Equal(SingleStarted)) + Expect(out.JobID).To(Equal("job-1")) + Expect(out.Err()).NotTo(HaveOccurred()) + }) + + It("is refused when the item ended without a job, with its key and error", func() { + out := SingleOutcome(run, Item{Key: "gallery:a", Phase: PhaseFailed, ErrorKey: "download", Error: "registry down"}) + Expect(out.State).To(Equal(SingleRefused)) + Expect(out.ErrorKey).To(Equal("download")) + Expect(out.Error).To(Equal("registry down")) + var refused *RefusedError + Expect(errors.As(out.Err(), &refused)).To(BeTrue()) + Expect(refused.ErrorKey).To(Equal("download")) + }) + + It("gives the unknown key to a refusal without one", func() { + out := SingleOutcome(run, Item{Key: "gallery:a", Phase: PhaseSkipped}) + Expect(out.State).To(Equal(SingleRefused)) + Expect(out.ErrorKey).To(Equal(ErrKeyUnknown)) + }) + + DescribeTable("is pending while the item has no job and did not end", + func(phase Phase) { + out := SingleOutcome(run, Item{Key: "gallery:a", Phase: phase}) + Expect(out.State).To(Equal(SinglePending)) + Expect(out.JobID).To(BeEmpty()) + Expect(out.RunID).To(Equal("run-1")) + var pending *PendingError + Expect(errors.As(out.Err(), &pending)).To(BeTrue()) + Expect(pending.RunID).To(Equal("run-1")) + Expect(out.Err().Error()).NotTo(ContainSubstring("started")) + }, + Entry("queued", PhaseQueued), + Entry("running, not yet accepted", PhaseRunning), + ) + + It("answers pending, not started, when StartOne waits out before the operation is accepted", func() { + h := newHarness(harnessOpts{}) + h.backends.add(Candidate{Kind: KindGallery, Name: "slow"}) + gate := make(chan struct{}) + DeferCleanup(func() { close(gate) }) + h.starter.block(gate) + ctx := context.Background() + run, item, err := h.svc.StartOne(ctx, "admin", si(KindGallery, "slow"), SourceManual, 100*time.Millisecond) + Expect(err).NotTo(HaveOccurred()) + out := SingleOutcome(run, item) + Expect(out.State).To(Equal(SinglePending)) + Expect(out.RunID).To(Equal(run.ID)) + }) +}) diff --git a/core/services/upgraderun/upgraderuntest/fakes.go b/core/services/upgraderun/upgraderuntest/fakes.go index 1197dda31dbf..5b0b89d05d2a 100644 --- a/core/services/upgraderun/upgraderuntest/fakes.go +++ b/core/services/upgraderun/upgraderuntest/fakes.go @@ -115,6 +115,15 @@ type Starter struct { byKey map[string]string actors []string err error + gate chan struct{} +} + +// Block holds every later start until gate is closed or the start's context +// ends, as a starter whose operation is slow to be accepted. +func (s *Starter) Block(gate chan struct{}) { + s.mu.Lock() + defer s.mu.Unlock() + s.gate = gate } // SetErr makes every start fail with err; nil starts again. @@ -127,7 +136,17 @@ func (s *Starter) SetErr(err error) { // NewStarter starts jobs in jobs. func NewStarter(jobs *Jobs) *Starter { return &Starter{jobs: jobs, byKey: map[string]string{}} } -func (s *Starter) Start(_ context.Context, actor string, it upgraderun.Item) (string, error) { +func (s *Starter) Start(ctx context.Context, actor string, it upgraderun.Item) (string, error) { + s.mu.Lock() + gate := s.gate + s.mu.Unlock() + if gate != nil { + select { + case <-gate: + case <-ctx.Done(): + return "", ctx.Err() + } + } s.mu.Lock() defer s.mu.Unlock() s.actors = append(s.actors, actor) diff --git a/docs/content/models/upgrade-runs.md b/docs/content/models/upgrade-runs.md index 684168eae2af..19e99294b098 100644 --- a/docs/content/models/upgrade-runs.md +++ b/docs/content/models/upgrade-runs.md @@ -558,6 +558,13 @@ runs and the check of the run does not list the item (it was not checked yet, or an older listing), or the server keeps no runs, they queue the upgrade directly, as before. +Each route waits up to 30 seconds for the run to get the operation accepted. +When the wait ends first, the route answers `202` with code `pending`, +`run_id` and `run`, and no job: the run goes on and starts the item later. +Follow it with `GET /api/updates/runs/{run_id}`. The add-on route answers +`202` with the operation status, `run` and `runId` in the payload, and no +`jobId`; the run then runs the operation the route recorded. + A model upgrade with `config_only` or `choices`, and a model retry (`POST /api/models/{name}/upgrade/retry`), are always direct: a run makes no such choice. While a run runs, they are refused with `409` `run_active` too. @@ -580,7 +587,9 @@ starts, reads and cancels runs of backends and models: The assistant asks you to confirm before it starts or cancels a run. `upgrade_backend` and `upgrade_model` still upgrade one item; they start a run -of one item too. `upgrade_backend` refuses a backend that is not installed or +of one item too. When the run did not start the operation within the wait, +they answer with an error that names the run to follow, never a job. +`upgrade_backend` refuses a backend that is not installed or has no update before it starts anything, as the REST routes do. While a run runs, every upgrade from the assistant (also `upgrade_model` with the actions `config_only` and `retry`) is refused with `run_active`. diff --git a/swagger/docs.go b/swagger/docs.go index de8566230248..16e25d99fd90 100644 --- a/swagger/docs.go +++ b/swagger/docs.go @@ -3492,6 +3492,12 @@ const docTemplate = `{ "$ref": "#/definitions/contract.Result" } }, + "202": { + "description": "Operation accepted and handed to an upgrade run that did not start it within the wait; the payload has run and runId but no jobId, and the run starts the recorded operation later", + "schema": { + "$ref": "#/definitions/contract.Result" + } + }, "400": { "description": "Malformed request", "schema": { @@ -15909,6 +15915,12 @@ const docTemplate = `{ "$ref": "#/definitions/localai.ModelUpgradeRunResponse" } }, + "202": { + "description": "The run did not get the operation accepted in time; it starts it later (code pending)", + "schema": { + "$ref": "#/definitions/localai.SingleUpgradePending" + } + }, "404": { "description": "Not installed", "schema": { @@ -19846,6 +19858,12 @@ const docTemplate = `{ "$ref": "#/definitions/schema.BackendResponse" } }, + "202": { + "description": "An upgrade run took the request and did not get the operation accepted in time; it starts it later (code pending)", + "schema": { + "$ref": "#/definitions/localai.SingleUpgradePending" + } + }, "403": { "description": "Backend installation is disabled on this server (code backend_install_disabled)", "schema": { @@ -20116,6 +20134,12 @@ const docTemplate = `{ "$ref": "#/definitions/schema.BackendResponse" } }, + "202": { + "description": "An upgrade run took the request and did not get the operation accepted in time; it starts it later (code pending)", + "schema": { + "$ref": "#/definitions/localai.SingleUpgradePending" + } + }, "403": { "description": "Backend installation is disabled on this server (code backend_install_disabled)", "schema": { @@ -27278,6 +27302,24 @@ const docTemplate = `{ } } }, + "localai.SingleUpgradePending": { + "type": "object", + "properties": { + "code": { + "description": "Code is always \"pending\".", + "type": "string" + }, + "message": { + "type": "string" + }, + "run": { + "$ref": "#/definitions/upgraderun.Run" + }, + "run_id": { + "type": "string" + } + } + }, "localai.TTSModelVoices": { "type": "object", "properties": { diff --git a/swagger/swagger.json b/swagger/swagger.json index cbda7c3105b0..82496b7b7cb2 100644 --- a/swagger/swagger.json +++ b/swagger/swagger.json @@ -3489,6 +3489,12 @@ "$ref": "#/definitions/contract.Result" } }, + "202": { + "description": "Operation accepted and handed to an upgrade run that did not start it within the wait; the payload has run and runId but no jobId, and the run starts the recorded operation later", + "schema": { + "$ref": "#/definitions/contract.Result" + } + }, "400": { "description": "Malformed request", "schema": { @@ -15906,6 +15912,12 @@ "$ref": "#/definitions/localai.ModelUpgradeRunResponse" } }, + "202": { + "description": "The run did not get the operation accepted in time; it starts it later (code pending)", + "schema": { + "$ref": "#/definitions/localai.SingleUpgradePending" + } + }, "404": { "description": "Not installed", "schema": { @@ -19843,6 +19855,12 @@ "$ref": "#/definitions/schema.BackendResponse" } }, + "202": { + "description": "An upgrade run took the request and did not get the operation accepted in time; it starts it later (code pending)", + "schema": { + "$ref": "#/definitions/localai.SingleUpgradePending" + } + }, "403": { "description": "Backend installation is disabled on this server (code backend_install_disabled)", "schema": { @@ -20113,6 +20131,12 @@ "$ref": "#/definitions/schema.BackendResponse" } }, + "202": { + "description": "An upgrade run took the request and did not get the operation accepted in time; it starts it later (code pending)", + "schema": { + "$ref": "#/definitions/localai.SingleUpgradePending" + } + }, "403": { "description": "Backend installation is disabled on this server (code backend_install_disabled)", "schema": { @@ -27275,6 +27299,24 @@ } } }, + "localai.SingleUpgradePending": { + "type": "object", + "properties": { + "code": { + "description": "Code is always \"pending\".", + "type": "string" + }, + "message": { + "type": "string" + }, + "run": { + "$ref": "#/definitions/upgraderun.Run" + }, + "run_id": { + "type": "string" + } + } + }, "localai.TTSModelVoices": { "type": "object", "properties": { diff --git a/swagger/swagger.yaml b/swagger/swagger.yaml index e3b4d9a50d39..24cfc80607ed 100644 --- a/swagger/swagger.yaml +++ b/swagger/swagger.yaml @@ -3992,6 +3992,18 @@ definitions: split_server: type: boolean type: object + localai.SingleUpgradePending: + properties: + code: + description: Code is always "pending". + type: string + message: + type: string + run: + $ref: '#/definitions/upgraderun.Run' + run_id: + type: string + type: object localai.TTSModelVoices: properties: model: @@ -17576,6 +17588,12 @@ paths: description: Operation accepted; the payload is the operation status schema: $ref: '#/definitions/contract.Result' + "202": + description: Operation accepted and handed to an upgrade run that did not + start it within the wait; the payload has run and runId but no jobId, + and the run starts the recorded operation later + schema: + $ref: '#/definitions/contract.Result' "400": description: Malformed request schema: @@ -29477,6 +29495,11 @@ paths: description: Operation, and the run when one started it schema: $ref: '#/definitions/localai.ModelUpgradeRunResponse' + "202": + description: The run did not get the operation accepted in time; it starts + it later (code pending) + schema: + $ref: '#/definitions/localai.SingleUpgradePending' "404": description: Not installed schema: @@ -32094,6 +32117,11 @@ paths: description: Response schema: $ref: '#/definitions/schema.BackendResponse' + "202": + description: An upgrade run took the request and did not get the operation + accepted in time; it starts it later (code pending) + schema: + $ref: '#/definitions/localai.SingleUpgradePending' "403": description: Backend installation is disabled on this server (code backend_install_disabled) schema: @@ -32282,6 +32310,11 @@ paths: description: Response schema: $ref: '#/definitions/schema.BackendResponse' + "202": + description: An upgrade run took the request and did not get the operation + accepted in time; it starts it later (code pending) + schema: + $ref: '#/definitions/localai.SingleUpgradePending' "403": description: Backend installation is disabled on this server (code backend_install_disabled) schema: From f9de46dc7b36cb05ce710913caf9bc87f7ab17c5 Mon Sep 17 00:00:00 2001 From: Ettore Di Giacinto Date: Tue, 24 Nov 2026 15:47:46 +0000 Subject: [PATCH 02/19] fix(addons): keep the recorded upgrade operation with the run item The upgrade route recorded the owner's operation ID in a map of its own process. When another frontend took the run over, its starter found no ID and sent a second update-queue, which the owner refused as upgrade_conflict. The first record stayed accepted and the add-on stayed blocked. A cancelled or skipped item, or a start that failed after the route stopped waiting, also left the record accepted. The route now passes the operation ID as extra data of the start item, which the run stores with the item (operation_id). The add-on starter hands it to the upgrader, which runs that record instead of recording a new one. As an observer of the runs, the upgrader drops the record of an add-on item that ended without starting it. Assisted-by: Claude:claude-opus-5-5 --- core/application/upgrade_runs.go | 3 + core/http/endpoints/addons/upgrade_run.go | 89 ++++++++------ .../http/endpoints/addons/upgrade_run_test.go | 111 ++++++++++++++++++ core/services/upgraderun/adapters_test.go | 11 +- core/services/upgraderun/jobs.go | 12 +- core/services/upgraderun/planner.go | 26 +++- core/services/upgraderun/single_test.go | 17 +++ docs/content/models/upgrade-runs.md | 6 +- scripts/addons/suites.json | 5 +- 9 files changed, 236 insertions(+), 44 deletions(-) diff --git a/core/application/upgrade_runs.go b/core/application/upgrade_runs.go index 2a4171f67acc..27647bc674ee 100644 --- a/core/application/upgrade_runs.go +++ b/core/application/upgrade_runs.go @@ -130,6 +130,9 @@ func (a *Application) startUpgradeRuns() { // 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}) + // An add-on item that ended without starting the operation its upgrade + // route recorded drops that record on the owner. + svc.AddObserver(a.addonRunUpgrader) a.upgradeRuns = svc a.upgradeRunsStop = func() { stop() diff --git a/core/http/endpoints/addons/upgrade_run.go b/core/http/endpoints/addons/upgrade_run.go index d36bf243dec2..2280381d2fce 100644 --- a/core/http/endpoints/addons/upgrade_run.go +++ b/core/http/endpoints/addons/upgrade_run.go @@ -9,6 +9,8 @@ import ( "net/http" "sync" + "github.com/mudler/xlog" + "github.com/google/uuid" "github.com/labstack/echo/v4" "gorm.io/gorm" @@ -103,38 +105,22 @@ func RunPrincipal(c echo.Context, db *gorm.DB, mode string) string { // QueuedUpgrader starts the add-on items of upgrade runs // (upgraderun.AddonUpgrader). +// +// The operation the upgrade route recorded on the owner is stored with the +// item (upgraderun.ExtraOperationID), not in this process, so whichever +// frontend runs the item runs that record. As an observer of the runs +// (upgraderun.Observer) it drops a recorded operation whose item ended +// without starting it, so the add-on is free again. Distributed mode: the +// observer acts on Local changes only, on the frontend that runs the run; +// dropped holds the items it already dropped on this process, and a second +// drop after a takeover is harmless (the owner answers the dropped record). type QueuedUpgrader struct { Gateway func() *gateway.Gateway Queue func() *galleryop.GalleryService // OpCache lists the operation in /api/operations; nil does not. OpCache func() *galleryop.OpCache - mu sync.Mutex - // recorded are upgrades the upgrade route already recorded with the - // operation ID of its caller, waiting for the run of one item that - // route starts: the run runs that record instead of making a second one. - recorded map[string]string -} - -func recordedKey(a contract.Actor, addonID, expected, candidate string) string { - return a.UserID + "\x00" + a.CredentialID + "\x00" + addonID + "\x00" + expected + "\x00" + candidate -} - -func (u *QueuedUpgrader) expect(key, opID string) { - u.mu.Lock() - defer u.mu.Unlock() - if u.recorded == nil { - u.recorded = map[string]string{} - } - u.recorded[key] = opID -} - -func (u *QueuedUpgrader) take(key string) string { - u.mu.Lock() - defer u.mu.Unlock() - opID := u.recorded[key] - delete(u.recorded, key) - return opID + dropped sync.Map } func (u *QueuedUpgrader) gateway() *gateway.Gateway { @@ -164,7 +150,7 @@ func ownerRefusal(f *gateway.UpdateFailure) error { // StartAddonUpgrade records the upgrade on the owner as the run's actor and // queues it. See the comment at the top of this file. -func (u *QueuedUpgrader) StartAddonUpgrade(ctx context.Context, actorText, addonID, expectedDigest, candidateDigest string) (string, error) { +func (u *QueuedUpgrader) StartAddonUpgrade(ctx context.Context, actorText, addonID, expectedDigest, candidateDigest, opID string) (string, error) { a, human, ok := DecodeRunActor(actorText) if actorText == managerpkg.AutoUpgradeActor.UserID { // The automatic update upgrades its add-on items on the owner's own @@ -187,7 +173,6 @@ func (u *QueuedUpgrader) StartAddonUpgrade(ctx context.Context, actorText, addon if expectedDigest == "" || candidateDigest == "" { return "", &upgraderun.StartError{ErrorKey: upgraderun.ErrKeyOperationConflict, Err: errors.New("the installed and the candidate digest are required")} } - opID := u.take(recordedKey(a, addonID, expectedDigest, candidateDigest)) if opID == "" { opID = "run-" + uuid.NewString() args, _ := json.Marshal(struct { @@ -265,13 +250,9 @@ func runUpgrade(c echo.Context, g *gateway.Gateway, s settings, svc *upgraderun. data, err := queueUpgrade(g, s, a, id, opID, status) return data, 0, err } - key := recordedKey(a, id, req.ExpectedDigest, req.CandidateDigest) - s.upgrader.expect(key, opID) - drop := func() { - s.upgrader.take(key) - _, _ = g.Dispatch(context.WithoutCancel(ctx), a, contract.Request{AddonID: id, OperationID: opID, Action: gateway.ActionUpdateDropQueued, Arguments: json.RawMessage(`{}`)}) - } - run, item, err := svc.StartOne(ctx, EncodeRunActor(a, true), upgraderun.StartItem{Kind: upgraderun.KindAddon, Name: id, ExpectedTo: req.CandidateDigest}, upgraderun.SourceManual, runStartWait) + drop := func() { dropRecorded(context.WithoutCancel(ctx), g, a, id, opID) } + run, item, err := svc.StartOne(ctx, EncodeRunActor(a, true), upgraderun.StartItem{Kind: upgraderun.KindAddon, Name: id, ExpectedTo: req.CandidateDigest, + Extra: map[string]string{upgraderun.ExtraOperationID: opID}}, upgraderun.SourceManual, runStartWait) switch upgraderun.CodeOf(err) { case "": case upgraderun.CodeRunActive: @@ -281,7 +262,6 @@ func runUpgrade(c echo.Context, g *gateway.Gateway, s settings, svc *upgraderun. // The run's check does not list the add-on as the owner just did // (the check is older, or this frontend does not list add-ons): the // owner accepted the upgrade, so queue it as before. - s.upgrader.take(key) data, err := queueUpgrade(g, s, a, id, opID, status) return data, 0, err default: @@ -311,6 +291,43 @@ func runUpgrade(c echo.Context, g *gateway.Gateway, s settings, svc *upgraderun. return data, answer, err } +// dropRecorded drops an upgrade the owner recorded and nothing started, so +// the add-on is free again. A record that already ran or was dropped stays +// as it is. +func dropRecorded(ctx context.Context, g *gateway.Gateway, a contract.Actor, id, opID string) { + if g == nil { + return + } + if _, err := g.Dispatch(ctx, a, contract.Request{AddonID: id, OperationID: opID, Action: gateway.ActionUpdateDropQueued, Arguments: json.RawMessage(`{}`)}); err != nil { + xlog.Warn("could not drop a recorded add-on upgrade; the add-on stays busy until the record ends", "addon", id, "operation", opID, "error", err) + } +} + +// RunChanged drops the recorded operation of an add-on item that ended +// without starting it: cancelled while queued, skipped, refused, or failed +// after the upgrade route stopped waiting. +func (u *QueuedUpgrader) RunChanged(c upgraderun.Change) { + if !c.Local { + return + } + for _, it := range c.Run.Items { + opID := it.Extra[upgraderun.ExtraOperationID] + if it.Kind != upgraderun.KindAddon || opID == "" || it.JobID != "" || !it.Phase.Terminal() { + continue + } + if _, done := u.dropped.LoadOrStore(c.Run.ID+"\x00"+it.Key, struct{}{}); done { + continue + } + a, _, ok := DecodeRunActor(c.Run.Actor) + if !ok { + continue + } + // The observer runs on the runner's goroutine and must return + // quickly: the owner answers on its own time. + go dropRecorded(context.Background(), u.gateway(), a, it.Name, opID) + } +} + // GatewayUpdateChecker lists the add-ons with an update for upgrade runs // (upgraderun.Checker), through the gateway, as the actor of the run: the // gateway serves the owner's answer on the owner and forwards to it on every diff --git a/core/http/endpoints/addons/upgrade_run_test.go b/core/http/endpoints/addons/upgrade_run_test.go index 961b97cb230e..11d67ffc2357 100644 --- a/core/http/endpoints/addons/upgrade_run_test.go +++ b/core/http/endpoints/addons/upgrade_run_test.go @@ -286,6 +286,117 @@ var _ = Describe("the add-on upgrade route when its run is slow to start", Label }) }) +// failingStarter refuses every start, after its gate opens. +type failingStarter struct{ gate chan struct{} } + +func (f failingStarter) Start(ctx context.Context, _ string, _ upgraderun.Item) (string, error) { + select { + case <-f.gate: + case <-ctx.Done(): + } + return "", &upgraderun.StartError{ErrorKey: upgraderun.ErrKeyUnavailable, Retryable: true, Err: fmt.Errorf("the owner did not answer")} +} + +var _ = Describe("the operation an add-on upgrade route recorded for its run", Label("updates"), func() { + var ( + s *updatesStack + gs *galleryop.GalleryService + e *echo.Echo + route *QueuedUpgrader + alice func(string) func(*http.Request) + ) + + // stack serves the upgrade route with route as its upgrader, and runs the + // add-on items with starter. + stack := func(starter upgraderun.Starter) *upgraderuntest.Harness { + h, err := upgraderuntest.NewHarness(GinkgoT().TempDir(), upgraderuntest.Options{ + Jobs: gs, Starters: map[upgraderun.Kind]upgraderun.Starter{upgraderun.KindAddon: starter}, + }) + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(h.Service.Close) + h.Service.AddObserver(route) + e = echo.New() + e.Use(auth.Middleware(s.db, s.cfg)) + group := e.Group("/api/addons", auth.RequireFeature(s.db, auth.FeatureAddons), auth.CSRFMiddleware(), BrowserProtection()) + group.POST("/dispatch", Dispatch(s.gateway, s.db, WithOwnership(s.mode))) + group.POST("/:id/upgrade", UpgradeAddon(s.gateway, s.db, WithOwnership(s.mode), WithOperationQueue(gs, nil), + WithUpgradeRuns(func() *upgraderun.Service { return h.Service }, route))) + return h + } + offer := func(h *upgraderuntest.Harness) (string, string) { + before := s.installedDigest() + next := s.publish("build-2", catalog.Requirements{}) + Expect(send(s.frontends["owner"], "POST", "/api/addons/notes/update/check", `{"operationId":"c"}`, alice("c")).code).To(Equal(200)) + h.Addons.Add(upgraderun.Candidate{Kind: upgraderun.KindAddon, Name: "notes", From: before, To: next.Digest, + Extra: map[string]string{upgraderun.ExtraExpectedDigest: before, upgraderun.ExtraCandidateDigest: next.Digest}}) + return before, next.Digest + } + body := func(op, before, candidate string) string { + return fmt.Sprintf(`{"operationId":%q,"expectedDigest":%q,"candidateDigest":%q}`, op, before, candidate) + } + + BeforeEach(func() { + s = newUpdatesStack() + gs = galleryop.NewGalleryService(&config.ApplicationConfig{}, nil) + qctx, stop := context.WithCancel(context.Background()) + DeferCleanup(stop) + Expect(gs.Start(qctx, nil, nil)).To(Succeed()) + route = &QueuedUpgrader{Gateway: func() *gateway.Gateway { return s.gateway }, Queue: func() *galleryop.GalleryService { return gs }} + alice = func(op string) func(*http.Request) { return humanTab(s.cookies["alice"], op) } + old := runStartWait + runStartWait = 200 * time.Millisecond + DeferCleanup(func() { runStartWait = old }) + }) + + It("is the one another frontend runs when it takes the run over", func() { + // The item starts on another process: its upgrader is not the one + // the route handed the operation to. + other := &QueuedUpgrader{Gateway: func() *gateway.Gateway { return s.gateway }, Queue: func() *galleryop.GalleryService { return gs }} + gate := make(chan struct{}) + h := stack(gatedStarter{inner: upgraderun.AddonStarter{Upgrader: other}, gate: gate}) + before, candidate := offer(h) + res := send(e, "POST", "/api/addons/notes/upgrade", body("a-1", before, candidate), alice("a-1")) + Expect(res.code).To(Equal(http.StatusAccepted), fmt.Sprint(res.body)) + runID := res.body["payload"].(map[string]any)["runId"].(string) + close(gate) + Eventually(func() string { + r, err := h.Service.Get(context.Background(), runID) + Expect(err).NotTo(HaveOccurred()) + it := r.Item("addon:notes") + if it.JobID == "" { + Expect(it.Phase.Terminal()).To(BeFalse(), it.Error) + } + return it.JobID + }, 10*time.Second, 20*time.Millisecond).ShouldNot(BeEmpty()) + Expect(awaitLifecycle(e, "notes", "a-1", alice("a-1"))).To(HaveKeyWithValue("Phase", "completed")) + Expect(s.generation()).To(Equal(uint64(2))) + }) + + It("is dropped on the owner when the item ends without starting it, so the add-on is free again", func() { + gate := make(chan struct{}) + h := stack(failingStarter{gate: gate}) + before, candidate := offer(h) + res := send(e, "POST", "/api/addons/notes/upgrade", body("f-1", before, candidate), alice("f-1")) + Expect(res.code).To(Equal(http.StatusAccepted), fmt.Sprint(res.body)) + close(gate) + Expect(awaitLifecycle(e, "notes", "f-1", alice("f-1"))).To(HaveKeyWithValue("Phase", "failed")) + // A new upgrade of the same transition is accepted, not refused as a + // conflict with the dropped one. + Eventually(func() int { + r, err := h.Service.List(context.Background(), upgraderun.ListOptions{}) + Expect(err).NotTo(HaveOccurred()) + for _, run := range r { + if run.Active() { + return 1 + } + } + return 0 + }, 5*time.Second).Should(BeZero()) + again := send(e, "POST", "/api/addons/notes/upgrade", body("f-2", before, candidate), alice("f-2")) + Expect(again.errType()).NotTo(Equal("upgrade_conflict"), fmt.Sprint(again.body)) + }) +}) + var _ = Describe("add-on items of upgrade runs on a frontend that is not the owner", Label("updates"), func() { var ( s *updatesStack diff --git a/core/services/upgraderun/adapters_test.go b/core/services/upgraderun/adapters_test.go index 43f895a557f5..1b2134ecbe8b 100644 --- a/core/services/upgraderun/adapters_test.go +++ b/core/services/upgraderun/adapters_test.go @@ -60,8 +60,8 @@ func (f *fakeModelEnqueuer) EnqueueModelUpgrade(name string, opts galleryop.Mode type fakeAddonUpgrader struct{ args []string } -func (f *fakeAddonUpgrader) StartAddonUpgrade(_ context.Context, actor, id, expected, candidate string) (string, error) { - f.args = []string{actor, id, expected, candidate} +func (f *fakeAddonUpgrader) StartAddonUpgrade(_ context.Context, actor, id, expected, candidate, operationID string) (string, error) { + f.args = []string{actor, id, expected, candidate, operationID} return "addon-job", nil } @@ -276,7 +276,12 @@ var _ = Describe("Starters", func() { id, err := AddonStarter{Upgrader: u}.Start(ctx, "admin", Item{Kind: KindAddon, Name: "notes", From: "sha256:old", ExpectedTo: "sha256:new"}) Expect(err).NotTo(HaveOccurred()) Expect(id).To(Equal("addon-job")) - Expect(u.args).To(Equal([]string{"admin", "notes", "sha256:old", "sha256:new"})) + Expect(u.args).To(Equal([]string{"admin", "notes", "sha256:old", "sha256:new", ""})) + // The operation the upgrade route recorded travels with the item. + _, err = AddonStarter{Upgrader: u}.Start(ctx, "admin", Item{Kind: KindAddon, Name: "notes", From: "sha256:old", ExpectedTo: "sha256:new", + Extra: map[string]string{ExtraOperationID: "op-1"}}) + Expect(err).NotTo(HaveOccurred()) + Expect(u.args).To(Equal([]string{"admin", "notes", "sha256:old", "sha256:new", "op-1"})) _, err = AddonStarter{}.Start(ctx, "admin", Item{Kind: KindAddon, Name: "notes"}) Expect(err).To(HaveOccurred()) }) diff --git a/core/services/upgraderun/jobs.go b/core/services/upgraderun/jobs.go index d665ee222622..23285f2308a3 100644 --- a/core/services/upgraderun/jobs.go +++ b/core/services/upgraderun/jobs.go @@ -334,14 +334,22 @@ func (s LibraryStarter) Start(_ context.Context, _ string, it Item) (string, err // installed digest the run saw to the candidate digest, and returns the job // of /api/operations that runs it. The add-on routes implement it with the // gateway (the upgrade queue of POST /api/addons/{id}/upgrade). +// +// operationID is the operation the owner already recorded for the upgrade +// (the upgrade route records it before it starts a run of one item); empty +// records a new one. type AddonUpgrader interface { - StartAddonUpgrade(ctx context.Context, actor, addonID, expectedDigest, candidateDigest string) (jobID string, err error) + StartAddonUpgrade(ctx context.Context, actor, addonID, expectedDigest, candidateDigest, operationID string) (jobID string, err error) } // Extra keys of an add-on item. Without them From and ExpectedTo are used. const ( ExtraExpectedDigest = "expected_digest" ExtraCandidateDigest = "candidate_digest" + // ExtraOperationID is the operation the upgrade route recorded on the + // owner. It is stored with the item, so the frontend that takes the run + // over runs that record instead of asking for a second one. + ExtraOperationID = "operation_id" ) // AddonStarter upgrades an add-on through an AddonUpgrader. @@ -360,5 +368,5 @@ func (s AddonStarter) Start(ctx context.Context, actor string, it Item) (string, if candidate == "" { candidate = it.ExpectedTo } - return s.Upgrader.StartAddonUpgrade(ctx, actor, it.Name, expected, candidate) + return s.Upgrader.StartAddonUpgrade(ctx, actor, it.Name, expected, candidate, it.Extra[ExtraOperationID]) } diff --git a/core/services/upgraderun/planner.go b/core/services/upgraderun/planner.go index 4781ea60e480..ad9e1eb25412 100644 --- a/core/services/upgraderun/planner.go +++ b/core/services/upgraderun/planner.go @@ -276,6 +276,10 @@ type StartItem struct { // ExpectedTo is the version or digest the caller saw as the target // (PlanItem.ExpectedTo). A start whose target moved since is refused. ExpectedTo string `json:"expected_to"` + // Extra is added to the extra data of the item and stored with it, for + // its job path (the operation an add-on upgrade route recorded, say). + // Never read from a request body. + Extra map[string]string `json:"-"` } // StartRequest asks for a run. @@ -300,6 +304,7 @@ func planStart(cands []Candidate, unchecked map[Kind]bool, req StartRequest) ([] } var chosen []Candidate expected := map[string]string{} + extra := map[string]map[string]string{} for _, si := range req.Items { if !si.Kind.Valid() || si.Name == "" { return nil, refuse(CodeInvalid, Key(si.Kind, si.Name), "unknown item kind or empty name") @@ -322,6 +327,9 @@ func planStart(cands []Candidate, unchecked map[Kind]bool, req StartRequest) ([] return nil, refuse(CodeStale, k, "the update moved to %q since it was shown", c.To) } expected[k] = c.pin() + if len(si.Extra) > 0 { + extra[k] = si.Extra + } chosen = append(chosen, c) } sortCandidates(chosen) @@ -329,7 +337,7 @@ func planStart(cands []Candidate, unchecked map[Kind]bool, req StartRequest) ([] for _, c := range chosen { it := Item{ Key: c.Key(), Kind: c.Kind, Name: c.Name, Title: c.Title, From: c.From, To: c.To, ExpectedTo: expected[c.Key()], - Phase: PhaseQueued, Extra: c.Extra, + Phase: PhaseQueued, Extra: mergeExtra(c.Extra, extra[c.Key()]), } switch skipReason(c) { case ReasonHeld: @@ -341,3 +349,19 @@ func planStart(cands []Candidate, unchecked map[Kind]bool, req StartRequest) ([] } return items, nil } + +// mergeExtra copies the extra data of a candidate and adds the request's; the +// candidate's own map is never changed. +func mergeExtra(cand, req map[string]string) map[string]string { + if len(req) == 0 { + return cand + } + out := make(map[string]string, len(cand)+len(req)) + for k, v := range cand { + out[k] = v + } + for k, v := range req { + out[k] = v + } + return out +} diff --git a/core/services/upgraderun/single_test.go b/core/services/upgraderun/single_test.go index 93b28b69c618..8bbae90733b3 100644 --- a/core/services/upgraderun/single_test.go +++ b/core/services/upgraderun/single_test.go @@ -65,4 +65,21 @@ var _ = Describe("The outcome of a run of one item", func() { Expect(out.State).To(Equal(SinglePending)) Expect(out.RunID).To(Equal(run.ID)) }) + + It("stores the extra data of a start item with the item, beside the candidate's", func() { + h := newHarness(harnessOpts{}) + h.addons.add(Candidate{Kind: KindAddon, Name: "notes", Extra: map[string]string{ExtraCandidateDigest: "sha256:b"}}) + gate := make(chan struct{}) + DeferCleanup(func() { close(gate) }) + h.starter.block(gate) + item := si(KindAddon, "notes") + item.Extra = map[string]string{ExtraOperationID: "op-1"} + run, err := h.svc.Start(context.Background(), "admin", StartRequest{Items: []StartItem{item}}) + Expect(err).NotTo(HaveOccurred()) + _, rows, err := h.store.Get(run.ID) + Expect(err).NotTo(HaveOccurred()) + Expect(rows).To(HaveLen(1)) + Expect(rows[0].Extra).To(ContainSubstring(`"operation_id":"op-1"`)) + Expect(rows[0].Extra).To(ContainSubstring(`"candidate_digest":"sha256:b"`)) + }) }) diff --git a/docs/content/models/upgrade-runs.md b/docs/content/models/upgrade-runs.md index 19e99294b098..21d304444e76 100644 --- a/docs/content/models/upgrade-runs.md +++ b/docs/content/models/upgrade-runs.md @@ -563,7 +563,11 @@ When the wait ends first, the route answers `202` with code `pending`, `run_id` and `run`, and no job: the run goes on and starts the item later. Follow it with `GET /api/updates/runs/{run_id}`. The add-on route answers `202` with the operation status, `run` and `runId` in the payload, and no -`jobId`; the run then runs the operation the route recorded. +`jobId`; the run then runs the operation the route recorded. The run stores +that operation with the item, so a frontend that takes the run over runs the +same record. When the item ends without starting it (cancelled, skipped or +refused), the run drops the record on the owner and the add-on is free for a +new upgrade. A model upgrade with `config_only` or `choices`, and a model retry (`POST /api/models/{name}/upgrade/retry`), are always direct: a run makes no diff --git a/scripts/addons/suites.json b/scripts/addons/suites.json index 7d84fed87c7e..c377a391dae6 100644 --- a/scripts/addons/suites.json +++ b/scripts/addons/suites.json @@ -2396,7 +2396,10 @@ "refuses the cookie without the confirm header", "refuses the cookie on a tool call", "refuses a cookie that is not a configured key", - "refuses the cookie in named-user mode" + "refuses the cookie in named-user mode", + "answers 202 with the run and no job, and the run later runs the caller's recorded operation", + "is the one another frontend runs when it takes the run over", + "is dropped on the owner when the item ends without starting it, so the add-on is free again" ] }, { From 2f6088e8b044efb8a3331e70a5ddb11d370a49d6 Mon Sep 17 00:00:00 2001 From: Ettore Di Giacinto Date: Tue, 24 Nov 2026 15:49:12 +0000 Subject: [PATCH 03/19] fix(gallery): report a failed restore after a cancel as a failure When a user cancelled an upgrade after the swap and the previous build could not be put back, rollbackError returned the cancel joined with the restore error. The operation queue checks for a cancel first, so it reported the operation as cancelled although the backend was left on the failed build. rollbackError now checks the restore error first and returns an upgrade error that carries ErrUpgradeRestore, with the cause kept in the chain. The operation queue reports such an error as a failure. The restore messages name the backend directory by its base name, not by its path. Assisted-by: Claude:claude-opus-5-5 --- core/gallery/start_check.go | 20 +++++----- core/gallery/upgrade_errors.go | 5 +++ core/gallery/upgrade_rollback_test.go | 17 ++++++++ .../backend_upgrade_error_key_test.go | 39 +++++++++++++++++++ core/services/galleryop/backends.go | 5 ++- 5 files changed, 75 insertions(+), 11 deletions(-) diff --git a/core/gallery/start_check.go b/core/gallery/start_check.go index 77992d01f9a8..f21a4c1a2e8e 100644 --- a/core/gallery/start_check.go +++ b/core/gallery/start_check.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "os" + "path/filepath" "github.com/mudler/LocalAI/pkg/model" "github.com/mudler/LocalAI/pkg/system" @@ -91,7 +92,7 @@ func restoreBackup(backendPath, backupPath string) error { if backErr := renameBackend(failedPath, backendPath); backErr != nil { xlog.Error("Could not put the failed build back after a failed restore", "path", backendPath, "error", backErr) } - return fmt.Errorf("restoring the previous build from %s: %w", backupPath, err) + return fmt.Errorf("restoring the previous build from %s: %w", filepath.Base(backupPath), err) } if err := os.RemoveAll(failedPath); err != nil { xlog.Warn("Could not remove the failed build after the restore", "path", failedPath, "error", err) @@ -116,17 +117,18 @@ func rollbackSwap(ctx context.Context, systemState *system.SystemState, modelLoa // rollbackError is the error of a step that failed after the swap. It carries // code, says whether the previous build is back, and keeps the cause. A -// cancelled context keeps its own error (callers read it as a stop), but the -// restore still runs before it is returned. +// restore that failed wins over a cancel: the error carries ErrUpgradeRestore +// with the cause still in the chain, so a caller that reads a cancel first +// does not report the operation as cancelled. A cancel whose restore +// succeeded keeps its own error (callers read it as a stop). The message +// names the backend directory by its base name only. func rollbackError(ctx context.Context, code UpgradeFailureCode, cause, restoreErr error, backendPath string) error { + if restoreErr != nil { + restore := fmt.Errorf("%w (%s): %w", ErrUpgradeRestore, filepath.Base(backendPath), restoreErr) + return &UpgradeError{Code: code, Err: errors.Join(cause, restore)} + } if ctx.Err() != nil && errors.Is(cause, ctx.Err()) { - if restoreErr != nil { - return errors.Join(cause, restoreErr) - } return cause } - if restoreErr != nil { - return &UpgradeError{Code: code, Err: fmt.Errorf("%w; the previous build of %s could not be restored: %v", cause, backendPath, restoreErr)} - } return &UpgradeError{Code: code, RolledBack: true, Err: fmt.Errorf("%w; the previous build was restored", cause)} } diff --git a/core/gallery/upgrade_errors.go b/core/gallery/upgrade_errors.go index d09d0277dfef..2b7b9f3a05a3 100644 --- a/core/gallery/upgrade_errors.go +++ b/core/gallery/upgrade_errors.go @@ -75,6 +75,11 @@ var ( ErrUpgradeStale = &UpgradeError{Code: UpgradeFailureStale} ) +// ErrUpgradeRestore marks a failed upgrade whose previous build could not be +// put back. It wins over a cancel: the backend is not at the version it ran +// before, so the operation failed whatever stopped it. +var ErrUpgradeRestore = errors.New("the previous build could not be restored") + // WithUpgradeCode tags err with a code. An error that already carries a code // keeps it (the inner step knows best), and nil stays nil. func WithUpgradeCode(code UpgradeFailureCode, err error) error { diff --git a/core/gallery/upgrade_rollback_test.go b/core/gallery/upgrade_rollback_test.go index f699aeceac31..d4b0c2a62282 100644 --- a/core/gallery/upgrade_rollback_test.go +++ b/core/gallery/upgrade_rollback_test.go @@ -240,11 +240,28 @@ var _ = Describe("Rollback of a backend upgrade whose new build fails", func() { Expect(UpgradeCodeOf(err)).To(Equal(UpgradeFailureStart)) Expect(UpgradeRolledBack(err)).To(BeFalse()) Expect(err.Error()).To(ContainSubstring("could not be restored")) + Expect(errors.Is(err, ErrUpgradeRestore)).To(BeTrue()) + Expect(err.Error()).NotTo(ContainSubstring(backends), "the message names no server path") Expect(filepath.Join(backends, name+".backup", "version")).To(BeAnExistingFile(), "the previous build is kept") Expect(installedVersion()).To(Equal("v2"), "the failed build stays in place for diagnosis") expectNoProcess() }) + It("reports a restore that failed after a cancel as a failure, and keeps the cancel in the chain", func() { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + err := rollbackError(ctx, UpgradeFailureStart, ctx.Err(), errors.New("rename refused"), filepath.Join(backends, name)) + Expect(errors.Is(err, ErrUpgradeRestore)).To(BeTrue()) + Expect(errors.Is(err, context.Canceled)).To(BeTrue(), "the cancel stays in the chain") + Expect(UpgradeCodeOf(err)).To(Equal(UpgradeFailureStart)) + Expect(UpgradeRolledBack(err)).To(BeFalse()) + Expect(err.Error()).To(ContainSubstring("rename refused")) + Expect(err.Error()).NotTo(ContainSubstring(backends)) + + // A cancel whose restore succeeded is still the plain cancel. + Expect(rollbackError(ctx, UpgradeFailureStart, ctx.Err(), nil, filepath.Join(backends, name))).To(MatchError(context.Canceled)) + }) + It("does not list the directories of a swap as backends", func() { for _, suffix := range []string{".backup", ".upgrade-tmp", ".install-tmp", ".install-backup", ".failed"} { side := filepath.Join(backends, name+suffix) diff --git a/core/services/galleryop/backend_upgrade_error_key_test.go b/core/services/galleryop/backend_upgrade_error_key_test.go index 78c1fea48cc6..19dc3801ca1d 100644 --- a/core/services/galleryop/backend_upgrade_error_key_test.go +++ b/core/services/galleryop/backend_upgrade_error_key_test.go @@ -31,6 +31,19 @@ func (m scriptedUpgradeManager) InstallBackend(context.Context, *galleryop.Manag return m.err } +// cancellingUpgradeManager cancels the operation, as a user does while the +// upgrade rolls back, and returns err. +type cancellingUpgradeManager struct { + blockingBackendManager + cancel context.CancelFunc + err error +} + +func (m cancellingUpgradeManager) UpgradeBackend(context.Context, *galleryop.ManagementOp[gallery.GalleryBackend, any], galleryop.ProgressCallback) error { + m.cancel() + return m.err +} + var _ = Describe("backend upgrade error key", func() { runWith := func(manager scriptedUpgradeManager, upgrade bool) *galleryop.OpStatus { dir, err := os.MkdirTemp("", "error-key-backends-*") @@ -70,6 +83,32 @@ var _ = Describe("backend upgrade error key", func() { Expect(st.Error).To(MatchError("raw failure")) }) + It("reports a failed restore after a cancel as a failure, not as cancelled", func() { + dir, err := os.MkdirTemp("", "error-key-backends-*") + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(func() { Expect(os.RemoveAll(dir)).To(Succeed()) }) + systemState, err := system.GetSystemState(system.WithBackendPath(dir)) + Expect(err).NotTo(HaveOccurred()) + opCtx, opCancel := context.WithCancel(context.Background()) + DeferCleanup(opCancel) + svc := galleryop.NewGalleryService(&config.ApplicationConfig{SystemState: systemState}, nil) + svc.SetBackendManager(cancellingUpgradeManager{cancel: opCancel, + err: &gallery.UpgradeError{Code: gallery.UpgradeFailureStart, Err: errors.Join(context.Canceled, gallery.ErrUpgradeRestore)}}) + ctx, cancel := context.WithCancel(context.Background()) + DeferCleanup(cancel) + Expect(svc.Start(ctx, nil, systemState)).To(Succeed()) + svc.EnqueueBackendOp(galleryop.ManagementOp[gallery.GalleryBackend, any]{ID: "op", GalleryElementName: "b", Upgrade: true, Context: opCtx}) + Eventually(func() bool { + st := svc.GetStatus("op") + return st != nil && st.Processed + }, "5s", "20ms").Should(BeTrue()) + st := svc.GetStatus("op") + Expect(st.Cancelled).To(BeFalse()) + Expect(st.Error).To(HaveOccurred()) + Expect(errors.Is(st.Error, gallery.ErrUpgradeRestore)).To(BeTrue()) + Expect(st.ErrorKey).To(Equal(string(gallery.UpgradeFailureStart))) + }) + It("leaves the key empty for a failed install", func() { st := runWith(scriptedUpgradeManager{err: errors.New("raw failure")}, false) Expect(st.ErrorKey).To(BeEmpty()) diff --git a/core/services/galleryop/backends.go b/core/services/galleryop/backends.go index 874cf0b594f0..17422d2d818f 100644 --- a/core/services/galleryop/backends.go +++ b/core/services/galleryop/backends.go @@ -102,8 +102,9 @@ func (g *GalleryService) backendHandler(op *ManagementOp[gallery.GalleryBackend, } if err != nil { legacyCoalescer.Close() - // Check if error is due to cancellation - if op.Context != nil && errors.Is(err, op.Context.Err()) { + // Check if error is due to cancellation. A restore that failed + // after the cancel is a failure: the previous build is not back. + if op.Context != nil && errors.Is(err, op.Context.Err()) && !errors.Is(err, gallery.ErrUpgradeRestore) { g.UpdateStatus(op.ID, &OpStatus{ Cancelled: true, Processed: true, From 1f5fc01ec7c42c430a3e74c8a4db5f0a73fe93ac Mon Sep 17 00:00:00 2001 From: Ettore Di Giacinto Date: Tue, 24 Nov 2026 15:51:01 +0000 Subject: [PATCH 04/19] fix(gallery): never delete a previous build that a failed restore kept A failed restore and the leftover sweep at start keep the backup directory of a swap on purpose: it can be the last build that worked. The next install or upgrade then deleted it without a check before it started its own swap. Install and upgrade now move a previous build they find at the backup path to ".kept-