diff --git a/.nextchanges/air/run-json-validation-errors.md b/.nextchanges/air/run-json-validation-errors.md new file mode 100644 index 00000000000..3d1404e7040 --- /dev/null +++ b/.nextchanges/air/run-json-validation-errors.md @@ -0,0 +1 @@ +* `air run -o json` now reports config-validation errors as a JSON error envelope instead of plain text. A missing profile reports `UNAUTHENTICATED`, other workspace client setup errors (such as an unknown profile) report `INVALID_ARGS`, and with `--dry-run` rejected credentials report `UNAUTHENTICATED` and a missing permission on `config:validate` reports the new `PERMISSION_DENIED` code. ([#7864](https://github.com/databricks/cli/pull/7864)) diff --git a/acceptance/air/run-backend-error/output.txt b/acceptance/air/run-backend-error/output.txt index bc9d2188d01..0cc3d32297e 100644 --- a/acceptance/air/run-backend-error/output.txt +++ b/acceptance/air/run-backend-error/output.txt @@ -8,3 +8,17 @@ Error: config validation failed: Tip: use the --debug flag to see more details and a trace of this error: databricks --debug air run … + +=== backend field errors fail dry-run (json) + +>>> [CLI] air run -f valid.yaml --dry-run -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "INVALID_ARGS", + "kind": "PERMANENT", + "message": "config validation failed:\n deployments[0].compute.accelerator_count: accelerator_count must be at most 1024, but was 1032.\n env_variables[1INVALID]: env_variables[1INVALID] contains characters that are not allowed.", + "retryable": false + } +} diff --git a/acceptance/air/run-backend-error/script b/acceptance/air/run-backend-error/script index 6b211207ba9..c843d11eec4 100644 --- a/acceptance/air/run-backend-error/script +++ b/acceptance/air/run-backend-error/script @@ -1,2 +1,5 @@ title "backend field errors fail dry-run" musterr trace $CLI air run -f valid.yaml --dry-run + +title "backend field errors fail dry-run (json)" +musterr trace $CLI air run -f valid.yaml --dry-run -o json diff --git a/acceptance/air/run-rejected-credentials/me-401/out.test.toml b/acceptance/air/run-rejected-credentials/me-401/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/air/run-rejected-credentials/me-401/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/air/run-rejected-credentials/me-401/output.txt b/acceptance/air/run-rejected-credentials/me-401/output.txt new file mode 100644 index 00000000000..76c78ed1367 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/me-401/output.txt @@ -0,0 +1,14 @@ + +=== a 401 from the current-user lookup is rejected credentials (json) + +>>> [CLI] air run -f [TESTROOT]/air/run-rejected-credentials/me-401/../valid.yaml --dry-run -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "UNAUTHENTICATED", + "kind": "PERMANENT", + "message": "authentication was not successful: failed to resolve current user: Invalid access token.", + "retryable": false + } +} diff --git a/acceptance/air/run-rejected-credentials/me-401/script b/acceptance/air/run-rejected-credentials/me-401/script new file mode 100644 index 00000000000..dba50d661da --- /dev/null +++ b/acceptance/air/run-rejected-credentials/me-401/script @@ -0,0 +1,2 @@ +title "a 401 from the current-user lookup is rejected credentials (json)" +musterr trace $CLI air run -f $TESTDIR/../valid.yaml --dry-run -o json diff --git a/acceptance/air/run-rejected-credentials/me-401/test.toml b/acceptance/air/run-rejected-credentials/me-401/test.toml new file mode 100644 index 00000000000..7dbe6bb14f9 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/me-401/test.toml @@ -0,0 +1,9 @@ +[[Server]] +Pattern = "GET /api/2.0/preview/scim/v2/Me" +Response.Body = ''' +{ + "error_code": "UNAUTHENTICATED", + "message": "Invalid access token." +} +''' +Response.StatusCode = 401 diff --git a/acceptance/air/run-rejected-credentials/me-403/out.test.toml b/acceptance/air/run-rejected-credentials/me-403/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/air/run-rejected-credentials/me-403/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/air/run-rejected-credentials/me-403/output.txt b/acceptance/air/run-rejected-credentials/me-403/output.txt new file mode 100644 index 00000000000..d653e7001b6 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/me-403/output.txt @@ -0,0 +1,14 @@ + +=== a 403 from the current-user lookup is rejected credentials (json) + +>>> [CLI] air run -f [TESTROOT]/air/run-rejected-credentials/me-403/../valid.yaml --dry-run -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "UNAUTHENTICATED", + "kind": "PERMANENT", + "message": "authentication was not successful: failed to resolve current user: Invalid access token.", + "retryable": false + } +} diff --git a/acceptance/air/run-rejected-credentials/me-403/script b/acceptance/air/run-rejected-credentials/me-403/script new file mode 100644 index 00000000000..f7437beaaa6 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/me-403/script @@ -0,0 +1,2 @@ +title "a 403 from the current-user lookup is rejected credentials (json)" +musterr trace $CLI air run -f $TESTDIR/../valid.yaml --dry-run -o json diff --git a/acceptance/air/run-rejected-credentials/me-403/test.toml b/acceptance/air/run-rejected-credentials/me-403/test.toml new file mode 100644 index 00000000000..1afa1d60c84 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/me-403/test.toml @@ -0,0 +1,9 @@ +[[Server]] +Pattern = "GET /api/2.0/preview/scim/v2/Me" +Response.Body = ''' +{ + "error_code": "PERMISSION_DENIED", + "message": "Invalid access token." +} +''' +Response.StatusCode = 403 diff --git a/acceptance/air/run-rejected-credentials/valid.yaml b/acceptance/air/run-rejected-credentials/valid.yaml new file mode 100644 index 00000000000..b82a321b051 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/valid.yaml @@ -0,0 +1,5 @@ +experiment_name: smoke-test +command: python train.py +compute: + accelerator_type: GPU_1xH100 + num_accelerators: 1 diff --git a/acceptance/air/run-rejected-credentials/validate-401/out.test.toml b/acceptance/air/run-rejected-credentials/validate-401/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/air/run-rejected-credentials/validate-401/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/air/run-rejected-credentials/validate-401/output.txt b/acceptance/air/run-rejected-credentials/validate-401/output.txt new file mode 100644 index 00000000000..c6c3b07999a --- /dev/null +++ b/acceptance/air/run-rejected-credentials/validate-401/output.txt @@ -0,0 +1,14 @@ + +=== a 401 from config:validate is rejected credentials (json) + +>>> [CLI] air run -f [TESTROOT]/air/run-rejected-credentials/validate-401/../valid.yaml --dry-run -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "UNAUTHENTICATED", + "kind": "PERMANENT", + "message": "authentication was not successful: failed to validate config: Invalid access token.", + "retryable": false + } +} diff --git a/acceptance/air/run-rejected-credentials/validate-401/script b/acceptance/air/run-rejected-credentials/validate-401/script new file mode 100644 index 00000000000..bab16c56875 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/validate-401/script @@ -0,0 +1,2 @@ +title "a 401 from config:validate is rejected credentials (json)" +musterr trace $CLI air run -f $TESTDIR/../valid.yaml --dry-run -o json diff --git a/acceptance/air/run-rejected-credentials/validate-401/test.toml b/acceptance/air/run-rejected-credentials/validate-401/test.toml new file mode 100644 index 00000000000..fdc1b5f0e07 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/validate-401/test.toml @@ -0,0 +1,9 @@ +[[Server]] +Pattern = "POST /api/2.0/ai-training/config:validate" +Response.Body = ''' +{ + "error_code": "UNAUTHENTICATED", + "message": "Invalid access token." +} +''' +Response.StatusCode = 401 diff --git a/acceptance/air/run-rejected-credentials/validate-403/out.test.toml b/acceptance/air/run-rejected-credentials/validate-403/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/air/run-rejected-credentials/validate-403/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/air/run-rejected-credentials/validate-403/output.txt b/acceptance/air/run-rejected-credentials/validate-403/output.txt new file mode 100644 index 00000000000..0fdc0f12c4d --- /dev/null +++ b/acceptance/air/run-rejected-credentials/validate-403/output.txt @@ -0,0 +1,14 @@ + +=== a 403 from config:validate is a missing permission (json) + +>>> [CLI] air run -f [TESTROOT]/air/run-rejected-credentials/validate-403/../valid.yaml --dry-run -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "PERMISSION_DENIED", + "kind": "PERMANENT", + "message": "failed to validate config: User does not have access to the accelerator pool.", + "retryable": false + } +} diff --git a/acceptance/air/run-rejected-credentials/validate-403/script b/acceptance/air/run-rejected-credentials/validate-403/script new file mode 100644 index 00000000000..9181f814995 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/validate-403/script @@ -0,0 +1,2 @@ +title "a 403 from config:validate is a missing permission (json)" +musterr trace $CLI air run -f $TESTDIR/../valid.yaml --dry-run -o json diff --git a/acceptance/air/run-rejected-credentials/validate-403/test.toml b/acceptance/air/run-rejected-credentials/validate-403/test.toml new file mode 100644 index 00000000000..51a8f127655 --- /dev/null +++ b/acceptance/air/run-rejected-credentials/validate-403/test.toml @@ -0,0 +1,9 @@ +[[Server]] +Pattern = "POST /api/2.0/ai-training/config:validate" +Response.Body = ''' +{ + "error_code": "PERMISSION_DENIED", + "message": "User does not have access to the accelerator pool." +} +''' +Response.StatusCode = 403 diff --git a/acceptance/air/run/broken-bundle/databricks.yml b/acceptance/air/run/broken-bundle/databricks.yml new file mode 100644 index 00000000000..efaa43cf06a --- /dev/null +++ b/acceptance/air/run/broken-bundle/databricks.yml @@ -0,0 +1,10 @@ +bundle: + name: broken-bundle + +# Two targets both marked default is an invalid bundle, so loading it prints +# diagnostics before air run reaches the workspace. +targets: + dev: + default: true + dev2: + default: true diff --git a/acceptance/air/run/output.txt b/acceptance/air/run/output.txt index 64cba1975ae..6c79f8243b0 100644 --- a/acceptance/air/run/output.txt +++ b/acceptance/air/run/output.txt @@ -63,6 +63,20 @@ Error: code_source include_paths select no files under [TEST_TMP_DIR]: data. Che Tip: use the --debug flag to see more details and a trace of this error: databricks --debug air run … +=== include_paths entry that selects no files is rejected (json) + +>>> [CLI] air run -f include-unmatched.yaml --dry-run -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "INVALID_ARGS", + "kind": "PERMANENT", + "message": "code_source include_paths select no files under [TEST_TMP_DIR]: data. Check that these paths exist under root_path and hold files git does not ignore (`git check-ignore -v \u003cfile\u003e` shows the rule for a file); empty directories, nested git repositories and submodules add no files", + "retryable": false + } +} + === include_paths pathspec that selects files outside root_path is rejected >>> [CLI] air run -f include-outside-root.yaml --dry-run @@ -120,6 +134,118 @@ Tip: use the --debug flag to see more details and a trace of this error: Exit code: 1 +=== invalid config is rejected (json) + +>>> [CLI] air run -f invalid.yaml --dry-run -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "INVALID_ARGS", + "kind": "PERMANENT", + "message": "invalid experiment_name \"bad.name\": only alphanumeric characters, hyphens (-), and underscores (_) are allowed", + "retryable": false + } +} + +=== dry-run without credentials reports an authentication error (json) + +>>> env -u DATABRICKS_HOST -u DATABRICKS_TOKEN [CLI] air run -f valid.yaml --dry-run -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "UNAUTHENTICATED", + "kind": "PERMANENT", + "message": "no default profile is set: pass --profile (-p) or configure a default profile in your .databrickscfg", + "retryable": false + } +} + +=== dry-run without credentials keeps the original error in text mode + +>>> env -u DATABRICKS_HOST -u DATABRICKS_TOKEN [CLI] air run -f valid.yaml --dry-run +Error: default auth: cannot configure default credentials, please check https://docs.databricks.com/en/dev-tools/auth.html#databricks-client-unified-authentication to configure credentials for your preferred authentication method. Config: databricks_cli_path=[CLI]. Env: DATABRICKS_CLI_PATH + +Tip: use the --debug flag to see more details and a trace of this error: + databricks --debug air run … + +=== submit without credentials reports an authentication error (json) + +>>> env -u DATABRICKS_HOST -u DATABRICKS_TOKEN [CLI] air run -f valid.yaml -o json +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "UNAUTHENTICATED", + "kind": "PERMANENT", + "message": "no default profile is set: pass --profile (-p) or configure a default profile in your .databrickscfg", + "retryable": false + } +} + +=== dry-run reports an over-long idempotency key before missing credentials (json) + +>>> env -u DATABRICKS_HOST -u DATABRICKS_TOKEN [CLI] air run -f valid.yaml --dry-run -o json --idempotency-key aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "INVALID_ARGS", + "kind": "PERMANENT", + "message": "idempotency token must be 64 characters or less, got 65", + "retryable": false + } +} + +=== dry-run with an unknown profile is a permanent config error (json) + +>>> env -u DATABRICKS_HOST -u DATABRICKS_TOKEN DATABRICKS_CONFIG_FILE=profiles.databrickscfg [CLI] air run -f valid.yaml --dry-run -o json -p does-not-exist +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "INVALID_ARGS", + "kind": "PERMANENT", + "message": "resolve: profiles.databrickscfg has no does-not-exist profile configured. Config: profile=does-not-exist, config_file=profiles.databrickscfg, databricks_cli_path=[CLI]. Env: DATABRICKS_CONFIG_FILE, DATABRICKS_CLI_PATH", + "retryable": false + } +} + +=== bundle diagnostics are reported once (json) + +>>> [CLI] air run -f ../valid.yaml --dry-run -o json +Error: multiple targets are marked as default ([TARGETS]) + + +>>> [CLI] air run -f ../valid.yaml -o json +Error: multiple targets are marked as default ([TARGETS]) + + +=== bundle diagnostics come before the idempotency key error + +>>> [CLI] air run -f ../valid.yaml --dry-run --idempotency-key aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +Error: multiple targets are marked as default ([TARGETS]) + +Error: idempotency token must be 64 characters or less, got 65 + +Tip: use the --debug flag to see more details and a trace of this error: + databricks --debug air run … + +>>> [CLI] air run -f ../valid.yaml --dry-run -o json --idempotency-key aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +Error: multiple targets are marked as default ([TARGETS]) + +{ + "v": 1, + "ts": "[TIMESTAMP]", + "error": { + "code": "INVALID_ARGS", + "kind": "PERMANENT", + "message": "idempotency token must be 64 characters or less, got 65", + "retryable": false + } +} + === unknown field suggests the near match >>> [CLI] air run -f unknown-field.yaml --dry-run diff --git a/acceptance/air/run/profiles.databrickscfg b/acceptance/air/run/profiles.databrickscfg new file mode 100644 index 00000000000..3c1dacccfea --- /dev/null +++ b/acceptance/air/run/profiles.databrickscfg @@ -0,0 +1,3 @@ +[other] +host = https://other.test +token = other-token diff --git a/acceptance/air/run/script b/acceptance/air/run/script index 45c5437b857..db03189e526 100644 --- a/acceptance/air/run/script +++ b/acceptance/air/run/script @@ -29,6 +29,9 @@ trace $CLI air run -f with-code-source.yaml --dry-run title "include_paths entry that selects no files is rejected" musterr trace $CLI air run -f include-unmatched.yaml --dry-run +title "include_paths entry that selects no files is rejected (json)" +musterr trace $CLI air run -f include-unmatched.yaml --dry-run -o json + title "include_paths pathspec that selects files outside root_path is rejected" # :(top) resolves against the repository root, so from root_path src it selects ../valid.yaml. musterr trace $CLI air run -f include-outside-root.yaml --dry-run @@ -62,6 +65,32 @@ errcode trace $CLI air run -f git-remote.yaml --dry-run title "invalid config is rejected" errcode trace $CLI air run -f invalid.yaml --dry-run +title "invalid config is rejected (json)" +musterr trace $CLI air run -f invalid.yaml --dry-run -o json + +title "dry-run without credentials reports an authentication error (json)" +musterr trace env -u DATABRICKS_HOST -u DATABRICKS_TOKEN $CLI air run -f valid.yaml --dry-run -o json + +title "dry-run without credentials keeps the original error in text mode" +musterr trace env -u DATABRICKS_HOST -u DATABRICKS_TOKEN $CLI air run -f valid.yaml --dry-run + +title "submit without credentials reports an authentication error (json)" +musterr trace env -u DATABRICKS_HOST -u DATABRICKS_TOKEN $CLI air run -f valid.yaml -o json + +title "dry-run reports an over-long idempotency key before missing credentials (json)" +musterr trace env -u DATABRICKS_HOST -u DATABRICKS_TOKEN $CLI air run -f valid.yaml --dry-run -o json --idempotency-key aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + +title "dry-run with an unknown profile is a permanent config error (json)" +musterr trace env -u DATABRICKS_HOST -u DATABRICKS_TOKEN DATABRICKS_CONFIG_FILE=profiles.databrickscfg $CLI air run -f valid.yaml --dry-run -o json -p does-not-exist + +title "bundle diagnostics are reported once (json)" +musterr withdir broken-bundle trace $CLI air run -f ../valid.yaml --dry-run -o json +musterr withdir broken-bundle trace $CLI air run -f ../valid.yaml -o json + +title "bundle diagnostics come before the idempotency key error" +musterr withdir broken-bundle trace $CLI air run -f ../valid.yaml --dry-run --idempotency-key aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +musterr withdir broken-bundle trace $CLI air run -f ../valid.yaml --dry-run -o json --idempotency-key aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + title "unknown field suggests the near match" errcode trace $CLI air run -f unknown-field.yaml --dry-run diff --git a/acceptance/air/run/test.toml b/acceptance/air/run/test.toml index 3daed6e5e2c..d3d0e7cb0eb 100644 --- a/acceptance/air/run/test.toml +++ b/acceptance/air/run/test.toml @@ -1,3 +1,8 @@ [[Server]] Pattern = "POST /api/2.0/ai-training/config:validate" Response.Body = '{}' + +# The bundle loader lists default targets in map order. +[[Repls]] +Old = 'marked as default \((dev, dev2|dev2, dev)\)' +New = 'marked as default ([TARGETS])' diff --git a/cmd/air/run.go b/cmd/air/run.go index 1baf2ad0e60..fef02f4b5a0 100644 --- a/cmd/air/run.go +++ b/cmd/air/run.go @@ -13,11 +13,14 @@ import ( "unicode/utf8" "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/auth/u2m" "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/databricks/databricks-sdk-go/apierr" + "github.com/databricks/databricks-sdk-go/config" "github.com/spf13/cobra" ) @@ -55,7 +58,7 @@ func warnExperimentalContainers(ctx context.Context, cfg *runConfig) { func validateDryRunInWorkspace(ctx context.Context, cmd *cobra.Command, args []string, cfg *runConfig, idempotencyToken string, timeout time.Duration) (context.Context, error) { if !cmdctx.HasWorkspaceClient(ctx) { if err := root.MustWorkspaceClient(cmd, args); err != nil { - return ctx, err + return ctx, &workspaceClientError{err} } ctx = cmd.Context() } @@ -65,6 +68,10 @@ func validateDryRunInWorkspace(ctx context.Context, cmd *cobra.Command, args []s if err != nil { unavailable, retryable := classifyValidationFailure(err) if !unavailable { + // The current-user lookup rejects only bad credentials, even with a 403. + if errors.Is(err, apierr.ErrUnauthenticated) || errors.Is(err, apierr.ErrPermissionDenied) { + return ctx, &validationAuthenticationError{err} + } return ctx, err } return ctx, asValidationUnavailable(err, retryable) @@ -73,6 +80,57 @@ func validateDryRunInWorkspace(ctx context.Context, cmd *cobra.Command, args []s return ctx, validateDryRunConfig(ctx, w, cfg, commandPath, submittedContainers(cfg, funcDir), idempotencyToken, timeout) } +// workspaceClientError marks a --dry-run failure to build the workspace client, +// so RunE classifies it with renderWorkspaceClientError rather than as a +// validation error. +type workspaceClientError struct { + err error +} + +func (e *workspaceClientError) Error() string { return e.err.Error() } +func (e *workspaceClientError) Unwrap() error { return e.err } + +// renderWorkspaceClientError renders a failure to build the workspace client. +// Bundle diagnostics that were already printed pass through, as in air get. A +// missing profile, rejected credentials, or a failure that may pass on retry +// (network, timeout, 429, 5xx) go through authError, and an expired login is +// UNAUTHENTICATED. Any other setup failure (an unknown or account-only profile, +// for example) is a config mistake that a retry can't fix, so it is +// INVALID_ARGS rather than authError's retryable fallback. Text mode keeps the +// original error. +func renderWorkspaceClientError(ctx context.Context, cmd *cobra.Command, err error) error { + _, transient := classifyValidationFailure(err) + _, expiredLogin := errors.AsType[*u2m.InvalidRefreshTokenError](err) + switch { + case errors.Is(err, root.ErrAlreadyPrinted), root.OutputType(cmd) != flags.OutputJSON: + return err + case expiredLogin: + return renderError(ctx, cmd, "UNAUTHENTICATED", "PERMANENT", false, err) + case errors.Is(err, config.ErrCannotConfigureDefault), errors.Is(err, apierr.ErrUnauthenticated), errors.Is(err, apierr.ErrPermissionDenied), transient: + return authError(ctx, cmd, err) + } + return renderError(ctx, cmd, "INVALID_ARGS", "PERMANENT", false, err) +} + +// renderDryRunCallerError renders a --dry-run failure that is the caller's to +// fix, keeping credential and permission failures apart from config errors so +// agents don't edit a valid config. A 401 or 403 from the current-user lookup +// and a 401 from config:validate go through authError, as in air get. A 403 +// from config:validate is PERMISSION_DENIED: the same credentials just passed the +// current-user lookup. Text mode keeps the original error. +func renderDryRunCallerError(ctx context.Context, cmd *cobra.Command, err error) error { + _, credentialsRejected := errors.AsType[*validationAuthenticationError](err) + switch { + case root.OutputType(cmd) != flags.OutputJSON: + return err + case credentialsRejected || errors.Is(err, apierr.ErrUnauthenticated): + return authError(ctx, cmd, err) + case errors.Is(err, apierr.ErrPermissionDenied): + return renderError(ctx, cmd, "PERMISSION_DENIED", "PERMANENT", false, err) + } + return renderError(ctx, cmd, "INVALID_ARGS", "PERMANENT", false, err) +} + func newRunCommand() *cobra.Command { return newRunCommandWithValidationTimeout(dryRunValidationTimeout) } @@ -154,7 +212,10 @@ databricks-ai-runtime skill: if dryRun { return nil } - return root.MustWorkspaceClient(cmd, args) + 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 { @@ -162,7 +223,7 @@ databricks-ai-runtime skill: cfg, err := loadRunConfigWithOverrides(ctx, file, overrides) if err != nil { - return err + return renderError(ctx, cmd, "INVALID_ARGS", "PERMANENT", false, err) } if msg := missingTorchWarning(ctx, cfg, file); msg != "" { @@ -175,19 +236,22 @@ databricks-ai-runtime skill: if cfg.CodeSource != nil && cfg.CodeSource.Snapshot != nil { count, err := countSnapshotFiles(ctx, cfg.CodeSource.Snapshot, file) if err != nil { - return err + return renderError(ctx, cmd, "INVALID_ARGS", "PERMANENT", false, err) } snapshotFileCount = &count } idempotencyToken := effectiveIdempotencyToken(idempotencyKey, cfg) ctx, validationErr := validateDryRunInWorkspace(ctx, cmd, args, cfg, idempotencyToken, validationTimeout) if err := validateIdempotencyToken(idempotencyToken); err != nil { - return err + return renderError(ctx, cmd, "INVALID_ARGS", "PERMANENT", false, err) + } + if clientErr, ok := errors.AsType[*workspaceClientError](validationErr); ok { + return renderWorkspaceClientError(ctx, cmd, clientErr.err) } if validationErr != nil { unavailable, ok := validationUnavailable(validationErr) if !ok { - return validationErr + return renderDryRunCallerError(ctx, cmd, validationErr) } kind := "PERMANENT" if unavailable.retryable { diff --git a/cmd/air/run_test.go b/cmd/air/run_test.go index 78f4deb3129..ca012b9c36e 100644 --- a/cmd/air/run_test.go +++ b/cmd/air/run_test.go @@ -3,18 +3,23 @@ package aircmd import ( "bytes" "encoding/json" + "errors" "net/http" "net/http/httptest" + "net/url" "strings" "sync/atomic" "testing" "time" "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/auth" + "github.com/databricks/cli/libs/auth/u2m" "github.com/databricks/cli/libs/cmdctx" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/testserver" + "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -266,6 +271,35 @@ func TestRunDryRunRetriesUnavailableResponseOnce(t *testing.T) { } } +// Workspace-client setup failures that a retry can't fix must not be reported +// as retryable, while a transient failure while authenticating still is. +func TestRenderWorkspaceClientError(t *testing.T) { + _, expiredLogin := auth.RewriteAuthError(t.Context(), "https://host.test", "", "dev", &u2m.InvalidRefreshTokenError{}) + tests := []struct { + name string + err error + code string + retryable bool + }{ + {"expired login", expiredLogin, "UNAUTHENTICATED", false}, + {"network", &url.Error{Op: "Get", URL: "https://host.test", Err: errors.New("connection refused")}, "INTERNAL_ERROR", true}, + {"account-only profile", root.ErrAccountOnlyProfile{}, "INVALID_ARGS", false}, + {"unknown profile", errors.New("resolve: .databrickscfg has no dev profile configured"), "INVALID_ARGS", false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + ctx := cmdio.InContext(t.Context(), cmdio.NewIO(t.Context(), flags.OutputJSON, nil, &buf, &buf, "", "")) + err := renderWorkspaceClientError(ctx, withOutput(&cobra.Command{}, flags.OutputJSON), tc.err) + require.ErrorIs(t, err, root.ErrAlreadyPrinted) + var got errorEnvelope + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, tc.code, got.Error.Code) + assert.Equal(t, tc.retryable, got.Error.Retryable) + }) + } +} + func TestRunDryRunValidatesIdempotencyTokenAfterWorkspaceValidation(t *testing.T) { var requests []dryRunRequest srv := dryRunServer(t, validateConfigResponse{}, &requests)