diff --git a/cmd/model/removeModel.go b/cmd/model/removeModel.go index 1ef28a95..443390af 100644 --- a/cmd/model/removeModel.go +++ b/cmd/model/removeModel.go @@ -1,7 +1,11 @@ package model import ( + "encoding/json" + "errors" "fmt" + "io" + "net/http" "strings" "github.com/runpod/runpodctl/api" @@ -21,15 +25,177 @@ var ( getModelForRemove = api.GetModel removeModelFromRepo = api.RemoveModel updateModelVersionStatusByIdentifier = api.UpdateModelVersionStatusByIdentifier + listDependentEndpoints = defaultListDependentEndpoints ) +// DependentEndpoint identifies a serverless endpoint whose model reference +// points at a Model Repo model/version that is about to be removed. +type DependentEndpoint struct { + ID string + Name string +} + +// dependentEndpointsError blocks a removal because active endpoints still +// reference the model/version. There is no override: a model/version that is +// in use cannot be removed at all. ErrorCode gives agents a stable, machine +// readable way to detect this specific condition rather than parsing the +// message string. +type dependentEndpointsError struct { + endpoints []DependentEndpoint +} + +func (e *dependentEndpointsError) Error() string { + return fmt.Sprintf( + "cannot remove: %d endpoint(s) reference this model: %s. detach or replace it first with 'runpodctl serverless update --clear-models' (or --model-reference ), then retry", + len(e.endpoints), formatDependentEndpoints(e.endpoints), + ) +} + +func (e *dependentEndpointsError) ErrorCode() string { return "dependent_endpoints" } + +func formatDependentEndpoints(endpoints []DependentEndpoint) string { + parts := make([]string, len(endpoints)) + for i, ep := range endpoints { + name := ep.Name + if name == "" { + name = ep.ID + } + parts[i] = fmt.Sprintf("%s (%s)", ep.ID, name) + } + return strings.Join(parts, ", ") +} + +// defaultListDependentEndpoints lists serverless endpoints whose model +// references point at the given Model Repo model (owner/name), optionally +// pinned to a specific version hash. Pass hash="" to match any version of the +// model (used when removing the whole model rather than a single version). +// +// This goes through the GraphQL api (api.Query), not internal/api's REST +// client: verified live that REST GET /v1/endpoints and /v1/endpoints/{id} +// never include modelReferences at all (confirmed by inspecting the raw REST +// response for a real endpoint), so ListEndpoints() would silently find zero +// dependents every time. modelReferences is exposed via GraphQL, e.g. +// myself { endpoints { modelReferences } }. +func defaultListDependentEndpoints(owner, name, hash string) ([]DependentEndpoint, error) { + gqlInput := api.Input{ + Query: ` + query listEndpointsForModelDependencyCheck { + myself { + endpoints { + id + name + modelReferences + } + } + } + `, + } + + res, err := api.Query(gqlInput) + if err != nil { + return nil, err + } + defer res.Body.Close() + + rawData, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("statuscode %d: %s", res.StatusCode, string(rawData)) + } + + var data struct { + Data *struct { + Myself *struct { + Endpoints []struct { + ID string `json:"id"` + Name string `json:"name"` + ModelReferences []string `json:"modelReferences"` + } `json:"endpoints"` + } `json:"myself"` + } `json:"data"` + Errors []*api.GraphQLError `json:"errors"` + } + if err := json.Unmarshal(rawData, &data); err != nil { + return nil, err + } + if len(data.Errors) > 0 { + return nil, errors.New(data.Errors[0].Message) + } + if data.Data == nil || data.Data.Myself == nil { + return nil, fmt.Errorf("data is nil: %s", string(rawData)) + } + + var dependents []DependentEndpoint + for _, ep := range data.Data.Myself.Endpoints { + for _, ref := range ep.ModelReferences { + if modelReferenceMatches(ref, owner, name, hash) { + dependents = append(dependents, DependentEndpoint{ID: ep.ID, Name: ep.Name}) + break + } + } + } + + return dependents, nil +} + +// modelReferenceMatches reports whether an endpoint's model reference string +// points at the given Model Repo model/version. Model Repo references are +// emitted client-side as "https://local//:" (see +// formatModelURL), but verified live against prod that the backend persists +// the scheme+host in uppercase ("https://LOCAL/..."). The prefix comparison is +// therefore case-insensitive; the owner/name/hash path segments stay +// case-sensitive exact matches. +func modelReferenceMatches(ref, owner, name, hash string) bool { + const schemeHost = "https://local/" + if len(ref) < len(schemeHost) || !strings.EqualFold(ref[:len(schemeHost)], schemeHost) { + return false + } + + path := ref[len(schemeHost):] + prefix := owner + "/" + name + ":" + if !strings.HasPrefix(path, prefix) { + return false + } + + if hash == "" { + return true + } + return path[len(prefix):] == hash +} + +// checkDependentEndpoints looks up endpoints that reference owner/name +// (optionally pinned to hash) and blocks the removal if any are found. There +// is no override for this: a model/version in active use cannot be removed. +// A failure to complete the check itself blocks the removal too — if we +// cannot verify it is safe, it is not safe to proceed. +func checkDependentEndpoints(owner, name, hash string) error { + dependents, err := listDependentEndpoints(owner, name, hash) + if err != nil { + return fmt.Errorf("failed to check for dependent endpoints, refusing to remove: %w", err) + } + + if len(dependents) == 0 { + return nil + } + + return &dependentEndpointsError{endpoints: dependents} +} + var removeCmd = &cobra.Command{ Use: "remove", Aliases: []string{"rm", "delete"}, Args: cobra.ExactArgs(0), Short: "remove a model", - Long: "remove a model from the runpod model repository", - RunE: runRemoveModel, + Long: "remove a model from the runpod model repository. blocked if any endpoints still reference it — a model/version in active use cannot be removed.", + Example: ` # blocked if an endpoint still references this model, listing which one(s) + runpodctl model remove --owner --name my-model + + # detach it from the endpoint first, then remove + runpodctl serverless update --clear-models + runpodctl model remove --owner --name my-model`, + RunE: runRemoveModel, } var RemoveModelCmd = &cobra.Command{ @@ -73,6 +239,9 @@ func runRemoveModel(cmd *cobra.Command, args []string) error { if hash != "" || version != "" { result, err = removeModelVersion(removeOwner, removeName, hash, version) } else { + if err := checkDependentEndpoints(removeOwner, removeName, ""); err != nil { + return err + } input := &api.RemoveModelInput{ Owner: removeOwner, Name: removeName, @@ -106,6 +275,13 @@ func removeModelVersion(owner, name, hash, version string) (*api.ModelRepoMutati return nil, fmt.Errorf("model version %q not found for %s/%s", version, owner, name) } + // endpoints reference a version by its hash (see formatModelURL), so the + // dependent-endpoint check always keys off target.Hash regardless of + // whether the caller identified the version by --hash or --version. + if err := checkDependentEndpoints(owner, name, target.Hash); err != nil { + return nil, err + } + input := &api.UpdateModelVersionStatusInput{ Status: api.ModelVersionStatusPodRemoved, } diff --git a/cmd/model/removeModel_test.go b/cmd/model/removeModel_test.go index bb8eef9c..4643ddbb 100644 --- a/cmd/model/removeModel_test.go +++ b/cmd/model/removeModel_test.go @@ -1,6 +1,7 @@ package model import ( + "errors" "testing" "github.com/runpod/runpodctl/api" @@ -80,9 +81,11 @@ func TestRemoveModelVersionUpdatesTargetVersion(t *testing.T) { t.Run(tt.name, func(t *testing.T) { originalGet := getModelForRemove originalUpdate := updateModelVersionStatusByIdentifier + originalList := listDependentEndpoints t.Cleanup(func() { getModelForRemove = originalGet updateModelVersionStatusByIdentifier = originalUpdate + listDependentEndpoints = originalList }) getModelForRemove = func(input *api.GetModelInput) (*api.Model, error) { @@ -92,6 +95,10 @@ func TestRemoveModelVersionUpdatesTargetVersion(t *testing.T) { return tt.model, nil } + listDependentEndpoints = func(owner, name, hash string) ([]DependentEndpoint, error) { + return nil, nil + } + updateModelVersionStatusByIdentifier = func(input *api.UpdateModelVersionStatusInput) (*api.ModelVersion, error) { if input.Hash != tt.wantHash || input.UUID != tt.wantUUID || input.Status != api.ModelVersionStatusPodRemoved { t.Fatalf("unexpected update input: %#v", input) @@ -112,3 +119,126 @@ func TestRemoveModelVersionUpdatesTargetVersion(t *testing.T) { }) } } + +func TestModelReferenceMatches(t *testing.T) { + tests := []struct { + name string + ref string + owner string + model string + hash string + want bool + }{ + { + name: "exact match lowercase scheme", + ref: "https://local/owner/name:hash", + owner: "owner", + model: "name", + hash: "hash", + want: true, + }, + { + name: "exact match uppercase scheme+host as persisted by the backend", + ref: "https://LOCAL/owner/name:hash", + owner: "owner", + model: "name", + hash: "hash", + want: true, + }, + { + name: "whole-model match ignores hash when hash is empty", + ref: "https://LOCAL/owner/name:some-other-hash", + owner: "owner", + model: "name", + hash: "", + want: true, + }, + { + name: "different hash does not match when hash is pinned", + ref: "https://LOCAL/owner/name:some-other-hash", + owner: "owner", + model: "name", + hash: "hash", + want: false, + }, + { + name: "different owner does not match", + ref: "https://LOCAL/other-owner/name:hash", + owner: "owner", + model: "name", + hash: "hash", + want: false, + }, + { + name: "huggingface passthrough reference never matches (not a model repo entry)", + ref: "https://huggingface.co/owner/name:hash", + owner: "owner", + model: "name", + hash: "hash", + want: false, + }, + { + name: "name prefix collision does not match (name vs name-2)", + ref: "https://LOCAL/owner/name-2:hash", + owner: "owner", + model: "name", + hash: "", + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := modelReferenceMatches(tt.ref, tt.owner, tt.model, tt.hash) + if got != tt.want { + t.Fatalf("modelReferenceMatches(%q, %q, %q, %q) = %v, want %v", tt.ref, tt.owner, tt.model, tt.hash, got, tt.want) + } + }) + } +} + +func TestCheckDependentEndpoints(t *testing.T) { + t.Run("no dependents proceeds silently", func(t *testing.T) { + originalList := listDependentEndpoints + t.Cleanup(func() { listDependentEndpoints = originalList }) + listDependentEndpoints = func(owner, name, hash string) ([]DependentEndpoint, error) { + return nil, nil + } + + if err := checkDependentEndpoints("owner", "name", "hash"); err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + + t.Run("dependents found always blocks with a coded error and no override", func(t *testing.T) { + originalList := listDependentEndpoints + t.Cleanup(func() { listDependentEndpoints = originalList }) + listDependentEndpoints = func(owner, name, hash string) ([]DependentEndpoint, error) { + return []DependentEndpoint{{ID: "ep-1", Name: "my-endpoint"}}, nil + } + + err := checkDependentEndpoints("owner", "name", "hash") + if err == nil { + t.Fatal("expected an error, got nil") + } + var coder interface{ ErrorCode() string } + if !errors.As(err, &coder) { + t.Fatalf("expected error to implement ErrorCode(), got %#v", err) + } + if coder.ErrorCode() != "dependent_endpoints" { + t.Fatalf("expected code %q, got %q", "dependent_endpoints", coder.ErrorCode()) + } + }) + + t.Run("check failure blocks too — cannot verify safety means cannot proceed", func(t *testing.T) { + originalList := listDependentEndpoints + t.Cleanup(func() { listDependentEndpoints = originalList }) + listDependentEndpoints = func(owner, name, hash string) ([]DependentEndpoint, error) { + return nil, errors.New("boom") + } + + if err := checkDependentEndpoints("owner", "name", "hash"); err == nil { + t.Fatal("expected an error, got nil") + } + }) +} diff --git a/docs/runpodctl_model_remove.md b/docs/runpodctl_model_remove.md index 8d015a2a..8f0e9a7a 100644 --- a/docs/runpodctl_model_remove.md +++ b/docs/runpodctl_model_remove.md @@ -4,12 +4,23 @@ remove a model ### Synopsis -remove a model from the runpod model repository +remove a model from the runpod model repository. blocked if any endpoints still reference it — a model/version in active use cannot be removed. ``` runpodctl model remove [flags] ``` +### Examples + +``` + # blocked if an endpoint still references this model, listing which one(s) + runpodctl model remove --owner --name my-model + + # detach it from the endpoint first, then remove + runpodctl serverless update --clear-models + runpodctl model remove --owner --name my-model +``` + ### Options ``` diff --git a/internal/api/endpoints.go b/internal/api/endpoints.go index 3085e5f9..1535e618 100644 --- a/internal/api/endpoints.go +++ b/internal/api/endpoints.go @@ -273,6 +273,21 @@ func (c *Client) UpdateEndpointModels(endpointID string, modelRefs []string) (*E nvIDs[i] = NetworkVolumeIDInput{NetworkVolumeID: nv.NetworkVolumeID} } + // REST GET /v1/endpoints/{id} returns a "flashboot" bool, not the + // "flashBootType" enum string saveEndpoint expects — so endpoint.FlashBootType + // is always empty after GetEndpoint, and sending "" fails saveEndpoint's + // FlashBootType enum validation. Verified live (STO-360 e2e test): calling + // UpdateEndpointModels on a real endpoint returned + // `Value "" does not exist in "FlashBootType" enum.` every time. Derive the + // enum from the REST bool the same way cmd/serverless/create.go does. + flashBootType := endpoint.FlashBootType + if flashBootType == "" { + flashBootType = "OFF" + if endpoint.Flashboot != nil && *endpoint.Flashboot { + flashBootType = "FLASHBOOT" + } + } + query := ` mutation SaveEndpoint($input: EndpointInput!) { saveEndpoint(input: $input) { @@ -316,7 +331,7 @@ func (c *Client) UpdateEndpointModels(endpointID string, modelRefs []string) (*E "scalerValue": endpoint.ScalerValue, "executionTimeoutMs": endpoint.ExecutionTimeoutMs, "minCudaVersion": endpoint.MinCudaVersion, - "flashBootType": endpoint.FlashBootType, + "flashBootType": flashBootType, "modelReferences": modelRefs, }, } diff --git a/internal/api/endpoints_test.go b/internal/api/endpoints_test.go index e0a09f62..4ed60d2d 100644 --- a/internal/api/endpoints_test.go +++ b/internal/api/endpoints_test.go @@ -493,6 +493,76 @@ func TestUpdateEndpointModels_RoundTripsConfig(t *testing.T) { if nvobj["networkVolumeId"] != "vol-9" { t.Errorf("expected networkVolumeId vol-9, got %v", nvobj) } + + // the REST fixture above has neither "flashboot" nor "flashBootType", so + // this must fall back to the "OFF" default rather than sending "". + if got := gqlInput["flashBootType"]; got != "OFF" { + t.Errorf("expected flashBootType OFF when REST returns no flash boot info, got %v", got) + } +} + +// TestUpdateEndpointModels_DerivesFlashBootTypeFromRESTBool covers a bug found +// live (STO-360 e2e test): REST GET /v1/endpoints/{id} returns a "flashboot" +// bool, never the "flashBootType" enum string saveEndpoint requires, so +// endpoint.FlashBootType was always "" after GetEndpoint and saveEndpoint +// rejected it with `Value "" does not exist in "FlashBootType" enum.` on every +// real endpoint. UpdateEndpointModels must derive the enum from the REST bool. +func TestUpdateEndpointModels_DerivesFlashBootTypeFromRESTBool(t *testing.T) { + oldAPIURL := viper.GetString("apiUrl") + t.Cleanup(func() { viper.Set("apiUrl", oldAPIURL) }) + + var gqlInput map[string]interface{} + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/endpoints/"): + // REST read: the real wire shape — "flashboot" bool, no "flashBootType". + w.Write([]byte(`{ + "id": "ep-abc", + "name": "my-ep", + "templateId": "tpl-1", + "gpuIds": "ADA_24", + "workersMin": 0, + "workersMax": 1, + "flashboot": true + }`)) + case r.Method == http.MethodPost: + var body struct { + Variables struct { + Input map[string]interface{} `json:"input"` + } `json:"variables"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("decode gql body: %v", err) + } + gqlInput = body.Variables.Input + json.NewEncoder(w).Encode(map[string]interface{}{ + "data": map[string]interface{}{ + "saveEndpoint": map[string]interface{}{ + "id": "ep-abc", + "name": "my-ep", + }, + }, + }) + default: + t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + t.Setenv("RUNPOD_API_KEY", "test-key") + viper.Set("apiUrl", server.URL) + + client, _ := NewClient() + client.baseURL = server.URL + + if _, err := client.UpdateEndpointModels("ep-abc", nil); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if got := gqlInput["flashBootType"]; got != "FLASHBOOT" { + t.Errorf("expected flashBootType FLASHBOOT when REST flashboot=true, got %v", got) + } } func TestDeleteEndpoint(t *testing.T) {