Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 178 additions & 2 deletions cmd/model/removeModel.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package model

import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"

"github.com/runpod/runpodctl/api"
Expand All @@ -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 <endpoint-id> --clear-models' (or --model-reference <new-url>), 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/<owner>/<name>:<hash>" (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 <owner> --name my-model

# detach it from the endpoint first, then remove
runpodctl serverless update <endpoint-id> --clear-models
runpodctl model remove --owner <owner> --name my-model`,
RunE: runRemoveModel,
}

var RemoveModelCmd = &cobra.Command{
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
}
Expand Down
130 changes: 130 additions & 0 deletions cmd/model/removeModel_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package model

import (
"errors"
"testing"

"github.com/runpod/runpodctl/api"
Expand Down Expand Up @@ -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) {
Expand All @@ -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)
Expand All @@ -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")
}
})
}
13 changes: 12 additions & 1 deletion docs/runpodctl_model_remove.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <owner> --name my-model

# detach it from the endpoint first, then remove
runpodctl serverless update <endpoint-id> --clear-models
runpodctl model remove --owner <owner> --name my-model
```

### Options

```
Expand Down
Loading
Loading