Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(cli): handle large runtime deletion conflicts (#10213)
Danila Katalshov305ee22bfb3b
diff --git a/server/cmd/multica/cmd_runtime.go b/server/cmd/multica/cmd_runtime.goindex 84a9e3beb9..345b4461b3 100644--- a/server/cmd/multica/cmd_runtime.go+++ b/server/cmd/multica/cmd_runtime.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "io""net/http""os""strconv"@@ -236,26 +237,25 @@ func runRuntimeDelete(cmd *cobra.Command, args []string) error {ctx, cancel := cli.APIContext(context.Background())defer cancel()- err = client.DeleteJSON(ctx, "/api/runtimes/"+runtimeID)- if err == nil {+ var conflict runtimeDeleteConflictPayload+ hadConflict := false+ err = client.DeleteJSONWithConflict(ctx, "/api/runtimes/"+runtimeID, func(body io.Reader) error {+ hadConflict = true+ return readRuntimeDeleteConflict(body, &conflict)+ })+ if err != nil {+ if hadConflict {+ return err+ }+ return fmt.Errorf("delete runtime: %w", err)+ }+ if !hadConflict {return printRuntimeDeleteResult(cmd, map[string]any{"id": runtimeID,"deleted": true,})}- conflict, ok := runtimeDeleteConflict(err)- if !ok {- // Any other 409 is a deliberate, already-explained refusal — most often- // a profile-backed instance that cannot be deleted on its own. Show the- // server's guidance instead of a raw HTTP wrapper; --cascade cannot get- // past these, so there is nothing more for this command to try.- if _, msg, isConflict := serverConflictMessage(err); isConflict {- return errors.New(msg)- }- return fmt.Errorf("delete runtime: %w", err)- }-cascade, _ := cmd.Flags().GetBool("cascade")if !cascade {return fmt.Errorf(@@ -269,6 +269,18 @@ func runRuntimeDelete(cmd *cobra.Command, args []string) error {}var result map[string]anyif err := client.PostJSON(ctx, "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete", body, &result); err != nil {+ var httpErr *cli.HTTPError+ if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusConflict {+ // A changed plan includes fresh agent instructions. Do not retain+ // that body in the error chain, even for --debug output.+ var refusal struct {+ Error string `json:"error"`+ }+ if json.Unmarshal([]byte(httpErr.Body), &refusal) == nil && refusal.Error != "" {+ return fmt.Errorf("cascade delete runtime: %s", refusal.Error)+ }+ return errors.New("cascade delete runtime: server refused confirmation; recheck active-agent bindings and retry")+ }return fmt.Errorf("cascade delete runtime: %w", err)}result["id"] = runtimeID@@ -463,19 +475,29 @@ type runtimeDeleteConflictPayload struct {} `json:"active_agents"`}-func runtimeDeleteConflict(err error) (runtimeDeleteConflictPayload, bool) {- var httpErr *cli.HTTPError- if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {- return runtimeDeleteConflictPayload{}, false- }- var payload runtimeDeleteConflictPayload- if json.Unmarshal([]byte(httpErr.Body), &payload) != nil {- return runtimeDeleteConflictPayload{}, false+func readRuntimeDeleteConflict(body io.Reader, payload *runtimeDeleteConflictPayload) error {+ // This response contains full agent representations. Read the entire+ // snapshot within a bounded budget; never confirm a truncated list.+ const maxSnapshotBytes = 8 << 20+ data, err := io.ReadAll(io.LimitReader(body, maxSnapshotBytes+1))+ if err != nil || len(data) > maxSnapshotBytes {+ return errors.New("delete runtime: cannot read the complete active-agent snapshot; rebind agents before retrying")+ }+ if err := json.Unmarshal(data, payload); err != nil {+ // An invalid response can still contain agent instructions. Do not+ // print it as plain text or confirm a partial snapshot.+ return errors.New("delete runtime: invalid conflict response; no agents were unbound")+ }+ if payload.Code != "runtime_has_active_agents" {+ if payload.Error != "" {+ return errors.New(payload.Error)+ }+ return errors.New("delete runtime: server refused the request without an explanation")}- if payload.Code != "runtime_has_active_agents" || len(payload.ActiveAgents) == 0 {- return runtimeDeleteConflictPayload{}, false+ if len(payload.ActiveAgents) == 0 || len(payload.AgentIDs()) != len(payload.ActiveAgents) {+ return errors.New("delete runtime: incomplete active-agent snapshot; no agents were unbound")}- return payload, true+ return nil}func (p runtimeDeleteConflictPayload) AgentIDs() []string {diff --git a/server/cmd/multica/cmd_runtime_test.go b/server/cmd/multica/cmd_runtime_test.goindex 5369ecefb2..a979425a2f 100644--- a/server/cmd/multica/cmd_runtime_test.go+++ b/server/cmd/multica/cmd_runtime_test.go@@ -9,6 +9,7 @@ import ("strings""testing"+ "github.com/multica-ai/multica/server/internal/cli""github.com/spf13/cobra")@@ -143,8 +144,8 @@ func TestRunRuntimeDeleteCascadeConfirmsActiveAgentSnapshot(t *testing.T) {"code": "runtime_has_active_agents","error": "cannot delete runtime: it has active agents bound to it.","active_agents": []map[string]any{- {"id": "agent-1", "name": "Codex"},- {"id": "agent-2", "name": "Claude"},+ {"id": "agent-1", "name": "Codex", "instructions": strings.Repeat("a", 40<<10)},+ {"id": "agent-2", "name": "Claude", "instructions": strings.Repeat("b", 40<<10)},},})case r.Method == http.MethodPost && r.URL.Path == "/api/runtimes/rt-1/unbind-agents-and-delete":@@ -247,6 +248,76 @@ func TestRunRuntimeDeleteConflictWithoutMessageKeepsWrapper(t *testing.T) {}}+func TestRuntimeDeleteDoesNotConfirmIncompleteSnapshot(t *testing.T) {+ redirectTestHome(t, t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ const marker = "fixture-instruction"+ for _, tc := range []struct {+ name, body string+ }{+ {"oversized", `{"active_agents":[{"id":"agent-1","instructions":"` + marker + strings.Repeat("a", 8<<20) + `"}],"code":"runtime_has_active_agents"}`},+ {"truncated", `{"active_agents":[{"instructions":"` + marker},+ {"JSON with BOM", "\ufeff" + `{"error":"` + marker + `"}`},+ {"JSON string", `"` + marker + `"`},+ {"proxy plaintext", "proxy: " + marker},+ {"missing ID", `{"code":"runtime_has_active_agents","active_agents":[{"id":"agent-1"},{"name":"second"}]}`},+ } {+ t.Run(tc.name, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodDelete {+ t.Errorf("unexpected confirmation request: %s %s", r.Method, r.URL.Path)+ }+ w.WriteHeader(http.StatusConflict)+ _, _ = io.WriteString(w, tc.body)+ }))+ defer srv.Close()++ cmd := newRuntimeDeleteTestCmd(srv.URL)+ _ = cmd.Flags().Set("cascade", "true")+ err := runRuntimeDelete(cmd, []string{"rt-1"})+ if err == nil || strings.Contains(err.Error(), marker) {+ t.Fatal("expected a safe error without agent instructions")+ }+ })+ }+}++func TestRuntimeDeleteCascadeRefusalDoesNotExposeInstructions(t *testing.T) {+ redirectTestHome(t, t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ const marker = "private-instruction-fixture"+ for _, tc := range []struct{ name, body string }{+ {"complete JSON", `{"code":"runtime_delete_plan_changed","error":"bindings changed","active_agents":[{"instructions":"` + marker + `"}]}`},+ {"large JSON", `{"code":"runtime_delete_plan_changed","error":"bindings changed","active_agents":[{"instructions":"` + marker + strings.Repeat("a", 80<<10) + `"}]}`},+ {"malformed JSON", `{"active_agents":[{"instructions":"` + marker},+ {"proxy plaintext", "proxy: " + marker},+ } {+ t.Run(tc.name, func(t *testing.T) {+ deletes, confirmations := 0, 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusConflict)+ if r.Method == http.MethodDelete {+ deletes+++ _, _ = io.WriteString(w, `{"code":"runtime_has_active_agents","active_agents":[{"id":"agent-1"}]}`)+ return+ }+ confirmations+++ _, _ = io.WriteString(w, tc.body)+ }))+ defer srv.Close()+ cmd := newRuntimeDeleteTestCmd(srv.URL)+ _ = cmd.Flags().Set("cascade", "true")+ err := runRuntimeDelete(cmd, []string{"rt-1"})+ if err == nil || strings.Contains(cli.FormatError(err, true), marker) {+ t.Fatal("expected a safe cascade refusal, including debug output")+ }+ if deletes != 1 || confirmations != 1 {+ t.Fatalf("requests DELETE/POST=%d/%d, want 1/1 without retry", deletes, confirmations)+ }+ })+ }+}+func newRuntimeUpdateTestCmd(serverURL, output string) *cobra.Command {cmd := &cobra.Command{Use: "update"}cmd.Flags().String("server-url", "", "")diff --git a/server/internal/cli/client.go b/server/internal/cli/client.goindex 8d7764ae30..7d60728710 100644--- a/server/internal/cli/client.go+++ b/server/internal/cli/client.go@@ -323,6 +323,17 @@ func (c *APIClient) DeleteJSON(ctx context.Context, path string) error {// DeleteJSONResponse performs a DELETE request and optionally decodes the JSON response.func (c *APIClient) DeleteJSONResponse(ctx context.Context, path string, out any) error {+ return c.deleteJSON(ctx, path, out, nil)+}++// DeleteJSONWithConflict lets callers consume a structured 409 in full before+// deciding whether a follow-up request is safe. Other HTTP errors use the+// usual bounded diagnostic body.+func (c *APIClient) DeleteJSONWithConflict(ctx context.Context, path string, onConflict func(io.Reader) error) error {+ return c.deleteJSON(ctx, path, nil, onConflict)+}++func (c *APIClient) deleteJSON(ctx context.Context, path string, out any, onConflict func(io.Reader) error) error {req, err := http.NewRequestWithContext(ctx, http.MethodDelete, c.BaseURL+path, nil)if err != nil {return err@@ -336,6 +347,9 @@ func (c *APIClient) DeleteJSONResponse(ctx context.Context, path string, out any}defer resp.Body.Close()+ if resp.StatusCode == http.StatusConflict && onConflict != nil {+ return onConflict(resp.Body)+ }if resp.StatusCode >= 400 {return newHTTPError(http.MethodDelete, path, resp)}