Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

fix(cli): honor the atespace flag when applying resources (#415)

ktsoator256b58a67df9
diff --git a/cmd/ax/apply_test.go b/cmd/ax/apply_test.go
index 3641a2a..5d1efd6 100644
--- a/cmd/ax/apply_test.go
+++ b/cmd/ax/apply_test.go
@@ -79,7 +79,7 @@ spec:
}
docNode := node.Content[0]
- kind, name, outcome, err := applyDocument(context.Background(), client, docNode)
+ kind, name, outcome, err := applyDocument(context.Background(), client, docNode, nil)
if err != nil {
t.Fatalf("expected applyDocument to succeed, got: %v", err)
}
@@ -114,7 +114,7 @@ spec:
}
docNode := node.Content[0]
- _, _, _, err := applyDocument(context.Background(), client, docNode)
+ _, _, _, err := applyDocument(context.Background(), client, docNode, nil)
if err == nil {
t.Fatalf("expected error applying to existing task, got nil")
}
diff --git a/cmd/ax/main.go b/cmd/ax/main.go
index dc817d4..5c4e1cc 100644
--- a/cmd/ax/main.go
+++ b/cmd/ax/main.go
@@ -107,7 +107,11 @@ func main() {
switch cmd {
case "apply":
- err = runApply(serverURL, cleanArgs)
+ var atespaceFlag *string
+ if opts.atespaceExplicit {
+ atespaceFlag = &atespace
+ }
+ err = runApply(serverURL, atespaceFlag, cleanArgs)
case "get":
err = runGet(serverURL, atespace, cleanArgs)
case "describe":
@@ -137,12 +141,13 @@ func main() {
// globalArgs holds the command name, the flags shared by every command, and the
// remaining arguments for the command itself.
type globalArgs struct {
- cmd string
- args []string
- atespace string
- server string
- kubeContext string
- namespace string
+ cmd string
+ args []string
+ atespace string
+ atespaceExplicit bool
+ server string
+ kubeContext string
+ namespace string
}
// parseGlobalArgs extracts the command name and the global flags from args. It
@@ -158,10 +163,12 @@ func parseGlobalArgs(args []string) globalArgs {
} else if arg == "-a" || arg == "--atespace" {
if i+1 < len(args) {
g.atespace = args[i+1]
+ g.atespaceExplicit = true
i++
}
} else if strings.HasPrefix(arg, "--atespace=") {
g.atespace = strings.TrimPrefix(arg, "--atespace=")
+ g.atespaceExplicit = true
} else if arg == "--server" {
if i+1 < len(args) {
g.server = args[i+1]
@@ -238,7 +245,8 @@ func getAXClient(serverURL string) (v1alpha1.AXClient, *grpc.ClientConn, error)
return v1alpha1.NewAXClient(conn), conn, nil
}
-func runApply(serverURL string, args []string) error {
+// A nil atespace leaves manifest atespaces unchanged and lets the server default missing ones.
+func runApply(serverURL string, atespace *string, args []string) error {
data, ok, err := manifestFromArgs(args)
if err != nil {
return err
@@ -278,7 +286,7 @@ func runApply(serverURL string, args []string) error {
}
}
- kind, name, outcome, err := applyDocument(ctx, client, &doc)
+ kind, name, outcome, err := applyDocument(ctx, client, &doc, atespace)
if err != nil {
return fmt.Errorf("applying document %d: %w", docIndex, err)
}
@@ -287,9 +295,9 @@ func runApply(serverURL string, args []string) error {
}
// applyDocument decodes one manifest by its kind and submits it with the matching
-// Update RPC. It reports the kind, the resource name, and whether the resource was
+// RPC. It reports the kind, the resource name, and whether the resource was
// created, configured (spec changed), or unchanged, in the style of kubectl apply.
-func applyDocument(ctx context.Context, client v1alpha1.AXClient, doc *yaml.Node) (kind, name, outcome string, err error) {
+func applyDocument(ctx context.Context, client v1alpha1.AXClient, doc *yaml.Node, atespace *string) (kind, name, outcome string, err error) {
var head struct {
Kind string `yaml:"kind"`
}
@@ -303,6 +311,9 @@ func applyDocument(ctx context.Context, client v1alpha1.AXClient, doc *yaml.Node
if err := doc.Decode(&task); err != nil {
return "", "", "", err
}
+ if err := setApplyAtespace(task.Metadata, atespace); err != nil {
+ return "", "", "", err
+ }
res, err := client.CreateTask(ctx, &v1alpha1.CreateTaskRequest{Task: &task})
if err != nil {
return "", "", "", err
@@ -314,6 +325,9 @@ func applyDocument(ctx context.Context, client v1alpha1.AXClient, doc *yaml.Node
if err := doc.Decode(&ws); err != nil {
return "", "", "", err
}
+ if err := setApplyAtespace(ws.Metadata, atespace); err != nil {
+ return "", "", "", err
+ }
existing, err := client.GetWorkspace(ctx, &v1alpha1.GetWorkspaceRequest{Atespace: ws.GetMetadata().GetAtespace(), Name: ws.GetMetadata().GetName()})
outcome, err := applyOutcome(err, existing.GetSpec(), ws.GetSpec())
if err != nil {
@@ -327,6 +341,9 @@ func applyDocument(ctx context.Context, client v1alpha1.AXClient, doc *yaml.Node
if err := doc.Decode(&m); err != nil {
return "", "", "", err
}
+ if err := setApplyAtespace(m.Metadata, atespace); err != nil {
+ return "", "", "", err
+ }
existing, err := client.GetModel(ctx, &v1alpha1.GetModelRequest{Atespace: m.GetMetadata().GetAtespace(), Name: m.GetMetadata().GetName()})
outcome, err := applyOutcome(err, existing.GetSpec(), m.GetSpec())
if err != nil {
@@ -342,6 +359,18 @@ func applyDocument(ctx context.Context, client v1alpha1.AXClient, doc *yaml.Node
}
}
+// setApplyAtespace fills a missing atespace or rejects a mismatch with an explicit flag.
+func setApplyAtespace(meta *v1alpha1.ObjectMeta, atespace *string) error {
+ if meta == nil || atespace == nil {
+ return nil
+ }
+ if meta.Atespace != "" && meta.Atespace != *atespace {
+ return fmt.Errorf("metadata.atespace %q does not match --atespace %q", meta.Atespace, *atespace)
+ }
+ meta.Atespace = *atespace
+ return nil
+}
+
// applyOutcome classifies an apply from the result of looking up the existing
// resource: "created" when it did not exist, "unchanged" when its spec already
// matches, and "configured" otherwise. Lookup failures other than NotFound are
@@ -434,7 +463,6 @@ func runGet(serverURL, atespace string, args []string) error {
return yaml.NewEncoder(os.Stdout).Encode(task)
}
-
if (resource == "workspaces" || resource == "workspace") && len(args) == 1 {
resp, err := client.ListWorkspaces(ctx, &v1alpha1.ListWorkspacesRequest{Atespace: atespace})
if err != nil {
@@ -641,7 +669,6 @@ func runDescribe(serverURL, atespace string, args []string) error {
return nil
}
-
task, err := client.GetTask(ctx, &v1alpha1.GetTaskRequest{Atespace: atespace, Name: name})
if err != nil {
return fmt.Errorf("getting task %q: %w", name, err)
diff --git a/cmd/ax/main_test.go b/cmd/ax/main_test.go
index c0b7785..df96280 100644
--- a/cmd/ax/main_test.go
+++ b/cmd/ax/main_test.go
@@ -17,8 +17,10 @@ package main
import (
"context"
"errors"
+ "fmt"
"net"
"os"
+ "os/exec"
"path/filepath"
"reflect"
"strings"
@@ -34,6 +36,103 @@ import (
"gopkg.in/yaml.v3"
)
+func TestApplyAtespace(t *testing.T) {
+ // Exercise flag parsing and dispatch as well as the resource RPCs.
+ binary := filepath.Join(t.TempDir(), "ax")
+ if output, err := exec.Command("go", "build", "-o", binary, ".").CombinedOutput(); err != nil {
+ t.Fatalf("building CLI: %v\n%s", err, output)
+ }
+ for _, kind := range []string{"Task", "Workspace", "Model"} {
+ for _, tc := range []struct {
+ name string
+ manifestAtespace string
+ flags []string
+ wantAtespace string
+ wantErr string
+ }{
+ {name: "default", wantAtespace: "default"},
+ {name: "flag only", flags: []string{"-a", "team-a"}, wantAtespace: "team-a"},
+ {name: "manifest only", manifestAtespace: "team-a", wantAtespace: "team-a"},
+ {name: "matching", manifestAtespace: "team-a", flags: []string{"--atespace", "team-a"}, wantAtespace: "team-a"},
+ {name: "conflicting", manifestAtespace: "team-a", flags: []string{"--atespace=team-b"}, wantErr: `metadata.atespace "team-a" does not match --atespace "team-b"`},
+ {name: "explicit default", manifestAtespace: "team-a", flags: []string{"-a", "default"}, wantErr: `metadata.atespace "team-a" does not match --atespace "default"`},
+ } {
+ t.Run(kind+"/"+tc.name, func(t *testing.T) {
+ s := memory.NewStore()
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := server.NewServer(s).GRPCServer()
+ t.Cleanup(srv.Stop)
+ go func() { _ = srv.Serve(listener) }()
+
+ path := filepath.Join(t.TempDir(), "resource.yaml")
+ manifest := fmt.Sprintf("apiVersion: ax.io/v1alpha1\nkind: %s\nmetadata:\n name: example\n", kind)
+ if tc.manifestAtespace != "" {
+ manifest += fmt.Sprintf(" atespace: %q\n", tc.manifestAtespace)
+ }
+ manifest += "spec: {}\n"
+ if err := os.WriteFile(path, []byte(manifest), 0600); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ args := append([]string{"--server", listener.Addr().String(), "apply", "-f", path}, tc.flags...)
+ output, err := exec.CommandContext(ctx, binary, args...).CombinedOutput()
+ if tc.wantErr != "" {
+ var exitErr *exec.ExitError
+ if !errors.As(err, &exitErr) || exitErr.ExitCode() != 1 || !strings.Contains(string(output), tc.wantErr) {
+ t.Fatalf("expected exit 1 with %q, got %v\n%s", tc.wantErr, err, output)
+ }
+ } else {
+ wantOutput := strings.ToLower(kind) + ".ax.io/example created\n"
+ if err != nil || string(output) != wantOutput {
+ t.Fatalf("expected %q, got %v\n%s", wantOutput, err, output)
+ }
+ // Tasks are immutable; other resources remain unchanged on reapply.
+ output, err = exec.CommandContext(ctx, binary, args...).CombinedOutput()
+ if kind == "Task" {
+ var exitErr *exec.ExitError
+ wantErr := fmt.Sprintf("code = FailedPrecondition desc = task %s/example already exists and is immutable", tc.wantAtespace)
+ if !errors.As(err, &exitErr) || exitErr.ExitCode() != 1 || !strings.Contains(string(output), wantErr) {
+ t.Fatalf("expected exit 1 with %q on reapply, got %v\n%s", wantErr, err, output)
+ }
+ } else {
+ wantOutput = strings.ToLower(kind) + ".ax.io/example unchanged\n"
+ if err != nil || string(output) != wantOutput {
+ t.Fatalf("expected %q on reapply, got %v\n%s", wantOutput, err, output)
+ }
+ }
+ }
+
+ for _, atespace := range []string{"default", "team-a", "team-b"} {
+ var meta *v1alpha1.ObjectMeta
+ var getErr error
+ switch kind {
+ case "Task":
+ resource, err := s.GetTask(ctx, atespace, "example")
+ meta, getErr = resource.GetMetadata(), err
+ case "Workspace":
+ resource, err := s.GetWorkspace(ctx, atespace, "example")
+ meta, getErr = resource.GetMetadata(), err
+ case "Model":
+ resource, err := s.GetModel(ctx, atespace, "example")
+ meta, getErr = resource.GetMetadata(), err
+ }
+ if atespace == tc.wantAtespace {
+ if getErr != nil || meta.GetAtespace() != atespace {
+ t.Errorf("expected resource in %q, got metadata %v, error %v", atespace, meta, getErr)
+ }
+ } else if !errors.Is(getErr, store.ErrNotFound) {
+ t.Errorf("expected no resource in %q, got metadata %v, error %v", atespace, meta, getErr)
+ }
+ }
+ })
+ }
+ }
+}
+
func TestRunApplyEmptyDocuments(t *testing.T) {
const first = "apiVersion: ax.io/v1alpha1\nkind: Workspace\nmetadata:\n name: first\nspec: {}\n"
second := strings.Replace(first, "name: first", "name: second", 1)
@@ -81,7 +180,7 @@ func TestRunApplyEmptyDocuments(t *testing.T) {
_ = output.Close()
})
- runErr := runApply(listener.Addr().String(), []string{"-f", path})
+ runErr := runApply(listener.Addr().String(), nil, []string{"-f", path})
if tc.wantErr == "" {
if runErr != nil {
t.Fatal(runErr)
@@ -289,26 +388,57 @@ func TestParseGlobalArgs(t *testing.T) {
{
name: "flags before and after the command",
args: []string{"-a", "team", "get", "tasks", "--namespace=ax"},
- want: globalArgs{cmd: "get", args: []string{"tasks"}, atespace: "team", namespace: "ax"},
+ want: globalArgs{cmd: "get", args: []string{"tasks"}, atespace: "team", atespaceExplicit: true, namespace: "ax"},
+ },
+ {
+ name: "omitted atespace is not explicit",
+ args: []string{"apply", "-f", "resource.yaml"},
+ want: globalArgs{cmd: "apply", args: []string{"-f", "resource.yaml"}, atespace: "default", namespace: "ax-system"},
+ },
+ {
+ name: "explicit default atespace",
+ args: []string{"apply", "-a", "default"},
+ want: globalArgs{cmd: "apply", atespace: "default", atespaceExplicit: true, namespace: "ax-system"},
+ },
+ {
+ name: "long atespace flag",
+ args: []string{"apply", "--atespace", "team"},
+ want: globalArgs{cmd: "apply", atespace: "team", atespaceExplicit: true, namespace: "ax-system"},
+ },
+ {
+ name: "atespace with equals",
+ args: []string{"apply", "--atespace=team"},
+ want: globalArgs{cmd: "apply", atespace: "team", atespaceExplicit: true, namespace: "ax-system"},
+ },
+ {
+ name: "explicit default with equals",
+ args: []string{"apply", "--atespace=default"},
+ want: globalArgs{cmd: "apply", atespace: "default", atespaceExplicit: true, namespace: "ax-system"},
+ },
+ {
+ name: "last atespace flag wins",
+ args: []string{"-a", "team", "apply", "--atespace=default"},
+ want: globalArgs{cmd: "apply", atespace: "default", atespaceExplicit: true, namespace: "ax-system"},
},
{
name: "flags after -- belong to the remote command",
- args: []string{"ssh", "task123", "--", "grep", "-n", "foo", "-a", "file"},
+ args: []string{"ssh", "task123", "--", "cmd", "-n", "foo", "-a", "file", "--atespace", "remote", "--atespace=remote"},
want: globalArgs{
cmd: "ssh",
- args: []string{"task123", "--", "grep", "-n", "foo", "-a", "file"},
+ args: []string{"task123", "--", "cmd", "-n", "foo", "-a", "file", "--atespace", "remote", "--atespace=remote"},
atespace: "default",
namespace: "ax-system",
},
},
{
name: "global flags before -- still apply",
- args: []string{"ssh", "-a", "team", "task123", "--", "ls", "--context=x"},
+ args: []string{"ssh", "-a", "team", "task123", "--", "cmd", "--context=x", "--atespace=remote"},
want: globalArgs{
- cmd: "ssh",
- args: []string{"task123", "--", "ls", "--context=x"},
- atespace: "team",
- namespace: "ax-system",
+ cmd: "ssh",
+ args: []string{"task123", "--", "cmd", "--context=x", "--atespace=remote"},
+ atespace: "team",
+ atespaceExplicit: true,
+ namespace: "ax-system",
},
},
}
diff --git a/docs/manifests.md b/docs/manifests.md
index b066455..c721277 100644
--- a/docs/manifests.md
+++ b/docs/manifests.md
@@ -4,6 +4,8 @@ All four kinds can live in one multi-document YAML file. See [`examples/task.yam
`metadata.name` and `metadata.atespace` become Substrate resource names, so they must be lowercase RFC 1123 labels: at most 63 lowercase alphanumeric characters or `-`, starting and ending with an alphanumeric character. `ax apply` rejects anything else up front rather than letting the task fail later with `ActorCreationFailed`.
+When `metadata.atespace` is omitted, `ax apply -a team-a -f manifest.yaml` uses `team-a`. Without `-a` or `--atespace`, the manifest's atespace is preserved, or defaults to `default` if omitted. If an explicit flag disagrees with `metadata.atespace`, that resource is rejected before it is submitted.
+
## Task
```yaml