diff --git a/cmd/air/air.go b/cmd/air/air.go index 7bb15f1e995..ed01edfef32 100644 --- a/cmd/air/air.go +++ b/cmd/air/air.go @@ -51,7 +51,7 @@ see your active runs with "databricks air list".` wrapRunErrorWithDebugTip(runCommand) addToGroup(cmd, runGroupID, runCommand) addToGroup(cmd, manageGroupID, newGetCommand(), newListCommand(), newLogsCommand(), newCancelCommand()) - addToGroup(cmd, packageGroupID, newConvertToDabsCommand(), newImagesCommand()) + addToGroup(cmd, packageGroupID, newRegisterCommand(), newConvertToDabsCommand(), newImagesCommand()) addToGroup(cmd, capacityGroupID, newPoolsCommand()) // Subcommands inherit this help func, so the footer is printed only for `air` itself. diff --git a/cmd/air/air_test.go b/cmd/air/air_test.go index 15877be56fe..9738ded9081 100644 --- a/cmd/air/air_test.go +++ b/cmd/air/air_test.go @@ -19,7 +19,7 @@ func TestNewRegistersAllSubcommands(t *testing.T) { registered[c.Name()] = true } - want := []string{"run", "get", "list", "pools", "logs", "cancel", "convert-to-dabs", "images"} + want := []string{"run", "get", "list", "pools", "logs", "cancel", "register", "convert-to-dabs", "images"} for _, name := range want { assert.True(t, registered[name], "subcommand %q is not registered", name) } diff --git a/cmd/air/modelcmd.go b/cmd/air/modelcmd.go index a2277e16a91..a1dcc49e4ef 100644 --- a/cmd/air/modelcmd.go +++ b/cmd/air/modelcmd.go @@ -3,16 +3,19 @@ package aircmd import ( "context" "errors" + "fmt" "net/http" "regexp" "sync" + "unicode/utf16" "github.com/databricks/databricks-sdk-go/apierr" "github.com/databricks/databricks-sdk-go/retries" + "github.com/spf13/cobra" ) -// This file holds what `air register` and `air serve` share: their JSON error codes -// and how they report a wait they stopped. +// This file holds what `air register` and `air serve` share: their JSON error codes, +// how they report a wait they stopped, and the names and numbers both files take. // Errors a model command wraps when it stops waiting, as "air register was // interrupted". The server keeps working, and the error says how to continue. @@ -94,5 +97,88 @@ func modelErrorCode(err error) (code string, retryable bool) { return codeInternalError, true } +// serveCommandPath is the command air register's output points to for serving a +// version, and whose -h documents serveConfig. +const serveCommandPath = "databricks air serve" + +// Flags the model commands share. +const ( + ucModelFlag = "uc-model" + endpointNameFlag = "endpoint-name" + modelVersionFlag = "model-version" + modelSourceFlag = "model-source" +) + +// changedFlags reports which of names were passed on the command line. +func changedFlags(cmd *cobra.Command, names ...string) map[string]bool { + changed := map[string]bool{} + for _, name := range names { + changed[name] = cmd.Flags().Changed(name) + } + return changed +} + +// renderModelError renders a model command's failure, if any, with its JSON error +// code and whether retrying can help. +func renderModelError(cmd *cobra.Command, err error) error { + if err == nil { + return nil + } + code, retryable := modelErrorCode(err) + kind := "PERMANENT" + if retryable { + kind = "TRANSIENT" + } + return renderError(cmd.Context(), cmd, code, kind, retryable, err) +} + +// schemaHelp is the help of a model command whose YAML schema documents a field +// given as a positional argument to -h, as in `-h config.compute`. cobra passes +// -h's positional args to the help func before Args/required-flag validation, so +// a field is documented without needing -f. +func schemaHelp(schema func() configField, commandPath string) func(*cobra.Command, []string) { + return func(c *cobra.Command, args []string) { + fields := c.Flags().Args() + if len(fields) == 0 { + // Parent() is nil for a detached command (unit tests). + if parent := c.Parent(); parent != nil { + parent.HelpFunc()(c, args) + return + } + _ = c.Usage() + return + } + field, err := resolveSchemaField(schema(), fields[0]) + if err != nil { + c.PrintErrln("Error:", err) + return + } + renderConfigField(c.OutOrStdout(), commandPath, field, nil) + } +} + +// registeredModelRe matches .. with the characters the +// server accepts in each part. +var registeredModelRe = sync.OnceValue(func() *regexp.Regexp { return regexp.MustCompile("^[^\\s./`]+\\.[^\\s./`]+\\.[^\\s./`]+$") }) + // modelVersionRe matches a Unity Catalog model version number. var modelVersionRe = sync.OnceValue(func() *regexp.Regexp { return regexp.MustCompile(`^[1-9][0-9]*$`) }) + +// validateUCModelName checks a Unity Catalog model name from source, the YAML field +// or a flag. +func validateUCModelName(name, source string) error { + if !registeredModelRe().MatchString(name) { + return fmt.Errorf("%s must be a Unity Catalog model name as .., got %q", source, name) + } + return nil +} + +// serverLength is the length of s as the server's limits count it, in UTF-16 +// code units. +func serverLength(s string) int { + n := 0 + for _, r := range s { + n += utf16.RuneLen(r) + } + return n +} diff --git a/cmd/air/modelcmd_test.go b/cmd/air/modelcmd_test.go index 16a8681e622..ee6776a73b3 100644 --- a/cmd/air/modelcmd_test.go +++ b/cmd/air/modelcmd_test.go @@ -51,3 +51,10 @@ func TestModelErrorCode(t *testing.T) { assert.Equal(t, tt.retryable, retryable, tt.name) } } + +func TestValidateUCModelName(t *testing.T) { + assert.NoError(t, validateUCModelName("main.serving.defect-detector", "uc_model")) + for _, name := range []string{"", "qwen", "a.b", "a.b.c.d", "a.b/c.d", "a. b.c", "main.models.`qwen`"} { + assert.ErrorContains(t, validateUCModelName(name, "--uc-model"), "--uc-model must be a Unity Catalog model name", name) + } +} diff --git a/cmd/air/register.go b/cmd/air/register.go new file mode 100644 index 00000000000..7631ea3219a --- /dev/null +++ b/cmd/air/register.go @@ -0,0 +1,345 @@ +package aircmd + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "strings" + "time" + + "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/cmdctx" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/flags" + "github.com/databricks/cli/libs/shellquote" + "github.com/databricks/databricks-sdk-go" + "github.com/spf13/cobra" +) + +// defaultRegisterTimeout bounds the wait for a checkpoint's weights to be copied. +const defaultRegisterTimeout = time.Hour + +// registerResult is the JSON payload for `air register`. +type registerResult struct { + Status string `json:"status"` + DryRun bool `json:"dry_run,omitempty"` + Plan *registerPlan `json:"plan,omitempty"` + UCModel string `json:"uc_model,omitempty"` + ModelVersion string `json:"model_version,omitempty"` + ModelID string `json:"model_id,omitempty"` + IdempotencyKey string `json:"idempotency_key,omitempty"` + // EnvironmentStagingFailed is set when the version's serving environment + // couldn't be prepared ahead of time, so an endpoint can be slower to start. + EnvironmentStagingFailed bool `json:"environment_staging_failed,omitempty"` +} + +// registerPlan is the registration a dry run reports: what serves the checkpoint, +// command or dedicated, and the request that would register it, without a key. +type registerPlan struct { + Variant string `json:"variant"` + Request registerModelPackageRequest `json:"request"` +} + +// registerOptions are the `air register` flags. +type registerOptions struct { + file string + overrides []string + modelSource string + ucModel string + // flagsSet records which of the model source and model flags were passed, so an + // empty value (say, from an unset shell variable) fails instead of falling back to + // the file. + flagsSet map[string]bool + dryRun bool + // idempotencyKeySet records an explicit --idempotency-key, so an empty value + // (say, from an unset shell variable) fails instead of registering anew. + idempotencyKeySet bool + idempotencyKey string + retryFailedStaging bool + timeout time.Duration +} + +func newRegisterCommand() *cobra.Command { + return newRegisterCommandWithPollInterval(registrationPollInterval) +} + +func newRegisterCommandWithPollInterval(pollInterval time.Duration) *cobra.Command { + var opts registerOptions + cmd := &cobra.Command{ + Use: "register", + Args: root.NoArgs, + Short: "Register a checkpoint as a model version in Unity Catalog", + Long: `Register a checkpoint in a Unity Catalog volume as a new version of a Unity +Catalog model, ready to serve with databricks air serve. + +Describe the registration in a YAML file (see --file), or name the checkpoint and +the model with --model-source and --uc-model. A file with engine registers a +checkpoint served by your command; without engine, Databricks serves the +checkpoint with dedicated inference. + +air register copies the checkpoint's weights into the version and waits until the +version is ready. Registration is idempotent: run air register again with the +idempotency key it prints to continue an interrupted registration. To look up a +YAML field, pass its path to -h as a separate argument: + + databricks air register -h config all fields, with examples + databricks air register -h config.engine one section`, + Example: ` # Register a checkpoint described in a file + databricks air register -f register.yaml + + # Register a checkpoint for dedicated inference + databricks air register --model-source /Volumes/main/weights/gemma4_e4b --uc-model main.serving.gemma4 + + # Continue a registration that was interrupted + databricks air register -f register.yaml --idempotency-key 3f6c0b52-4c7e-4d0b-9b8e-0f7ad6a4c2d1`, + // Hidden until the registration API is available in every workspace. + Hidden: true, + } + cmd.SetHelpFunc(schemaHelp(registerSchema, registerCommandPath)) + + // List flags in declaration order (most used first) rather than alphabetically. + cmd.Flags().SortFlags = false + cmd.Flags().StringVarP(&opts.file, "file", "f", "", "Path to the registration YAML config") + cmd.Flags().StringVar(&opts.modelSource, modelSourceFlag, "", "Volume directory of the checkpoint, overriding the file's model_source") + cmd.Flags().StringVar(&opts.ucModel, ucModelFlag, "", "Unity Catalog model to register a version of, overriding the file's uc_model") + cmd.Flags().StringArrayVar(&opts.overrides, "override", nil, "Override a YAML field, e.g. engine.environment.version=6 (repeatable)") + cmd.Flags().BoolVar(&opts.dryRun, "dry-run", false, "Validate the config, and show the plan, without changing anything") + cmd.Flags().StringVar(&opts.idempotencyKey, "idempotency-key", "", "Continue the registration that used this key, instead of registering another version") + cmd.Flags().BoolVar(&opts.retryFailedStaging, "retry-failed-staging", false, "Copy the checkpoint's weights again after copying them failed") + cmd.Flags().DurationVar(&opts.timeout, "timeout", defaultRegisterTimeout, "How long to wait for the version to be ready") + + // --dry-run never authenticates, so it reports config mistakes without + // credentials. + cmd.PreRunE = func(cmd *cobra.Command, args []string) error { + if opts.dryRun { + return nil + } + if err := root.MustWorkspaceClient(cmd, args); err != nil { + return renderWorkspaceClientError(cmd.Context(), cmd, err) + } + return nil + } + + cmd.RunE = func(cmd *cobra.Command, args []string) error { + opts.idempotencyKeySet = cmd.Flags().Changed("idempotency-key") + opts.flagsSet = changedFlags(cmd, modelSourceFlag, ucModelFlag) + return renderModelError(cmd, runRegister(cmd, opts, pollInterval)) + } + return cmd +} + +// loadRegisterConfig reads the config from --file, if set, then applies the +// --model-source and --uc-model flags over it, and validates the result. +func loadRegisterConfig(ctx context.Context, opts registerOptions) (*registerConfig, error) { + if err := validateRegisterFlags(opts); err != nil { + return nil, err + } + cfg := ®isterConfig{} + switch { + case opts.file != "": + loaded, document, err := loadModelConfig[registerConfig](ctx, opts.file, opts.overrides, registerSchema(), registerCommandPath) + if err != nil { + return nil, err + } + // YAML reads an engine whose fields are all commented out as no engine, which + // would register the checkpoint for dedicated inference instead. + if node, _ := mappingValue(document.Content[0], "engine"); loaded.Engine == nil && node != nil { + return nil, errors.New("engine is empty: set engine.command and engine.environment, or remove engine to register the checkpoint for dedicated inference") + } + cfg = loaded + case len(opts.overrides) > 0: + return nil, errors.New("--override applies to a file; set --file, or pass the fields as flags") + case opts.modelSource == "" || opts.ucModel == "": + return nil, errors.New("set --file, or both --model-source and --uc-model") + } + if opts.modelSource != "" { + cfg.ModelSource = opts.modelSource + } + if opts.ucModel != "" { + cfg.UCModel = opts.ucModel + } + return cfg, cfg.validate() +} + +// validateRegisterFlags checks the model source and model flags that were passed, +// naming the flag in the error. +func validateRegisterFlags(opts registerOptions) error { + for _, flag := range []struct{ name, value string }{{modelSourceFlag, opts.modelSource}, {ucModelFlag, opts.ucModel}} { + if opts.flagsSet[flag.name] && strings.TrimSpace(flag.value) == "" { + return fmt.Errorf("--%s cannot be empty", flag.name) + } + } + if opts.modelSource != "" && !strings.HasPrefix(opts.modelSource, loggedModelSourcePrefix) { + if err := validateVolumeDirectory("--"+modelSourceFlag, opts.modelSource); err != nil { + return err + } + } + if opts.ucModel != "" { + return validateUCModelName(opts.ucModel, "--"+ucModelFlag) + } + return nil +} + +func runRegister(cmd *cobra.Command, opts registerOptions, pollInterval time.Duration) error { + ctx := cmd.Context() + if opts.timeout <= 0 { + return withCode(codeInvalidArgs, false, fmt.Errorf("--timeout must be positive, got %s", opts.timeout)) + } + if opts.idempotencyKeySet { + if err := validateRegistrationKey(opts.idempotencyKey); err != nil { + return withCode(codeInvalidArgs, false, err) + } + } + cfg, err := loadRegisterConfig(ctx, opts) + if err != nil { + return withCode(codeInvalidArgs, false, err) + } + + jsonOut := root.OutputType(cmd) == flags.OutputJSON + if opts.dryRun { + return renderRegisterDryRun(ctx, cfg, jsonOut) + } + + w := cmdctx.WorkspaceClient(ctx) + ctx, cancel := context.WithTimeout(ctx, opts.timeout) + defer cancel() + ctx, stop := notifyInterrupt(ctx) + defer stop() + + key := effectiveIdempotencyToken(opts.idempotencyKey, nil) + resp, err := registerVersion(ctx, w, cfg, opts, key, pollInterval, !jsonOut) + if err != nil { + return err + } + result := registerResult{ + Status: "READY", + UCModel: cfg.UCModel, + ModelVersion: resp.ModelVersion, + ModelID: resp.ModelID, + IdempotencyKey: key, + EnvironmentStagingFailed: resp.environmentState() == stagingStateFailed, + } + if jsonOut { + return renderEnvelope(ctx, result) + } + if result.EnvironmentStagingFailed { + cmdio.LogString(ctx, "Warning: the version's serving environment couldn't be prepared ahead of time, so an endpoint can be slower to start, or fail to start.") + } + serve := []string{serveCommandPath, "--" + ucModelFlag, shellquote.BashArg(cfg.UCModel), "--" + endpointNameFlag, "", "--" + modelVersionFlag, shellquote.BashArg(resp.ModelVersion)} + if profile := w.Config.Profile; profile != "" { + serve = append(serve, "-p", shellquote.BashArg(profile)) + } + fmt.Fprintf(cmd.OutOrStdout(), "Version %s of %s is ready. To serve it, run:\n %s\n", stripControl(resp.ModelVersion), cfg.UCModel, strings.Join(serve, " ")) + return nil +} + +// renderRegisterDryRun reports the registration of a valid config, without +// changing anything. +func renderRegisterDryRun(ctx context.Context, cfg *registerConfig, jsonOut bool) error { + plan := registerPlan{Variant: cfg.variant(), Request: cfg.registrationRequest("")} + if jsonOut { + return renderEnvelope(ctx, registerResult{Status: "DRY_RUN_OK", DryRun: true, Plan: &plan}) + } + served := "its command" + if plan.Variant == variantDedicated { + served = "dedicated inference" + } + described, err := json.MarshalIndent(plan, " ", " ") + if err != nil { + return withCode(codeInternalError, false, err) + } + cmdio.LogString(ctx, fmt.Sprintf("Dry run: would register a new version of %s from %s, served by %s:\n %s", cfg.UCModel, cfg.ModelSource, served, described)) + cmdio.LogString(ctx, "Dry run: configuration is valid; nothing was changed.") + return nil +} + +// registerVersion registers the version and makes it ready to serve, showing +// progress on a spinner when show is true. Its errors say how to continue. +func registerVersion(ctx context.Context, w *databricks.WorkspaceClient, cfg *registerConfig, opts registerOptions, key string, pollInterval time.Duration, show bool) (*registerModelPackageResponse, error) { + // Printed to stderr in every output mode, before the first request, so a run + // that is killed can still be continued with this key. + cmdio.LogString(ctx, fmt.Sprintf("Registering a version of %s with idempotency key %s", cfg.UCModel, key)) + req := cfg.registrationRequest(key) + req.RetryFailedStaging = opts.retryFailedStaging + + progress := func(*registerModelPackageResponse) {} + if show { + sp := cmdio.NewSpinner(ctx) + defer sp.Close() + progress = func(resp *registerModelPackageResponse) { + sp.Update(registrationProgress(cfg, resp)) + } + } + resp, err := registerAndFinalize(ctx, w, req, pollInterval, progress) + if err == nil { + return resp, nil + } + resume := registerResumeCommand(w.Config.Profile, opts, key) + if errors.Is(err, errStagingFailed) { + return nil, withCode(codeStagingFailed, true, fmt.Errorf("copying the weights in %s into version %s of %s failed. Check that you can read every file, then run:\n %s --retry-failed-staging", cfg.ModelSource, stripControl(resp.ModelVersion), cfg.UCModel, resume)) + } + if stopped := stoppedWaiting(ctx, err); stopped != nil { + continuing := "" + switch { + case resp == nil: + case resp.weightsState() == stagingStateSucceeded: + continuing = " The weights are copied, so continuing finalizes the version." + case resp.weightsState() != "": + continuing = " Copying the weights continues meanwhile." + } + return nil, fmt.Errorf("air register %w while registering a version of %s.%s To continue, run:\n %s", stopped, cfg.UCModel, continuing, resume) + } + if _, ok := errors.AsType[*finalizeError](err); ok { + return nil, fmt.Errorf("finalizing version %s of %s failed: %w\n\nTo try again, run:\n %s", stripControl(resp.ModelVersion), cfg.UCModel, err, resume) + } + failed := fmt.Errorf("registering a version of %s with idempotency key %s failed: %w", cfg.UCModel, key, err) + // A retryable failure is retried with the same key, so no other version is + // registered. + if _, retryable := modelErrorCode(err); retryable { + return nil, fmt.Errorf("%w\n\nTo try again, run:\n %s", failed, resume) + } + return nil, failed +} + +// registrationProgress describes a registration response on the spinner. +func registrationProgress(cfg *registerConfig, resp *registerModelPackageResponse) string { + state := resp.weightsState() + switch state { + case "": + return fmt.Sprintf("Registering version %s of %s…", stripControl(resp.ModelVersion), cfg.UCModel) + case stagingStateSucceeded: + return fmt.Sprintf("Finalizing version %s of %s…", stripControl(resp.ModelVersion), cfg.UCModel) + } + return fmt.Sprintf("Copying the weights into version %s of %s (%s)…", stripControl(resp.ModelVersion), cfg.UCModel, stripControl(state)) +} + +// registerResumeCommand is the command that continues this registration: the same +// config (by absolute path, so it runs from any directory), overrides, flags and +// profile, with the registration's key. The inputs are part of the request the key +// was first used with, so they must be repeated. +func registerResumeCommand(profile string, opts registerOptions, key string) string { + args := []string{registerCommandPath} + if opts.file != "" { + file := opts.file + if abs, err := filepath.Abs(file); err == nil { + file = abs + } + args = append(args, "-f", shellquote.BashArg(filepath.ToSlash(file))) + } + for _, override := range opts.overrides { + args = append(args, "--override", shellquote.BashArg(override)) + } + if opts.modelSource != "" { + args = append(args, "--model-source", shellquote.BashArg(opts.modelSource)) + } + if opts.ucModel != "" { + args = append(args, "--uc-model", shellquote.BashArg(opts.ucModel)) + } + args = append(args, "--idempotency-key", shellquote.BashArg(key)) + if profile != "" { + args = append(args, "-p", shellquote.BashArg(profile)) + } + return strings.Join(args, " ") +} diff --git a/cmd/air/register_test.go b/cmd/air/register_test.go new file mode 100644 index 00000000000..b96ab9e7a66 --- /dev/null +++ b/cmd/air/register_test.go @@ -0,0 +1,340 @@ +package aircmd + +import ( + "bytes" + "encoding/json" + "io" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/cmdctx" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/flags" + "github.com/databricks/cli/libs/retry" + "github.com/databricks/cli/libs/shellquote" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// registerServer serves registerModelPackage with responses, and the staging status +// and finalizeModelPackage with their defaults. +func registerServer(t *testing.T, responses ...string) (*httptest.Server, *fakeModelServing) { + t.Helper() + fake := newFakeModelServing(t, responses...) + return fake.start(), fake +} + +// runModelCmd runs cmd with the given flags. An empty srvURL runs it without a +// workspace client, as --dry-run does. +func runModelCmd(t *testing.T, cmd *cobra.Command, out flags.Output, buf *bytes.Buffer, srvURL string, flagValues ...string) error { + t.Helper() + cmd = withOutput(cmd, out) + for i := 0; i < len(flagValues); i += 2 { + require.NoError(t, cmd.Flags().Set(flagValues[i], flagValues[i+1])) + } + // JSON tests parse buf, so stderr's progress lines go elsewhere. + var stderr io.Writer = buf + if out == flags.OutputJSON { + stderr = io.Discard + } + ctx := cmdio.InContext(fastRetries(t.Context()), cmdio.NewIO(t.Context(), out, nil, buf, stderr, "", "")) + if srvURL != "" { + ctx = cmdctx.SetWorkspaceClient(ctx, newTestWorkspaceClient(t, srvURL)) + } + cmd.SetContext(ctx) + cmd.SetOut(buf) + return cmd.RunE(cmd, nil) +} + +// runRegisterCmd runs `air register` on config with the given flags. +func runRegisterCmd(t *testing.T, out flags.Output, buf *bytes.Buffer, srvURL, config string, flagValues ...string) error { + t.Helper() + flagValues = append([]string{"file", writeConfigFile(t, "register.yaml", config)}, flagValues...) + return runModelCmd(t, newRegisterCommandWithPollInterval(time.Millisecond), out, buf, srvURL, flagValues...) +} + +func TestRegisterCommandJSON(t *testing.T) { + srv, fake := registerServer(t, stagingInProgress) + + var buf bytes.Buffer + require.NoError(t, runRegisterCmd(t, flags.OutputJSON, &buf, srv.URL, commandRegisterConfig, "idempotency-key", "key-1")) + var got struct { + Data registerResult `json:"data"` + } + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, registerResult{ + Status: "READY", + UCModel: "main.models.qwen", + ModelVersion: "3", + ModelID: "m-1", + IdempotencyKey: "key-1", + }, got.Data) + + bodies := fake.requests() + require.Len(t, bodies, 1) + assert.Equal(t, "key-1", bodies[0].IdempotencyKey) + assert.Equal(t, "/Volumes/main/models/weights/qwen3_8b", bodies[0].ModelSource) + assert.Equal(t, []finalizeModelPackageRequest{{UCModel: "main.models.qwen", ModelVersion: "3"}}, fake.finalizeRequests) +} + +func TestRegisterCommandText(t *testing.T) { + srv, _ := registerServer(t, stagingReady) + + var buf bytes.Buffer + require.NoError(t, runRegisterCmd(t, flags.OutputText, &buf, srv.URL, commandRegisterConfig)) + out := buf.String() + assert.Contains(t, out, "Registering a version of main.models.qwen with idempotency key ") + assert.Contains(t, out, "Version 3 of main.models.qwen is ready. To serve it, run:\n databricks air serve --uc-model main.models.qwen --endpoint-name --model-version 3\n") + assert.NotContains(t, out, "Warning") +} + +func TestRegisterDedicatedFromFlags(t *testing.T) { + srv, fake := registerServer(t, stagingReady) + + var buf bytes.Buffer + require.NoError(t, runModelCmd(t, newRegisterCommandWithPollInterval(time.Millisecond), flags.OutputJSON, &buf, srv.URL, + "model-source", "/Volumes/main/models/weights/gemma", "uc-model", "main.models.gemma")) + bodies := fake.requests() + require.Len(t, bodies, 1) + assert.Nil(t, bodies[0].Engine) + assert.Equal(t, "/Volumes/main/models/weights/gemma", bodies[0].ModelSource) + assert.Equal(t, "main.models.gemma", bodies[0].UCModel) +} + +func TestRegisterWarnsWhenTheEnvironmentFailedToStage(t *testing.T) { + environmentFailed := strings.Replace(stagingReady, `"environment_artifact": {"state": "SUCCEEDED"}`, `"environment_artifact": {"state": "FAILED"}`, 1) + srv, _ := registerServer(t, environmentFailed) + + var buf bytes.Buffer + require.NoError(t, runRegisterCmd(t, flags.OutputText, &buf, srv.URL, commandRegisterConfig)) + assert.Contains(t, buf.String(), "Warning: the version's serving environment couldn't be prepared ahead of time") + + buf.Reset() + require.NoError(t, runRegisterCmd(t, flags.OutputJSON, &buf, srv.URL, commandRegisterConfig)) + assert.Contains(t, buf.String(), `"environment_staging_failed": true`) +} + +func TestRegisterWarnsWhenTheFinalizedEnvironmentFailedToStage(t *testing.T) { + srv, fake := registerServer(t, stagingInProgress) + fake.finalizations = []string{strings.Replace(finalizedResponse, `"environment_artifact": {"state": "IN_PROGRESS"}`, `"environment_artifact": {"state": "FAILED"}`, 1)} + + var buf bytes.Buffer + require.NoError(t, runRegisterCmd(t, flags.OutputText, &buf, srv.URL, commandRegisterConfig)) + assert.Contains(t, buf.String(), "Warning: the version's serving environment couldn't be prepared ahead of time") +} + +func TestRegisterUsesTheFlagKeyElseANewOne(t *testing.T) { + srv, fake := registerServer(t, stagingReady) + + var buf bytes.Buffer + require.NoError(t, runRegisterCmd(t, flags.OutputJSON, &buf, srv.URL, commandRegisterConfig, "idempotency-key", "from-flag")) + require.NoError(t, runRegisterCmd(t, flags.OutputJSON, &buf, srv.URL, commandRegisterConfig)) + bodies := fake.requests() + require.Len(t, bodies, 2) + assert.Equal(t, "from-flag", bodies[0].IdempotencyKey) + assert.Regexp(t, registrationKeyRe(), bodies[1].IdempotencyKey) + assert.NotEqual(t, "from-flag", bodies[1].IdempotencyKey) +} + +func TestRegisterPrintsTheKeyBeforeRegisteringInJSONMode(t *testing.T) { + srv, _ := registerServer(t, conflictResponse) + + var stdout, stderr bytes.Buffer + cmd := withOutput(newRegisterCommandWithPollInterval(time.Millisecond), flags.OutputJSON) + require.NoError(t, cmd.Flags().Set("file", writeConfigFile(t, "register.yaml", commandRegisterConfig))) + require.NoError(t, cmd.Flags().Set("idempotency-key", "key-1")) + ctx := cmdio.InContext(t.Context(), cmdio.NewIO(t.Context(), flags.OutputJSON, nil, &stdout, &stderr, "", "")) + cmd.SetContext(cmdctx.SetWorkspaceClient(ctx, newTestWorkspaceClient(t, srv.URL))) + require.ErrorIs(t, cmd.RunE(cmd, nil), root.ErrAlreadyPrinted) + assert.Equal(t, "Registering a version of main.models.qwen with idempotency key key-1\n", stderr.String()) + assert.Contains(t, stdout.String(), `"code": "RESOURCE_CONFLICT"`) +} + +func TestRegisterSendsRetryFailedStaging(t *testing.T) { + srv, fake := registerServer(t, stagingInProgress) + + var buf bytes.Buffer + require.NoError(t, runRegisterCmd(t, flags.OutputJSON, &buf, srv.URL, commandRegisterConfig, "retry-failed-staging", "true")) + bodies := fake.requests() + require.Len(t, bodies, 1) + assert.True(t, bodies[0].RetryFailedStaging) +} + +func TestRegisterFailedStagingSaysHowToRetry(t *testing.T) { + srv, _ := registerServer(t, stagingFailed) + + var buf bytes.Buffer + err := runRegisterCmd(t, flags.OutputText, &buf, srv.URL, commandRegisterConfig, "idempotency-key", "key-1") + require.Error(t, err) + assert.Contains(t, err.Error(), "copying the weights in /Volumes/main/models/weights/qwen3_8b into version 3 of main.models.qwen failed") + assert.Contains(t, err.Error(), " --idempotency-key key-1 --retry-failed-staging") +} + +func TestRegisterReportsRegistrationErrors(t *testing.T) { + srv, _ := registerServer(t, conflictResponse) + + var buf bytes.Buffer + err := runRegisterCmd(t, flags.OutputText, &buf, srv.URL, commandRegisterConfig, "idempotency-key", "key-1") + assert.ErrorContains(t, err, "registering a version of main.models.qwen with idempotency key key-1 failed: The idempotency key can't be used for this registration") +} + +func TestRegisterReportsErrorsAsJSON(t *testing.T) { + srv, _ := registerServer(t, conflictResponse) + + var buf bytes.Buffer + err := runRegisterCmd(t, flags.OutputJSON, &buf, srv.URL, commandRegisterConfig) + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + var got errorEnvelope + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, "RESOURCE_CONFLICT", got.Error.Code) + assert.Equal(t, "PERMANENT", got.Error.Kind) + assert.False(t, got.Error.Retryable) + + buf.Reset() + err = runRegisterCmd(t, flags.OutputJSON, &buf, "", "model_source: /Volumes/a/b/c/w\nuc_model: x\n", "dry-run", "true") + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, "INVALID_ARGS", got.Error.Code) + assert.Contains(t, got.Error.Message, "uc_model must be a Unity Catalog model name") +} + +func TestRegisterTimesOutWhileCopyingTheWeights(t *testing.T) { + srv, fake := registerServer(t, stagingInProgress) + fake.statuses = []string{statusInProgress} + + // Polls are spaced as the SDK's rate limiter allows, so the deadline, not the + // limiter, stops the wait. + var buf bytes.Buffer + cmd := withOutput(newRegisterCommandWithPollInterval(100*time.Millisecond), flags.OutputJSON) + require.NoError(t, cmd.Flags().Set("file", writeConfigFile(t, "register.yaml", commandRegisterConfig))) + require.NoError(t, cmd.Flags().Set("idempotency-key", "key-1")) + require.NoError(t, cmd.Flags().Set("timeout", "500ms")) + ctx := cmdio.InContext(t.Context(), cmdio.NewIO(t.Context(), flags.OutputJSON, nil, &buf, io.Discard, "", "")) + cmd.SetContext(cmdctx.SetWorkspaceClient(ctx, newTestWorkspaceClient(t, srv.URL))) + require.ErrorIs(t, cmd.RunE(cmd, nil), root.ErrAlreadyPrinted) + var got errorEnvelope + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, "TIMEOUT", got.Error.Code) + assert.True(t, got.Error.Retryable) + assert.Contains(t, got.Error.Message, "air register timed out while registering a version of main.models.qwen. Copying the weights continues") + assert.Contains(t, got.Error.Message, " --idempotency-key key-1") + assert.Len(t, fake.requests(), 1) + assert.Empty(t, fake.finalizeRequests) +} + +func TestRegisterFinalizeFailureSaysHowToRetry(t *testing.T) { + srv, fake := registerServer(t, stagingSucceeded) + fake.finalizations = []string{notFinalizableResponse} + + var buf bytes.Buffer + err := runRegisterCmd(t, flags.OutputText, &buf, srv.URL, commandRegisterConfig, "idempotency-key", "key-1") + require.Error(t, err) + assert.Contains(t, err.Error(), "finalizing version 3 of main.models.qwen failed: Version 3 of model main.models.qwen can't be finalized yet") + assert.Contains(t, err.Error(), "To try again, run:\n databricks air register -f ") + assert.Contains(t, err.Error(), " --idempotency-key key-1") +} + +func TestRegisterRetryableRegistrationFailureSaysHowToRetry(t *testing.T) { + srv, fake := registerServer(t, serverErrorResponse) + + var buf bytes.Buffer + err := runRegisterCmd(t, flags.OutputText, &buf, srv.URL, commandRegisterConfig, "idempotency-key", "key-1") + require.Error(t, err) + assert.Contains(t, err.Error(), "failed: Something went wrong.\n\nTo try again, run:\n databricks air register -f ") + assert.Contains(t, err.Error(), " --idempotency-key key-1") + assert.Len(t, fake.requests(), retry.MaxRetries+1) +} + +func TestRegisterDryRunNeedsNoWorkspace(t *testing.T) { + cmd := newRegisterCommand() + require.NoError(t, cmd.Flags().Set("dry-run", "true")) + assert.NoError(t, cmd.PreRunE(cmd, nil)) + + var buf bytes.Buffer + require.NoError(t, runRegisterCmd(t, flags.OutputText, &buf, "", commandRegisterConfig, "dry-run", "true")) + out := buf.String() + assert.Contains(t, out, "Dry run: would register a new version of main.models.qwen from /Volumes/main/models/weights/qwen3_8b, served by its command:") + assert.Contains(t, out, `"command": "python -m vllm.entrypoints.openai.api_server --model qwen3_8b --port 8080"`) + assert.Contains(t, out, "Dry run: configuration is valid; nothing was changed.") + + buf.Reset() + require.NoError(t, runRegisterCmd(t, flags.OutputJSON, &buf, "", dedicatedRegisterConfig, "dry-run", "true")) + var got struct { + Data registerResult `json:"data"` + } + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, "DRY_RUN_OK", got.Data.Status) + assert.Equal(t, ®isterPlan{Variant: "dedicated", Request: registerModelPackageRequest{ModelSource: "/Volumes/main/models/weights/qwen3_8b", UCModel: "main.models.qwen"}}, got.Data.Plan) +} + +func TestRegisterFlagValidation(t *testing.T) { + tests := []struct { + name string + flagValues []string + wantErr string + }{ + {"zero timeout", []string{"timeout", "0s"}, "--timeout must be positive"}, + {"bad key", []string{"idempotency-key", "a/b"}, "--idempotency-key must be 1 to 128 letters"}, + {"empty key", []string{"idempotency-key", ""}, `--idempotency-key must be 1 to 128 letters, digits, '.', '_' or '-', got ""`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + err := runRegisterCmd(t, flags.OutputText, &buf, "", commandRegisterConfig, append(tt.flagValues, "dry-run", "true")...) + assert.ErrorContains(t, err, tt.wantErr) + }) + } +} + +func TestRegisterRefusesAnEmptyModelSourceFlag(t *testing.T) { + var buf bytes.Buffer + err := runRegisterCmd(t, flags.OutputText, &buf, "", commandRegisterConfig, "model-source", "", "dry-run", "true") + assert.ErrorContains(t, err, "--model-source cannot be empty") +} + +func TestRegisterResumeCommand(t *testing.T) { + abs, err := filepath.Abs("my register.yaml") + require.NoError(t, err) + opts := registerOptions{file: "my register.yaml", overrides: []string{"engine.task=llm/v1/chat"}, ucModel: "main.models.other"} + assert.Equal(t, + "databricks air register -f "+shellquote.BashArg(filepath.ToSlash(abs))+" --override 'engine.task=llm/v1/chat' --uc-model main.models.other --idempotency-key k-1 -p dev", + registerResumeCommand("dev", opts, "k-1")) + + assert.Equal(t, + "databricks air register --model-source /Volumes/a/b/c/w --uc-model a.b.c --idempotency-key k-2", + registerResumeCommand("", registerOptions{modelSource: "/Volumes/a/b/c/w", ucModel: "a.b.c"}, "k-2")) +} + +func TestRegisterHelpDocumentsAField(t *testing.T) { + var out strings.Builder + cmd := newRegisterCommand() + cmd.SetOut(&out) + cmd.SetArgs([]string{"-h", "config.model_source"}) + require.NoError(t, cmd.Execute()) + assert.Contains(t, out.String(), "config.model_source\n Unity Catalog volume directory") + assert.Contains(t, out.String(), "Required: yes") + + out.Reset() + cmd = newRegisterCommand() + cmd.SetOut(&out) + cmd.SetArgs([]string{"-h", "config"}) + require.NoError(t, cmd.Execute()) + // The coding agent skill writes run YAML, so the register help leaves it out. + assert.NotContains(t, out.String(), "databricks-ai-runtime") +} + +func TestRegisterHelpNamesTheVersionsType(t *testing.T) { + var out strings.Builder + cmd := newRegisterCommand() + cmd.SetOut(&out) + cmd.SetArgs([]string{"-h", "config.engine.environment.version"}) + require.NoError(t, cmd.Execute()) + // version is a *stringOrInt, which documents as its union, not as an object. + assert.Contains(t, out.String(), "string or int") + assert.NotContains(t, out.String(), "object") +} diff --git a/cmd/air/registerapi.go b/cmd/air/registerapi.go index d2f76ac9299..a8432943b6e 100644 --- a/cmd/air/registerapi.go +++ b/cmd/air/registerapi.go @@ -29,6 +29,10 @@ const stagingStatusPath = "/api/2.0/serving-endpoints:checkModelDeploymentStagin // as it is. const finalizeModelPackagePath = "/api/2.0/serving-endpoints:finalizeModelPackage" +// registrationPollInterval is how often air register checks on a checkpoint's +// weights while they are staged. +const registrationPollInterval = 15 * time.Second + // ModelDeploymentStagingStatus states air register acts on. const ( // stagingStateNotStaged: no staging record exists for the version. diff --git a/cmd/air/registerapi_test.go b/cmd/air/registerapi_test.go index ad58dc383d0..9604a55899c 100644 --- a/cmd/air/registerapi_test.go +++ b/cmd/air/registerapi_test.go @@ -394,6 +394,35 @@ func TestRegisterAndFinalizeStopsWhenCanceled(t *testing.T) { assert.Empty(t, fake.finalizeRequests) } +func TestRegistrationRequestForCommandJSON(t *testing.T) { + cfg, err := loadRegisterConfigText(t, commandRegisterConfig) + require.NoError(t, err) + raw, err := json.Marshal(cfg.registrationRequest("k")) + require.NoError(t, err) + assert.JSONEq(t, `{ + "model_source": "/Volumes/main/models/weights/qwen3_8b", + "uc_model": "main.models.qwen", + "idempotency_key": "k", + "engine": { + "environment": {"version": "6", "dependencies": ["einops==0.8.0"]}, + "command": "python -m vllm.entrypoints.openai.api_server --model qwen3_8b --port 8080", + "task": "llm/v1/chat" + } + }`, string(raw)) +} + +func TestRegistrationRequestForDedicatedJSON(t *testing.T) { + cfg, err := loadRegisterConfigText(t, dedicatedRegisterConfig) + require.NoError(t, err) + raw, err := json.Marshal(cfg.registrationRequest("k")) + require.NoError(t, err) + assert.JSONEq(t, `{ + "model_source": "/Volumes/main/models/weights/qwen3_8b", + "uc_model": "main.models.qwen", + "idempotency_key": "k" + }`, string(raw)) +} + func TestRegisterModelPackageRequestJSON(t *testing.T) { raw, err := json.Marshal(checkpointRequest()) require.NoError(t, err) diff --git a/cmd/air/registerconfig.go b/cmd/air/registerconfig.go new file mode 100644 index 00000000000..9a6328849da --- /dev/null +++ b/cmd/air/registerconfig.go @@ -0,0 +1,251 @@ +package aircmd + +import ( + "bytes" + "context" + "errors" + "fmt" + "reflect" + "regexp" + "strconv" + "strings" + "sync" + + "go.yaml.in/yaml/v3" +) + +// This file defines the `air register` YAML schema and its validation. engine selects +// what serves the checkpoint: the user's command when it's set, dedicated inference when +// it isn't. The server validates what needs the workspace, such as task names, runtimes +// and dependencies. + +// registerCommandPath is the command whose -h documents registerConfig. +const registerCommandPath = "databricks air register" + +// What serves a registered checkpoint. +const ( + // variantCommand: the command in engine. + variantCommand = "command" + // variantDedicated: Databricks, with dedicated inference. + variantDedicated = "dedicated" +) + +// Prefixes of model_source: a volume directory holding a checkpoint, or a logged +// model, named as MLflow names it. +const ( + volumeSourcePrefix = "/Volumes/" + loggedModelSourcePrefix = "models:/" +) + +// Limits the server enforces on a registration, checked here to fail early. +const ( + maxServingCommandChars = 32 * 1024 + maxVolumePathChars = 1024 + maxDependencies = 1000 +) + +// registrationKeyRe matches the registration keys the server records. +var registrationKeyRe = sync.OnceValue(func() *regexp.Regexp { return regexp.MustCompile(`^[A-Za-z0-9._-]{1,128}$`) }) + +// registerConfig is the `air register` YAML schema: a checkpoint to register as a +// new version of a Unity Catalog model. +type registerConfig struct { + ModelSource string `yaml:"model_source" help:"Unity Catalog volume directory holding a checkpoint's weights, as /Volumes////. Model Serving copies it, with its subdirectories, into the new version." required:"yes"` + UCModel string `yaml:"uc_model" help:"Unity Catalog model, as ... The checkpoint is registered as a new version of it, creating the model if it doesn't exist." required:"yes"` + Engine *registerEngineConfig `yaml:"engine" help:"Your own model server for the checkpoint: the command that starts it and the serverless environment it runs on. Without engine, Databricks serves the checkpoint with dedicated inference."` +} + +// registerEngineConfig is the `engine` block: the model server of a checkpoint. +type registerEngineConfig struct { + Environment *registerEnvironmentConfig `yaml:"environment" help:"Serverless environment to serve the command on, and the packages to install. The model uses its Python version." required:"yes"` + Command *string `yaml:"command" help:"Shell command that starts a model server over the checkpoint's weights on port 8080, at most 32,768 characters. It runs from the directory where the checkpoint appears under its own name." required:"yes"` + Task *string `yaml:"task" help:"The task Model Serving routes to the command: llm/v1/chat (the default), or another such as llm/v1/embeddings or llm/v1/audio/transcriptions."` +} + +// registerEnvironmentConfig is the `engine.environment` block. +type registerEnvironmentConfig struct { + Version *stringOrInt `yaml:"version" required:"yes" help:"Serverless environment to serve on: 6 for the Standard environment or databricks_ai_v6 for the Databricks AI environment, as for air run. The model uses its Python version. Standard includes CUDA but not PyTorch; the Databricks AI environment adds PyTorch, Transformers and vLLM, and needs GPU compute. A command that doesn't install SGLang runs on the Databricks AI environment either way."` + Dependencies []string `yaml:"dependencies" help:"pip requirement lines to install, e.g. einops==0.8.0, at most 1,000."` +} + +// variant is what serves the checkpoint: its command when engine is set, else +// dedicated inference. +func (c *registerConfig) variant() string { + if c.Engine != nil { + return variantCommand + } + return variantDedicated +} + +// validate checks the whole config, returning the first failure. Fields are checked +// in declaration order to keep errors stable. +func (c *registerConfig) validate() error { + // TODO: register a logged model (models:/m-), which needs the server to copy + // the logged model's files into the version. + if strings.HasPrefix(c.ModelSource, loggedModelSourcePrefix) { + return fmt.Errorf("model_source can't be a logged model yet, got %q: register it with MLflow's register_model, then serve the version with %s", c.ModelSource, serveCommandPath) + } + if err := validateVolumeDirectory("model_source", c.ModelSource); err != nil { + return err + } + if err := validateUCModelName(c.UCModel, "uc_model"); err != nil { + return err + } + if c.Engine == nil { + return nil + } + return c.Engine.validate() +} + +// validate checks the engine of a checkpoint served by command. +func (e *registerEngineConfig) validate() error { + if e.Command == nil { + return errors.New("engine.command is required: the shell command that starts your model server on port 8080") + } + if strings.TrimSpace(*e.Command) == "" { + return errors.New("engine.command cannot be empty") + } + if n := serverLength(*e.Command); n > maxServingCommandChars { + return fmt.Errorf("engine.command must be at most %d characters, got %d", maxServingCommandChars, n) + } + if e.Task != nil && strings.TrimSpace(*e.Task) == "" { + return errors.New("engine.task cannot be empty; leave it out to serve llm/v1/chat") + } + if e.Environment == nil { + return errors.New("engine.environment is required: the serverless environment and packages to serve the command on") + } + return e.Environment.validate() +} + +// validateVolumeDirectory checks a Unity Catalog volume directory the server +// copies into the version. +func validateVolumeDirectory(field, v string) error { + if !strings.HasPrefix(v, volumeSourcePrefix) || serverLength(v) > maxVolumePathChars { + return fmt.Errorf("%s must be a Unity Catalog volume directory as /Volumes////, of at most %d characters, got %q", field, maxVolumePathChars, v) + } + return nil +} + +// validate checks the environment version and dependency lines. +func (e *registerEnvironmentConfig) validate() error { + if e.Version == nil { + return errors.New("engine.environment.version is required: the serverless environment to serve the command on, such as 6 or databricks_ai_v6") + } + if _, _, err := e.runtimeVersion(); err != nil { + return err + } + if len(e.Dependencies) > maxDependencies { + return fmt.Errorf("engine.environment.dependencies can list at most %d packages, got %d", maxDependencies, len(e.Dependencies)) + } + for i, dependency := range e.Dependencies { + if strings.TrimSpace(dependency) == "" { + return fmt.Errorf("engine.environment.dependencies[%d] cannot be empty", i) + } + } + return nil +} + +// runtimeVersion is engine.environment.version as a version number, and whether it names +// the Databricks AI environment, as air run reads the same field. +func (e *registerEnvironmentConfig) runtimeVersion() (int, bool, error) { + if e.Version == nil { + return 0, false, errors.New("engine.environment.version is required") + } + normalized, err := validateRuntimeVersion(e.Version.raw, "engine.environment.version") + if err != nil { + return 0, false, err + } + ai := strings.HasPrefix(normalized, databricksAIPrefix) + major, err := strconv.Atoi(strings.TrimPrefix(normalized, databricksAIPrefix)) + if err != nil || major < 1 { + return 0, false, fmt.Errorf("engine.environment.version must be a serverless environment version such as 6 or databricks_ai_v6, got %q", e.Version.raw) + } + return major, ai, nil +} + +// validateRegistrationKey checks a registration key from the --idempotency-key flag +// against the server's rule. +func validateRegistrationKey(key string) error { + if !registrationKeyRe().MatchString(key) { + return fmt.Errorf("--idempotency-key must be 1 to 128 letters, digits, '.', '_' or '-', got %q", key) + } + return nil +} + +// registrationRequest builds the request that registers the checkpoint under key: the +// file's fields as they are, with the environment version in its canonical form, such +// as 6 for "06" or databricks_ai_v6 for "Databricks_AI_v6". The version was validated +// when the config loaded; the server defaults an omitted task to llm/v1/chat. +func (c *registerConfig) registrationRequest(key string) registerModelPackageRequest { + req := registerModelPackageRequest{ModelSource: c.ModelSource, UCModel: c.UCModel, IdempotencyKey: key} + if c.Engine == nil { + return req + } + major, ai, _ := c.Engine.Environment.runtimeVersion() + version := strconv.Itoa(major) + if ai { + version = databricksAIPrefix + version + } + req.Engine = &modelPackageEngine{ + Environment: modelPackageEnvironment{Version: version, Dependencies: c.Engine.Environment.Dependencies}, + Command: *c.Engine.Command, + } + if c.Engine.Task != nil { + req.Engine.Task = *c.Engine.Task + } + return req +} + +// registerSchema is the reflection walk over registerConfig, shared by +// `air register -h config.` and --override path validation. +func registerSchema() configField { + return configField{ + path: configHelpRoot, + help: `Registration YAML schema. For details on a field, pass its path to -h, for example: + + databricks air register -h config.model_source + + A checkpoint served by a command of your own: + model_source: /Volumes/main/weights/qwen3_30b_a3b + uc_model: main.serving.qwen30b_sglang + engine: + environment: + version: 6 + dependencies: [sglang==0.5.23] + command: python -m sglang.launch_server --model-path qwen3_30b_a3b --attention-backend triton --sampling-backend pytorch --host 0.0.0.0 --port 8080 + + A checkpoint served with dedicated inference: + model_source: /Volumes/main/weights/gemma4_e4b + uc_model: main.serving.gemma4`, + children: describeStruct(reflect.TypeFor[registerConfig](), configHelpRoot), + } +} + +// loadModelConfig reads a model command's YAML, applies --override entries against +// schema, and decodes it with unknown keys rejected, naming command's -h for the +// list of fields. It also returns the document, in +// which a key set to null is still present. ctx is used only to log applied overrides. +// The caller validates the result. +func loadModelConfig[T any](ctx context.Context, path string, overrides []string, schema configField, command string) (*T, *yaml.Node, error) { + var ( + document *yaml.Node + validationYAML []byte + err error + ) + if len(overrides) == 0 { + document, validationYAML, err = readRunConfigDocument(path) + } else { + document, validationYAML, err = readConfigWithOverrides(ctx, path, overrides, schema) + } + if err != nil { + return nil, nil, err + } + if len(document.Content) == 0 { + return nil, nil, fmt.Errorf("config %s is empty", path) + } + if err := checkUnknownSchemaFields(path, document.Content[0], schema, command); err != nil { + return nil, nil, err + } + cfg, err := decodeConfigReader[T](bytes.NewReader(validationYAML), path) + return cfg, document, err +} diff --git a/cmd/air/registerconfig_test.go b/cmd/air/registerconfig_test.go new file mode 100644 index 00000000000..5d62a74faa4 --- /dev/null +++ b/cmd/air/registerconfig_test.go @@ -0,0 +1,297 @@ +package aircmd + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// commandRegisterConfig is a checkpoint served by a command. +const commandRegisterConfig = `model_source: /Volumes/main/models/weights/qwen3_8b +uc_model: main.models.qwen +engine: + environment: + version: 6 + dependencies: [einops==0.8.0] + command: python -m vllm.entrypoints.openai.api_server --model qwen3_8b --port 8080 + task: llm/v1/chat +` + +// dedicatedRegisterConfig is a checkpoint served with dedicated inference. +const dedicatedRegisterConfig = `model_source: /Volumes/main/models/weights/qwen3_8b +uc_model: main.models.qwen +` + +func loadRegisterConfigText(t *testing.T, text string, overrides ...string) (*registerConfig, error) { + t.Helper() + return loadRegisterConfig(t.Context(), registerOptions{file: writeConfigFile(t, "register.yaml", text), overrides: overrides}) +} + +func TestLoadRegisterConfigVariant(t *testing.T) { + cfg, err := loadRegisterConfigText(t, commandRegisterConfig) + require.NoError(t, err) + assert.Equal(t, variantCommand, cfg.variant()) + + cfg, err = loadRegisterConfigText(t, dedicatedRegisterConfig) + require.NoError(t, err) + assert.Equal(t, variantDedicated, cfg.variant()) +} + +func TestLoadRegisterConfigCommand(t *testing.T) { + cfg, err := loadRegisterConfigText(t, commandRegisterConfig) + require.NoError(t, err) + assert.Equal(t, registerModelPackageRequest{ + ModelSource: "/Volumes/main/models/weights/qwen3_8b", + UCModel: "main.models.qwen", + IdempotencyKey: "key-1", + Engine: &modelPackageEngine{ + Environment: modelPackageEnvironment{Version: "6", Dependencies: []string{"einops==0.8.0"}}, + Command: "python -m vllm.entrypoints.openai.api_server --model qwen3_8b --port 8080", + Task: "llm/v1/chat", + }, + }, cfg.registrationRequest("key-1")) +} + +func TestLoadRegisterConfigCommandTask(t *testing.T) { + // The server serves llm/v1/chat for an omitted task. + cfg, err := loadRegisterConfigText(t, dropLine(" task:")(commandRegisterConfig)) + require.NoError(t, err) + assert.Empty(t, cfg.registrationRequest("k").Engine.Task) + + cfg, err = loadRegisterConfigText(t, replaceFirst("task: llm/v1/chat", "task: llm/v1/audio/transcriptions")(commandRegisterConfig)) + require.NoError(t, err) + assert.Equal(t, "llm/v1/audio/transcriptions", cfg.registrationRequest("k").Engine.Task) +} + +func TestLoadRegisterConfigCommandOnDatabricksAI(t *testing.T) { + cfg, err := loadRegisterConfigText(t, replaceFirst(" version: 6\n", " version: Databricks_AI_v6\n")(commandRegisterConfig)) + require.NoError(t, err) + assert.Equal(t, modelPackageEnvironment{Version: "databricks_ai_v6", Dependencies: []string{"einops==0.8.0"}}, cfg.registrationRequest("k").Engine.Environment) +} + +func TestRegistrationRequestSendsTheCanonicalVersion(t *testing.T) { + for given, want := range map[string]string{ + "6": "6", + `"06"`: "6", + "databricks_ai_v6": "databricks_ai_v6", + "Databricks_AI_v06": "databricks_ai_v6", + } { + cfg, err := loadRegisterConfigText(t, replaceFirst(" version: 6\n", " version: "+given+"\n")(commandRegisterConfig)) + require.NoError(t, err, given) + assert.Equal(t, want, cfg.registrationRequest("k").Engine.Environment.Version, given) + } +} + +func TestLoadRegisterConfigDedicated(t *testing.T) { + cfg, err := loadRegisterConfigText(t, dedicatedRegisterConfig) + require.NoError(t, err) + assert.Equal(t, registerModelPackageRequest{ + ModelSource: "/Volumes/main/models/weights/qwen3_8b", + UCModel: "main.models.qwen", + IdempotencyKey: "key-1", + }, cfg.registrationRequest("key-1")) +} + +func TestLoadRegisterConfigFromFlags(t *testing.T) { + cfg, err := loadRegisterConfig(t.Context(), registerOptions{modelSource: "/Volumes/main/models/weights/gemma", ucModel: "main.models.gemma"}) + require.NoError(t, err) + assert.Equal(t, ®isterConfig{ModelSource: "/Volumes/main/models/weights/gemma", UCModel: "main.models.gemma"}, cfg) +} + +func TestLoadRegisterConfigFlagsOverrideTheFile(t *testing.T) { + cfg, err := loadRegisterConfig(t.Context(), registerOptions{ + file: writeConfigFile(t, "register.yaml", commandRegisterConfig), + modelSource: "/Volumes/main/models/weights/other", + ucModel: "main.models.other", + }) + require.NoError(t, err) + assert.Equal(t, "/Volumes/main/models/weights/other", cfg.ModelSource) + assert.Equal(t, "main.models.other", cfg.UCModel) + assert.Equal(t, variantCommand, cfg.variant()) +} + +func TestLoadRegisterConfigRefusesAnEmptyEngine(t *testing.T) { + _, err := loadRegisterConfigText(t, dedicatedRegisterConfig+"engine:\n # command: python serve.py\n") + assert.ErrorContains(t, err, "engine is empty: set engine.command and engine.environment, or remove engine to register the checkpoint for dedicated inference") +} + +func TestLoadRegisterConfigChecksFlagsByName(t *testing.T) { + tests := []struct { + name string + opts registerOptions + wantErr string + }{ + {"an empty model source", registerOptions{ucModel: "a.b.c", flagsSet: map[string]bool{modelSourceFlag: true}}, "--model-source cannot be empty"}, + {"an empty model over a file", registerOptions{file: "unused.yaml", flagsSet: map[string]bool{ucModelFlag: true}}, "--uc-model cannot be empty"}, + {"a bad model source", registerOptions{modelSource: "/dbfs/w", ucModel: "a.b.c"}, `--model-source must be a Unity Catalog volume directory as /Volumes////, of at most 1024 characters, got "/dbfs/w"`}, + {"a bad model", registerOptions{modelSource: "/Volumes/a/b/c/w", ucModel: "qwen"}, `--uc-model must be a Unity Catalog model name as .., got "qwen"`}, + {"a logged model", registerOptions{modelSource: "models:/m-1", ucModel: "a.b.c"}, "model_source can't be a logged model yet"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := loadRegisterConfig(t.Context(), tt.opts) + assert.ErrorContains(t, err, tt.wantErr) + }) + } +} + +func TestLoadRegisterConfigNeedsAFileOrBothFlags(t *testing.T) { + for _, opts := range []registerOptions{ + {}, + {modelSource: "/Volumes/a/b/c/w"}, + {ucModel: "a.b.c"}, + } { + _, err := loadRegisterConfig(t.Context(), opts) + assert.ErrorContains(t, err, "set --file, or both --model-source and --uc-model") + } + _, err := loadRegisterConfig(t.Context(), registerOptions{modelSource: "/Volumes/a/b/c/w", ucModel: "a.b.c", overrides: []string{"engine.task=x"}}) + assert.ErrorContains(t, err, "--override applies to a file") +} + +func TestRegisterConfigValidation(t *testing.T) { + tests := []struct { + name string + edit func(string) string + wantErr string + }{ + {"no model source", dropLine("model_source:"), `model_source must be a Unity Catalog volume directory as /Volumes////, of at most 1024 characters, got ""`}, + {"a logged model", replaceFirst("/Volumes/main/models/weights/qwen3_8b", "models:/m-0123456789abcdef0123456789abcdef"), `model_source can't be a logged model yet, got "models:/m-0123456789abcdef0123456789abcdef": register it with MLflow's register_model, then serve the version with databricks air serve`}, + {"path outside volumes", replaceFirst("/Volumes/main/models/weights/qwen3_8b", "/dbfs/weights"), "model_source must be a Unity Catalog volume directory"}, + {"path too long", replaceFirst("/Volumes/main/models/weights/qwen3_8b", "/Volumes/"+strings.Repeat("a", 1100)), "of at most 1024 characters"}, + {"path too long in characters", replaceFirst("/Volumes/main/models/weights/qwen3_8b", "/Volumes/"+strings.Repeat("é", 1020)), "model_source must be a Unity Catalog volume directory"}, + {"no model name", dropLine("uc_model:"), `uc_model must be a Unity Catalog model name as .., got ""`}, + {"bad model name", replaceFirst("uc_model: main.models.qwen", "uc_model: qwen"), "uc_model must be a Unity Catalog model name"}, + {"backticked model name", replaceFirst("uc_model: main.models.qwen", "uc_model: main.models.`qwen`"), "uc_model must be a Unity Catalog model name"}, + {"engine without a command", dropLine(" command:"), "engine.command is required"}, + {"empty command", replaceFirst("command: python -m vllm.entrypoints.openai.api_server --model qwen3_8b --port 8080", `command: " "`), "engine.command cannot be empty"}, + {"command too long", replaceFirst("command: python", "command: python "+strings.Repeat("x", maxServingCommandChars)), "engine.command must be at most 32768 characters"}, + {"empty task", replaceFirst("task: llm/v1/chat", `task: " "`), "engine.task cannot be empty; leave it out to serve llm/v1/chat"}, + {"engine without an environment", dropBlock(" environment:"), "engine.environment is required"}, + {"environment without a version", dropLine(" version:"), "engine.environment.version is required"}, + {"AI environment before version 5", replaceFirst(" version: 6\n", " version: databricks_ai_v4\n"), "databricks_ai_v in engine.environment.version requires AI Runtime version 5 or higher"}, + {"bad environment version", replaceFirst(" version: 6\n", " version: six\n"), "unsupported client image version"}, + {"zero environment version", replaceFirst(" version: 6\n", " version: 0\n"), "engine.environment.version must be a serverless environment version such as 6 or databricks_ai_v6"}, + {"empty dependency", replaceFirst("[einops==0.8.0]", `[""]`), "engine.environment.dependencies[0] cannot be empty"}, + {"an unknown field", appendText("mlflow_experiment_path: /Shared/qwen\n"), `line 9: unknown field "mlflow_experiment_path"; run "databricks air register -h config" for the list of fields`}, + {"a serve field", appendText("endpoint_name: qwen-chat\n"), `line 9: unknown field "endpoint_name"; run "databricks air register -h config" for the list of fields`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := loadRegisterConfigText(t, tt.edit(commandRegisterConfig)) + assert.ErrorContains(t, err, tt.wantErr) + }) + } +} + +func TestRegisterConfigCountsCharactersNotBytes(t *testing.T) { + // 1,000 two-byte characters fit the 1,024-character cap on a volume path. + _, err := loadRegisterConfigText(t, replaceFirst("/Volumes/main/models/weights/qwen3_8b", "/Volumes/"+strings.Repeat("é", 1000))(commandRegisterConfig)) + assert.NoError(t, err) +} + +func TestLoadRegisterConfigOverride(t *testing.T) { + cfg, err := loadRegisterConfigText(t, commandRegisterConfig, "engine.environment.version=5") + require.NoError(t, err) + assert.Equal(t, "5", cfg.registrationRequest("k").Engine.Environment.Version) + + _, err = loadRegisterConfigText(t, commandRegisterConfig, "engine.workers=2") + assert.ErrorContains(t, err, `"workers" is not a known field`) +} + +func TestLoadRegisterConfigRejectsEmptyFile(t *testing.T) { + _, err := loadRegisterConfigText(t, "") + assert.ErrorContains(t, err, "is empty") +} + +func TestRegisterSchemaHelp(t *testing.T) { + root, err := resolveSchemaField(registerSchema(), "config") + require.NoError(t, err) + var out strings.Builder + renderConfigField(&out, registerCommandPath, root, nil) + assert.Contains(t, out.String(), " databricks air register -h config.model_source\n") + + field, err := resolveSchemaField(registerSchema(), "engine.environment.version") + require.NoError(t, err) + assert.Equal(t, "yes", field.required) + + _, err = resolveSchemaField(registerSchema(), "model_sorce") + assert.ErrorContains(t, err, `did you mean "model_source"?`) +} + +// The examples in the schema help must load, so the help can't drift from the YAML. +func TestRegisterSchemaHelpExamplesLoad(t *testing.T) { + for _, example := range helpExamples(t, registerSchema(), 2) { + _, err := loadRegisterConfigText(t, example) + assert.NoError(t, err, example) + } +} + +// helpExamples returns the YAML examples in a schema's help: the blocks after its +// opening sentence and -h example, without their titles and indentation. +func helpExamples(t *testing.T, schema configField, want int) []string { + t.Helper() + blocks := strings.Split(schema.help, "\n\n ")[2:] + require.Len(t, blocks, want) + var examples []string + for _, block := range blocks { + _, body, _ := strings.Cut(block, ":\n") + var lines []string + for line := range strings.SplitSeq(body, "\n") { + lines = append(lines, strings.TrimPrefix(line, " ")) + } + examples = append(examples, strings.Join(lines, "\n")+"\n") + } + return examples +} + +func replaceFirst(old, with string) func(string) string { + return func(s string) string { + if !strings.Contains(s, old) { + panic("fixture does not contain " + old) + } + return strings.Replace(s, old, with, 1) + } +} + +func appendText(extra string) func(string) string { + return func(s string) string { return s + extra } +} + +// dropLine removes the first line starting with prefix. +func dropLine(prefix string) func(string) string { + return func(s string) string { + lines := strings.SplitAfter(s, "\n") + for i, line := range lines { + if strings.HasPrefix(line, prefix) { + return strings.Join(append(lines[:i:i], lines[i+1:]...), "") + } + } + panic("fixture has no line starting with " + prefix) + } +} + +// dropBlock removes the first line starting with prefix, a key at the indentation +// prefix has, and the lines indented under it. +func dropBlock(prefix string) func(string) string { + nested := strings.Repeat(" ", len(prefix)-len(strings.TrimLeft(prefix, " "))) + " " + return func(s string) string { + var kept []string + dropping, dropped := false, false + for _, line := range strings.SplitAfter(s, "\n") { + switch { + case !dropped && strings.HasPrefix(line, prefix): + dropping, dropped = true, true + case dropping && strings.HasPrefix(line, nested): + default: + dropping = false + kept = append(kept, line) + } + } + if !dropped { + panic("fixture has no line starting with " + prefix) + } + return strings.Join(kept, "") + } +} diff --git a/cmd/air/run.go b/cmd/air/run.go index 202163446b5..a55392cce78 100644 --- a/cmd/air/run.go +++ b/cmd/air/run.go @@ -194,7 +194,7 @@ databricks-ai-runtime skill: if field.path == "config.compute" || field.path == "config.compute.accelerator_type" { computeOptions = loadComputeOptionsForHelp(c, args) } - renderConfigField(c.OutOrStdout(), field, computeOptions) + renderConfigField(c.OutOrStdout(), runCommandPath, field, computeOptions) }) // List flags in declaration order (most used first) rather than alphabetically. @@ -240,7 +240,7 @@ databricks-ai-runtime skill: } snapshotFileCount = &count } - idempotencyToken := effectiveIdempotencyToken(idempotencyKey, cfg) + idempotencyToken := effectiveIdempotencyToken(idempotencyKey, cfg.IdempotencyToken) ctx, validationErr := validateDryRunInWorkspace(ctx, cmd, args, cfg, idempotencyToken, validationTimeout) if err := validateIdempotencyToken(idempotencyToken); err != nil { return renderError(ctx, cmd, "INVALID_ARGS", "PERMANENT", false, err) diff --git a/cmd/air/runconfig.go b/cmd/air/runconfig.go index 2ebb3fa5da3..e14b5f4e2f7 100644 --- a/cmd/air/runconfig.go +++ b/cmd/air/runconfig.go @@ -608,13 +608,16 @@ func (p *permission) validate() error { // or bare `compute`). const configHelpRoot = "config" +// runCommandPath is the command whose -h documents runConfig. +const runCommandPath = "databricks air run" + // writeConfigFieldHelp resolves a dotted config path and writes its docs. func writeConfigFieldHelp(w io.Writer, path string) error { field, err := resolveConfigField(path) if err != nil { return err } - renderConfigField(w, field, nil) + renderConfigField(w, runCommandPath, field, nil) return nil } @@ -675,8 +678,13 @@ func configSchema() configField { // resolveConfigField resolves a dotted YAML path against the run config schema. // The leading "config." is optional; an empty path describes the whole schema. func resolveConfigField(path string) (configField, error) { + return resolveSchemaField(configSchema(), path) +} + +// resolveSchemaField resolves a dotted YAML path against a config schema rooted +// at root, as resolveConfigField does for the run config. +func resolveSchemaField(root configField, path string) (configField, error) { trimmed := strings.TrimPrefix(strings.TrimPrefix(path, configHelpRoot), ".") - root := configSchema() if trimmed == "" { return root, nil } @@ -834,12 +842,12 @@ func describeStruct(t reflect.Type, prefix string) []configField { // configTypeName renders a field's YAML-facing type. func configTypeName(t reflect.Type) string { - if name, ok := configTypeNames[t]; ok { - return name - } for t.Kind() == reflect.Pointer { t = t.Elem() } + if name, ok := configTypeNames[t]; ok { + return name + } switch t.Kind() { case reflect.String: return "string" @@ -864,12 +872,12 @@ func configTypeName(t reflect.Type) string { // type a field decodes into, or nil if it is not a struct. The polymorphic unions // are excluded: they are structs, but their YAML shape is scalar or list. func underlyingConfigStruct(t reflect.Type) reflect.Type { - if _, ok := configTypeNames[t]; ok { - return nil - } for t.Kind() == reflect.Pointer || t.Kind() == reflect.Slice { t = t.Elem() } + if _, ok := configTypeNames[t]; ok { + return nil + } if t.Kind() == reflect.Struct { return t } @@ -878,7 +886,8 @@ func underlyingConfigStruct(t reflect.Type) reflect.Type { // renderConfigField writes a resolved field's documentation. An object lists its // immediate children; a leaf gets its type, required-ness, and description. -func renderConfigField(w io.Writer, f configField, computeOptions []computeOption) { +// command is the command whose -h documents the schema. +func renderConfigField(w io.Writer, command string, f configField, computeOptions []computeOption) { fmt.Fprintf(w, "%s\n", f.path) if f.help != "" { fmt.Fprintf(w, " %s\n", f.help) @@ -927,8 +936,9 @@ func renderConfigField(w io.Writer, f configField, computeOptions []computeOptio fmt.Fprintf(w, " %-*s %s\n", width, configLeafName(c.path), configFieldSummary(c)) } } - fmt.Fprintf(w, "\nFor details on a field, run \"databricks air run -h %s.\".\n", f.path) - if f.path == configHelpRoot { + fmt.Fprintf(w, "\nFor details on a field, run \"%s -h %s.\".\n", command, f.path) + // The runtime and skill notes are about run YAML, so only `air run -h config` shows them. + if f.path == configHelpRoot && command == runCommandPath { fmt.Fprint(w, runtimeEnvHelp) fmt.Fprint(w, agentSkillHelp) } diff --git a/cmd/air/runconfig_load.go b/cmd/air/runconfig_load.go index 131408a0007..a277c0848ef 100644 --- a/cmd/air/runconfig_load.go +++ b/cmd/air/runconfig_load.go @@ -19,10 +19,16 @@ import ( // decodeRunConfigReader decodes and unknown-key-checks a run YAML from r. path is // used only for error messages. func decodeRunConfigReader(r io.Reader, path string) (*runConfig, error) { + return decodeConfigReader[runConfig](r, path) +} + +// decodeConfigReader decodes and unknown-key-checks a YAML config from r into a +// T. path is used only for error messages. +func decodeConfigReader[T any](r io.Reader, path string) (*T, error) { dec := yaml.NewDecoder(r) dec.KnownFields(true) - var cfg runConfig + var cfg T if err := dec.Decode(&cfg); err != nil { if errors.Is(err, io.EOF) { return nil, fmt.Errorf("config %s is empty", path) @@ -60,30 +66,41 @@ func loadRunConfigWithOverrides(ctx context.Context, path string, overrides []st if len(overrides) == 0 { return loadRunConfig(path) } + document, validationYAML, err := readConfigWithOverrides(ctx, path, overrides, configSchema()) + if err != nil { + return nil, err + } + return finishRunConfigLoad(path, document, validationYAML) +} +// readConfigWithOverrides reads a YAML config and applies --override KEY=VALUE +// entries, checked against schema, to its ordered YAML tree. It returns the tree +// and its serialization, which the caller decodes with unknown keys rejected. +// ctx is used only to log applied overrides. +func readConfigWithOverrides(ctx context.Context, path string, overrides []string, schema configField) (*yaml.Node, []byte, error) { entries, err := parseOverrides(overrides) if err != nil { - return nil, err + return nil, nil, err } - if err := validateOverridePaths(entries); err != nil { - return nil, err + if err := validateOverridePaths(entries, schema); err != nil { + return nil, nil, err } document, _, err := readRunConfigDocument(path) if err != nil { - return nil, err + return nil, nil, err } if len(document.Content) == 0 { document.Kind = yaml.DocumentNode document.Content = []*yaml.Node{newMappingNode()} } if err := applyOverrides(ctx, document, entries); err != nil { - return nil, err + return nil, nil, err } validationYAML, err := yaml.Marshal(document) if err != nil { - return nil, fmt.Errorf("failed to serialize config %s: %w", path, err) + return nil, nil, fmt.Errorf("failed to serialize config %s: %w", path, err) } - return finishRunConfigLoad(path, document, validationYAML) + return document, validationYAML, nil } func readRunConfigDocument(path string) (*yaml.Node, []byte, error) { @@ -133,8 +150,14 @@ func finishRunConfigLoad(path string, document *yaml.Node, validationYAML []byte // strict decode that follows rejects them too, but its error names the Go struct // rather than the field's path and offers no suggestion. func checkUnknownConfigFields(path string, root *yaml.Node) error { - schema := configSchema() - unknown := unknownConfigFields(root, schema, schema.path, nil) + return checkUnknownSchemaFields(path, root, configSchema(), runCommandPath) +} + +// checkUnknownSchemaFields rejects keys absent from schema, as +// checkUnknownConfigFields does for the run config. command is the command whose +// -h lists schema's fields. +func checkUnknownSchemaFields(path string, root *yaml.Node, schema configField, command string) error { + unknown := unknownConfigFields(root, schema, schema.path, nil, command) switch len(unknown) { case 0: return nil @@ -152,7 +175,7 @@ func checkUnknownConfigFields(path string, root *yaml.Node) error { // // Aliases are never followed: one may point at its own ancestor, and the strict // decode checks whatever they expand to. -func unknownConfigFields(node *yaml.Node, field configField, helpPath string, keys []string) []string { +func unknownConfigFields(node *yaml.Node, field configField, helpPath string, keys []string, command string) []string { // Only objects have schema-defined keys; free-form maps and leaves do not. if len(field.children) == 0 { return nil @@ -162,7 +185,7 @@ func unknownConfigFields(node *yaml.Node, field configField, helpPath string, ke case yaml.SequenceNode: for _, element := range node.Content { if element.Kind == yaml.MappingNode { - unknown = append(unknown, unknownConfigFields(element, field, helpPath, keys)...) + unknown = append(unknown, unknownConfigFields(element, field, helpPath, keys, command)...) } } case yaml.MappingNode: @@ -181,14 +204,14 @@ func unknownConfigFields(node *yaml.Node, field configField, helpPath string, ke } else { msg += "; run" } - unknown = append(unknown, fmt.Sprintf("%s \"databricks air run -h %s\" for the list of fields", msg, helpPath)) + unknown = append(unknown, fmt.Sprintf("%s \"%s -h %s\" for the list of fields", msg, command, helpPath)) continue } childHelpPath := helpPath if helpPath == field.path && !child.hidden { childHelpPath = child.path } - unknown = append(unknown, unknownConfigFields(value, child, childHelpPath, keyPath)...) + unknown = append(unknown, unknownConfigFields(value, child, childHelpPath, keyPath, command)...) } default: // Scalars hold no keys, and aliases are left to the decoder. diff --git a/cmd/air/runconfig_override.go b/cmd/air/runconfig_override.go index 306308edfd4..8cb51d25c5e 100644 --- a/cmd/air/runconfig_override.go +++ b/cmd/air/runconfig_override.go @@ -44,11 +44,10 @@ type overrideEntry struct { raw string } -// validateOverridePaths checks every dotted path against the runConfig schema +// validateOverridePaths checks every dotted path against a config schema // before mutation, so an error names the exact --override key rather than the // re-decode's Go-type language. -func validateOverridePaths(entries []overrideEntry) error { - schema := configSchema() +func validateOverridePaths(entries []overrideEntry, schema configField) error { for _, e := range entries { if err := checkOverridePath(strings.Split(e.path, "."), schema, e.path); err != nil { return err @@ -92,7 +91,7 @@ func applyOverrides(ctx context.Context, document *yaml.Node, entries []override root = document.Content[0] } if root.Kind != yaml.MappingNode { - return errors.New("run config must be a YAML mapping") + return errors.New("config must be a YAML mapping") } for _, e := range entries { diff --git a/cmd/air/runconfig_override_test.go b/cmd/air/runconfig_override_test.go index c0dc4937138..982f9ad74a0 100644 --- a/cmd/air/runconfig_override_test.go +++ b/cmd/air/runconfig_override_test.go @@ -90,7 +90,7 @@ func TestValidateOverridePaths(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := validateOverridePaths([]overrideEntry{{path: tt.path, raw: "x"}}) + err := validateOverridePaths([]overrideEntry{{path: tt.path, raw: "x"}}, configSchema()) if tt.wantErr != "" { require.ErrorContains(t, err, tt.wantErr) return diff --git a/cmd/air/runconfig_test.go b/cmd/air/runconfig_test.go index c46869192e8..229288197eb 100644 --- a/cmd/air/runconfig_test.go +++ b/cmd/air/runconfig_test.go @@ -1145,14 +1145,14 @@ func TestConfigSchemaSharedByHelpAndOverride(t *testing.T) { for _, p := range []string{"code_source.type", "code_source.snapshot.root_path"} { t.Run(p+" compatibility override", func(t *testing.T) { - require.NoError(t, validateOverridePaths([]overrideEntry{{path: p, raw: "x"}})) + require.NoError(t, validateOverridePaths([]overrideEntry{{path: p, raw: "x"}}, configSchema())) _, err := resolveConfigField(p) require.Error(t, err) }) } for _, p := range paths { t.Run(p, func(t *testing.T) { - require.NoError(t, validateOverridePaths([]overrideEntry{{path: p, raw: "x"}})) + require.NoError(t, validateOverridePaths([]overrideEntry{{path: p, raw: "x"}}, configSchema())) // The help path accepts the same field (free-form sub-paths resolve to // the map itself, which is the schema's most specific node). _, err := resolveConfigField(p) @@ -1163,7 +1163,7 @@ func TestConfigSchemaSharedByHelpAndOverride(t *testing.T) { } // A field unknown to one is unknown to the other. - require.Error(t, validateOverridePaths([]overrideEntry{{path: "compute.bogus", raw: "x"}})) + require.Error(t, validateOverridePaths([]overrideEntry{{path: "compute.bogus", raw: "x"}}, configSchema())) _, err := resolveConfigField("compute.bogus") require.Error(t, err) } diff --git a/cmd/air/runsubmit.go b/cmd/air/runsubmit.go index 1dfa5bd253b..1c4dabe477b 100644 --- a/cmd/air/runsubmit.go +++ b/cmd/air/runsubmit.go @@ -275,10 +275,10 @@ func aiRuntimeTaskFromSubmitBody(body map[string]any) (map[string]any, error) { // effectiveIdempotencyToken resolves the token sent to validation and submit: // the --idempotency-key flag wins, then the config's token, else a generated one. -func effectiveIdempotencyToken(flag string, cfg *runConfig) string { +func effectiveIdempotencyToken(flag string, configured *string) string { token := flag - if token == "" && cfg.IdempotencyToken != nil { - token = *cfg.IdempotencyToken + if token == "" && configured != nil { + token = *configured } if token == "" { token = uuid.New().String() @@ -350,7 +350,7 @@ func submitWorkload(ctx context.Context, w *databricks.WorkspaceClient, cfg *run return 0, "", err } containers := submittedContainers(cfg, funcDir) - token := effectiveIdempotencyToken(idempotencyKey, cfg) + token := effectiveIdempotencyToken(idempotencyKey, cfg.IdempotencyToken) deps, _ := cfg.inlineDependencies() diff --git a/cmd/air/runsubmit_test.go b/cmd/air/runsubmit_test.go index 2a5c739f4f5..d0ea032ed61 100644 --- a/cmd/air/runsubmit_test.go +++ b/cmd/air/runsubmit_test.go @@ -33,9 +33,9 @@ func stubValidateConfig(server *testserver.Server) { func TestEffectiveIdempotencyToken(t *testing.T) { cfg := &runConfig{IdempotencyToken: new("from-config")} - assert.Equal(t, "from-flag", effectiveIdempotencyToken("from-flag", cfg)) - assert.Equal(t, "from-config", effectiveIdempotencyToken("", cfg)) - assert.NotEmpty(t, effectiveIdempotencyToken("", &runConfig{})) + assert.Equal(t, "from-flag", effectiveIdempotencyToken("from-flag", cfg.IdempotencyToken)) + assert.Equal(t, "from-config", effectiveIdempotencyToken("", cfg.IdempotencyToken)) + assert.NotEmpty(t, effectiveIdempotencyToken("", nil)) } func TestDlRuntimeImage(t *testing.T) {