From 6492a94d230c7f3075707f150d607b578d60478e Mon Sep 17 00:00:00 2001 From: shivamj-del Date: Mon, 30 Nov 2026 11:09:18 +0530 Subject: [PATCH] fix: stop brev create from retrying every instance type after billing errors --- pkg/cmd/gpucreate/gpucreate.go | 119 +++++++++++++++------ pkg/cmd/gpucreate/gpucreate_test.go | 143 ++++++++++++++++++++++++++ pkg/cmd/gpusearch/gpusearch.go | 25 +++++ pkg/cmd/gpusearch/gpusearch_test.go | 31 ++++++ pkg/store/http.go | 22 ++++ pkg/store/http_response_error_test.go | 23 +++++ 6 files changed, 333 insertions(+), 30 deletions(-) diff --git a/pkg/cmd/gpucreate/gpucreate.go b/pkg/cmd/gpucreate/gpucreate.go index 1cc9b9c47..b811219c6 100644 --- a/pkg/cmd/gpucreate/gpucreate.go +++ b/pkg/cmd/gpucreate/gpucreate.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "math" "math/rand/v2" "net" "net/http" @@ -63,6 +64,10 @@ tries to create ALL instances using the first type before falling back to the ne 3. If first type fails for some instances, try second type for remaining instances 4. Continue until all instances are created or all types are exhausted +If the organization is out of credits, the command stops. If a type is rejected +for the organization's hourly spending limit, or because its credits can't cover +30 minutes of that type, only the cheaper types left in the list are tried. + Example with --count 2 and types [A, B]: - Try A for instance-1 → success - Try A for instance-2 → success @@ -982,6 +987,8 @@ type typeCreateResult struct { successes []*entity.Workspace hadFailure bool fatalError error + // tooExpensive is a billing rejection that depends on the type's price, so cheaper types can still pass. + tooExpensive error } // validateInstanceTypeAvailability errors when the type is invalid or has no capacity. Returns nil when the listing is missing. @@ -1047,9 +1054,9 @@ func (c *createContext) createInstancesWithType(spec InstanceSpec, startIdx, cou // runWorker processes instance creation requests from the channel func (c *createContext) runWorker(workerID int, spec InstanceSpec, indices <-chan int, result *typeCreateResult, mu *sync.Mutex) { for idx := range indices { - // Check if we've already created enough + // Check if we've already created enough, or the rest of this type would be rejected too mu.Lock() - if len(result.successes) >= c.opts.Count { + if len(result.successes) >= c.opts.Count || result.fatalError != nil || result.tooExpensive != nil { mu.Unlock() return } @@ -1089,11 +1096,25 @@ func (c *createContext) handleCreateError(workerID int, instanceType, instanceNa c.logf("[Worker %d] %s Failed: %s\n", workerID+1, c.colorize(instanceType, c.t.Yellow), errStr) result.hadFailure = true - if strings.Contains(errStr, "duplicate workspace") { + switch { + case strings.Contains(errStr, "duplicate workspace"): result.fatalError = fmt.Errorf("workspace '%s' already exists. Use a different name or delete the existing workspace", instanceName) + case store.IsHTTPErrorCode(err, http.StatusBadRequest, codeCreditExhausted): + result.fatalError = fmt.Errorf("organization '%s' is out of credits. Add credits and try again", c.org.Name) + case store.IsHTTPErrorCode(err, http.StatusBadRequest, codeInsufficientCredits): + result.tooExpensive = fmt.Errorf("organization '%s' doesn't have enough credits to run %s for 30 minutes. Add credits or choose a cheaper instance type", c.org.Name, instanceType) + case store.IsHTTPErrorCode(err, http.StatusBadRequest, codeResourceLimitExceeded): + result.tooExpensive = fmt.Errorf("%s would put organization '%s' over its hourly spending limit. Stop running instances, choose a cheaper instance type, or contact support to raise the limit", instanceType, c.org.Name) } } +// Codes the Brev API puts on billing rejections. +const ( + codeCreditExhausted = "CREDIT_EXHAUSTED" + codeInsufficientCredits = "INSUFFICIENT_CREDITS" + codeResourceLimitExceeded = "RESOURCE_LIMIT_EXCEEDED" +) + // handleCreateSuccess processes a successful instance creation (must be called with lock held) func (c *createContext) handleCreateSuccess(workerID int, instanceType, instanceName string, workspace *entity.Workspace, result *typeCreateResult) { c.logf("[Worker %d] %s Success! Created instance '%s'\n", workerID+1, c.colorize(instanceType, c.t.Green), instanceName) @@ -1210,33 +1231,7 @@ func RunGPUCreate(parentCtx context.Context, t *terminal.Terminal, gpuCreateStor ctx.logf("Attempting to create %d instance(s) with %d parallel attempts\n", opts.Count, opts.Parallel) ctx.logf("Instance types to try: %s\n\n", formatInstanceSpecs(opts.InstanceTypes)) - var successfulWorkspaces []*entity.Workspace - - // Try each instance type in order - for _, spec := range opts.InstanceTypes { - if len(successfulWorkspaces) >= opts.Count { - break - } - - remaining := opts.Count - len(successfulWorkspaces) - ctx.logf("Trying %s for %d instance(s)...\n", spec.Type, remaining) - - result := ctx.createInstancesWithType(spec, len(successfulWorkspaces), remaining) - successfulWorkspaces = append(successfulWorkspaces, result.successes...) - - if result.fatalError != nil { - ctx.logf("\nError: %s\n", result.fatalError.Error()) - break - } - - if !result.hadFailure && len(successfulWorkspaces) >= opts.Count { - break - } - - if len(successfulWorkspaces) < opts.Count && result.hadFailure { - ctx.logf("\nType %s had failures, trying next type...\n\n", spec.Type) - } - } + successfulWorkspaces, stopErr := ctx.createWithFallback() // Check if we created enough instances if len(successfulWorkspaces) < opts.Count { @@ -1247,6 +1242,9 @@ func RunGPUCreate(parentCtx context.Context, t *terminal.Terminal, gpuCreateStor ctx.logf(" - %s (ID: %s)\n", ws.Name, ws.ID) } } + if stopErr != nil { + return breverrors.NewValidationError(stopErr.Error()) + } return breverrors.NewValidationError(fmt.Sprintf("could only create %d/%d instances", len(successfulWorkspaces), opts.Count)) } @@ -1259,6 +1257,67 @@ func RunGPUCreate(parentCtx context.Context, t *terminal.Terminal, gpuCreateStor return nil } +func (c *createContext) createWithFallback() ([]*entity.Workspace, error) { + var created []*entity.Workspace + var tooExpensive error + maxCost := math.Inf(1) + + for i, spec := range c.opts.InstanceTypes { + if len(created) >= c.opts.Count { + break + } + cost, priced := c.hourlyCost(spec) + if tooExpensive != nil && (!priced || cost >= maxCost) { + continue + } + + remaining := c.opts.Count - len(created) + c.logf("Trying %s for %d instance(s)...\n", spec.Type, remaining) + + result := c.createInstancesWithType(spec, len(created), remaining) + created = append(created, result.successes...) + + switch { + case result.fatalError != nil: + return created, result.fatalError + case result.tooExpensive != nil && !priced: + // Without this type's price there is no telling which types are cheaper. + return created, result.tooExpensive + case result.tooExpensive != nil: + tooExpensive, maxCost = result.tooExpensive, cost + if !c.anyCheaper(c.opts.InstanceTypes[i+1:], maxCost) { + return created, tooExpensive + } + c.logf("\nTrying only the remaining types that cost less than %s ($%.2f/hr)...\n\n", spec.Type, cost) + case result.hadFailure && len(created) < c.opts.Count: + c.logf("\nType %s had failures, trying next type...\n\n", spec.Type) + } + } + + if len(created) < c.opts.Count { + return created, tooExpensive + } + return created, nil +} + +// anyCheaper reports whether any of specs is known to cost less than maxCost. +func (c *createContext) anyCheaper(specs []InstanceSpec, maxCost float64) bool { + for _, spec := range specs { + if cost, ok := c.hourlyCost(spec); ok && cost < maxCost { + return true + } + } + return false +} + +// hourlyCost estimates what the billing checks charge per hour for spec. +func (c *createContext) hourlyCost(spec InstanceSpec) (float64, bool) { + if c.allInstanceTypes == nil { + return 0, false + } + return c.allInstanceTypes.HourlyCost(spec.Type, spec.DiskGB) +} + // createWorkspace creates a workspace with the specified instance type and name func (c *createContext) createWorkspace(name string, spec InstanceSpec) (*entity.Workspace, error) { clusterID := config.GlobalConfig.GetDefaultClusterID() diff --git a/pkg/cmd/gpucreate/gpucreate_test.go b/pkg/cmd/gpucreate/gpucreate_test.go index 4fe40eb12..383c49e84 100644 --- a/pkg/cmd/gpucreate/gpucreate_test.go +++ b/pkg/cmd/gpucreate/gpucreate_test.go @@ -16,6 +16,7 @@ import ( breverrors "github.com/brevdev/brev-cli/pkg/errors" "github.com/brevdev/brev-cli/pkg/store" "github.com/brevdev/brev-cli/pkg/terminal" + resty "github.com/go-resty/resty/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -44,10 +45,12 @@ type MockGPUCreateStore struct { CreateErrorTypes map[string]error // Errors for specific instance types EnvironmentStatuses map[string]devplanev1.EnvironmentStatus EnvironmentStatusMessages map[string]string + CreateAttempts []string // Instance types passed to CreateWorkspace, including failed calls CreatedOptions []*store.CreateWorkspacesOptions CreatedWorkspaces []*entity.Workspace DeletedWorkspaceIDs []string FetchedLifeCycleScriptIDs []string + AllInstanceTypes *gpusearch.AllInstanceTypesResponse // Replaces the default org instance-type listing when set } func NewMockGPUCreateStore() *MockGPUCreateStore { @@ -93,6 +96,7 @@ func (m *MockGPUCreateStore) GetEnvironment(_ context.Context, environmentID str } func (m *MockGPUCreateStore) CreateWorkspace(organizationID string, options *store.CreateWorkspacesOptions) (*entity.Workspace, error) { + m.CreateAttempts = append(m.CreateAttempts, options.InstanceType) // Check for type-specific errors first if err, ok := m.CreateErrorTypes[options.InstanceType]; ok { return nil, err @@ -119,6 +123,9 @@ func (m *MockGPUCreateStore) GetWorkspaceByNameOrID(orgID string, nameOrID strin } func (m *MockGPUCreateStore) GetAllInstanceTypesWithCloudCreds(orgID string) (*gpusearch.AllInstanceTypesResponse, error) { + if m.AllInstanceTypes != nil { + return m.AllInstanceTypes, nil + } return &gpusearch.AllInstanceTypesResponse{ AllInstanceTypes: []gpusearch.InstanceType{ {Type: "test.fail.quota", CloudCredID: "testkube-brev-test"}, @@ -1219,6 +1226,142 @@ func TestRunGPUCreateLifecycle(t *testing.T) { } } +// badRequestError returns the error the store produces for an HTTP 400 API response with the given body. +func badRequestError(t *testing.T, body string) error { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + resp, err := resty.New().R().Post(srv.URL) + require.NoError(t, err) + return store.NewHTTPResponseError(resp) +} + +// billingTestListing prices the instance types used by the billing rejection tests. +var billingTestListing = &gpusearch.AllInstanceTypesResponse{AllInstanceTypes: []gpusearch.InstanceType{ + {Type: "big", CloudCredID: "cc", BasePrice: gpusearch.BasePrice{Amount: "4.00"}}, + {Type: "same", CloudCredID: "cc", BasePrice: gpusearch.BasePrice{Amount: "4.00"}}, + {Type: "small", CloudCredID: "cc", BasePrice: gpusearch.BasePrice{Amount: "2.00"}}, + {Type: "unpriced", CloudCredID: "cc"}, +}} + +// runCreate runs RunGPUCreate over types and returns the instance types it tried and created. +func runCreate(mock *MockGPUCreateStore, types []string, count int) (attempts, created []string, err error) { + var specs []InstanceSpec + for _, instanceType := range types { + specs = append(specs, InstanceSpec{Type: instanceType}) + } + err = RunGPUCreate(context.Background(), terminal.New(), mock, GPUCreateOptions{ + Name: "repro", Count: count, Parallel: 1, InstanceTypes: specs, Detached: true, + }) + for _, ws := range mock.CreatedWorkspaces { + created = append(created, ws.InstanceType) + } + return mock.CreateAttempts, created, err +} + +func TestRunGPUCreateBillingRejections(t *testing.T) { + creditExhausted := badRequestError(t, `{"errors":[{"type":"BadRequestError","code":"CREDIT_EXHAUSTED","message":"Credits are exhausted."}]}`) + insufficientCredits := badRequestError(t, `{"errors":[{"type":"BadRequestError","code":"INSUFFICIENT_CREDITS","message":"Insufficient credits to fund 30 minutes of runtime."}]}`) + spendingLimit := badRequestError(t, `{"errors":[{"type":"BadRequestError","code":"RESOURCE_LIMIT_EXCEEDED","message":"Organization spending limit exceeded. Contact support to increase your limit."}]}`) + unnamed := badRequestError(t, `{"errors":[{"type":"BadRequestError","message":"Bad Request"}]}`) + + cases := []struct { + name string + errs map[string]error + types []string + count int + wantAttempts []string + wantCreated []string + wantErr string + }{ + { + name: "out of credits stops before trying other types", + errs: map[string]error{"big": creditExhausted}, + types: []string{"big", "small"}, + count: 1, + wantAttempts: []string{"big"}, + wantErr: "organization 'test-org' is out of credits", + }, + { + name: "out of credits stops the remaining instances of the type", + errs: map[string]error{"big": creditExhausted}, + types: []string{"big", "small"}, + count: 3, + wantAttempts: []string{"big"}, + wantErr: "organization 'test-org' is out of credits", + }, + { + name: "spending limit skips types that cost as much or have no price, then tries a cheaper one", + errs: map[string]error{"big": spendingLimit}, + types: []string{"big", "same", "unpriced", "small"}, + count: 1, + wantAttempts: []string{"big", "small"}, + wantCreated: []string{"small"}, + }, + { + name: "insufficient credits also tries only cheaper types", + errs: map[string]error{"big": insufficientCredits}, + types: []string{"big", "same", "unpriced", "small"}, + count: 1, + wantAttempts: []string{"big", "small"}, + wantCreated: []string{"small"}, + }, + { + name: "insufficient credits with a single type in the list stops there", + errs: map[string]error{"big": insufficientCredits}, + types: []string{"big"}, + count: 1, + wantAttempts: []string{"big"}, + wantErr: "doesn't have enough credits to run big for 30 minutes", + }, + { + name: "spending limit on the cheapest type stops, since every other type costs more", + errs: map[string]error{"small": spendingLimit}, + types: []string{"small", "big"}, + count: 1, + wantAttempts: []string{"small"}, + wantErr: "small would put organization 'test-org' over its hourly spending limit", + }, + { + name: "spending limit moves the remaining instances to a cheaper type", + errs: map[string]error{"big": spendingLimit}, + types: []string{"big", "small"}, + count: 3, + wantAttempts: []string{"big", "small", "small", "small"}, + wantCreated: []string{"small", "small", "small"}, + }, + { + name: "unnamed failure still falls through to the next type", + errs: map[string]error{"big": unnamed}, + types: []string{"big", "same"}, + count: 1, + wantAttempts: []string{"big", "same"}, + wantCreated: []string{"same"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mock := NewMockGPUCreateStore() + mock.AllInstanceTypes = billingTestListing + mock.CreateErrorTypes = tc.errs + + attempts, created, err := runCreate(mock, tc.types, tc.count) + + assert.Equal(t, tc.wantAttempts, attempts) + assert.Equal(t, tc.wantCreated, created) + if tc.wantErr == "" { + require.NoError(t, err) + } else { + require.ErrorContains(t, err, tc.wantErr) + } + }) + } +} + func TestInlineLaunchableLifeCycleScript(t *testing.T) { t.Run("fetches and inlines lifecycle script body", func(t *testing.T) { mockStore := NewMockGPUCreateStore() diff --git a/pkg/cmd/gpusearch/gpusearch.go b/pkg/cmd/gpusearch/gpusearch.go index d9060da97..dac6d114d 100644 --- a/pkg/cmd/gpusearch/gpusearch.go +++ b/pkg/cmd/gpusearch/gpusearch.go @@ -113,6 +113,31 @@ func (r *AllInstanceTypesResponse) HasInstanceType(instanceType string) bool { return false } +func (r *AllInstanceTypesResponse) HourlyCost(instanceType string, diskGB float64) (float64, bool) { + for _, it := range r.AllInstanceTypes { + if it.Type != instanceType { + continue + } + cost, err := strconv.ParseFloat(it.BasePrice.Amount, 64) + if err != nil { + return 0, false + } + if len(it.SupportedStorage) == 0 { + return cost, true + } + storage := it.SupportedStorage[0] + perGBHr, err := strconv.ParseFloat(storage.PricePerGBHr.Amount, 64) + if err != nil { + return cost, true // storage is bundled into the base price + } + if diskGB <= 0 { + diskGB = parseSizeToGB(storage.Size) + } + return cost + diskGB*perGBHr, true + } + return 0, false +} + // GPUSearchStore defines the interface for fetching instance types type GPUSearchStore interface { GetInstanceTypes(includeCPU bool) (*InstanceTypesResponse, error) diff --git a/pkg/cmd/gpusearch/gpusearch_test.go b/pkg/cmd/gpusearch/gpusearch_test.go index 5749d3a69..d55a2fd24 100644 --- a/pkg/cmd/gpusearch/gpusearch_test.go +++ b/pkg/cmd/gpusearch/gpusearch_test.go @@ -627,6 +627,37 @@ func TestAllInstanceTypesResponseLookup(t *testing.T) { }) } +func TestAllInstanceTypesResponseHourlyCost(t *testing.T) { + resp := &AllInstanceTypesResponse{ + AllInstanceTypes: []InstanceType{ + {Type: "bundled", BasePrice: BasePrice{Amount: "2.50"}, SupportedStorage: []Storage{{Size: "500GiB"}}}, + {Type: "flex", BasePrice: BasePrice{Amount: "2.00"}, SupportedStorage: []Storage{{Size: "100GiB", PricePerGBHr: BasePrice{Amount: "0.001"}}}}, + {Type: "unpriced"}, + }, + } + + cases := []struct { + name string + instanceType string + diskGB float64 + want float64 + wantOK bool + }{ + {"storage bundled into the base price", "bundled", 1000, 2.50, true}, + {"requested disk at the storage price", "flex", 500, 2.50, true}, + {"default disk size when none is requested", "flex", 0, 2.10, true}, + {"type without a price", "unpriced", 0, 0, false}, + {"unknown type", "missing", 0, 0, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, ok := resp.HourlyCost(tc.instanceType, tc.diskGB) + assert.Equal(t, tc.wantOK, ok) + assert.InDelta(t, tc.want, got, 1e-9) + }) + } +} + // trackingStore is a GPUSearchStore mock that records the includeCPU flag passed to // GetInstanceTypes so command dispatch tests can assert which search path executed. // It returns an empty (but non-nil) response by default so RunGPUSearch/RunCPUSearch diff --git a/pkg/store/http.go b/pkg/store/http.go index 5c452865e..e7bf78b04 100644 --- a/pkg/store/http.go +++ b/pkg/store/http.go @@ -2,6 +2,7 @@ package store import ( "encoding/json" + stderrors "errors" "fmt" "log" "net/http" @@ -311,9 +312,30 @@ type BrevDeployErrorList struct { type BrevDeployError struct { Kind string `json:"type"` + Code string `json:"code"` Message string `json:"message"` } +func IsHTTPErrorCode(err error, status int, code string) bool { + if code == "" { + return false + } + var responseErr *HTTPResponseError + if !stderrors.As(err, &responseErr) || responseErr.Response == nil || responseErr.Response.StatusCode() != status { + return false + } + var envelope BrevDeployErrorList + if json.Unmarshal(responseErr.Response.Body(), &envelope) != nil { + return false + } + for _, item := range envelope.Errors { + if item.Code == code { + return true + } + } + return false +} + type HTTPResponseError struct { Response *resty.Response } diff --git a/pkg/store/http_response_error_test.go b/pkg/store/http_response_error_test.go index 489a237f1..aea6c6fa6 100644 --- a/pkg/store/http_response_error_test.go +++ b/pkg/store/http_response_error_test.go @@ -1,6 +1,7 @@ package store import ( + "fmt" "net/http" "net/http/httptest" "strings" @@ -11,6 +12,28 @@ import ( "github.com/stretchr/testify/require" ) +func TestIsHTTPErrorCode(t *testing.T) { + cases := []struct { + name string + status int + body string + code string + want bool + }{ + {"matching Brev code", http.StatusBadRequest, `{"errors":[{"type":"BadRequestError","code":"WORKSPACE_ALREADY_EXISTS","message":"Request could not be completed"}]}`, "WORKSPACE_ALREADY_EXISTS", true}, + {"other code", http.StatusBadRequest, `{"errors":[{"type":"BadRequestError","code":"OTHER","message":"Request could not be completed"}]}`, "WORKSPACE_ALREADY_EXISTS", false}, + {"wrong status", http.StatusInternalServerError, `{"errors":[{"type":"InternalServerError","code":"WORKSPACE_ALREADY_EXISTS","message":"Request could not be completed"}]}`, "WORKSPACE_ALREADY_EXISTS", false}, + {"unstructured body", http.StatusBadRequest, `{"message":"WORKSPACE_ALREADY_EXISTS"}`, "WORKSPACE_ALREADY_EXISTS", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := fmt.Errorf("create workspace: %w", doRequestWithToken(t, tc.status, tc.body, "")) + assert.Equal(t, tc.want, IsHTTPErrorCode(err, http.StatusBadRequest, tc.code)) + }) + } + assert.False(t, IsHTTPErrorCode(fmt.Errorf("WORKSPACE_ALREADY_EXISTS"), http.StatusBadRequest, "WORKSPACE_ALREADY_EXISTS")) +} + const unauthorizedBody = `{"errors":[{"type":"UnauthorizedError"}]}` func doRequestWithToken(t *testing.T, status int, body, token string) *HTTPResponseError {