From a908f375a11fd4357dc1beb62dc206602577309a Mon Sep 17 00:00:00 2001 From: Jaakko Varjo Date: Wed, 18 Nov 2026 16:04:27 +0200 Subject: [PATCH 1/6] fix(serverless): env writes target the deployment's container, not the deployment The container env endpoints key on container_name = the container inside the deployment, which the API names "-0" (we never send a name on create). env set/unset were sending the deployment name, so every add, update and delete failed with not_found. Resolve the real container name via a deployment GET (containerNameOf), the same way update already does. The GET /environment-variables response is grouped per container ([{container_name, env[]}]); SDK v1.7.1 GetEnvironmentVariables decodes it as a flat []ContainerEnvVar and yields one blank entry per container. Read the grouped shape directly (fetchEnvVars via the SDK client) and pick the resolved container's group. env list warns when a deployment exposes more than one container. Drop fetchEnvVars once the SDK returns groups. Tests serve the grouped response and assert container_name is the inner container; adds a no-containers case and two multi-container cases. Co-Authored-By: Claude Opus 4.8 --- internal/verda-cli/cmd/serverless/CLAUDE.md | 1 + internal/verda-cli/cmd/serverless/README.md | 2 + .../verda-cli/cmd/serverless/container_env.go | 97 ++++++++++- .../cmd/serverless/container_env_test.go | 159 +++++++++++++++++- 4 files changed, 246 insertions(+), 13 deletions(-) diff --git a/internal/verda-cli/cmd/serverless/CLAUDE.md b/internal/verda-cli/cmd/serverless/CLAUDE.md index b818b96..747f708 100644 --- a/internal/verda-cli/cmd/serverless/CLAUDE.md +++ b/internal/verda-cli/cmd/serverless/CLAUDE.md @@ -147,6 +147,7 @@ Describe cards (`renderContainerDeploymentCard`, `renderJobDeploymentCard`) prin - **Scaling preset + legacy rows on describe.** When a deployment was created via the web UI with a custom queue-load (say 10), our CLI shows `custom (10)` rather than a named preset. Don't try to round-trip it back to a named preset — exact threshold wins. - **`ContainerDeployment.Status` is NOT in the `GetDeployments` list response.** The list endpoint returns `ContainerDeployment` without status. We call `GetDeploymentStatus(name)` per-row in `describe`, but NOT in `list` (would N+1). If the web UI grows a bulk status endpoint, wire it in. - **Env-var name validation:** `^[A-Z_][A-Z0-9_]*$`. Lowercase or leading-digit names are rejected client-side in both `parseEnvFlag` and `promptEnvVar`. This is stricter than POSIX (which allows lowercase) but matches Verda's conventions. +- **Env endpoints key on the inner container, not the deployment.** `POST/PATCH/DELETE /container-deployments/{name}/environment-variables` take `container_name` = `Containers[0].Name`, which the API assigns as `-0` on create (we never send a container name). Passing the deployment name returns `not_found` ("A container with the name 'x' does not exist in the deployment 'x'"). `env set`/`env unset` resolve it via `containerNameOf` (one extra GET). The GET response is also grouped per container (`[{container_name, env[]}]`); SDK v1.9.0 `GetEnvironmentVariables` decodes it flat and yields one blank entry per container, so `fetchEnvVars` reads the grouped shape via `client.NewRequest`/`Do` and `envVarsOf` picks the container's group. Drop `fetchEnvVars` once the SDK returns groups. Multi-container deployments: the CLI always targets `Containers[0]`; `env list` warns when more groups exist. Both found live on prod 2026-11-18. - **Secret mount path must be absolute.** `parseSecretMountFlag` and `promptSecretMount` both check `strings.HasPrefix(path, "/")`. No trailing-slash normalization is applied. - **Update commands use fetch-then-merge-then-PATCH.** GET current state, overlay only `cmd.Flags().Changed()` flags, send one PATCH. nil/omitted fields in the request mean "don't change". Container update needs two GETs (deployment + scaling) because `ContainerDeployment` doesn't include scaling; job update needs one (scaling is inline). - **Env merge on update is type-partitioned.** `--env` replaces ALL plain vars and carries all secret vars unchanged; `--env-secret` replaces ALL secret vars and carries all plain vars unchanged. Both flags set → full replacement. Neither → no env field in PATCH. diff --git a/internal/verda-cli/cmd/serverless/README.md b/internal/verda-cli/cmd/serverless/README.md index 80199ac..6826f23 100644 --- a/internal/verda-cli/cmd/serverless/README.md +++ b/internal/verda-cli/cmd/serverless/README.md @@ -205,6 +205,8 @@ Env names must match `^[A-Z_][A-Z0-9_]*$` (uppercase alphanumerics + underscore, The describe card shows env names only. `-o json|yaml` and `--agent` print plain values verbatim, as the API returns them. Put sensitive values in secrets (`--env-secret`): output shows only the secret name. +`verda container env list|set|unset` operate on the deployment's first container (the CLI creates exactly one, named `-0` by the API). On a deployment with several containers, `env list` shows the first and prints a warning. + ## See also - `CLAUDE.md` in this directory — domain knowledge + gotchas for future Claude sessions diff --git a/internal/verda-cli/cmd/serverless/container_env.go b/internal/verda-cli/cmd/serverless/container_env.go index 5d379ce..8fbceca 100644 --- a/internal/verda-cli/cmd/serverless/container_env.go +++ b/internal/verda-cli/cmd/serverless/container_env.go @@ -17,6 +17,8 @@ package serverless import ( "context" "fmt" + "net/http" + "net/url" "strings" "text/tabwriter" @@ -28,6 +30,75 @@ import ( const envValueMasked = "***" +// containerNameOf: the env endpoints key `container_name` on the container +// inside the deployment (the API names it "-0"), not on the +// deployment; sending the deployment name returns not_found. +func containerNameOf(ctx context.Context, client *verda.Client, deployment string) (string, error) { + d, err := client.ContainerDeployments.GetDeploymentByName(ctx, deployment) + if err != nil { + return "", err + } + if len(d.Containers) == 0 { + return "", fmt.Errorf("deployment %q has no containers", deployment) + } + return d.Containers[0].Name, nil +} + +// envVarGroup is one element of the GET environment-variables response, +// which is grouped per container (GetDeploymentEnvVariablesPublicApiResponseDto). +type envVarGroup struct { + ContainerName string `json:"container_name"` + Env []verda.ContainerEnvVar `json:"env"` +} + +// fetchEnvVars reads the grouped response directly. SDK v1.9.0's +// GetEnvironmentVariables decodes it as a flat []ContainerEnvVar, which +// yields one blank entry per container; drop this once the SDK returns groups. +func fetchEnvVars(ctx context.Context, client *verda.Client, deployment string) ([]envVarGroup, error) { + req, err := client.NewRequest(ctx, http.MethodGet, "/container-deployments/"+url.PathEscape(deployment)+"/environment-variables", nil) + if err != nil { + return nil, err + } + var groups []envVarGroup + if _, err := client.Do(req, &groups); err != nil { + return nil, err + } + return groups, nil +} + +// envTarget is what an env write needs: the container to key on and its current variables. +type envTarget struct { + Container string + Vars []verda.ContainerEnvVar +} + +func loadEnvTarget(ctx context.Context, client *verda.Client, deployment string) (*envTarget, error) { + cn, err := containerNameOf(ctx, client, deployment) + if err != nil { + return nil, err + } + groups, err := fetchEnvVars(ctx, client, deployment) + if err != nil { + return nil, err + } + return &envTarget{Container: cn, Vars: envVarsOf(groups, cn)}, nil +} + +// envVarsOf: the variables of container; "" picks the first group. The +// deployment GET and the env GET are separate reads, so the container may be +// missing from the groups (no vars yet, or a lagging read): that is empty, not an error. +func envVarsOf(groups []envVarGroup, container string) []verda.ContainerEnvVar { + if container == "" && len(groups) > 0 { + return groups[0].Env + } + for i := range groups { + if groups[i].ContainerName == container { + return groups[i].Env + } + } + return nil +} + func newCmdContainerEnv(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command { cmd := &cobra.Command{ Use: "env", @@ -70,12 +141,16 @@ func newCmdEnvList(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Comman ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) defer cancel() - vars, err := cmdutil.WithSpinner(ctx, f.Status(), "Fetching environment variables...", func(ctx context.Context) ([]verda.ContainerEnvVar, error) { - return client.ContainerDeployments.GetEnvironmentVariables(ctx, name) + groups, err := cmdutil.WithSpinner(ctx, f.Status(), "Fetching environment variables...", func(ctx context.Context) ([]envVarGroup, error) { + return fetchEnvVars(ctx, client, name) }) if err != nil { return err } + if len(groups) > 1 { + _, _ = fmt.Fprintf(ioStreams.ErrOut, "Warning: deployment has %d containers; showing %q\n", len(groups), groups[0].ContainerName) + } + vars := envVarsOf(groups, "") if wrote, werr := cmdutil.WriteStructured(ioStreams.Out, f.OutputFormat(), vars); wrote { return werr @@ -156,12 +231,13 @@ func newCmdEnvSet(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) defer cancel() - current, err := cmdutil.WithSpinner(ctx, f.Status(), "Fetching current variables...", func(ctx context.Context) ([]verda.ContainerEnvVar, error) { - return client.ContainerDeployments.GetEnvironmentVariables(ctx, name) + target, err := cmdutil.WithSpinner(ctx, f.Status(), "Fetching current variables...", func(ctx context.Context) (*envTarget, error) { + return loadEnvTarget(ctx, client, name) }) if err != nil { return err } + containerName, current := target.Container, target.Vars existing := make(map[string]bool, len(current)) for _, v := range current { @@ -178,7 +254,7 @@ func newCmdEnvSet(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command } if len(toAdd) > 0 { - req := &verda.ContainerEnvVarsRequest{ContainerName: name, Env: toAdd} + req := &verda.ContainerEnvVarsRequest{ContainerName: containerName, Env: toAdd} cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "Add env vars:", req) if err := cmdutil.RunWithSpinner(ctx, f.Status(), "Adding environment variables...", func(ctx context.Context) error { return client.ContainerDeployments.AddEnvironmentVariables(ctx, name, req) @@ -187,7 +263,7 @@ func newCmdEnvSet(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Command } } if len(toUpdate) > 0 { - req := &verda.ContainerEnvVarsRequest{ContainerName: name, Env: toUpdate} + req := &verda.ContainerEnvVarsRequest{ContainerName: containerName, Env: toUpdate} cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "Update env vars:", req) if err := cmdutil.RunWithSpinner(ctx, f.Status(), "Updating environment variables...", func(ctx context.Context) error { return client.ContainerDeployments.UpdateEnvironmentVariables(ctx, name, req) @@ -266,8 +342,15 @@ func newCmdEnvUnset(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Comma ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) defer cancel() + containerName, err := cmdutil.WithSpinner(ctx, f.Status(), "Loading deployment...", func(ctx context.Context) (string, error) { + return containerNameOf(ctx, client, deployment) + }) + if err != nil { + return err + } + req := &verda.DeleteContainerEnvVarsRequest{ - ContainerName: deployment, + ContainerName: containerName, Env: args, } cmdutil.DebugJSON(ioStreams.ErrOut, f.Debug(), "Delete env vars:", req) diff --git a/internal/verda-cli/cmd/serverless/container_env_test.go b/internal/verda-cli/cmd/serverless/container_env_test.go index ca4532a..f2fc4cc 100644 --- a/internal/verda-cli/cmd/serverless/container_env_test.go +++ b/internal/verda-cli/cmd/serverless/container_env_test.go @@ -52,12 +52,24 @@ func newEnvRecordingServer(t *testing.T, vars []verda.ContainerEnvVar) *envRecor }) }) - mux.HandleFunc("GET /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, _ *http.Request) { + // Mirrors the API: the single container is named "-0", and + // the env write endpoints key on that, not on the deployment name. + mux.HandleFunc("GET /container-deployments/{name}", func(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(verda.ContainerDeployment{ + Name: name, + Containers: []verda.DeploymentContainer{{Name: name + "-0", Image: verda.ContainerImage{Image: "nginx:1.27.3"}}}, + }) + }) + + // Grouped per container, as the API returns it (one group per container). + mux.HandleFunc("GET /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, r *http.Request) { rec.mu.Lock() v := rec.envVars rec.mu.Unlock() w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode(v) + _ = json.NewEncoder(w).Encode([]map[string]any{{"container_name": r.PathValue("name") + "-0", "env": v}}) }) mux.HandleFunc("POST /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, r *http.Request) { @@ -186,8 +198,8 @@ func TestEnvSet_AddNew(t *testing.T) { if err := json.Unmarshal(addBody, &got); err != nil { t.Fatalf("unmarshal add body: %v\nbody: %s", err, addBody) } - if got.ContainerName != "my-endpoint" { - t.Errorf("container_name: got %q, want my-endpoint", got.ContainerName) + if got.ContainerName != "my-endpoint-0" { + t.Errorf("container_name: got %q, want the inner container my-endpoint-0", got.ContainerName) } if len(got.Env) != 1 || got.Env[0].Name != "FOO" || got.Env[0].ValueOrReferenceToSecret != "bar" { t.Errorf("env: got %+v", got.Env) @@ -231,6 +243,43 @@ func TestEnvSet_UpdateExisting(t *testing.T) { if len(got.Env) != 1 || got.Env[0].Name != "FOO" || got.Env[0].ValueOrReferenceToSecret != "new" { t.Errorf("patch env: got %+v", got.Env) } + if got.ContainerName != "my-endpoint-0" { + t.Errorf("container_name: got %q, want the inner container my-endpoint-0", got.ContainerName) + } +} + +// A deployment read with no containers has nothing to key the env write on; +// fail before sending rather than let the API return a confusing not_found. +func TestEnvSet_NoContainers(t *testing.T) { + t.Parallel() + mux := http.NewServeMux() + mux.HandleFunc("POST /oauth2/token", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"access_token": "test-token", "token_type": "Bearer"}) + }) + mux.HandleFunc("GET /container-deployments/{name}", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(verda.ContainerDeployment{Name: "my-endpoint"}) + }) + var wrote bool + mux.HandleFunc("/container-deployments/{name}/environment-variables", func(w http.ResponseWriter, _ *http.Request) { + wrote = true + w.WriteHeader(http.StatusNoContent) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + f := newTestFactory(t, srv.URL) + + var stdout, stderr bytes.Buffer + cmd := NewCmdContainer(f, cmdutil.IOStreams{Out: &stdout, ErrOut: &stderr}) + cmd.SetArgs([]string{"env", "set", "my-endpoint", "--env", "FOO=bar"}) + err := cmd.Execute() + if err == nil || !strings.Contains(err.Error(), "has no containers") { + t.Fatalf("want 'has no containers' error, got %v", err) + } + if wrote { + t.Error("env endpoint must not be called when the container name is unknown") + } } func TestEnvSet_MixedAddUpdate(t *testing.T) { @@ -351,8 +400,8 @@ func TestEnvUnset_WithYes(t *testing.T) { if err := json.Unmarshal(delBody, &got); err != nil { t.Fatalf("unmarshal delete body: %v\nbody: %s", err, delBody) } - if got.ContainerName != "my-endpoint" { - t.Errorf("container_name: got %q, want my-endpoint", got.ContainerName) + if got.ContainerName != "my-endpoint-0" { + t.Errorf("container_name: got %q, want the inner container my-endpoint-0", got.ContainerName) } if len(got.Env) != 1 || got.Env[0] != "HF_HOME" { t.Errorf("env: got %v, want [HF_HOME]", got.Env) @@ -570,3 +619,101 @@ func TestEnvUnset_AgentMode_RequiresDeployment(t *testing.T) { t.Errorf("code: got %q, want MISSING_REQUIRED_FLAGS", agentErr.Code) } } + +// newMultiContainerServer serves a two-container deployment whose env groups +// differ, so tests can tell which group a command read. +func newMultiContainerServer(t *testing.T) (*httptest.Server, *envRecordingServer) { + t.Helper() + rec := &envRecordingServer{} + mux := http.NewServeMux() + mux.HandleFunc("POST /oauth2/token", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"access_token": "test-token", "token_type": "Bearer"}) + }) + mux.HandleFunc("GET /container-deployments/{name}", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(verda.ContainerDeployment{ + Name: "my-endpoint", + Containers: []verda.DeploymentContainer{{Name: "my-endpoint-0"}, {Name: "sidecar-1"}}, + }) + }) + mux.HandleFunc("GET /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]map[string]any{ + {"container_name": "my-endpoint-0", "env": []verda.ContainerEnvVar{{Name: "MAIN_ONLY", Type: "plain", ValueOrReferenceToSecret: "1"}}}, + {"container_name": "sidecar-1", "env": []verda.ContainerEnvVar{{Name: "SIDE_ONLY", Type: "plain", ValueOrReferenceToSecret: "2"}}}, + }) + }) + mux.HandleFunc("POST /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + rec.mu.Lock() + rec.addBody = body + rec.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("PATCH /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + rec.mu.Lock() + rec.patchBody = body + rec.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return srv, rec +} + +// list shows the first container's group and warns that others exist. +func TestEnvList_MultiContainer_ShowsFirstAndWarns(t *testing.T) { + t.Parallel() + srv, _ := newMultiContainerServer(t) + f := newTestFactory(t, srv.URL) + + var stdout, stderr bytes.Buffer + cmd := NewCmdContainer(f, cmdutil.IOStreams{Out: &stdout, ErrOut: &stderr}) + cmd.SetArgs([]string{"env", "list", "my-endpoint"}) + if err := cmd.Execute(); err != nil { + t.Fatalf("env list failed: %v\nstderr:\n%s", err, stderr.String()) + } + var got []struct{ Name string } + if err := json.Unmarshal(stdout.Bytes(), &got); err != nil { + t.Fatalf("unmarshal: %v\nstdout: %s", err, stdout.String()) + } + if len(got) != 1 || got[0].Name != "MAIN_ONLY" { + t.Errorf("want only MAIN_ONLY from the first group, got %+v", got) + } + if !strings.Contains(stderr.String(), "2 containers") { + t.Errorf("want multi-container warning on stderr, got %q", stderr.String()) + } +} + +// set partitions add/update against the resolved container's group, not +// another container's: SIDE_ONLY exists only on the sidecar, so it is added. +func TestEnvSet_MultiContainer_UsesOwnGroup(t *testing.T) { + t.Parallel() + srv, rec := newMultiContainerServer(t) + f := newTestFactory(t, srv.URL) + + var stdout, stderr bytes.Buffer + cmd := NewCmdContainer(f, cmdutil.IOStreams{Out: &stdout, ErrOut: &stderr}) + cmd.SetArgs([]string{"env", "set", "my-endpoint", "--env", "SIDE_ONLY=x", "--env", "MAIN_ONLY=y"}) + if err := cmd.Execute(); err != nil { + t.Fatalf("env set failed: %v\nstderr:\n%s", err, stderr.String()) + } + var add, patch struct { + ContainerName string `json:"container_name"` + Env []struct{ Name string } `json:"env"` + } + if err := json.Unmarshal(rec.getAddBody(), &add); err != nil { + t.Fatalf("unmarshal add: %v", err) + } + if err := json.Unmarshal(rec.getPatchBody(), &patch); err != nil { + t.Fatalf("unmarshal patch: %v", err) + } + if add.ContainerName != "my-endpoint-0" || len(add.Env) != 1 || add.Env[0].Name != "SIDE_ONLY" { + t.Errorf("add: want SIDE_ONLY on my-endpoint-0, got %+v", add) + } + if patch.ContainerName != "my-endpoint-0" || len(patch.Env) != 1 || patch.Env[0].Name != "MAIN_ONLY" { + t.Errorf("patch: want MAIN_ONLY on my-endpoint-0, got %+v", patch) + } +} From f4c0bf9a5422f1afb69fa34cfa69a8240d6889d1 Mon Sep 17 00:00:00 2001 From: Jaakko Varjo Date: Wed, 18 Nov 2026 17:52:04 +0200 Subject: [PATCH 2/6] test(serverless): cover env error, confirm and picker paths Bring container_env.go to full statement coverage (bar the unreachable NewRequest error branch): missing client, missing name without a terminal, failures on every env endpoint and on the deployment lookup, a container absent from the env GET groups, env-flag validation, unset confirm accept/decline/prompter-failure, and the interactive picker for list, set and unset including cancel, empty list and list-load failure. Also a unit test for envVarsOf. Co-Authored-By: Claude Fable 5.1 --- .../serverless/container_env_paths_test.go | 539 ++++++++++++++++++ 1 file changed, 539 insertions(+) create mode 100644 internal/verda-cli/cmd/serverless/container_env_paths_test.go diff --git a/internal/verda-cli/cmd/serverless/container_env_paths_test.go b/internal/verda-cli/cmd/serverless/container_env_paths_test.go new file mode 100644 index 0000000..e459025 --- /dev/null +++ b/internal/verda-cli/cmd/serverless/container_env_paths_test.go @@ -0,0 +1,539 @@ +// Copyright 2026 Verda Cloud Oy +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package serverless + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" + + cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" + tuitest "github.com/verda-cloud/verda-cli/pkg/tui/testing" +) + +// envServerConfig drives newEnvServer: which routes fail, what the env GET +// groups are keyed on, and which deployments the picker sees. +type envServerConfig struct { + // fail maps a route key to the HTTP status it returns instead of succeeding. + // Keys: "GET list", "GET deployment", "GET env", "POST env", "PATCH env", "DELETE env". + fail map[string]int + // groupContainer overrides container_name in the env GET group; "" means "-0". + groupContainer string + // deployments is what GET /container-deployments lists for the picker. + deployments []string + envVars []verda.ContainerEnvVar +} + +func (c envServerConfig) failed(w http.ResponseWriter, key string) bool { + status, ok := c.fail[key] + if !ok { + return false + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]string{"code": "test_failure", "message": key + " failed"}) + return true +} + +func newEnvServer(t *testing.T, cfg envServerConfig) *envRecordingServer { + t.Helper() + rec := &envRecordingServer{envVars: cfg.envVars} + mux := http.NewServeMux() + + mux.HandleFunc("POST /oauth2/token", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"access_token": "test-token", "token_type": "Bearer"}) + }) + + mux.HandleFunc("GET /container-deployments", func(w http.ResponseWriter, _ *http.Request) { + if cfg.failed(w, "GET list") { + return + } + list := make([]verda.ContainerDeployment, 0, len(cfg.deployments)) + for _, name := range cfg.deployments { + list = append(list, verda.ContainerDeployment{Name: name}) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(list) + }) + + mux.HandleFunc("GET /container-deployments/{name}", func(w http.ResponseWriter, r *http.Request) { + if cfg.failed(w, "GET deployment") { + return + } + name := r.PathValue("name") + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(verda.ContainerDeployment{ + Name: name, + Containers: []verda.DeploymentContainer{{Name: name + "-0"}}, + }) + }) + + mux.HandleFunc("GET /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, r *http.Request) { + if cfg.failed(w, "GET env") { + return + } + group := cfg.groupContainer + if group == "" { + group = r.PathValue("name") + "-0" + } + rec.mu.Lock() + v := rec.envVars + rec.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]map[string]any{{"container_name": group, "env": v}}) + }) + + record := func(key string, slot *[]byte) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if cfg.failed(w, key) { + return + } + body, _ := io.ReadAll(r.Body) + rec.mu.Lock() + *slot = body + rec.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + } + } + mux.HandleFunc("POST /container-deployments/{name}/environment-variables", record("POST env", &rec.addBody)) + mux.HandleFunc("PATCH /container-deployments/{name}/environment-variables", record("PATCH env", &rec.patchBody)) + mux.HandleFunc("DELETE /container-deployments/{name}/environment-variables", record("DELETE env", &rec.delBody)) + + rec.srv = httptest.NewServer(mux) + t.Cleanup(rec.srv.Close) + return rec +} + +// runEnv executes `verda container env ` and returns stdout, stderr, err. +func runEnv(t *testing.T, f cmdutil.Factory, args ...string) (string, string, error) { + t.Helper() + var stdout, stderr bytes.Buffer + cmd := NewCmdContainer(f, cmdutil.IOStreams{Out: &stdout, ErrOut: &stderr}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + cmd.SetArgs(append([]string{"env"}, args...)) + err := cmd.Execute() + return stdout.String(), stderr.String(), err +} + +// --- no client / no name --- + +// Every subcommand surfaces the missing-credentials error from the factory +// instead of panicking or prompting. +func TestEnv_NoClient(t *testing.T) { + t.Parallel() + cases := map[string][]string{ + "list": {"list", "my-endpoint"}, + "set": {"set", "my-endpoint", "--env", "A=1"}, + "unset": {"unset", "--deployment", "my-endpoint", "--yes", "A"}, + } + for name, args := range cases { + t.Run(name, func(t *testing.T) { + t.Parallel() + f := &cmdutil.TestFactory{OutputFormatOverride: "json"} + _, _, err := runEnv(t, f, args...) + if !errors.Is(err, cmdutil.ErrNoClient) { + t.Fatalf("want ErrNoClient, got %v", err) + } + }) + } +} + +// Without a terminal (here: json output) and without a name, list and set +// cannot open the picker and must report the missing argument. +func TestEnv_MissingName_NonInteractive(t *testing.T) { + t.Parallel() + cases := map[string][]string{ + "list": {"list"}, + "set": {"set", "--env", "A=1"}, + "unset": {"unset", "A"}, + } + for name, args := range cases { + t.Run(name, func(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{}) + f := newTestFactory(t, rec.srv.URL) + f.AgentModeOverride = false + _, _, err := runEnv(t, f, args...) + if agentErrorCode(err) != "MISSING_REQUIRED_FLAGS" { + t.Fatalf("want MISSING_REQUIRED_FLAGS, got %v", err) + } + }) + } +} + +// --- API failures --- + +func TestEnvList_FetchError(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"GET env": http.StatusInternalServerError}}) + f := newTestFactory(t, rec.srv.URL) + stdout, _, err := runEnv(t, f, "list", "my-endpoint") + if err == nil { + t.Fatal("want error from env GET, got nil") + } + if stdout != "" { + t.Errorf("want no stdout on failure, got %q", stdout) + } +} + +func TestEnvSet_DeploymentLookupError(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"GET deployment": http.StatusNotFound}}) + f := newTestFactory(t, rec.srv.URL) + _, _, err := runEnv(t, f, "set", "missing", "--env", "A=1") + if err == nil { + t.Fatal("want error from deployment GET, got nil") + } + if rec.getAddBody() != nil || rec.getPatchBody() != nil { + t.Error("want no env write after a failed deployment lookup") + } +} + +func TestEnvSet_EnvFetchError(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"GET env": http.StatusInternalServerError}}) + f := newTestFactory(t, rec.srv.URL) + _, _, err := runEnv(t, f, "set", "my-endpoint", "--env", "A=1") + if err == nil { + t.Fatal("want error from env GET, got nil") + } + if rec.getAddBody() != nil || rec.getPatchBody() != nil { + t.Error("want no env write after a failed env fetch") + } +} + +// The env GET and the deployment GET are separate reads; when the resolved +// container has no group yet, every variable counts as new and is added. +func TestEnvSet_ContainerMissingFromGroups(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{ + groupContainer: "someone-else-0", + envVars: []verda.ContainerEnvVar{{Name: "A", Type: "plain", ValueOrReferenceToSecret: "old"}}, + }) + f := newTestFactory(t, rec.srv.URL) + stdout, _, err := runEnv(t, f, "set", "my-endpoint", "--env", "A=new") + if err != nil { + t.Fatalf("env set: %v", err) + } + if rec.getPatchBody() != nil { + t.Error("want no PATCH: A is not known on my-endpoint-0") + } + var add struct { + ContainerName string `json:"container_name"` + } + if err := json.Unmarshal(rec.getAddBody(), &add); err != nil { + t.Fatalf("unmarshal add body: %v", err) + } + if add.ContainerName != "my-endpoint-0" { + t.Errorf("add container_name: got %q, want my-endpoint-0", add.ContainerName) + } + if !strings.Contains(stdout, `"added": 1`) || !strings.Contains(stdout, `"updated": 0`) { + t.Errorf("want added=1 updated=0, got %s", stdout) + } +} + +func TestEnvSet_InvalidEnvFlag(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{}) + f := newTestFactory(t, rec.srv.URL) + _, _, err := runEnv(t, f, "set", "my-endpoint", "--env", "lower=1") + if err == nil { + t.Fatal("want validation error for lowercase env name, got nil") + } + if rec.getAddBody() != nil { + t.Error("want no API write on a validation error") + } +} + +func TestEnvSet_AddError(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"POST env": http.StatusBadRequest}}) + f := newTestFactory(t, rec.srv.URL) + stdout, _, err := runEnv(t, f, "set", "my-endpoint", "--env", "A=1") + if err == nil { + t.Fatal("want error from POST, got nil") + } + if stdout != "" { + t.Errorf("want no success output, got %q", stdout) + } +} + +func TestEnvSet_UpdateError(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{ + fail: map[string]int{"PATCH env": http.StatusBadRequest}, + envVars: []verda.ContainerEnvVar{{Name: "A", Type: "plain", ValueOrReferenceToSecret: "old"}}, + }) + f := newTestFactory(t, rec.srv.URL) + stdout, _, err := runEnv(t, f, "set", "my-endpoint", "--env", "A=new", "--env", "B=1") + if err == nil { + t.Fatal("want error from PATCH, got nil") + } + if rec.getAddBody() == nil { + t.Error("want the add to have been sent before the failing update") + } + if stdout != "" { + t.Errorf("want no success output, got %q", stdout) + } +} + +func TestEnvUnset_DeploymentLookupError(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"GET deployment": http.StatusNotFound}}) + f := newTestFactory(t, rec.srv.URL) + _, _, err := runEnv(t, f, "unset", "--deployment", "missing", "--yes", "A") + if err == nil { + t.Fatal("want error from deployment GET, got nil") + } + if rec.getDelBody() != nil { + t.Error("want no DELETE after a failed deployment lookup") + } +} + +func TestEnvUnset_DeleteError(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"DELETE env": http.StatusInternalServerError}}) + f := newTestFactory(t, rec.srv.URL) + stdout, _, err := runEnv(t, f, "unset", "--deployment", "my-endpoint", "--yes", "A") + if err == nil { + t.Fatal("want error from DELETE, got nil") + } + if stdout != "" { + t.Errorf("want no success output, got %q", stdout) + } +} + +// --- unset confirmation --- + +func TestEnvUnset_Confirm(t *testing.T) { + t.Parallel() + t.Run("accepted sends the delete", func(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{}) + f := newTestFactory(t, rec.srv.URL) + f.AgentModeOverride = false + f.PrompterOverride = tuitest.New().AddConfirm(true) + _, stderr, err := runEnv(t, f, "unset", "--deployment", "my-endpoint", "A", "B") + if err != nil { + t.Fatalf("env unset: %v", err) + } + if !strings.Contains(stderr, "Remove 2 variable(s) from my-endpoint") { + t.Errorf("want warning heading on stderr, got %q", stderr) + } + var del struct { + ContainerName string `json:"container_name"` + Env []string `json:"env"` + } + if err := json.Unmarshal(rec.getDelBody(), &del); err != nil { + t.Fatalf("unmarshal delete body: %v", err) + } + if del.ContainerName != "my-endpoint-0" || len(del.Env) != 2 { + t.Errorf("delete body: got %+v", del) + } + }) + t.Run("declined is a clean no-op", func(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{}) + f := newTestFactory(t, rec.srv.URL) + f.AgentModeOverride = false + f.PrompterOverride = tuitest.New().AddConfirm(false) + stdout, _, err := runEnv(t, f, "unset", "--deployment", "my-endpoint", "A") + if err != nil { + t.Fatalf("want nil on decline, got %v", err) + } + if rec.getDelBody() != nil { + t.Error("want no DELETE when the confirm is declined") + } + if stdout != "" { + t.Errorf("want no output on decline, got %q", stdout) + } + }) + t.Run("prompter failure is surfaced", func(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{}) + f := newTestFactory(t, rec.srv.URL) + f.AgentModeOverride = false + f.PrompterOverride = tuitest.New() // no confirm queued → real error + _, _, err := runEnv(t, f, "unset", "--deployment", "my-endpoint", "A") + if err == nil || cmdutil.IsPromptCancel(err) { + t.Fatalf("want a real prompter error, got %v", err) + } + if rec.getDelBody() != nil { + t.Error("want no DELETE after a prompter failure") + } + }) +} + +// --- interactive picker --- + +// interactiveEnvFactory: table output, non-agent, scripted prompter; pair with withTerminal. +func interactiveEnvFactory(t *testing.T, rec *envRecordingServer, p *tuitest.Prompter) *cmdutil.TestFactory { + t.Helper() + f := newTestFactory(t, rec.srv.URL) + f.AgentModeOverride = false + f.OutputFormatOverride = outputTable + f.PrompterOverride = p + return f +} + +var pickerDeployments = []string{"alpha", "beta"} + +// The picker path mutates the package-level terminal probe, so these tests +// are not parallel; the subtests share the override. +func TestEnvList_InteractivePicker(t *testing.T) { + withTerminal(t) + deployments := pickerDeployments + + t.Run("list picks a deployment", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{ + deployments: deployments, + envVars: []verda.ContainerEnvVar{{Name: "A", Type: "plain", ValueOrReferenceToSecret: "1"}}, + }) + stdout, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New().AddSelect(1)), "list") + if err != nil { + t.Fatalf("env list: %v", err) + } + if !strings.Contains(stdout, "A") || !strings.Contains(stdout, "plain") { + t.Errorf("want table with A, got %q", stdout) + } + }) + t.Run("list cancel at picker exits cleanly", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{deployments: deployments}) + stdout, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New().AddSelect(len(deployments))), "list") + if err != nil { + t.Fatalf("want nil on cancel, got %v", err) + } + if stdout != "" { + t.Errorf("want no output on cancel, got %q", stdout) + } + }) + t.Run("list with no deployments", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{}) + stdout, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New()), "list") + if err != nil { + t.Fatalf("want nil on empty list, got %v", err) + } + if !strings.Contains(stdout, "No container deployments found") { + t.Errorf("want empty-list notice, got %q", stdout) + } + }) + t.Run("list picker load error", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"GET list": http.StatusInternalServerError}}) + if _, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New()), "list"); err == nil { + t.Fatal("want error from deployments GET, got nil") + } + }) +} + +func TestEnvWrite_InteractivePicker(t *testing.T) { + withTerminal(t) + deployments := pickerDeployments + + t.Run("set picks a deployment and writes to its container", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{deployments: deployments}) + stdout, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New().AddSelect(0)), "set", "--env", "A=1") + if err != nil { + t.Fatalf("env set: %v", err) + } + var add struct { + ContainerName string `json:"container_name"` + } + if err := json.Unmarshal(rec.getAddBody(), &add); err != nil { + t.Fatalf("unmarshal add body: %v", err) + } + if add.ContainerName != "alpha-0" { + t.Errorf("add container_name: got %q, want alpha-0", add.ContainerName) + } + if !strings.Contains(stdout, `deployment "alpha"`) { + t.Errorf("want success line naming alpha, got %q", stdout) + } + }) + t.Run("set cancel at picker exits cleanly", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{deployments: deployments}) + _, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New().AddSelect(len(deployments))), "set", "--env", "A=1") + if err != nil { + t.Fatalf("want nil on cancel, got %v", err) + } + if rec.getAddBody() != nil { + t.Error("want no API write on cancel") + } + }) + t.Run("unset picks a deployment then confirms", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{deployments: deployments}) + stdout, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New().AddSelect(1).AddConfirm(true)), "unset", "A") + if err != nil { + t.Fatalf("env unset: %v", err) + } + var del struct { + ContainerName string `json:"container_name"` + } + if err := json.Unmarshal(rec.getDelBody(), &del); err != nil { + t.Fatalf("unmarshal delete body: %v", err) + } + if del.ContainerName != "beta-0" { + t.Errorf("delete container_name: got %q, want beta-0", del.ContainerName) + } + if !strings.Contains(stdout, `deployment "beta"`) { + t.Errorf("want success line naming beta, got %q", stdout) + } + }) + t.Run("unset cancel at picker exits cleanly", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{deployments: deployments}) + _, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New().AddSelect(len(deployments))), "unset", "A") + if err != nil { + t.Fatalf("want nil on cancel, got %v", err) + } + if rec.getDelBody() != nil { + t.Error("want no DELETE on cancel") + } + }) + t.Run("unset picker load error", func(t *testing.T) { + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"GET list": http.StatusInternalServerError}}) + if _, _, err := runEnv(t, interactiveEnvFactory(t, rec, tuitest.New()), "unset", "A"); err == nil { + t.Fatal("want error from deployments GET, got nil") + } + }) +} + +// --- helpers --- + +func TestEnvVarsOf(t *testing.T) { + t.Parallel() + a := []verda.ContainerEnvVar{{Name: "A"}} + b := []verda.ContainerEnvVar{{Name: "B"}} + groups := []envVarGroup{{ContainerName: "x-0", Env: a}, {ContainerName: "y-0", Env: b}} + + if got := envVarsOf(nil, ""); got != nil { + t.Errorf("no groups, first: want nil, got %v", got) + } + if got := envVarsOf(groups, ""); len(got) != 1 || got[0].Name != "A" { + t.Errorf("first group: want A, got %v", got) + } + if got := envVarsOf(groups, "y-0"); len(got) != 1 || got[0].Name != "B" { + t.Errorf("named group: want B, got %v", got) + } + if got := envVarsOf(groups, "z-0"); got != nil { + t.Errorf("unknown container: want nil, got %v", got) + } +} From 8ec7ad826f329c19f1f36251ce57d76296ef27eb Mon Sep 17 00:00:00 2001 From: Jaakko Varjo Date: Wed, 18 Nov 2026 18:15:31 +0200 Subject: [PATCH 3/6] chore: renamed a test script --- test/{test_serverless_features.sh => test-serverless-features.sh} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test/{test_serverless_features.sh => test-serverless-features.sh} (100%) diff --git a/test/test_serverless_features.sh b/test/test-serverless-features.sh similarity index 100% rename from test/test_serverless_features.sh rename to test/test-serverless-features.sh From c78522fdc164a2192cb641bebf16225aa3376d91 Mon Sep 17 00:00:00 2001 From: Jaakko Varjo Date: Wed, 18 Nov 2026 18:37:01 +0200 Subject: [PATCH 4/6] docs(serverless): document env list/set/unset by deployment name README gains a usage section for `verda container env` showing that every subcommand takes the deployment name and the CLI resolves the inner container. CLAUDE.md lists the env/secret/file-secret/registry-creds subtrees and the container_env.go file. `env list` gets an in-command example like set and unset already had. Co-Authored-By: Claude Fable 5.1 --- internal/verda-cli/cmd/serverless/CLAUDE.md | 3 ++- internal/verda-cli/cmd/serverless/README.md | 12 ++++++++++++ internal/verda-cli/cmd/serverless/container_env.go | 6 +++++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/internal/verda-cli/cmd/serverless/CLAUDE.md b/internal/verda-cli/cmd/serverless/CLAUDE.md index 747f708..fc15068 100644 --- a/internal/verda-cli/cmd/serverless/CLAUDE.md +++ b/internal/verda-cli/cmd/serverless/CLAUDE.md @@ -25,7 +25,7 @@ This rule applies equally to Claude, Codex, Cursor, or a human editing the packa - `verda container` → `/container-deployments` (continuous endpoints, supports spot) - `verda batchjob` → `/job-deployments` (one-shot jobs, deadline-based, **no spot**) - There is **no** `verda serverless` parent command — the two trees were promoted to root for shorter invocations. They still share this Go package because they share wizard step factories, validators, and the API cache. -- Verbs (both trees): `create`, `update`, `list` (alias `ls`), `describe` (aliases `get`, `show`), `delete` (aliases `rm`, `del`), `pause`, `resume`, `purge-queue`. Container also has `restart`, `scale` and `replicas`. +- Verbs (both trees): `create`, `update`, `list` (alias `ls`), `describe` (aliases `get`, `show`), `delete` (aliases `rm`, `del`), `pause`, `resume`, `purge-queue`. Container also has `restart`, `scale`, `replicas`, and the `env`, `secret`, `file-secret` and `registry-creds` subtrees. - Files: - `container.go`, `batchjob.go` — Top-level command builders. `NewCmdContainer` and `NewCmdBatchjob` are exported and called directly from `cmd/cmd.go`. Both are GA: registered unconditionally, visible, no `cmdutil.TagAnnotation`. `visibility_test.go` and `cmd/cmd_test.go` guard this (the former `VERDA_BATCHJOB_ENABLED` gate and `(beta)` tag are gone). - `container_create.go` — `containerCreateOptions`, flags, `request()`, validate(), wizard entry point. @@ -36,6 +36,7 @@ This rule applies equally to Claude, Codex, Cursor, or a human editing the packa - `container_scale.go` — `container scale`: flags → `scaling.Change`, confirm, PATCH, optional `--wait`. - `container_scale_wizard.go` — `buildScaleFlow`: setting multi-select, then one step per setting. - `container_replicas.go` — `container replicas`: `GetDeploymentReplicas` + table / structured output. + - `container_env.go` — `container env list|set|unset`: resolves the deployment's inner container (`containerNameOf`) and reads the grouped env GET (`fetchEnvVars`). See "Env endpoints key on the inner container" below. - `container_delete.go` — `DeleteDeployment(timeoutMs)` + destructive confirm. - `container_actions.go` — Data-driven action factory `newContainerActionCmd` (pause/resume/restart/purge-queue). - `batchjob_create.go` — `batchjobCreateOptions` (simpler: no spot, deadline required). diff --git a/internal/verda-cli/cmd/serverless/README.md b/internal/verda-cli/cmd/serverless/README.md index 6826f23..f97a632 100644 --- a/internal/verda-cli/cmd/serverless/README.md +++ b/internal/verda-cli/cmd/serverless/README.md @@ -205,6 +205,18 @@ Env names must match `^[A-Z_][A-Z0-9_]*$` (uppercase alphanumerics + underscore, The describe card shows env names only. `-o json|yaml` and `--agent` print plain values verbatim, as the API returns them. Put sensitive values in secrets (`--env-secret`): output shows only the secret name. +### Managing env on a running deployment + +`verda container env` changes variables in place, without a redeploy. Every subcommand takes the **deployment name**; the CLI resolves the container inside it. + +```bash +verda container env list my-endpoint +verda container env set my-endpoint --env HF_HOME=/data/.huggingface --env-secret API_KEY=my-secret +verda container env unset --deployment my-endpoint HF_HOME MODEL_NAME +``` + +`set` adds variables that do not exist yet and updates the ones that do. `unset` asks for confirmation (`--yes` to skip; required in agent mode). Without a name on a terminal, `list` and `set` open a deployment picker; `unset` uses `--deployment`. + `verda container env list|set|unset` operate on the deployment's first container (the CLI creates exactly one, named `-0` by the API). On a deployment with several containers, `env list` shows the first and prints a warning. ## See also diff --git a/internal/verda-cli/cmd/serverless/container_env.go b/internal/verda-cli/cmd/serverless/container_env.go index 8fbceca..c8760b9 100644 --- a/internal/verda-cli/cmd/serverless/container_env.go +++ b/internal/verda-cli/cmd/serverless/container_env.go @@ -124,7 +124,11 @@ func newCmdEnvList(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Comman Use: "list ", Aliases: []string{"ls"}, Short: "List environment variables", - Args: cobra.MaximumNArgs(1), + Example: cmdutil.Examples(` + # List variables on a deployment (secret-backed values are masked) + verda container env list my-endpoint + `), + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { name, err := resolveContainerName(cmd, f, ioStreams, args) if err != nil { From 0e942544e3b499892370b8df8f6def2d3bae1a8c Mon Sep 17 00:00:00 2001 From: Jaakko Varjo Date: Fri, 20 Nov 2026 12:40:09 +0200 Subject: [PATCH 5/6] chore .md file tweak --- internal/verda-cli/cmd/serverless/CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/verda-cli/cmd/serverless/CLAUDE.md b/internal/verda-cli/cmd/serverless/CLAUDE.md index fc15068..bec348e 100644 --- a/internal/verda-cli/cmd/serverless/CLAUDE.md +++ b/internal/verda-cli/cmd/serverless/CLAUDE.md @@ -148,7 +148,7 @@ Describe cards (`renderContainerDeploymentCard`, `renderJobDeploymentCard`) prin - **Scaling preset + legacy rows on describe.** When a deployment was created via the web UI with a custom queue-load (say 10), our CLI shows `custom (10)` rather than a named preset. Don't try to round-trip it back to a named preset — exact threshold wins. - **`ContainerDeployment.Status` is NOT in the `GetDeployments` list response.** The list endpoint returns `ContainerDeployment` without status. We call `GetDeploymentStatus(name)` per-row in `describe`, but NOT in `list` (would N+1). If the web UI grows a bulk status endpoint, wire it in. - **Env-var name validation:** `^[A-Z_][A-Z0-9_]*$`. Lowercase or leading-digit names are rejected client-side in both `parseEnvFlag` and `promptEnvVar`. This is stricter than POSIX (which allows lowercase) but matches Verda's conventions. -- **Env endpoints key on the inner container, not the deployment.** `POST/PATCH/DELETE /container-deployments/{name}/environment-variables` take `container_name` = `Containers[0].Name`, which the API assigns as `-0` on create (we never send a container name). Passing the deployment name returns `not_found` ("A container with the name 'x' does not exist in the deployment 'x'"). `env set`/`env unset` resolve it via `containerNameOf` (one extra GET). The GET response is also grouped per container (`[{container_name, env[]}]`); SDK v1.9.0 `GetEnvironmentVariables` decodes it flat and yields one blank entry per container, so `fetchEnvVars` reads the grouped shape via `client.NewRequest`/`Do` and `envVarsOf` picks the container's group. Drop `fetchEnvVars` once the SDK returns groups. Multi-container deployments: the CLI always targets `Containers[0]`; `env list` warns when more groups exist. Both found live on prod 2026-11-18. +- **Env endpoints key on the inner container, not the deployment.** `POST/PATCH/DELETE /container-deployments/{name}/environment-variables` take `container_name` = `Containers[0].Name`, which the API assigns as `-0` on create (we never send a container name). Passing the deployment name returns `not_found` ("A container with the name 'x' does not exist in the deployment 'x'"). `env set`/`env unset` resolve it via `containerNameOf` (one extra GET). The GET response is also grouped per container (`[{container_name, env[]}]`); SDK `GetEnvironmentVariables` decodes it flat and yields one blank entry per container, so `fetchEnvVars` reads the grouped shape via `client.NewRequest`/`Do` and `envVarsOf` picks the container's group. Drop `fetchEnvVars` once the SDK returns groups. Multi-container deployments: the CLI always targets `Containers[0]`; `env list` warns when more groups exist. Both found live on prod 2026-11-18. - **Secret mount path must be absolute.** `parseSecretMountFlag` and `promptSecretMount` both check `strings.HasPrefix(path, "/")`. No trailing-slash normalization is applied. - **Update commands use fetch-then-merge-then-PATCH.** GET current state, overlay only `cmd.Flags().Changed()` flags, send one PATCH. nil/omitted fields in the request mean "don't change". Container update needs two GETs (deployment + scaling) because `ContainerDeployment` doesn't include scaling; job update needs one (scaling is inline). - **Env merge on update is type-partitioned.** `--env` replaces ALL plain vars and carries all secret vars unchanged; `--env-secret` replaces ALL secret vars and carries all plain vars unchanged. Both flags set → full replacement. Neither → no env field in PATCH. From 4a6dbabf921c60ea57f364bf96e1672085ba135d Mon Sep 17 00:00:00 2001 From: Jaakko Varjo Date: Fri, 20 Nov 2026 12:59:43 +0200 Subject: [PATCH 6/6] fix: env list fix --- internal/verda-cli/cmd/serverless/CLAUDE.md | 2 +- .../verda-cli/cmd/serverless/container_env.go | 46 +++++------ .../serverless/container_env_paths_test.go | 21 ++++- .../cmd/serverless/container_env_test.go | 77 +++++++++++++------ 4 files changed, 95 insertions(+), 51 deletions(-) diff --git a/internal/verda-cli/cmd/serverless/CLAUDE.md b/internal/verda-cli/cmd/serverless/CLAUDE.md index bec348e..ec7c771 100644 --- a/internal/verda-cli/cmd/serverless/CLAUDE.md +++ b/internal/verda-cli/cmd/serverless/CLAUDE.md @@ -148,7 +148,7 @@ Describe cards (`renderContainerDeploymentCard`, `renderJobDeploymentCard`) prin - **Scaling preset + legacy rows on describe.** When a deployment was created via the web UI with a custom queue-load (say 10), our CLI shows `custom (10)` rather than a named preset. Don't try to round-trip it back to a named preset — exact threshold wins. - **`ContainerDeployment.Status` is NOT in the `GetDeployments` list response.** The list endpoint returns `ContainerDeployment` without status. We call `GetDeploymentStatus(name)` per-row in `describe`, but NOT in `list` (would N+1). If the web UI grows a bulk status endpoint, wire it in. - **Env-var name validation:** `^[A-Z_][A-Z0-9_]*$`. Lowercase or leading-digit names are rejected client-side in both `parseEnvFlag` and `promptEnvVar`. This is stricter than POSIX (which allows lowercase) but matches Verda's conventions. -- **Env endpoints key on the inner container, not the deployment.** `POST/PATCH/DELETE /container-deployments/{name}/environment-variables` take `container_name` = `Containers[0].Name`, which the API assigns as `-0` on create (we never send a container name). Passing the deployment name returns `not_found` ("A container with the name 'x' does not exist in the deployment 'x'"). `env set`/`env unset` resolve it via `containerNameOf` (one extra GET). The GET response is also grouped per container (`[{container_name, env[]}]`); SDK `GetEnvironmentVariables` decodes it flat and yields one blank entry per container, so `fetchEnvVars` reads the grouped shape via `client.NewRequest`/`Do` and `envVarsOf` picks the container's group. Drop `fetchEnvVars` once the SDK returns groups. Multi-container deployments: the CLI always targets `Containers[0]`; `env list` warns when more groups exist. Both found live on prod 2026-11-18. +- **Env endpoints key on the inner container, not the deployment.** `POST/PATCH/DELETE /container-deployments/{name}/environment-variables` take `container_name` = `Containers[0].Name`, which the API assigns as `-0` on create (we never send a container name). Passing the deployment name returns `not_found` ("A container with the name 'x' does not exist in the deployment 'x'"). All three env commands resolve it via `containerNameOf` (one extra GET), so `list` reads the same container `set` and `unset` write to. The GET response is also grouped per container (`[{container_name, env[]}]`); SDK `GetEnvironmentVariables` decodes it flat and yields one blank entry per container, so `fetchEnvVars` reads the grouped shape via `client.NewRequest`/`Do` and `envVarsOf` picks the container's group. Drop `fetchEnvVars` once the SDK returns groups. Multi-container deployments: the CLI always targets `Containers[0]`; `env list` warns when the deployment has more than one container (never key the choice on env-GET group order: the groups can come back reordered or miss a container with no vars). Both found live on prod 2026-11-18. - **Secret mount path must be absolute.** `parseSecretMountFlag` and `promptSecretMount` both check `strings.HasPrefix(path, "/")`. No trailing-slash normalization is applied. - **Update commands use fetch-then-merge-then-PATCH.** GET current state, overlay only `cmd.Flags().Changed()` flags, send one PATCH. nil/omitted fields in the request mean "don't change". Container update needs two GETs (deployment + scaling) because `ContainerDeployment` doesn't include scaling; job update needs one (scaling is inline). - **Env merge on update is type-partitioned.** `--env` replaces ALL plain vars and carries all secret vars unchanged; `--env-secret` replaces ALL secret vars and carries all plain vars unchanged. Both flags set → full replacement. Neither → no env field in PATCH. diff --git a/internal/verda-cli/cmd/serverless/container_env.go b/internal/verda-cli/cmd/serverless/container_env.go index c8760b9..d6628fd 100644 --- a/internal/verda-cli/cmd/serverless/container_env.go +++ b/internal/verda-cli/cmd/serverless/container_env.go @@ -32,16 +32,17 @@ const envValueMasked = "***" // containerNameOf: the env endpoints key `container_name` on the container // inside the deployment (the API names it "-0"), not on the -// deployment; sending the deployment name returns not_found. -func containerNameOf(ctx context.Context, client *verda.Client, deployment string) (string, error) { +// deployment; sending the deployment name returns not_found. Multi-container +// deployments always target Containers[0]; count is the deployment's size. +func containerNameOf(ctx context.Context, client *verda.Client, deployment string) (name string, count int, err error) { d, err := client.ContainerDeployments.GetDeploymentByName(ctx, deployment) if err != nil { - return "", err + return "", 0, err } if len(d.Containers) == 0 { - return "", fmt.Errorf("deployment %q has no containers", deployment) + return "", 0, fmt.Errorf("deployment %q has no containers", deployment) } - return d.Containers[0].Name, nil + return d.Containers[0].Name, len(d.Containers), nil } // envVarGroup is one element of the GET environment-variables response, @@ -66,14 +67,17 @@ func fetchEnvVars(ctx context.Context, client *verda.Client, deployment string) return groups, nil } -// envTarget is what an env write needs: the container to key on and its current variables. +// envTarget: the container every env command keys on and its current +// variables. list, set and unset all resolve it the same way so they never +// disagree on which container a multi-container deployment means. type envTarget struct { - Container string - Vars []verda.ContainerEnvVar + Container string + Containers int + Vars []verda.ContainerEnvVar } func loadEnvTarget(ctx context.Context, client *verda.Client, deployment string) (*envTarget, error) { - cn, err := containerNameOf(ctx, client, deployment) + cn, count, err := containerNameOf(ctx, client, deployment) if err != nil { return nil, err } @@ -81,16 +85,13 @@ func loadEnvTarget(ctx context.Context, client *verda.Client, deployment string) if err != nil { return nil, err } - return &envTarget{Container: cn, Vars: envVarsOf(groups, cn)}, nil + return &envTarget{Container: cn, Containers: count, Vars: envVarsOf(groups, cn)}, nil } -// envVarsOf: the variables of container; "" picks the first group. The -// deployment GET and the env GET are separate reads, so the container may be -// missing from the groups (no vars yet, or a lagging read): that is empty, not an error. +// envVarsOf: the variables of container. The deployment GET and the env GET +// are separate reads, so the container may be missing from the groups (no +// vars yet, or a lagging read): that is empty, not an error. func envVarsOf(groups []envVarGroup, container string) []verda.ContainerEnvVar { - if container == "" && len(groups) > 0 { - return groups[0].Env - } for i := range groups { if groups[i].ContainerName == container { return groups[i].Env @@ -145,16 +146,16 @@ func newCmdEnvList(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Comman ctx, cancel := context.WithTimeout(cmd.Context(), f.Options().Timeout) defer cancel() - groups, err := cmdutil.WithSpinner(ctx, f.Status(), "Fetching environment variables...", func(ctx context.Context) ([]envVarGroup, error) { - return fetchEnvVars(ctx, client, name) + target, err := cmdutil.WithSpinner(ctx, f.Status(), "Fetching environment variables...", func(ctx context.Context) (*envTarget, error) { + return loadEnvTarget(ctx, client, name) }) if err != nil { return err } - if len(groups) > 1 { - _, _ = fmt.Fprintf(ioStreams.ErrOut, "Warning: deployment has %d containers; showing %q\n", len(groups), groups[0].ContainerName) + if target.Containers > 1 { + _, _ = fmt.Fprintf(ioStreams.ErrOut, "Warning: deployment has %d containers; showing %q\n", target.Containers, target.Container) } - vars := envVarsOf(groups, "") + vars := target.Vars if wrote, werr := cmdutil.WriteStructured(ioStreams.Out, f.OutputFormat(), vars); wrote { return werr @@ -347,7 +348,8 @@ func newCmdEnvUnset(f cmdutil.Factory, ioStreams cmdutil.IOStreams) *cobra.Comma defer cancel() containerName, err := cmdutil.WithSpinner(ctx, f.Status(), "Loading deployment...", func(ctx context.Context) (string, error) { - return containerNameOf(ctx, client, deployment) + cn, _, err := containerNameOf(ctx, client, deployment) + return cn, err }) if err != nil { return err diff --git a/internal/verda-cli/cmd/serverless/container_env_paths_test.go b/internal/verda-cli/cmd/serverless/container_env_paths_test.go index e459025..3e627fd 100644 --- a/internal/verda-cli/cmd/serverless/container_env_paths_test.go +++ b/internal/verda-cli/cmd/serverless/container_env_paths_test.go @@ -197,6 +197,21 @@ func TestEnvList_FetchError(t *testing.T) { } } +// list resolves the container through the deployment GET like set and unset, +// so an unknown deployment fails there instead of reading someone's env GET. +func TestEnvList_DeploymentLookupError(t *testing.T) { + t.Parallel() + rec := newEnvServer(t, envServerConfig{fail: map[string]int{"GET deployment": http.StatusNotFound}}) + f := newTestFactory(t, rec.srv.URL) + stdout, _, err := runEnv(t, f, "list", "missing") + if err == nil { + t.Fatal("want error from deployment GET, got nil") + } + if stdout != "" { + t.Errorf("want no stdout on failure, got %q", stdout) + } +} + func TestEnvSet_DeploymentLookupError(t *testing.T) { t.Parallel() rec := newEnvServer(t, envServerConfig{fail: map[string]int{"GET deployment": http.StatusNotFound}}) @@ -524,10 +539,10 @@ func TestEnvVarsOf(t *testing.T) { b := []verda.ContainerEnvVar{{Name: "B"}} groups := []envVarGroup{{ContainerName: "x-0", Env: a}, {ContainerName: "y-0", Env: b}} - if got := envVarsOf(nil, ""); got != nil { - t.Errorf("no groups, first: want nil, got %v", got) + if got := envVarsOf(nil, "x-0"); got != nil { + t.Errorf("no groups: want nil, got %v", got) } - if got := envVarsOf(groups, ""); len(got) != 1 || got[0].Name != "A" { + if got := envVarsOf(groups, "x-0"); len(got) != 1 || got[0].Name != "A" { t.Errorf("first group: want A, got %v", got) } if got := envVarsOf(groups, "y-0"); len(got) != 1 || got[0].Name != "B" { diff --git a/internal/verda-cli/cmd/serverless/container_env_test.go b/internal/verda-cli/cmd/serverless/container_env_test.go index f2fc4cc..8f73017 100644 --- a/internal/verda-cli/cmd/serverless/container_env_test.go +++ b/internal/verda-cli/cmd/serverless/container_env_test.go @@ -620,9 +620,17 @@ func TestEnvUnset_AgentMode_RequiresDeployment(t *testing.T) { } } +// multiContainerGroups is the env GET body for the two-container deployment, +// in deployment order; tests pass other orders to show list keys on the +// deployment, not on group position. +var multiContainerGroups = []map[string]any{ + {"container_name": "my-endpoint-0", "env": []verda.ContainerEnvVar{{Name: "MAIN_ONLY", Type: "plain", ValueOrReferenceToSecret: "1"}}}, + {"container_name": "sidecar-1", "env": []verda.ContainerEnvVar{{Name: "SIDE_ONLY", Type: "plain", ValueOrReferenceToSecret: "2"}}}, +} + // newMultiContainerServer serves a two-container deployment whose env groups // differ, so tests can tell which group a command read. -func newMultiContainerServer(t *testing.T) (*httptest.Server, *envRecordingServer) { +func newMultiContainerServer(t *testing.T, groups []map[string]any) (*httptest.Server, *envRecordingServer) { t.Helper() rec := &envRecordingServer{} mux := http.NewServeMux() @@ -639,10 +647,7 @@ func newMultiContainerServer(t *testing.T) (*httptest.Server, *envRecordingServe }) mux.HandleFunc("GET /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(w).Encode([]map[string]any{ - {"container_name": "my-endpoint-0", "env": []verda.ContainerEnvVar{{Name: "MAIN_ONLY", Type: "plain", ValueOrReferenceToSecret: "1"}}}, - {"container_name": "sidecar-1", "env": []verda.ContainerEnvVar{{Name: "SIDE_ONLY", Type: "plain", ValueOrReferenceToSecret: "2"}}}, - }) + _ = json.NewEncoder(w).Encode(groups) }) mux.HandleFunc("POST /container-deployments/{name}/environment-variables", func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) @@ -663,27 +668,49 @@ func newMultiContainerServer(t *testing.T) (*httptest.Server, *envRecordingServe return srv, rec } -// list shows the first container's group and warns that others exist. +// list shows Containers[0] of the deployment, the same container set and +// unset write to, whatever order the env GET returns and even when that +// container has no group yet. The warning counts deployment containers. func TestEnvList_MultiContainer_ShowsFirstAndWarns(t *testing.T) { t.Parallel() - srv, _ := newMultiContainerServer(t) - f := newTestFactory(t, srv.URL) - - var stdout, stderr bytes.Buffer - cmd := NewCmdContainer(f, cmdutil.IOStreams{Out: &stdout, ErrOut: &stderr}) - cmd.SetArgs([]string{"env", "list", "my-endpoint"}) - if err := cmd.Execute(); err != nil { - t.Fatalf("env list failed: %v\nstderr:\n%s", err, stderr.String()) - } - var got []struct{ Name string } - if err := json.Unmarshal(stdout.Bytes(), &got); err != nil { - t.Fatalf("unmarshal: %v\nstdout: %s", err, stdout.String()) - } - if len(got) != 1 || got[0].Name != "MAIN_ONLY" { - t.Errorf("want only MAIN_ONLY from the first group, got %+v", got) - } - if !strings.Contains(stderr.String(), "2 containers") { - t.Errorf("want multi-container warning on stderr, got %q", stderr.String()) + reversed := []map[string]any{multiContainerGroups[1], multiContainerGroups[0]} + firstMissing := []map[string]any{multiContainerGroups[1]} + cases := []struct { + name string + groups []map[string]any + want []string + }{ + {"deployment order", multiContainerGroups, []string{"MAIN_ONLY"}}, + {"reversed order", reversed, []string{"MAIN_ONLY"}}, + {"first container missing", firstMissing, nil}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + srv, _ := newMultiContainerServer(t, tc.groups) + f := newTestFactory(t, srv.URL) + + var stdout, stderr bytes.Buffer + cmd := NewCmdContainer(f, cmdutil.IOStreams{Out: &stdout, ErrOut: &stderr}) + cmd.SetArgs([]string{"env", "list", "my-endpoint"}) + if err := cmd.Execute(); err != nil { + t.Fatalf("env list failed: %v\nstderr:\n%s", err, stderr.String()) + } + var got []struct{ Name string } + if err := json.Unmarshal(stdout.Bytes(), &got); err != nil { + t.Fatalf("unmarshal: %v\nstdout: %s", err, stdout.String()) + } + names := make([]string, 0, len(got)) + for _, v := range got { + names = append(names, v.Name) + } + if strings.Join(names, ",") != strings.Join(tc.want, ",") { + t.Errorf("want vars of my-endpoint-0 %v, got %v", tc.want, names) + } + if !strings.Contains(stderr.String(), `2 containers; showing "my-endpoint-0"`) { + t.Errorf("want multi-container warning naming my-endpoint-0 on stderr, got %q", stderr.String()) + } + }) } } @@ -691,7 +718,7 @@ func TestEnvList_MultiContainer_ShowsFirstAndWarns(t *testing.T) { // another container's: SIDE_ONLY exists only on the sidecar, so it is added. func TestEnvSet_MultiContainer_UsesOwnGroup(t *testing.T) { t.Parallel() - srv, rec := newMultiContainerServer(t) + srv, rec := newMultiContainerServer(t, multiContainerGroups) f := newTestFactory(t, srv.URL) var stdout, stderr bytes.Buffer