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
119 changes: 89 additions & 30 deletions pkg/cmd/gpucreate/gpucreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"math"
"math/rand/v2"
"net"
"net/http"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand All @@ -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))
}

Expand All @@ -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()
Expand Down
143 changes: 143 additions & 0 deletions pkg/cmd/gpucreate/gpucreate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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"},
Expand Down Expand Up @@ -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()
Expand Down
25 changes: 25 additions & 0 deletions pkg/cmd/gpusearch/gpusearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading