From 63995ea9a0769f2a70d18995cfd174f7af7a4265 Mon Sep 17 00:00:00 2001 From: Marcin Wisniewski <78590652+itsNotMyUsername@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:15:19 +0100 Subject: [PATCH 1/4] fix(serverless): say why a deploy --wait rollout failed when a worker could not start A rollout can fail after a ready build, for example when a worker cannot prepare a Shared Volume. The builds then hold no error, and by the time the app reads failed the API has stopped the worker and replaced its reason, so --wait printed only a hint to inspect the builds, or a bare timeout. --wait now reads the app's live workers on each poll, prints a line when a worker turns unhealthy or waits for disk, and names the last such worker and its reason when the app fails or the wait times out. Co-Authored-By: Claude Opus 5.5 --- internal/cmd/serverless/apps_lifecycle.go | 2 +- internal/cmd/serverless/apps_versions.go | 2 +- internal/cmd/serverless/deploy.go | 18 ++- internal/cmd/serverless/deploy_test.go | 10 +- internal/cmd/serverless/deploy_workers.go | 77 +++++++++ .../cmd/serverless/deploy_workers_test.go | 150 ++++++++++++++++++ 6 files changed, 250 insertions(+), 9 deletions(-) create mode 100644 internal/cmd/serverless/deploy_workers.go create mode 100644 internal/cmd/serverless/deploy_workers_test.go diff --git a/internal/cmd/serverless/apps_lifecycle.go b/internal/cmd/serverless/apps_lifecycle.go index 33b57153..5df8fa85 100644 --- a/internal/cmd/serverless/apps_lifecycle.go +++ b/internal/cmd/serverless/apps_lifecycle.go @@ -157,7 +157,7 @@ func runLifecycle(cmd *cobra.Command, logger *log.Logger, id, verb string, actio if !wait.Wait { return nil } - return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd)) + return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd), "") } func addDeleteConfirmFlags(cmd *cobra.Command, yes, force *bool) { diff --git a/internal/cmd/serverless/apps_versions.go b/internal/cmd/serverless/apps_versions.go index 0bf4d16e..678dff25 100644 --- a/internal/cmd/serverless/apps_versions.go +++ b/internal/cmd/serverless/apps_versions.go @@ -181,7 +181,7 @@ app that is deleting is 409.`, if _, skip := activateWaitNote(app.Status); skip { return nil } - return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd)) + return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd), "") }, } addAppWaitFlags(cmd, &wait, &timeout, &pollInterval) diff --git a/internal/cmd/serverless/deploy.go b/internal/cmd/serverless/deploy.go index 902c2898..d419c877 100644 --- a/internal/cmd/serverless/deploy.go +++ b/internal/cmd/serverless/deploy.go @@ -573,9 +573,13 @@ paths and an invoke example once the application is active.`, // command says what is left instead of waiting on it. rolloutNote, rollsLater := activateWaitNote(app.Status) waitOnApp := wait && (!sourceless || !rollsLater) + watch := &workerWatch{client: client, appID: appID} if waitOnApp && !serverlessapi.AppDeployTerminal(app.Status) { var lastStatus string app, err = waitForAppDeploy(waitCtx, client, appID, pollInterval, func(appStatus, buildStatus string) { + if trouble, changed := watch.observe(waitCtx); changed { + _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Application %s: %s\n", appID, trouble) + } msg := deployWaitMessage(appID, appStatus, buildStatus) if msg == lastStatus { return @@ -586,6 +590,9 @@ paths and an invoke example once the application is active.`, }) if err != nil { spin.Stop() + if cause := watch.cause(); cause != "" && waitCtx.Err() == context.DeadlineExceeded { + return fmt.Errorf("%w; last seen: %s", waitTimeoutErr(waitCtx, err, "application "+appID, timeout), cause) + } return waitTimeoutErr(waitCtx, err, "application "+appID, timeout) } } @@ -625,7 +632,7 @@ paths and an invoke example once the application is active.`, if !waitOnApp { return nil } - return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd)) + return appFailedErr(cmd.Context(), client, app, defaultEnvironment(cmd), watch.cause()) }, } @@ -1122,7 +1129,10 @@ func latestBuildStatus(ctx context.Context, client *serverlessapi.Client, appID return string(page.Data[0].Status) } -func appFailedErr(ctx context.Context, client *serverlessapi.Client, app *serverlessapi.App, defaultEnvironment string) error { +// appFailedErr is the error for an app a wait left in a status other than +// active. workerCause, when the wait saw one, is a worker that could not start: +// after a ready build it says why the rollout failed, where the builds do not. +func appFailedErr(ctx context.Context, client *serverlessapi.Client, app *serverlessapi.App, defaultEnvironment, workerCause string) error { if app == nil { return nil } @@ -1133,6 +1143,10 @@ func appFailedErr(ctx context.Context, client *serverlessapi.Client, app *server if msg := latestBuildError(ctx, client, app.AppId); msg != "" { return fmt.Errorf("application %s failed: %s", app.AppId, msg) } + if workerCause != "" { + return fmt.Errorf("application %s failed: %s; inspect workers with '%s'", app.AppId, workerCause, + appCommand(app, defaultEnvironment, "apps", "workers", app.AppId, "--version", "all")) + } return fmt.Errorf("application %s failed; inspect builds with '%s'", app.AppId, appCommand(app, defaultEnvironment, "apps", "builds", "list", app.AppId)) default: return fmt.Errorf("application %s ended in status %s", app.AppId, app.Status) diff --git a/internal/cmd/serverless/deploy_test.go b/internal/cmd/serverless/deploy_test.go index 8f0e144e..eb7378bc 100644 --- a/internal/cmd/serverless/deploy_test.go +++ b/internal/cmd/serverless/deploy_test.go @@ -1083,7 +1083,7 @@ func TestWaitForAppDeploy_ContinuesWhenBuildsFail(t *testing.T) { } func TestAppFailedErr(t *testing.T) { - if err := appFailedErr(context.Background(), nil, nil, ""); err != nil { + if err := appFailedErr(context.Background(), nil, nil, "", ""); err != nil { t.Fatalf("nil app: %v", err) } @@ -1091,7 +1091,7 @@ func TestAppFailedErr(t *testing.T) { AppId: testAppID, Status: serverlessapi.AppStatusActive, } - if err := appFailedErr(context.Background(), nil, active, ""); err != nil { + if err := appFailedErr(context.Background(), nil, active, "", ""); err != nil { t.Fatalf("active: %v", err) } @@ -1099,7 +1099,7 @@ func TestAppFailedErr(t *testing.T) { AppId: testAppID, Status: serverlessapi.AppStatusStopped, } - err := appFailedErr(context.Background(), nil, stopped, "") + err := appFailedErr(context.Background(), nil, stopped, "", "") if err == nil || !strings.Contains(err.Error(), "stopped") { t.Fatalf("stopped: %v", err) } @@ -1118,7 +1118,7 @@ func TestAppFailedErr(t *testing.T) { AppId: testAppID, Status: serverlessapi.AppStatusFailed, } - err = appFailedErr(context.Background(), client, failed, "") + err = appFailedErr(context.Background(), client, failed, "", "") if err == nil || !strings.Contains(err.Error(), "pip install failed") { t.Fatalf("failed with build error: %v", err) } @@ -1163,7 +1163,7 @@ func TestAppFailedErr_BuildsHintAddressesTheSameCopy(t *testing.T) { Status: serverlessapi.AppStatusFailed, } - err := appFailedErr(context.Background(), serverlessapi.NewClient("test-key", empty.URL, slog.Default()), failed, tc.defaultEnvironment) + err := appFailedErr(context.Background(), serverlessapi.NewClient("test-key", empty.URL, slog.Default()), failed, tc.defaultEnvironment, "") if err == nil || !strings.Contains(err.Error(), tc.wantHint) { t.Fatalf("err = %v, want it to contain %q", err, tc.wantHint) diff --git a/internal/cmd/serverless/deploy_workers.go b/internal/cmd/serverless/deploy_workers.go new file mode 100644 index 00000000..8e3cc946 --- /dev/null +++ b/internal/cmd/serverless/deploy_workers.go @@ -0,0 +1,77 @@ +package serverless + +import ( + "context" + "fmt" + + serverlessapi "github.com/runware/runware-cli/internal/api/serverless" +) + +const ( + workerStatusUnhealthy = "unhealthy" + // reasonVolumeDiskShort is a worker waiting for disk for its Shared Volumes' + // files. It is `pulling` while the wait may still end, so it is trouble + // before the worker turns unhealthy. + reasonVolumeDiskShort = "volume-disk-short" +) + +// workerTrouble is a worker that cannot start, with the reason the API gives, +// such as a Shared Volume the worker failed to prepare (`fetch-failed`, +// `deadline-exceeded`) or an app container that keeps exiting. +type workerTrouble struct { + id, status, reason string +} + +func (t workerTrouble) String() string { + if t.reason == "" { + return fmt.Sprintf("worker %s is %s", t.id, t.status) + } + return fmt.Sprintf("worker %s is %s: %s", t.id, t.status, t.reason) +} + +// workerWatch remembers the latest worker a deploy wait saw in trouble. The +// reason only exists while the worker does: once a rollout gives up, the API +// stops its workers and their reason becomes the stop, so the wait has to read +// it on the way. +type workerWatch struct { + client *serverlessapi.Client + appID string + last *workerTrouble +} + +// observe reads the app's live workers and returns the trouble it found when it +// differs from the last one. A worker in trouble stays the answer after it +// stops, and an unreadable list changes nothing: neither fails the wait. +func (w *workerWatch) observe(ctx context.Context) (workerTrouble, bool) { + all := "all" + live := serverlessapi.WorkerStateFilterLive + page, err := w.client.ListWorkers(ctx, w.appID, serverlessapi.ListWorkersParams{VersionId: &all, State: &live}) + if err != nil { + return workerTrouble{}, false + } + for i := range page.Data { + wk := &page.Data[i] + reason := "" + if wk.StatusReason != nil { + reason = *wk.StatusReason + } + if string(wk.Status) != workerStatusUnhealthy && reason != reasonVolumeDiskShort { + continue + } + t := workerTrouble{id: wk.Id.String(), status: string(wk.Status), reason: reason} + if w.last != nil && *w.last == t { + return t, false + } + w.last = &t + return t, true + } + return workerTrouble{}, false +} + +// cause is the last trouble seen, or "" when the wait saw none. +func (w *workerWatch) cause() string { + if w == nil || w.last == nil { + return "" + } + return w.last.String() +} diff --git a/internal/cmd/serverless/deploy_workers_test.go b/internal/cmd/serverless/deploy_workers_test.go new file mode 100644 index 00000000..490751da --- /dev/null +++ b/internal/cmd/serverless/deploy_workers_test.go @@ -0,0 +1,150 @@ +package serverless + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/charmbracelet/log" + + serverlessapi "github.com/runware/runware-cli/internal/api/serverless" +) + +const testWorkerID = "2ab2c491-26d6-40c1-a70e-f13b11de1eea" + +// rolloutStub is a create whose build is ready and whose rollout the API ends +// with appStatus after initializingReads reads. While it rolls, the workers +// list answers worker; after it, the list is empty, as when the API has +// stopped the worker and a live list drops it. +type rolloutStub struct { + t *testing.T + initializingReads int + appStatus string + worker string + + mu sync.Mutex + reads int +} + +func (s *rolloutStub) serve() { + s.t.Helper() + upload := newSourceUploadStub(s.t) + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if upload(w, r) { + return + } + appPath := testAppsPath + "/" + testAppID + w.Header().Set("Content-Type", "application/json") + s.mu.Lock() + defer s.mu.Unlock() + switch { + case r.Method == http.MethodGet && r.URL.Path == appPath && s.reads == 0: + s.reads++ + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, `{"type":"about:blank","title":"Not Found","status":404}`) + case r.Method == http.MethodPost && r.URL.Path == testAppsPath: + w.WriteHeader(http.StatusCreated) + _, _ = io.WriteString(w, s.app("initializing")) + case r.Method == http.MethodGet && r.URL.Path == appPath: + s.reads++ + if s.reads > s.initializingReads+1 { + _, _ = io.WriteString(w, s.app(s.appStatus)) + return + } + _, _ = io.WriteString(w, s.app("initializing")) + case r.Method == http.MethodGet && r.URL.Path == appPath+"/builds": + _, _ = io.WriteString(w, `{"data":[{"id":"33333333-3333-3333-3333-333333333333","status":"ready","createdAt":"2026-07-30T12:00:00Z"}]}`) + case r.Method == http.MethodGet && r.URL.Path == appPath+"/workers": + if got := r.URL.Query(); got.Get("versionId") != "all" || got.Get("state") != "live" { + s.t.Errorf("workers query = %v, want versionId=all and state=live", got) + } + if s.worker == "" || s.reads > s.initializingReads+1 { + _, _ = io.WriteString(w, `{"data":[],"summary":{"total":0}}`) + return + } + _, _ = io.WriteString(w, `{"data":[`+s.worker+`],"summary":{"total":1}}`) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/environments/"): + _, _ = io.WriteString(w, `{"name":"production"}`) + default: + s.t.Errorf("unexpected %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + s.t.Cleanup(api.Close) + s.t.Setenv("RUNWARE_API_KEY", "test-key") + s.t.Setenv("RUNWARE_SERVERLESS_BASE_URL", api.URL) +} + +func (s *rolloutStub) app(status string) string { + return strings.Replace(activeAppBody(""), `"status":"active"`, `"status":"`+status+`"`, 1) +} + +func workerBody(status, reason string) string { + return `{"id":"` + testWorkerID + `","appId":"` + testAppID + `","versionId":"` + newVersionID + `","status":"` + status + + `","statusReason":"` + reason + `","gpuCount":1,"createdAt":"2026-07-30T12:00:00Z","updatedAt":"2026-07-30T12:00:00Z"}` +} + +func runWaitedDeploy(t *testing.T, extra ...string) (stderr string, err error) { + t.Helper() + cmd := newDeployCmd(log.New(io.Discard)) + var buf bytes.Buffer + cmd.SetErr(&buf) + cmd.PersistentFlags().String("format", testTableFormat, "") + cmd.SetArgs(append(sourceArgs(t, testGPUTypeFlag, testGPUType, "--wait", "--poll-interval", "1ms"), extra...)) + _, err = captureStdout(t, cmd.Execute) + return buf.String(), err +} + +// A rollout that fails on a worker's Volume preparation says why: the builds +// hold no error, and by the end the API has stopped the worker, so the reason +// is the one --wait read while the worker was unhealthy. +func TestDeployWaitReportsTheWorkerReasonOfAFailedRollout(t *testing.T) { + stub := &rolloutStub{t: t, initializingReads: 3, appStatus: string(serverlessapi.AppStatusFailed), worker: workerBody("unhealthy", "fetch-failed")} + stub.serve() + + stderr, err := runWaitedDeploy(t) + want := "worker " + testWorkerID + " is unhealthy: fetch-failed" + if err == nil || !strings.Contains(err.Error(), "failed: "+want) { + t.Fatalf("err = %v, want the worker's reason", err) + } + if !strings.Contains(err.Error(), "apps workers "+testAppID+" --version all") { + t.Fatalf("err = %v, want the workers command", err) + } + // The wait reads the same trouble on several polls and prints it once. + if line := "Application " + testAppID + ": " + want + "\n"; strings.Count(stderr, line) != 1 { + t.Fatalf("stderr = %q, want %q once", stderr, line) + } +} + +// A worker waiting for disk is pulling, not unhealthy, while the wait may still +// end; a --wait that runs out first names it. +func TestDeployWaitTimeoutNamesAWorkerShortOfDisk(t *testing.T) { + stub := &rolloutStub{t: t, initializingReads: 1 << 30, appStatus: string(serverlessapi.AppStatusFailed), worker: workerBody("pulling", "volume-disk-short")} + stub.serve() + + _, err := runWaitedDeploy(t, "--timeout", "300ms") + if err == nil || !strings.Contains(err.Error(), "timed out waiting for application "+testAppID) || + !strings.Contains(err.Error(), "last seen: worker "+testWorkerID+" is pulling: volume-disk-short") { + t.Fatalf("err = %v, want the timeout and the worker short of disk", err) + } +} + +// Without a worker in trouble a failed rollout keeps pointing at the builds, +// and a preparing worker is not trouble. +func TestDeployWaitWithoutWorkerTroubleKeepsTheBuildsHint(t *testing.T) { + stub := &rolloutStub{t: t, initializingReads: 2, appStatus: string(serverlessapi.AppStatusFailed), worker: workerBody("pulling", "volume-preparing")} + stub.serve() + + stderr, err := runWaitedDeploy(t) + if err == nil || !strings.Contains(err.Error(), "inspect builds with") || strings.Contains(err.Error(), "worker") { + t.Fatalf("err = %v, want the builds hint only", err) + } + if strings.Contains(stderr, "volume-preparing") { + t.Fatalf("stderr = %q, want no worker line for a preparing worker", stderr) + } +} From 75b1655bd932716fc1b816bc019573b0ed6fc652 Mon Sep 17 00:00:00 2001 From: Marcin Wisniewski <78590652+itsNotMyUsername@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:17:40 +0100 Subject: [PATCH 2/4] fix(serverless): blame the newest troubled worker and forget one that recovered Of several workers in trouble the deploy wait now names the newest, which during an update is one of the version rolling out, and it forgets the trouble once live workers are listed and none is in trouble, so a worker that recovered is not blamed for a later failure. An empty list keeps it: that is the worker the API stopped. The list reads pages of 100. Co-Authored-By: Claude Opus 5.5 --- internal/cmd/serverless/deploy_workers.go | 49 ++++++++++----- .../cmd/serverless/deploy_workers_test.go | 60 ++++++++++++++++++- 2 files changed, 91 insertions(+), 18 deletions(-) diff --git a/internal/cmd/serverless/deploy_workers.go b/internal/cmd/serverless/deploy_workers.go index 8e3cc946..ec01f936 100644 --- a/internal/cmd/serverless/deploy_workers.go +++ b/internal/cmd/serverless/deploy_workers.go @@ -39,33 +39,52 @@ type workerWatch struct { last *workerTrouble } +// workersPageLimit is the most workers a list page holds. One page covers an +// app's live workers unless it runs more than that; the watch is best effort. +const workersPageLimit serverlessapi.Limit = 100 + // observe reads the app's live workers and returns the trouble it found when it -// differs from the last one. A worker in trouble stays the answer after it -// stops, and an unreadable list changes nothing: neither fails the wait. +// differs from the last one. Of several workers in trouble it takes the newest, +// which during an update is one of the version being rolled out. Once live +// workers are listed and none is in trouble, the last trouble is forgotten, so a +// worker that recovered is not blamed later. An empty list keeps it: that is the +// API having stopped the worker, whose reason is then the stop. An unreadable +// list changes nothing and never fails the wait. func (w *workerWatch) observe(ctx context.Context) (workerTrouble, bool) { all := "all" live := serverlessapi.WorkerStateFilterLive - page, err := w.client.ListWorkers(ctx, w.appID, serverlessapi.ListWorkersParams{VersionId: &all, State: &live}) - if err != nil { + limit := workersPageLimit + page, err := w.client.ListWorkers(ctx, w.appID, serverlessapi.ListWorkersParams{VersionId: &all, State: &live, Limit: &limit}) + if err != nil || len(page.Data) == 0 { return workerTrouble{}, false } + var newest *serverlessapi.Worker for i := range page.Data { wk := &page.Data[i] - reason := "" - if wk.StatusReason != nil { - reason = *wk.StatusReason - } - if string(wk.Status) != workerStatusUnhealthy && reason != reasonVolumeDiskShort { + if string(wk.Status) != workerStatusUnhealthy && workerReason(wk) != reasonVolumeDiskShort { continue } - t := workerTrouble{id: wk.Id.String(), status: string(wk.Status), reason: reason} - if w.last != nil && *w.last == t { - return t, false + if newest == nil || wk.CreatedAt.After(newest.CreatedAt) { + newest = wk } - w.last = &t - return t, true } - return workerTrouble{}, false + if newest == nil { + w.last = nil + return workerTrouble{}, false + } + t := workerTrouble{id: newest.Id.String(), status: string(newest.Status), reason: workerReason(newest)} + if w.last != nil && *w.last == t { + return t, false + } + w.last = &t + return t, true +} + +func workerReason(wk *serverlessapi.Worker) string { + if wk.StatusReason == nil { + return "" + } + return *wk.StatusReason } // cause is the last trouble seen, or "" when the wait saw none. diff --git a/internal/cmd/serverless/deploy_workers_test.go b/internal/cmd/serverless/deploy_workers_test.go index 490751da..229ce6b3 100644 --- a/internal/cmd/serverless/deploy_workers_test.go +++ b/internal/cmd/serverless/deploy_workers_test.go @@ -2,7 +2,9 @@ package serverless import ( "bytes" + "context" "io" + "log/slog" "net/http" "net/http/httptest" "strings" @@ -85,8 +87,60 @@ func (s *rolloutStub) app(status string) string { } func workerBody(status, reason string) string { - return `{"id":"` + testWorkerID + `","appId":"` + testAppID + `","versionId":"` + newVersionID + `","status":"` + status + - `","statusReason":"` + reason + `","gpuCount":1,"createdAt":"2026-07-30T12:00:00Z","updatedAt":"2026-07-30T12:00:00Z"}` + return workerBodyAt(testWorkerID, status, reason, "2026-07-30T12:00:00Z") +} + +func workerBodyAt(id, status, reason, createdAt string) string { + return `{"id":"` + id + `","appId":"` + testAppID + `","versionId":"` + newVersionID + `","status":"` + status + + `","statusReason":"` + reason + `","gpuCount":1,"createdAt":"` + createdAt + `","updatedAt":"` + createdAt + `"}` +} + +// watchPolls runs observe once per workers list body and returns the cause +// after each. +func watchPolls(t *testing.T, lists ...string) []string { + t.Helper() + var n int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.Query().Get("limit"); got != "100" { + t.Errorf("limit = %q, want 100", got) + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"data":[`+lists[n]+`],"summary":{"total":0}}`) + n++ + })) + t.Cleanup(srv.Close) + watch := &workerWatch{client: serverlessapi.NewClient("test-key", srv.URL, slog.Default()), appID: testAppID} + causes := make([]string, 0, len(lists)) + for range lists { + watch.observe(context.Background()) + causes = append(causes, watch.cause()) + } + return causes +} + +const testOlderWorkerID = "11111111-26d6-40c1-a70e-f13b11de1eea" + +// Of two workers in trouble the newest is the cause: during an update an older +// one can be the outgoing version's. +func TestWorkerWatchTakesTheNewestWorkerInTrouble(t *testing.T) { + causes := watchPolls(t, workerBodyAt(testOlderWorkerID, "unhealthy", "init-container-failed", "2026-07-30T11:00:00Z")+","+ + workerBodyAt(testWorkerID, "unhealthy", "fetch-failed", "2026-07-30T12:00:00Z")) + if want := "worker " + testWorkerID + " is unhealthy: fetch-failed"; causes[0] != want { + t.Fatalf("cause = %q, want %q", causes[0], want) + } +} + +// A worker that recovers is not blamed later; an empty list, the API having +// stopped the worker, keeps the cause. +func TestWorkerWatchForgetsARecoveredWorkerButNotAStoppedOne(t *testing.T) { + causes := watchPolls(t, workerBody("unhealthy", "fetch-failed"), workerBody("ready", ""), "") + if causes[0] == "" || causes[1] != "" || causes[2] != "" { + t.Fatalf("causes = %q, want trouble, then none after the recovery", causes) + } + causes = watchPolls(t, workerBody("unhealthy", "fetch-failed"), "") + if causes[1] != causes[0] || causes[1] == "" { + t.Fatalf("causes = %q, want the trouble kept once the list is empty", causes) + } } func runWaitedDeploy(t *testing.T, extra ...string) (stderr string, err error) { @@ -127,7 +181,7 @@ func TestDeployWaitTimeoutNamesAWorkerShortOfDisk(t *testing.T) { stub := &rolloutStub{t: t, initializingReads: 1 << 30, appStatus: string(serverlessapi.AppStatusFailed), worker: workerBody("pulling", "volume-disk-short")} stub.serve() - _, err := runWaitedDeploy(t, "--timeout", "300ms") + _, err := runWaitedDeploy(t, "--timeout", "1s") if err == nil || !strings.Contains(err.Error(), "timed out waiting for application "+testAppID) || !strings.Contains(err.Error(), "last seen: worker "+testWorkerID+" is pulling: volume-disk-short") { t.Fatalf("err = %v, want the timeout and the worker short of disk", err) From f48f400ac1aebc42e80040940802caff00f3763a Mon Sep 17 00:00:00 2001 From: Marcin Wisniewski <78590652+itsNotMyUsername@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:38:11 +0100 Subject: [PATCH 3/4] fix(serverless): name a failed start before a disk wait, and keep the cause while the worker stops The deploy wait now names an unhealthy worker before one still waiting for disk, which the rollout keeps waiting on, and the newest only among equals. It forgets a cause only when that same worker is seen serving again: a worker the API is stopping after the rollout failed reads stop-requested, and that poll erased the reason the failed-app error should name. Co-Authored-By: Claude Opus 5.5 --- internal/cmd/serverless/deploy_workers.go | 56 ++++++++++++++----- .../cmd/serverless/deploy_workers_test.go | 24 +++++++- 2 files changed, 63 insertions(+), 17 deletions(-) diff --git a/internal/cmd/serverless/deploy_workers.go b/internal/cmd/serverless/deploy_workers.go index ec01f936..f87b8ad4 100644 --- a/internal/cmd/serverless/deploy_workers.go +++ b/internal/cmd/serverless/deploy_workers.go @@ -9,9 +9,12 @@ import ( const ( workerStatusUnhealthy = "unhealthy" + workerStatusReady = "ready" + workerStatusBusy = "busy" // reasonVolumeDiskShort is a worker waiting for disk for its Shared Volumes' // files. It is `pulling` while the wait may still end, so it is trouble - // before the worker turns unhealthy. + // before the worker turns unhealthy. The published spec does not list + // statusReason values yet; this is the API's value for that wait. reasonVolumeDiskShort = "volume-disk-short" ) @@ -44,35 +47,41 @@ type workerWatch struct { const workersPageLimit serverlessapi.Limit = 100 // observe reads the app's live workers and returns the trouble it found when it -// differs from the last one. Of several workers in trouble it takes the newest, -// which during an update is one of the version being rolled out. Once live -// workers are listed and none is in trouble, the last trouble is forgotten, so a -// worker that recovered is not blamed later. An empty list keeps it: that is the -// API having stopped the worker, whose reason is then the stop. An unreadable -// list changes nothing and never fails the wait. +// differs from the last one. An unhealthy worker is the cause before one still +// waiting for disk, since the rollout keeps waiting on the latter; among equals +// the newest wins, which during an update is one of the version rolling out. +// +// A cause is forgotten only when that same worker is seen serving again, so a +// worker that recovered is not blamed later. A worker that is stopping or gone +// keeps it: that is the API stopping the worker after the rollout failed, when +// its reason becomes the stop. An unreadable list changes nothing and never +// fails the wait. func (w *workerWatch) observe(ctx context.Context) (workerTrouble, bool) { all := "all" live := serverlessapi.WorkerStateFilterLive limit := workersPageLimit page, err := w.client.ListWorkers(ctx, w.appID, serverlessapi.ListWorkersParams{VersionId: &all, State: &live, Limit: &limit}) - if err != nil || len(page.Data) == 0 { + if err != nil { return workerTrouble{}, false } - var newest *serverlessapi.Worker + var cause *serverlessapi.Worker for i := range page.Data { wk := &page.Data[i] - if string(wk.Status) != workerStatusUnhealthy && workerReason(wk) != reasonVolumeDiskShort { + rank := troubleRank(wk) + if rank == 0 { + if w.last != nil && wk.Id.String() == w.last.id && isServing(wk) { + w.last = nil + } continue } - if newest == nil || wk.CreatedAt.After(newest.CreatedAt) { - newest = wk + if cause == nil || rank > troubleRank(cause) || (rank == troubleRank(cause) && wk.CreatedAt.After(cause.CreatedAt)) { + cause = wk } } - if newest == nil { - w.last = nil + if cause == nil { return workerTrouble{}, false } - t := workerTrouble{id: newest.Id.String(), status: string(newest.Status), reason: workerReason(newest)} + t := workerTrouble{id: cause.Id.String(), status: string(cause.Status), reason: workerReason(cause)} if w.last != nil && *w.last == t { return t, false } @@ -80,6 +89,23 @@ func (w *workerWatch) observe(ctx context.Context) (workerTrouble, bool) { return t, true } +// troubleRank orders the trouble a worker is in: 2 for a failed start, 1 for a +// wait for disk, 0 for none. +func troubleRank(wk *serverlessapi.Worker) int { + switch { + case string(wk.Status) == workerStatusUnhealthy: + return 2 + case workerReason(wk) == reasonVolumeDiskShort: + return 1 + default: + return 0 + } +} + +func isServing(wk *serverlessapi.Worker) bool { + return string(wk.Status) == workerStatusReady || string(wk.Status) == workerStatusBusy +} + func workerReason(wk *serverlessapi.Worker) string { if wk.StatusReason == nil { return "" diff --git a/internal/cmd/serverless/deploy_workers_test.go b/internal/cmd/serverless/deploy_workers_test.go index 229ce6b3..5c959908 100644 --- a/internal/cmd/serverless/deploy_workers_test.go +++ b/internal/cmd/serverless/deploy_workers_test.go @@ -120,8 +120,28 @@ func watchPolls(t *testing.T, lists ...string) []string { const testOlderWorkerID = "11111111-26d6-40c1-a70e-f13b11de1eea" -// Of two workers in trouble the newest is the cause: during an update an older -// one can be the outgoing version's. +// A failed start is the cause before a newer worker still waiting for disk, +// which the rollout keeps waiting on. +func TestWorkerWatchPrefersAnUnhealthyWorkerToOneShortOfDisk(t *testing.T) { + causes := watchPolls(t, workerBodyAt(testOlderWorkerID, "unhealthy", "fetch-failed", "2026-07-30T11:00:00Z")+","+ + workerBodyAt(testWorkerID, "pulling", "volume-disk-short", "2026-07-30T12:00:00Z")) + if want := "worker " + testOlderWorkerID + " is unhealthy: fetch-failed"; causes[0] != want { + t.Fatalf("cause = %q, want %q", causes[0], want) + } +} + +// A worker the API is stopping keeps its cause, also beside other healthy +// workers: its reason is then the stop, not why it failed. +func TestWorkerWatchKeepsTheCauseOfAWorkerBeingStopped(t *testing.T) { + healthy := workerBodyAt(testOlderWorkerID, "ready", "", "2026-07-30T11:00:00Z") + causes := watchPolls(t, workerBody("unhealthy", "fetch-failed"), workerBody("stopping", "stop-requested")+","+healthy, healthy) + if want := "worker " + testWorkerID + " is unhealthy: fetch-failed"; causes[1] != want || causes[2] != want { + t.Fatalf("causes = %q, want %q kept", causes, want) + } +} + +// Of two workers in the same trouble the newest is the cause: during an update +// an older one can be the outgoing version's. func TestWorkerWatchTakesTheNewestWorkerInTrouble(t *testing.T) { causes := watchPolls(t, workerBodyAt(testOlderWorkerID, "unhealthy", "init-container-failed", "2026-07-30T11:00:00Z")+","+ workerBodyAt(testWorkerID, "unhealthy", "fetch-failed", "2026-07-30T12:00:00Z")) From c28ef3b20f02a04e968a17f5f26838e30a5fdd10 Mon Sep 17 00:00:00 2001 From: Marcin Wisniewski <78590652+itsNotMyUsername@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:52:48 +0100 Subject: [PATCH 4/4] fix(serverless): read every page of live workers in the deploy wait The watch read only the first 100 workers, so a worker in trouble behind a page of healthy ones was never seen. It now follows the cursor with the same filters, up to 10 pages a poll. Co-Authored-By: Claude Opus 5.5 --- internal/cmd/serverless/deploy_workers.go | 40 +++++++++++++++---- .../cmd/serverless/deploy_workers_test.go | 30 +++++++++++++- 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/internal/cmd/serverless/deploy_workers.go b/internal/cmd/serverless/deploy_workers.go index f87b8ad4..0d142217 100644 --- a/internal/cmd/serverless/deploy_workers.go +++ b/internal/cmd/serverless/deploy_workers.go @@ -42,10 +42,15 @@ type workerWatch struct { last *workerTrouble } -// workersPageLimit is the most workers a list page holds. One page covers an -// app's live workers unless it runs more than that; the watch is best effort. +// workersPageLimit is the most workers a list page holds, and workersMaxPages +// bounds how many pages one poll reads, so a poll stays a few requests. const workersPageLimit serverlessapi.Limit = 100 +const workersMaxPages = 10 + +// workersAllVersions is the versionId that lists the workers of every version. +const workersAllVersions = "all" + // observe reads the app's live workers and returns the trouble it found when it // differs from the last one. An unhealthy worker is the cause before one still // waiting for disk, since the rollout keeps waiting on the latter; among equals @@ -57,16 +62,13 @@ const workersPageLimit serverlessapi.Limit = 100 // its reason becomes the stop. An unreadable list changes nothing and never // fails the wait. func (w *workerWatch) observe(ctx context.Context) (workerTrouble, bool) { - all := "all" - live := serverlessapi.WorkerStateFilterLive - limit := workersPageLimit - page, err := w.client.ListWorkers(ctx, w.appID, serverlessapi.ListWorkersParams{VersionId: &all, State: &live, Limit: &limit}) + workers, err := w.liveWorkers(ctx) if err != nil { return workerTrouble{}, false } var cause *serverlessapi.Worker - for i := range page.Data { - wk := &page.Data[i] + for i := range workers { + wk := &workers[i] rank := troubleRank(wk) if rank == 0 { if w.last != nil && wk.Id.String() == w.last.id && isServing(wk) { @@ -89,6 +91,28 @@ func (w *workerWatch) observe(ctx context.Context) (workerTrouble, bool) { return t, true } +// liveWorkers lists the app's live workers of every version, following the +// cursor so a worker in trouble behind a page of healthy ones is still seen. +func (w *workerWatch) liveWorkers(ctx context.Context) ([]serverlessapi.Worker, error) { + all := workersAllVersions + live := serverlessapi.WorkerStateFilterLive + limit := workersPageLimit + params := serverlessapi.ListWorkersParams{VersionId: &all, State: &live, Limit: &limit} + var workers []serverlessapi.Worker + for range workersMaxPages { + page, err := w.client.ListWorkers(ctx, w.appID, params) + if err != nil { + return nil, err + } + workers = append(workers, page.Data...) + if page.NextCursor == nil || *page.NextCursor == "" { + break + } + params.Cursor = page.NextCursor + } + return workers, nil +} + // troubleRank orders the trouble a worker is in: 2 for a failed start, 1 for a // wait for disk, 0 for none. func troubleRank(wk *serverlessapi.Worker) int { diff --git a/internal/cmd/serverless/deploy_workers_test.go b/internal/cmd/serverless/deploy_workers_test.go index 5c959908..eb3e7cc6 100644 --- a/internal/cmd/serverless/deploy_workers_test.go +++ b/internal/cmd/serverless/deploy_workers_test.go @@ -62,7 +62,7 @@ func (s *rolloutStub) serve() { case r.Method == http.MethodGet && r.URL.Path == appPath+"/builds": _, _ = io.WriteString(w, `{"data":[{"id":"33333333-3333-3333-3333-333333333333","status":"ready","createdAt":"2026-07-30T12:00:00Z"}]}`) case r.Method == http.MethodGet && r.URL.Path == appPath+"/workers": - if got := r.URL.Query(); got.Get("versionId") != "all" || got.Get("state") != "live" { + if got := r.URL.Query(); got.Get("versionId") != workersAllVersions || got.Get("state") != "live" { s.t.Errorf("workers query = %v, want versionId=all and state=live", got) } if s.worker == "" || s.reads > s.initializingReads+1 { @@ -120,6 +120,34 @@ func watchPolls(t *testing.T, lists ...string) []string { const testOlderWorkerID = "11111111-26d6-40c1-a70e-f13b11de1eea" +// A worker in trouble behind a full page of healthy ones is still found: the +// watch follows the cursor with the same filters. +func TestWorkerWatchReadsEveryPage(t *testing.T) { + var cursors []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if q.Get("versionId") != workersAllVersions || q.Get("state") != "live" || q.Get("limit") != "100" { + t.Errorf("query = %v, want the same filters on every page", q) + } + cursors = append(cursors, q.Get("cursor")) + w.Header().Set("Content-Type", "application/json") + if q.Get("cursor") == "" { + _, _ = io.WriteString(w, `{"data":[`+workerBodyAt(testOlderWorkerID, "ready", "", "2026-07-30T13:00:00Z")+`],"nextCursor":"`+testLogCursor+`","summary":{"total":2}}`) + return + } + _, _ = io.WriteString(w, `{"data":[`+workerBody("unhealthy", "fetch-failed")+`],"summary":{"total":2}}`) + })) + t.Cleanup(srv.Close) + watch := &workerWatch{client: serverlessapi.NewClient("test-key", srv.URL, slog.Default()), appID: testAppID} + watch.observe(context.Background()) + if want := "worker " + testWorkerID + " is unhealthy: fetch-failed"; watch.cause() != want { + t.Fatalf("cause = %q, want %q", watch.cause(), want) + } + if len(cursors) != 2 || cursors[1] != testLogCursor { + t.Fatalf("cursors = %q, want the first page then the next cursor", cursors) + } +} + // A failed start is the cause before a newer worker still waiting for disk, // which the rollout keeps waiting on. func TestWorkerWatchPrefersAnUnhealthyWorkerToOneShortOfDisk(t *testing.T) {