From 2ccd407ee20d3ad372f562b6da8ca358d8d5c195 Mon Sep 17 00:00:00 2001 From: Arpit Agarwal Date: Wed, 25 Nov 2026 00:23:58 +0000 Subject: [PATCH] air: add the endpoint and MLmodel clients for serving a version serveOnEndpoint creates or updates a serving endpoint so it serves one version, without changing an endpoint that already does, and refuses one that serves another model or is of the other kind. readVersionPackage reads a version's MLmodel to tell a dedicated checkpoint from a command or any other model. No command calls them yet; air serve uses them in a follow-up. Co-authored-by: Isaac --- cmd/air/modelcmd.go | 7 + cmd/air/serveendpoint.go | 437 +++++++++++++++++++++++++ cmd/air/serveendpoint_test.go | 584 ++++++++++++++++++++++++++++++++++ cmd/air/servepackage.go | 100 ++++++ cmd/air/servepackage_test.go | 124 ++++++++ 5 files changed, 1252 insertions(+) create mode 100644 cmd/air/serveendpoint.go create mode 100644 cmd/air/serveendpoint_test.go create mode 100644 cmd/air/servepackage.go create mode 100644 cmd/air/servepackage_test.go diff --git a/cmd/air/modelcmd.go b/cmd/air/modelcmd.go index a1dcc49e4ef..5b30576c9c0 100644 --- a/cmd/air/modelcmd.go +++ b/cmd/air/modelcmd.go @@ -164,6 +164,13 @@ var registeredModelRe = sync.OnceValue(func() *regexp.Regexp { return regexp.Mus // modelVersionRe matches a Unity Catalog model version number. var modelVersionRe = sync.OnceValue(func() *regexp.Regexp { return regexp.MustCompile(`^[1-9][0-9]*$`) }) +// Audio tasks: their requests are multipart uploads of a recording, sent to the +// endpoint's audio route rather than to invocations. +const ( + taskAudioTranscriptions = "llm/v1/audio/transcriptions" + taskAudioTranslations = "llm/v1/audio/translations" +) + // validateUCModelName checks a Unity Catalog model name from source, the YAML field // or a flag. func validateUCModelName(name, source string) error { diff --git a/cmd/air/serveendpoint.go b/cmd/air/serveendpoint.go new file mode 100644 index 00000000000..93f12bc2103 --- /dev/null +++ b/cmd/air/serveendpoint.go @@ -0,0 +1,437 @@ +package aircmd + +import ( + "context" + "errors" + "fmt" + "net/http" + "slices" + "strings" + "time" + + "github.com/databricks/cli/libs/auth" + "github.com/databricks/cli/libs/retry" + "github.com/databricks/databricks-sdk-go" + "github.com/databricks/databricks-sdk-go/apierr" + "github.com/databricks/databricks-sdk-go/client" + "github.com/databricks/databricks-sdk-go/retries" + "github.com/databricks/databricks-sdk-go/service/serving" +) + +// servingEndpointsPath is the serving endpoints API. Dedicated endpoints are created +// and configured under dedicatedEndpointsPath. +const ( + servingEndpointsPath = "/api/2.0/serving-endpoints" + dedicatedEndpointsPath = servingEndpointsPath + "/pt" +) + +// workloadTypeCPU is the workload type of a replica without a GPU, the API's +// default. +const workloadTypeCPU = "CPU" + +// servingCompute is the serving compute of a version: the workload type of each +// replica, and the provisioned concurrency the endpoint scales between. ScaleToZero +// is set when the minimum is 0. +type servingCompute struct { + WorkloadType string + MinConcurrency int + MaxConcurrency int + ScaleToZero bool +} + +// dedicatedCompute is the dedicated compute a dedicated served entity gets. +type dedicatedCompute struct { + ComputeProfile string + ProvisionedModelUnits int64 +} + +// servedEntity is the one entity air serve serves on the endpoint: a version of the +// model on serving compute, or on dedicated compute when Dedicated is set. +type servedEntity struct { + EntityName string + EntityVersion string + // Serving is the serving compute. + Serving servingCompute + // Dedicated is the dedicated compute, nil for serving compute. + Dedicated *dedicatedCompute +} + +// servingInput is the entity as the serving endpoints API takes it: its scale as a +// range of provisioned concurrency, which the API takes instead of a workload size. +// scale_to_zero_enabled and a minimum of 0 are sent even though they are zero values, +// since the server's defaults aren't known to be zero. +func (e servedEntity) servingInput() serving.ServedEntityInput { + return serving.ServedEntityInput{ + EntityName: e.EntityName, + EntityVersion: e.EntityVersion, + WorkloadType: serving.ServingModelWorkloadType(e.Serving.WorkloadType), + MinProvisionedConcurrency: e.Serving.MinConcurrency, + MaxProvisionedConcurrency: e.Serving.MaxConcurrency, + ScaleToZeroEnabled: e.Serving.ScaleToZero, + ForceSendFields: []string{"MinProvisionedConcurrency", "ScaleToZeroEnabled"}, + } +} + +// dedicatedServedEntity is a dedicated served entity as the dedicated endpoints API +// takes it. The SDK has no compute_profile, so these requests are sent as JSON. The +// entity_version is empty in a dry run, before the registration produces one. +type dedicatedServedEntity struct { + EntityName string `json:"entity_name"` + EntityVersion string `json:"entity_version,omitempty"` + ProvisionedModelUnits int64 `json:"provisioned_model_units"` + ComputeProfile string `json:"compute_profile"` +} + +// dedicatedEndpointConfig is the config of a dedicated endpoint. +type dedicatedEndpointConfig struct { + ServedEntities []dedicatedServedEntity `json:"served_entities"` +} + +// dedicatedEndpointUpdate replaces the config of a dedicated endpoint. +type dedicatedEndpointUpdate struct { + Config dedicatedEndpointConfig `json:"config"` +} + +// dedicatedEndpointRequest creates a dedicated endpoint. +type dedicatedEndpointRequest struct { + Name string `json:"name"` + Config dedicatedEndpointConfig `json:"config"` +} + +// dedicatedJSON is the entity as the dedicated endpoints API takes it. +func (e servedEntity) dedicatedJSON() dedicatedServedEntity { + return dedicatedServedEntity{ + EntityName: e.EntityName, + EntityVersion: e.EntityVersion, + ProvisionedModelUnits: e.Dedicated.ProvisionedModelUnits, + ComputeProfile: e.Dedicated.ComputeProfile, + } +} + +// servingEndpoint is a serving endpoint as GET /api/2.0/serving-endpoints/{name} +// reports it, with the fields air serve reads. It replaces the SDK's type, which has +// no compute_profile for a dedicated served entity. +type servingEndpoint struct { + Name string `json:"name"` + State *serving.EndpointState `json:"state,omitempty"` + Config *endpointConfig `json:"config,omitempty"` + PendingConfig *endpointConfig `json:"pending_config,omitempty"` +} + +// endpointConfig is the served entities of an endpoint's current or pending config. +type endpointConfig struct { + ServedEntities []observedEntity `json:"served_entities,omitempty"` +} + +// observedEntity is a served entity as the endpoint reports it: a dedicated one by +// its units and profile, and any other by its workload type and concurrency range. +type observedEntity struct { + EntityName string `json:"entity_name"` + EntityVersion string `json:"entity_version"` + WorkloadType string `json:"workload_type"` + MinProvisionedConcurrency int `json:"min_provisioned_concurrency"` + MaxProvisionedConcurrency int `json:"max_provisioned_concurrency"` + ScaleToZeroEnabled bool `json:"scale_to_zero_enabled"` + EnvironmentVars map[string]string `json:"environment_vars"` + ProvisionedModelUnits int64 `json:"provisioned_model_units"` + ComputeProfile string `json:"compute_profile"` +} + +// endpointAPI calls the serving endpoints API for air serve. Endpoints are read as +// JSON, and dedicated endpoints written so; serving compute is written through the SDK. +type endpointAPI struct { + w *databricks.WorkspaceClient + api *client.DatabricksClient + headers map[string]string +} + +func newEndpointAPI(w *databricks.WorkspaceClient) (*endpointAPI, error) { + api, err := client.New(w.Config) + if err != nil { + return nil, withCode(codeInternalError, false, fmt.Errorf("failed to create API client: %w", err)) + } + return &endpointAPI{w: w, api: api, headers: auth.WorkspaceIDHeaders(w.Config)}, nil +} + +// read returns the endpoint named name, and the error the API gives when it doesn't +// exist. A transient failure is repeated. +func (e *endpointAPI) read(ctx context.Context, name string) (*servingEndpoint, error) { + return retry.With(ctx, retry.IsTransientRead, func() (*servingEndpoint, error) { + endpoint := &servingEndpoint{} + err := e.api.Do(ctx, http.MethodGet, servingEndpointsPath+"/"+name, e.headers, nil, nil, endpoint) + return endpoint, err + }) +} + +// get returns the endpoint named name, or nil if it doesn't exist. +func (e *endpointAPI) get(ctx context.Context, name string) (*servingEndpoint, error) { + endpoint, err := e.read(ctx, name) + if errors.Is(err, apierr.ErrResourceDoesNotExist) { + return nil, nil + } + return endpoint, err +} + +// create creates the endpoint named name with entity. It returns once the API accepts +// the request, not once the endpoint is up. +func (e *endpointAPI) create(ctx context.Context, name string, entity servedEntity) error { + if entity.Dedicated != nil { + request := dedicatedEndpointRequest{ + Name: name, + Config: dedicatedEndpointConfig{ServedEntities: []dedicatedServedEntity{entity.dedicatedJSON()}}, + } + return e.api.Do(ctx, http.MethodPost, dedicatedEndpointsPath, e.headers, nil, request, nil) + } + _, err := e.w.ServingEndpoints.Create(ctx, serving.CreateServingEndpoint{ + Name: name, + Config: &serving.EndpointCoreConfigInput{ServedEntities: []serving.ServedEntityInput{entity.servingInput()}}, + }) + return err +} + +// update replaces the endpoint named name's served entity with entity. It returns once +// the API accepts the update. +func (e *endpointAPI) update(ctx context.Context, name string, entity servedEntity) error { + if entity.Dedicated != nil { + update := dedicatedEndpointUpdate{Config: dedicatedEndpointConfig{ServedEntities: []dedicatedServedEntity{entity.dedicatedJSON()}}} + return e.api.Do(ctx, http.MethodPut, dedicatedEndpointsPath+"/"+name+"/config", e.headers, nil, update, nil) + } + _, err := e.w.ServingEndpoints.UpdateConfig(ctx, serving.EndpointCoreConfigInput{ + Name: name, + ServedEntities: []serving.ServedEntityInput{entity.servingInput()}, + }) + return err +} + +// checkKind fails when the endpoint serves on dedicated compute and dedicated is +// false, or the reverse: the server converts neither kind of endpoint to the other. +// An endpoint that reports no served entity is taken as either kind. +func checkKind(endpoint *servingEndpoint, dedicated bool) error { + served := append(currentEntities(endpoint), pendingEntities(endpoint)...) + if len(served) == 0 { + return nil + } + isDedicated := slices.ContainsFunc(served, func(e observedEntity) bool { return e.ComputeProfile != "" }) + if isDedicated == dedicated { + return nil + } + kind, want := "serving compute", "dedicated compute" + if isDedicated { + kind, want = want, kind + } + return withCode(codeInvalidArgs, false, fmt.Errorf("endpoint %s serves on %s, and this version is served on %s; an endpoint can't change between the two, so set endpoint_name to another name", stripControl(endpoint.Name), kind, want)) +} + +// checkReplaceable fails unless the endpoint serves at most one entity, a version +// of model, in its current and pending configs. Replacing anything else would +// remove another model or a traffic split the user didn't ask to change. The +// endpoint lists every served model under served_entities too (served_models +// mirrors it), so served_entities covers both. +func checkReplaceable(endpoint *servingEndpoint, model string) error { + for _, served := range [][]observedEntity{currentEntities(endpoint), pendingEntities(endpoint)} { + if len(served) > 1 || (len(served) == 1 && !strings.EqualFold(served[0].EntityName, model)) { + return withCode(codeInvalidArgs, false, fmt.Errorf("endpoint %s serves %s, and air serve replaces only a single version of %s; set endpoint_name to another name, or change this endpoint with databricks serving-endpoints update-config", stripControl(endpoint.Name), describeEntities(served), model)) + } + } + return nil +} + +// serveOnEndpoint makes the endpoint named name serve only entity, calling progress +// on every poll. It creates the endpoint if it doesn't exist. An endpoint that +// already serves entity isn't updated. With watch, it waits until the endpoint is +// ready, including for an update to entity that an earlier air serve started; +// without it, it returns once the endpoint accepts the update. It reports whether +// the endpoint serves entity and is ready. +func serveOnEndpoint(ctx context.Context, w *databricks.WorkspaceClient, name string, entity servedEntity, watch bool, progress func(*servingEndpoint)) (bool, error) { + e, err := newEndpointAPI(w) + if err != nil { + return false, err + } + endpoint, err := e.get(ctx, name) + if err != nil { + return false, err + } + if endpoint == nil { + if err := e.create(ctx, name, entity); err != nil { + return false, err + } + return watchServes(ctx, e, name, entity, watch, progress) + } + if updating(endpoint) && servesOnly(pendingEntities(endpoint), entity) { + return watchServes(ctx, e, name, entity, watch, progress) + } + // The checks read the pending config too, so an endpoint air serve won't change is + // refused before waiting behind its update. + if err := checkEndpoint(endpoint, entity); err != nil { + return false, err + } + if updating(endpoint) { + // The endpoint takes no other update until this one finishes, so this waits + // even without watch. How that update ends doesn't matter: either way the + // endpoint then takes this one. + endpoint, err = waitNotUpdating(ctx, e, name, progress, false) + if err != nil { + return false, err + } + if err := checkEndpoint(endpoint, entity); err != nil { + return false, err + } + } + if servesOnly(currentEntities(endpoint), entity) { + return checkServes(endpoint, entity) + } + if err := e.update(ctx, name, entity); err != nil { + return false, err + } + return watchServes(ctx, e, name, entity, watch, progress) +} + +// checkEndpoint fails when air serve won't make endpoint serve entity: it serves +// something else, or is of the other kind. +func checkEndpoint(endpoint *servingEndpoint, entity servedEntity) error { + if err := checkReplaceable(endpoint, entity.EntityName); err != nil { + return err + } + return checkKind(endpoint, entity.Dedicated != nil) +} + +// watchServes waits for the endpoint's update to entity to finish when watch is set. +func watchServes(ctx context.Context, e *endpointAPI, name string, entity servedEntity, watch bool, progress func(*servingEndpoint)) (bool, error) { + if !watch { + return false, nil + } + return waitServes(ctx, e, name, entity, progress) +} + +// waitNotUpdating waits until the endpoint has no update in progress, calling +// progress on every poll. When own is set, the update is air serve's and its failure +// is an error; another update's failure only frees the endpoint. Each poll repeats a +// transient failure, which ends the SDK's own wait: an endpoint can take many minutes +// to start. Creates and config updates aren't repeated this way, since a repeat after +// an applied write would fail. +func waitNotUpdating(ctx context.Context, e *endpointAPI, name string, progress func(*servingEndpoint), own bool) (*servingEndpoint, error) { + return retries.Poll(ctx, untilDeadline(ctx), func() (*servingEndpoint, *retries.Err) { + endpoint, err := e.read(ctx, name) + if err != nil { + return nil, retries.Halt(err) + } + if progress != nil { + progress(endpoint) + } + var state serving.EndpointStateConfigUpdate + if endpoint.State != nil { + state = endpoint.State.ConfigUpdate + } + switch state { + case serving.EndpointStateConfigUpdateNotUpdating: + return endpoint, nil + case serving.EndpointStateConfigUpdateUpdateFailed, serving.EndpointStateConfigUpdateUpdateCanceled: + if !own { + return endpoint, nil + } + return nil, retries.Halt(fmt.Errorf("the endpoint's update ended in %s; check its events and logs in the Serving UI", state)) + default: + return nil, retries.Continues(string(state)) + } + }) +} + +// waitServes waits until the endpoint's update finishes, then checks that it +// serves entity. +func waitServes(ctx context.Context, e *endpointAPI, name string, entity servedEntity, progress func(*servingEndpoint)) (bool, error) { + endpoint, err := waitNotUpdating(ctx, e, name, progress, true) + if err != nil { + return false, err + } + return checkServes(endpoint, entity) +} + +// errEndpointNotReady reports an endpoint that serves the version but isn't ready. +// Running air serve again doesn't make it ready; it reports success once the +// endpoint recovers, so the error isn't marked retryable. +var errEndpointNotReady = errors.New("endpoint isn't ready") + +// checkServes reports whether endpoint serves only entity and is ready to serve, +// failing when it doesn't. +func checkServes(endpoint *servingEndpoint, entity servedEntity) (bool, error) { + name := stripControl(endpoint.Name) + if !servesOnly(currentEntities(endpoint), entity) { + return false, fmt.Errorf("endpoint %s was changed to serve %s while air serve waited for it", name, describeEntities(currentEntities(endpoint))) + } + if endpoint.State == nil || endpoint.State.Ready != serving.EndpointStateReadyReady { + return false, withCode(codeEndpointNotReady, false, fmt.Errorf("%w: endpoint %s serves version %s of %s but isn't ready; check its events and logs in the Serving UI", errEndpointNotReady, name, entity.EntityVersion, entity.EntityName)) + } + return true, nil +} + +func updating(endpoint *servingEndpoint) bool { + return endpoint.State != nil && endpoint.State.ConfigUpdate == serving.EndpointStateConfigUpdateInProgress +} + +func currentEntities(endpoint *servingEndpoint) []observedEntity { + if endpoint.Config == nil { + return nil + } + return endpoint.Config.ServedEntities +} + +func pendingEntities(endpoint *servingEndpoint) []observedEntity { + if endpoint.PendingConfig == nil { + return nil + } + return endpoint.PendingConfig.ServedEntities +} + +// describeEntities names served entities for an error, e.g. "version 2 of a.b.c". +func describeEntities(served []observedEntity) string { + if len(served) == 0 { + return "nothing" + } + names := make([]string, 0, len(served)) + for _, s := range served { + name := stripControl(s.EntityName) + if s.EntityVersion == "" { + names = append(names, name) + continue + } + names = append(names, fmt.Sprintf("version %s of %s", stripControl(s.EntityVersion), name)) + } + return strings.Join(names, " and ") +} + +// servesOnly reports whether served is exactly entity. A dedicated entity must match +// its units and compute profile; any other must match its workload type, concurrency +// range and scale-to-zero setting, and have no environment variables, since air serve +// sets none. +func servesOnly(served []observedEntity, entity servedEntity) bool { + if len(served) != 1 { + return false + } + s := served[0] + // Unity Catalog names are case-insensitive, and the endpoint reports them as + // Unity Catalog stores them. + if !strings.EqualFold(s.EntityName, entity.EntityName) || s.EntityVersion != entity.EntityVersion { + return false + } + if entity.Dedicated != nil { + return s.ProvisionedModelUnits == entity.Dedicated.ProvisionedModelUnits && s.ComputeProfile == entity.Dedicated.ComputeProfile + } + // Where GPU APIs are off, the endpoint reports a CPU entity without its workload + // type, the API's default. + workloadType := s.WorkloadType + if workloadType == "" { + workloadType = workloadTypeCPU + } + return workloadType == entity.Serving.WorkloadType && + s.MinProvisionedConcurrency == entity.Serving.MinConcurrency && + s.MaxProvisionedConcurrency == entity.Serving.MaxConcurrency && + s.ScaleToZeroEnabled == entity.Serving.ScaleToZero && + len(s.EnvironmentVars) == 0 +} + +// untilDeadline is the time left before ctx's deadline, which air serve always +// sets from --timeout. +func untilDeadline(ctx context.Context) time.Duration { + deadline, _ := ctx.Deadline() + return time.Until(deadline) +} diff --git a/cmd/air/serveendpoint_test.go b/cmd/air/serveendpoint_test.go new file mode 100644 index 00000000000..fa4dbf4255b --- /dev/null +++ b/cmd/air/serveendpoint_test.go @@ -0,0 +1,584 @@ +package aircmd + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/databricks/databricks-sdk-go/service/serving" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// fakeEndpoints is a stateful fake of the serving endpoints API for one endpoint. +// A create or config update is applied at once, and the endpoint then reports +// finalState (READY and NOT_UPDATING unless a test sets otherwise). +type fakeEndpoints struct { + t *testing.T + mu sync.Mutex + endpoint *servingEndpoint + finalState serving.EndpointState + // writes names every create and config update: "create" and "update" for serving + // compute, "create dedicated" and "update dedicated" for dedicated compute. + writes []string + // rawWrites holds the body of every create and config update, as sent. + rawWrites []string + // gets counts the GETs of an existing endpoint. Those numbered in failOnGets + // answer 500, and from readyAfterGets on (when set) the endpoint is ready. + gets int + failOnGets map[int]bool + readyAfterGets int +} + +// withDeadline returns the test's context with a deadline, which the model +// commands always set from --timeout. +func withDeadline(t *testing.T) context.Context { + ctx, cancel := context.WithTimeout(fastRetries(t.Context()), time.Minute) + t.Cleanup(cancel) + return ctx +} + +func newFakeEndpoints(t *testing.T, existing *servingEndpoint) *fakeEndpoints { + return &fakeEndpoints{ + t: t, + endpoint: existing, + finalState: serving.EndpointState{Ready: serving.EndpointStateReadyReady, ConfigUpdate: serving.EndpointStateConfigUpdateNotUpdating}, + } +} + +func (f *fakeEndpoints) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + switch { + case r.Method == http.MethodPost && r.URL.Path == servingEndpointsPath: + var req serving.CreateServingEndpoint + if !f.decode(w, r, &req) { + return + } + f.writes = append(f.writes, "create") + var entities []observedEntity + for _, e := range req.Config.ServedEntities { + entities = append(entities, observeServing(e)) + } + f.endpoint = &servingEndpoint{Name: req.Name, Config: &endpointConfig{ServedEntities: entities}, State: &f.finalState} + case r.Method == http.MethodPost && r.URL.Path == dedicatedEndpointsPath: + var req dedicatedEndpointRequest + if !f.decode(w, r, &req) { + return + } + f.writes = append(f.writes, "create dedicated") + f.endpoint = &servingEndpoint{Name: req.Name, Config: &endpointConfig{ServedEntities: observeDedicated(req.Config.ServedEntities)}, State: &f.finalState} + case r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, dedicatedEndpointsPath+"/"): + var req dedicatedEndpointUpdate + if !f.decode(w, r, &req) { + return + } + // As the server does, which reads the entities from the request's config. + if len(req.Config.ServedEntities) == 0 { + http.Error(w, `{"error_code": "INVALID_PARAMETER_VALUE", "message": "config is required for dedicated inference"}`, http.StatusBadRequest) + return + } + if f.updateConflicts(w) { + return + } + f.writes = append(f.writes, "update dedicated") + f.endpoint.Config = &endpointConfig{ServedEntities: observeDedicated(req.Config.ServedEntities)} + f.endpoint.PendingConfig = nil + f.endpoint.State = &f.finalState + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/config"): + var req serving.EndpointCoreConfigInput + if !f.decode(w, r, &req) { + return + } + if f.updateConflicts(w) { + return + } + f.writes = append(f.writes, "update") + var entities []observedEntity + for _, e := range req.ServedEntities { + entities = append(entities, observeServing(e)) + } + f.endpoint.Config = &endpointConfig{ServedEntities: entities} + f.endpoint.PendingConfig = nil + f.endpoint.State = &f.finalState + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, servingEndpointsPath+"/"): + if f.endpoint != nil { + f.gets++ + if f.failOnGets[f.gets] { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"error_code": "INTERNAL_ERROR", "message": "Something went wrong."}`)) + return + } + if f.readyAfterGets > 0 && f.gets >= f.readyAfterGets { + f.endpoint.State = &readyState + } + } + if f.endpoint == nil { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error_code": "RESOURCE_DOES_NOT_EXIST", "message": "Endpoint not found"}`)) + return + } + default: + _, _ = w.Write([]byte(`{}`)) + return + } + assert.NoError(f.t, json.NewEncoder(w).Encode(f.endpoint)) +} + +// updateConflicts answers a config update that arrives while the endpoint is updating. +func (f *fakeEndpoints) updateConflicts(w http.ResponseWriter) bool { + if !updating(f.endpoint) { + return false + } + w.WriteHeader(http.StatusConflict) + _, _ = w.Write([]byte(`{"error_code": "RESOURCE_CONFLICT", "message": "The endpoint is being updated."}`)) + return true +} + +// decode reads a request body into v, failing the request (not the handler +// goroutine) when it can't. +func (f *fakeEndpoints) decode(w http.ResponseWriter, r *http.Request, v any) bool { + raw, err := io.ReadAll(r.Body) + if !assert.NoError(f.t, err) || !assert.NoError(f.t, json.Unmarshal(raw, v)) { + w.WriteHeader(http.StatusInternalServerError) + return false + } + f.rawWrites = append(f.rawWrites, string(raw)) + return true +} + +// observeServing is a served entity with serving compute, as the endpoint reports it. +func observeServing(e serving.ServedEntityInput) observedEntity { + return observedEntity{ + EntityName: e.EntityName, + EntityVersion: e.EntityVersion, + WorkloadType: string(e.WorkloadType), + MinProvisionedConcurrency: e.MinProvisionedConcurrency, + MaxProvisionedConcurrency: e.MaxProvisionedConcurrency, + ScaleToZeroEnabled: e.ScaleToZeroEnabled, + EnvironmentVars: e.EnvironmentVars, + } +} + +// observeDedicated are dedicated served entities, as the endpoint reports them. +func observeDedicated(entities []dedicatedServedEntity) []observedEntity { + var out []observedEntity + for _, e := range entities { + out = append(out, observedEntity{ + EntityName: e.EntityName, + EntityVersion: e.EntityVersion, + ProvisionedModelUnits: e.ProvisionedModelUnits, + ComputeProfile: e.ComputeProfile, + }) + } + return out +} + +// observe is entity as the endpoint reports it once it serves it. +func observe(entity servedEntity) observedEntity { + if entity.Dedicated != nil { + return observedEntity{ + EntityName: entity.EntityName, + EntityVersion: entity.EntityVersion, + ProvisionedModelUnits: entity.Dedicated.ProvisionedModelUnits, + ComputeProfile: entity.Dedicated.ComputeProfile, + } + } + return observedEntity{ + EntityName: entity.EntityName, + EntityVersion: entity.EntityVersion, + WorkloadType: entity.Serving.WorkloadType, + MinProvisionedConcurrency: entity.Serving.MinConcurrency, + MaxProvisionedConcurrency: entity.Serving.MaxConcurrency, + ScaleToZeroEnabled: entity.Serving.ScaleToZero, + } +} + +func (f *fakeEndpoints) start() *httptest.Server { + srv := httptest.NewServer(f) + f.t.Cleanup(srv.Close) + return srv +} + +// testEntity is a version of the test model on serving compute: one or two replicas +// of GPU_MEDIUM. +func testEntity(version string) servedEntity { + return servedEntity{ + EntityName: "main.models.qwen", + EntityVersion: version, + Serving: servingCompute{WorkloadType: "GPU_MEDIUM", MinConcurrency: 4, MaxConcurrency: 8}, + } +} + +// testDedicatedEntity is a version of the test model on dedicated compute. +func testDedicatedEntity(version string) servedEntity { + return servedEntity{ + EntityName: "main.models.qwen", + EntityVersion: version, + Dedicated: &dedicatedCompute{ComputeProfile: "COMPUTE_PROFILE_LOW_LATENCY", ProvisionedModelUnits: 600}, + } +} + +func endpointServing(entity servedEntity, state serving.EndpointState) *servingEndpoint { + return &servingEndpoint{ + Name: "qwen-chat", + Config: &endpointConfig{ServedEntities: []observedEntity{observe(entity)}}, + State: &state, + } +} + +var readyState = serving.EndpointState{Ready: serving.EndpointStateReadyReady, ConfigUpdate: serving.EndpointStateConfigUpdateNotUpdating} + +func TestServeOnEndpointCreatesAMissingEndpoint(t *testing.T) { + fake := newFakeEndpoints(t, nil) + srv := fake.start() + + ready, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), true, nil) + require.NoError(t, err) + assert.True(t, ready) + assert.Equal(t, []string{"create"}, fake.writes) + assert.Equal(t, "3", fake.endpoint.Config.ServedEntities[0].EntityVersion) +} + +func TestServeOnEndpointWithoutWatchReturnsOnceAccepted(t *testing.T) { + tests := []struct { + name string + existing *servingEndpoint + wantWrites []string + }{ + {"a missing endpoint", nil, []string{"create"}}, + {"another version", endpointServing(testEntity("2"), readyState), []string{"update"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fake := newFakeEndpoints(t, tt.existing) + srv := fake.start() + polls := 0 + ready, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), false, func(*servingEndpoint) { polls++ }) + require.NoError(t, err) + assert.False(t, ready) + assert.Equal(t, tt.wantWrites, fake.writes) + assert.Zero(t, polls, "nothing is waited for") + }) + } +} + +func TestServeOnEndpointWithoutWatchDoesntWaitForItsOwnPendingUpdate(t *testing.T) { + existing := endpointServing(testEntity("2"), serving.EndpointState{Ready: serving.EndpointStateReadyReady, ConfigUpdate: serving.EndpointStateConfigUpdateInProgress}) + existing.PendingConfig = &endpointConfig{ServedEntities: []observedEntity{observe(testEntity("3"))}} + fake := newFakeEndpoints(t, existing) + srv := fake.start() + + ready, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), false, nil) + require.NoError(t, err) + assert.False(t, ready) + assert.Empty(t, fake.writes) +} + +func TestServeOnEndpointWithoutWatchReportsAServedVersion(t *testing.T) { + fake := newFakeEndpoints(t, endpointServing(testEntity("3"), readyState)) + srv := fake.start() + + ready, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), false, nil) + require.NoError(t, err) + assert.True(t, ready) + assert.Empty(t, fake.writes) +} + +func TestServeOnEndpointRefusesAnotherModelBeforeWaitingBehindItsUpdate(t *testing.T) { + other := testEntity("5") + other.EntityName = "main.models.llama" + existing := endpointServing(other, serving.EndpointState{Ready: serving.EndpointStateReadyReady, ConfigUpdate: serving.EndpointStateConfigUpdateInProgress}) + existing.PendingConfig = &endpointConfig{ServedEntities: []observedEntity{observe(other)}} + fake := newFakeEndpoints(t, existing) + srv := fake.start() + + polls := 0 + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), false, func(*servingEndpoint) { polls++ }) + assert.ErrorContains(t, err, "endpoint qwen-chat serves version 5 of main.models.llama") + assert.Zero(t, polls) + assert.Empty(t, fake.writes) +} + +func TestServeOnEndpointUpdatesOnceAnotherUpdateFails(t *testing.T) { + existing := endpointServing(testEntity("1"), serving.EndpointState{Ready: serving.EndpointStateReadyReady, ConfigUpdate: serving.EndpointStateConfigUpdateInProgress}) + existing.PendingConfig = &endpointConfig{ServedEntities: []observedEntity{observe(testEntity("2"))}} + fake := newFakeEndpoints(t, existing) + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), true, func(endpoint *servingEndpoint) { + // The other update fails after the first poll, which frees the endpoint. + if updating(endpoint) { + fake.mu.Lock() + defer fake.mu.Unlock() + fake.endpoint = endpointServing(testEntity("1"), serving.EndpointState{Ready: serving.EndpointStateReadyReady, ConfigUpdate: serving.EndpointStateConfigUpdateUpdateFailed}) + } + }) + require.NoError(t, err) + assert.Equal(t, []string{"update"}, fake.writes) + assert.Equal(t, "3", fake.endpoint.Config.ServedEntities[0].EntityVersion) +} + +func TestServeOnEndpointUpdatesAnotherVersion(t *testing.T) { + fake := newFakeEndpoints(t, endpointServing(testEntity("2"), readyState)) + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), true, nil) + require.NoError(t, err) + assert.Equal(t, []string{"update"}, fake.writes) +} + +func TestServeOnEndpointUpdatesChangedCompute(t *testing.T) { + fake := newFakeEndpoints(t, endpointServing(testEntity("3"), readyState)) + srv := fake.start() + entity := testEntity("3") + entity.Serving.MaxConcurrency = 16 + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", entity, true, nil) + require.NoError(t, err) + assert.Equal(t, []string{"update"}, fake.writes) +} + +func TestServeOnEndpointLeavesAServedVersion(t *testing.T) { + fake := newFakeEndpoints(t, endpointServing(testEntity("3"), readyState)) + srv := fake.start() + // Unity Catalog reports names lowercased. + entity := testEntity("3") + entity.EntityName = "Main.Models.Qwen" + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", entity, true, nil) + require.NoError(t, err) + assert.Empty(t, fake.writes) +} + +func TestServeOnEndpointCreatesADedicatedEndpoint(t *testing.T) { + fake := newFakeEndpoints(t, nil) + srv := fake.start() + + ready, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testDedicatedEntity("3"), true, nil) + require.NoError(t, err) + assert.True(t, ready) + assert.Equal(t, []string{"create dedicated"}, fake.writes) + assert.Equal(t, "COMPUTE_PROFILE_LOW_LATENCY", fake.endpoint.Config.ServedEntities[0].ComputeProfile) + require.Len(t, fake.rawWrites, 1) + assert.JSONEq(t, `{ + "name": "qwen-chat", + "config": {"served_entities": [{ + "entity_name": "main.models.qwen", + "entity_version": "3", + "provisioned_model_units": 600, + "compute_profile": "COMPUTE_PROFILE_LOW_LATENCY" + }]} + }`, fake.rawWrites[0]) +} + +func TestServeOnEndpointUpdatesADedicatedEndpointWhenItsCapacityChanges(t *testing.T) { + tests := []struct { + name string + entity servedEntity + wantBody string + }{ + { + "units", + servedEntity{EntityName: "main.models.qwen", EntityVersion: "3", Dedicated: &dedicatedCompute{ComputeProfile: "COMPUTE_PROFILE_LOW_LATENCY", ProvisionedModelUnits: 900}}, + `{"config": {"served_entities": [{"entity_name": "main.models.qwen", "entity_version": "3", "provisioned_model_units": 900, "compute_profile": "COMPUTE_PROFILE_LOW_LATENCY"}]}}`, + }, + { + "profile", + servedEntity{EntityName: "main.models.qwen", EntityVersion: "3", Dedicated: &dedicatedCompute{ComputeProfile: "COMPUTE_PROFILE_FAST", ProvisionedModelUnits: 600}}, + `{"config": {"served_entities": [{"entity_name": "main.models.qwen", "entity_version": "3", "provisioned_model_units": 600, "compute_profile": "COMPUTE_PROFILE_FAST"}]}}`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fake := newFakeEndpoints(t, endpointServing(testDedicatedEntity("3"), readyState)) + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", tt.entity, true, nil) + require.NoError(t, err) + assert.Equal(t, []string{"update dedicated"}, fake.writes) + require.Len(t, fake.rawWrites, 1) + assert.JSONEq(t, tt.wantBody, fake.rawWrites[0]) + }) + } +} + +func TestServeOnEndpointLeavesADedicatedVersion(t *testing.T) { + fake := newFakeEndpoints(t, endpointServing(testDedicatedEntity("3"), readyState)) + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testDedicatedEntity("3"), true, nil) + require.NoError(t, err) + assert.Empty(t, fake.writes) +} + +func TestServeOnEndpointRefusesToChangeAnEndpointsKind(t *testing.T) { + tests := []struct { + name string + existing servedEntity + entity servedEntity + wantErr string + }{ + {"serving compute to dedicated", testEntity("3"), testDedicatedEntity("3"), "endpoint qwen-chat serves on serving compute, and this version is served on dedicated compute"}, + {"dedicated to serving compute", testDedicatedEntity("3"), testEntity("3"), "endpoint qwen-chat serves on dedicated compute, and this version is served on serving compute"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fake := newFakeEndpoints(t, endpointServing(tt.existing, readyState)) + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", tt.entity, true, nil) + assert.ErrorContains(t, err, tt.wantErr) + assert.Empty(t, fake.writes) + }) + } +} + +func TestServeOnEndpointWaitsForItsOwnPendingUpdate(t *testing.T) { + existing := endpointServing(testEntity("2"), serving.EndpointState{Ready: serving.EndpointStateReadyReady, ConfigUpdate: serving.EndpointStateConfigUpdateInProgress}) + existing.PendingConfig = &endpointConfig{ServedEntities: []observedEntity{observe(testEntity("3"))}} + fake := newFakeEndpoints(t, existing) + srv := fake.start() + + polls := 0 + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), true, func(*servingEndpoint) { + // The pending update finishes after the first poll. + polls++ + fake.mu.Lock() + defer fake.mu.Unlock() + fake.endpoint = endpointServing(testEntity("3"), readyState) + }) + require.NoError(t, err) + assert.Empty(t, fake.writes) + assert.Positive(t, polls) +} + +func TestServeOnEndpointWaitsForAnotherUpdateBeforeUpdating(t *testing.T) { + existing := endpointServing(testEntity("1"), serving.EndpointState{Ready: serving.EndpointStateReadyReady, ConfigUpdate: serving.EndpointStateConfigUpdateInProgress}) + existing.PendingConfig = &endpointConfig{ServedEntities: []observedEntity{observe(testEntity("2"))}} + fake := newFakeEndpoints(t, existing) + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), true, func(endpoint *servingEndpoint) { + // The other update finishes after the first poll. + if updating(endpoint) { + fake.mu.Lock() + defer fake.mu.Unlock() + fake.endpoint = endpointServing(testEntity("2"), readyState) + } + }) + require.NoError(t, err) + assert.Equal(t, []string{"update"}, fake.writes) + assert.Equal(t, "3", fake.endpoint.Config.ServedEntities[0].EntityVersion) +} + +func TestServeOnEndpointRefusesToReplaceOtherEntities(t *testing.T) { + other := testEntity("5") + other.EntityName = "main.models.llama" + split := endpointServing(testEntity("2"), readyState) + split.Config.ServedEntities = append(split.Config.ServedEntities, observe(testEntity("1"))) + tests := []struct { + name string + existing *servingEndpoint + wantErr string + }{ + {"another model", endpointServing(other, readyState), "endpoint qwen-chat serves version 5 of main.models.llama, and air serve replaces only a single version of main.models.qwen"}, + {"a traffic split", split, "endpoint qwen-chat serves version 2 of main.models.qwen and version 1 of main.models.qwen"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fake := newFakeEndpoints(t, tt.existing) + w := newTestWorkspaceClient(t, fake.start().URL) + + _, err := serveOnEndpoint(withDeadline(t), w, "qwen-chat", testEntity("3"), true, nil) + assert.ErrorContains(t, err, tt.wantErr) + assert.Empty(t, fake.writes) + }) + } +} + +func TestServeOnEndpointWaitsThroughTransientFailures(t *testing.T) { + fake := newFakeEndpoints(t, nil) + // The endpoint starts over three polls, and the first GET of each fails: more + // failures than one request may retry, spread over the wait. + fake.finalState = serving.EndpointState{Ready: serving.EndpointStateReadyNotReady, ConfigUpdate: serving.EndpointStateConfigUpdateInProgress} + fake.failOnGets = map[int]bool{1: true, 3: true, 5: true} + fake.readyAfterGets = 6 + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), true, nil) + require.NoError(t, err) + assert.Equal(t, []string{"create"}, fake.writes) + assert.Equal(t, 6, fake.gets) +} + +func TestServeOnEndpointReportsAFailedUpdate(t *testing.T) { + fake := newFakeEndpoints(t, nil) + fake.finalState = serving.EndpointState{Ready: serving.EndpointStateReadyNotReady, ConfigUpdate: serving.EndpointStateConfigUpdateUpdateFailed} + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), true, nil) + assert.ErrorContains(t, err, "UPDATE_FAILED") +} + +func TestServeOnEndpointReportsAnEndpointThatIsNotReady(t *testing.T) { + fake := newFakeEndpoints(t, endpointServing(testEntity("3"), serving.EndpointState{Ready: serving.EndpointStateReadyNotReady, ConfigUpdate: serving.EndpointStateConfigUpdateNotUpdating})) + srv := fake.start() + + _, err := serveOnEndpoint(withDeadline(t), newTestWorkspaceClient(t, srv.URL), "qwen-chat", testEntity("3"), true, nil) + assert.ErrorContains(t, err, "endpoint qwen-chat serves version 3 of main.models.qwen but isn't ready") +} + +func TestDedicatedEntityJSON(t *testing.T) { + entity := testDedicatedEntity("3") + raw, err := json.Marshal(entity.dedicatedJSON()) + require.NoError(t, err) + assert.JSONEq(t, `{"entity_name": "main.models.qwen", "entity_version": "3", "provisioned_model_units": 600, "compute_profile": "COMPUTE_PROFILE_LOW_LATENCY"}`, string(raw)) +} + +func TestServesOnly(t *testing.T) { + entity := testEntity("3") + assert.True(t, servesOnly([]observedEntity{observe(entity)}, entity)) + assert.False(t, servesOnly(nil, entity)) + assert.False(t, servesOnly([]observedEntity{observe(entity), observe(testEntity("2"))}, entity)) + + // air serve sets no environment variables, so an endpoint with any is updated. + withVars := observe(entity) + withVars.EnvironmentVars = map[string]string{"HF_TOKEN": "{{secrets/llm/hf_token}}"} + assert.False(t, servesOnly([]observedEntity{withVars}, entity)) + + // Where GPU APIs are off, the endpoint leaves out a CPU entity's workload type. + cpu := testEntity("3") + cpu.Serving.WorkloadType = "CPU" + reported := observe(cpu) + reported.WorkloadType = "" + assert.True(t, servesOnly([]observedEntity{reported}, cpu)) + assert.False(t, servesOnly([]observedEntity{reported}, entity), "a missing workload type is CPU, not a GPU") + + scaled := observe(entity) + scaled.ScaleToZeroEnabled = true + assert.False(t, servesOnly([]observedEntity{scaled}, entity)) + + for _, observed := range []func(*observedEntity){ + func(o *observedEntity) { o.MinProvisionedConcurrency = 8 }, + func(o *observedEntity) { o.MaxProvisionedConcurrency = 16 }, + func(o *observedEntity) { o.WorkloadType = "GPU_XLARGE" }, + } { + other := observe(entity) + observed(&other) + assert.False(t, servesOnly([]observedEntity{other}, entity), "%+v", other) + } +} + +func TestServesOnlyDedicated(t *testing.T) { + entity := testDedicatedEntity("3") + assert.True(t, servesOnly([]observedEntity{observe(entity)}, entity)) + assert.False(t, servesOnly([]observedEntity{observe(testEntity("3"))}, entity), "serving compute isn't a dedicated entity") + assert.False(t, servesOnly([]observedEntity{observe(entity)}, testEntity("3")), "a dedicated entity isn't serving compute") +} diff --git a/cmd/air/servepackage.go b/cmd/air/servepackage.go new file mode 100644 index 00000000000..584219b9ff4 --- /dev/null +++ b/cmd/air/servepackage.go @@ -0,0 +1,100 @@ +package aircmd + +import ( + "context" + "errors" + "fmt" + "io" + "strings" + + "github.com/databricks/databricks-sdk-go" + "github.com/databricks/databricks-sdk-go/apierr" + "github.com/databricks/databricks-sdk-go/service/files" + "go.yaml.in/yaml/v3" +) + +// Where a version's MLmodel is in the Files API, and the most of it air serve reads. +const ( + modelVersionFilesPrefix = "/Models/" + mlmodelFile = "MLmodel" + maxMLmodelBytes = 1 << 20 +) + +// MLmodel keys air serve reads: metadata.entrypoint is the command that serves a +// version, and python_function's model_dir artifact is a dedicated checkpoint. +const ( + mlmodelEntrypointKey = "entrypoint" + mlmodelTaskKey = "task" + mlmodelDedicatedArtifact = "model_dir" + llmTaskPrefix = "llm/v1/" +) + +// versionPackage is what a version's MLmodel says about how it is served. +type versionPackage struct { + // command is set for a version served by its own command. + command bool + // dedicated is set for a checkpoint registered for dedicated inference. + dedicated bool + // task is the task the version is served for, "" if the MLmodel names none. + task string +} + +// readVersionPackage reads version of model's MLmodel as the caller. +func readVersionPackage(ctx context.Context, w *databricks.WorkspaceClient, model, version string) (versionPackage, error) { + described := fmt.Sprintf("version %s of %s", version, model) + path := modelVersionFilesPrefix + strings.ReplaceAll(model, ".", "/") + "/" + version + "/" + mlmodelFile + resp, err := w.Files.Download(ctx, files.DownloadRequest{FilePath: path}) + if errors.Is(err, apierr.ErrNotFound) || errors.Is(err, apierr.ErrResourceDoesNotExist) { + return versionPackage{}, withCode(codeInvalidArgs, false, fmt.Errorf("%s doesn't exist or has no MLmodel, so air serve can't tell what serves it", described)) + } + if err != nil { + return versionPackage{}, fmt.Errorf("reading the MLmodel of %s: %w", described, err) + } + defer resp.Contents.Close() + content, err := io.ReadAll(io.LimitReader(resp.Contents, maxMLmodelBytes+1)) + if err != nil { + return versionPackage{}, fmt.Errorf("reading the MLmodel of %s: %w", described, err) + } + if len(content) > maxMLmodelBytes { + return versionPackage{}, withCode(codeInvalidArgs, false, fmt.Errorf("the MLmodel of %s is larger than %d bytes", described, maxMLmodelBytes)) + } + var doc map[string]any + if err := yaml.Unmarshal(content, &doc); err != nil { + return versionPackage{}, withCode(codeInvalidArgs, false, fmt.Errorf("the MLmodel of %s isn't valid YAML: %w", described, err)) + } + return mlmodelServedBy(doc), nil +} + +// mlmodelServedBy describes how an MLmodel's version is served. It follows the +// server's rule for a dedicated checkpoint: an LLM task, no entrypoint key whatever +// its value, and a model_dir artifact with a path. Fields of an unexpected shape read +// as absent, as the server's reader takes them. +func mlmodelServedBy(doc map[string]any) versionPackage { + metadata, _ := doc["metadata"].(map[string]any) + _, hasEntrypoint := metadata[mlmodelEntrypointKey] + task := nonEmptyString(metadata[mlmodelTaskKey]) + flavors, _ := doc["flavors"].(map[string]any) + pyfunc, _ := flavors["python_function"].(map[string]any) + artifacts, _ := pyfunc["artifacts"].(map[string]any) + checkpoint, _ := artifacts[mlmodelDedicatedArtifact].(map[string]any) + return versionPackage{ + command: nonEmptyString(metadata[mlmodelEntrypointKey]) != "", + dedicated: !hasEntrypoint && isLLMTask(task) && nonEmptyString(checkpoint["path"]) != "", + task: task, + } +} + +// isLLMTask reports whether task is one dedicated inference serves: an llm/v1 task +// other than audio, which is served only by a command. +func isLLMTask(task string) bool { + return strings.HasPrefix(task, llmTaskPrefix) && task != taskAudioTranscriptions && task != taskAudioTranslations +} + +// nonEmptyString is v when it is a string with something besides spaces, else "". +func nonEmptyString(v any) string { + s, _ := v.(string) + if strings.TrimSpace(s) == "" { + return "" + } + return s +} diff --git a/cmd/air/servepackage_test.go b/cmd/air/servepackage_test.go new file mode 100644 index 00000000000..87588922c80 --- /dev/null +++ b/cmd/air/servepackage_test.go @@ -0,0 +1,124 @@ +package aircmd + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.yaml.in/yaml/v3" +) + +// MLmodels of the versions air register writes, and of one MLflow logged. +const ( + commandMLmodel = `flavors: + python_function: + env: {virtualenv: python_env.yaml} + python_version: "3.12" +metadata: + task: llm/v1/chat + entrypoint: python -m vllm.entrypoints.openai.api_server --model base --port 8080 + volume_artifacts_path: /Volumes/main/models/weights/base +` + dedicatedMLmodel = `flavors: + python_function: + artifacts: + model_dir: {path: artifacts/gemma4_e4b, uri: /Volumes/main/models/weights/gemma4_e4b} + python_version: "3.12" +metadata: + task: llm/v1/chat + volume_artifacts_path: /Volumes/main/models/weights/gemma4_e4b +` + loggedMLmodel = `flavors: + python_function: + loader_module: mlflow.sklearn + python_version: "3.12" + sklearn: {pickled_model: model.pkl} +` +) + +func TestMLmodelServedBy(t *testing.T) { + tests := []struct { + name string + mlmodel string + want versionPackage + }{ + {"a command", commandMLmodel, versionPackage{command: true, task: "llm/v1/chat"}}, + {"a dedicated checkpoint", dedicatedMLmodel, versionPackage{dedicated: true, task: "llm/v1/chat"}}, + {"a logged model", loggedMLmodel, versionPackage{}}, + // The server writes MLmodel as JSON, which is valid YAML. + {"a dedicated checkpoint written as JSON", `{"flavors": {"python_function": {"artifacts": {"model_dir": {"path": "artifacts/gemma", "uri": "/Volumes/a/b/c/gemma"}}}}, "metadata": {"task": "llm/v1/chat"}}`, versionPackage{dedicated: true, task: "llm/v1/chat"}}, + {"a command written as JSON", `{"metadata": {"task": "llm/v1/embeddings", "entrypoint": "python serve.py"}}`, versionPackage{command: true, task: "llm/v1/embeddings"}}, + {"an audio command", replaceFirst("task: llm/v1/chat", "task: llm/v1/audio/transcriptions")(commandMLmodel), versionPackage{command: true, task: "llm/v1/audio/transcriptions"}}, + // The server refuses a custom entrypoint for dedicated inference. + {"a model_dir with an entrypoint", dedicatedMLmodel + " entrypoint: python serve.py\n", versionPackage{command: true, task: "llm/v1/chat"}}, + {"a model_dir without a path", replaceFirst("path: artifacts/gemma4_e4b, ", "")(dedicatedMLmodel), versionPackage{task: "llm/v1/chat"}}, + {"a blank entrypoint", replaceFirst("entrypoint: python -m vllm.entrypoints.openai.api_server --model base --port 8080", `entrypoint: " "`)(commandMLmodel), versionPackage{task: "llm/v1/chat"}}, + {"a model_dir that isn't a map", "flavors: {python_function: {artifacts: {model_dir: weights}}}\n", versionPackage{}}, + // The server serves only an LLM task with dedicated inference, so a custom + // Python model's model_dir artifact doesn't make it a dedicated checkpoint. + {"a model_dir without a task", replaceFirst(" task: llm/v1/chat\n", "")(dedicatedMLmodel), versionPackage{}}, + {"a model_dir with an audio task", replaceFirst("task: llm/v1/chat", "task: llm/v1/audio/transcriptions")(dedicatedMLmodel), versionPackage{task: "llm/v1/audio/transcriptions"}}, + {"a model_dir with another task", replaceFirst("task: llm/v1/chat", "task: classification")(dedicatedMLmodel), versionPackage{task: "classification"}}, + // The server refuses any entrypoint key, whatever its value. + {"a model_dir with a null entrypoint", dedicatedMLmodel + " entrypoint:\n", versionPackage{task: "llm/v1/chat"}}, + {"metadata that isn't a map", "metadata: []\nflavors: {python_function: x}\n", versionPackage{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var doc map[string]any + require.NoError(t, yaml.Unmarshal([]byte(tt.mlmodel), &doc)) + assert.Equal(t, tt.want, mlmodelServedBy(doc)) + }) + } +} + +// filesServer serves the Files API's download of path with body, and 404 for any +// other file. +func filesServer(t *testing.T, path, body string) *httptest.Server { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/api/2.0/fs/files"+path: + _, _ = w.Write([]byte(body)) + case strings.HasPrefix(r.URL.Path, "/api/2.0/fs/files/"): + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error_code": "NOT_FOUND", "message": "The file being accessed is not found."}`)) + default: + _, _ = w.Write([]byte(`{}`)) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func TestReadVersionPackage(t *testing.T) { + srv := filesServer(t, "/Models/main/models/qwen/3/MLmodel", dedicatedMLmodel) + pkg, err := readVersionPackage(t.Context(), newTestWorkspaceClient(t, srv.URL), "main.models.qwen", "3") + require.NoError(t, err) + assert.Equal(t, versionPackage{dedicated: true, task: "llm/v1/chat"}, pkg) +} + +func TestReadVersionPackageFailures(t *testing.T) { + tests := []struct { + name string + body string + version string + wantErr string + }{ + {"no MLmodel", dedicatedMLmodel, "4", "version 4 of main.models.qwen doesn't exist or has no MLmodel, so air serve can't tell what serves it"}, + {"not YAML", "flavors: [", "3", "the MLmodel of version 3 of main.models.qwen isn't valid YAML"}, + {"not a mapping", "- flavors\n", "3", "the MLmodel of version 3 of main.models.qwen isn't valid YAML"}, + {"too large", "metadata: {task: " + string(make([]byte, maxMLmodelBytes)) + "}", "3", "the MLmodel of version 3 of main.models.qwen is larger than 1048576 bytes"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := filesServer(t, "/Models/main/models/qwen/3/MLmodel", tt.body) + _, err := readVersionPackage(t.Context(), newTestWorkspaceClient(t, srv.URL), "main.models.qwen", tt.version) + assert.ErrorContains(t, err, tt.wantErr) + code, _ := modelErrorCode(err) + assert.Equal(t, codeInvalidArgs, code) + }) + } +}