diff --git a/.nextchanges/air/dry-run-relative-script-warning.md b/.nextchanges/air/dry-run-relative-script-warning.md new file mode 100644 index 00000000000..07c6e8673c0 --- /dev/null +++ b/.nextchanges/air/dry-run-relative-script-warning.md @@ -0,0 +1 @@ +* `air run --dry-run` warns when `command` refers to a file by a path relative to `code_source.root_path`, suggests `$CODE_SOURCE_PATH/` and links the docs for command paths. ([#7865](https://github.com/databricks/cli/pull/7865)) diff --git a/acceptance/air/run/non-git-subdir.yaml b/acceptance/air/run/non-git-subdir.yaml index b6b6c9878c7..d85a9476561 100644 --- a/acceptance/air/run/non-git-subdir.yaml +++ b/acceptance/air/run/non-git-subdir.yaml @@ -1,5 +1,5 @@ experiment_name: smoke-test -command: python main.py +command: python "$CODE_SOURCE_PATH/main.py" compute: accelerator_type: GPU_1xH100 num_accelerators: 1 diff --git a/acceptance/air/run/output.txt b/acceptance/air/run/output.txt index 64cba1975ae..78b1a3cbf2c 100644 --- a/acceptance/air/run/output.txt +++ b/acceptance/air/run/output.txt @@ -100,6 +100,15 @@ Dry run: configuration for "smoke-test" is valid; not submitting. Dry run: code_source snapshot would include 1 file(s). Dry run: configuration for "smoke-test" is valid; not submitting. +=== a script path relative to root_path warns to use CODE_SOURCE_PATH + +>>> [CLI] air run -f relative-script.yaml --dry-run +Warning: command refers to "train.py", a path relative to code_source.root_path. Consider "$CODE_SOURCE_PATH/train.py" instead. See how command paths and $CODE_SOURCE_PATH work: + AWS: https://docs.databricks.com/aws/en/machine-learning/ai-runtime/connecting/cli/yaml-config#command + Azure: https://learn.microsoft.com/azure/databricks/machine-learning/ai-runtime/connecting/cli/yaml-config#command +Dry run: code_source snapshot would include 1 file(s). +Dry run: configuration for "smoke-test" is valid; not submitting. + === git.remote is rejected >>> [CLI] air run -f git-remote.yaml --dry-run diff --git a/acceptance/air/run/relative-script.yaml b/acceptance/air/run/relative-script.yaml new file mode 100644 index 00000000000..13fbf85cddf --- /dev/null +++ b/acceptance/air/run/relative-script.yaml @@ -0,0 +1,7 @@ +experiment_name: smoke-test +command: python train.py +compute: + accelerator_type: GPU_1xA10 + num_accelerators: 1 +code_source: + root_path: script-src diff --git a/acceptance/air/run/script b/acceptance/air/run/script index 45c5437b857..419052f0bf1 100644 --- a/acceptance/air/run/script +++ b/acceptance/air/run/script @@ -56,6 +56,9 @@ trace $CLI air run -f torch-standard.yaml --dry-run title "the Databricks AI environment provides torch, so no warning" trace $CLI air run -f torch-databricks-ai.yaml --dry-run +title "a script path relative to root_path warns to use CODE_SOURCE_PATH" +trace $CLI air run -f relative-script.yaml --dry-run + title "git.remote is rejected" errcode trace $CLI air run -f git-remote.yaml --dry-run diff --git a/acceptance/air/run/script-src/train.py b/acceptance/air/run/script-src/train.py new file mode 100644 index 00000000000..11b15b1a458 --- /dev/null +++ b/acceptance/air/run/script-src/train.py @@ -0,0 +1 @@ +print("hello") diff --git a/cmd/air/run.go b/cmd/air/run.go index 1baf2ad0e60..08e0ae0a253 100644 --- a/cmd/air/run.go +++ b/cmd/air/run.go @@ -173,11 +173,15 @@ databricks-ai-runtime skill: // Local and credential-free, so it runs before workspace validation. var snapshotFileCount *int if cfg.CodeSource != nil && cfg.CodeSource.Snapshot != nil { - count, err := countSnapshotFiles(ctx, cfg.CodeSource.Snapshot, file) + files, err := listSnapshotFiles(ctx, cfg.CodeSource.Snapshot, file) if err != nil { return err } + count := len(files) snapshotFileCount = &count + if msg := relativeScriptWarning(cfg, files); msg != "" { + cmdio.LogString(ctx, msg) + } } idempotencyToken := effectiveIdempotencyToken(idempotencyKey, cfg) ctx, validationErr := validateDryRunInWorkspace(ctx, cmd, args, cfg, idempotencyToken, validationTimeout) diff --git a/cmd/air/scriptpathcheck.go b/cmd/air/scriptpathcheck.go new file mode 100644 index 00000000000..07a37233cc5 --- /dev/null +++ b/cmd/air/scriptpathcheck.go @@ -0,0 +1,78 @@ +package aircmd + +import ( + "fmt" + "path" + "slices" + "strings" + "unicode" +) + +// relativeScriptWarning returns a warning when command (or a container's +// command) refers to a snapshot file by a path relative to code_source.root_path, +// such as `python train.py`, or "" when none does. snapshotFiles are the +// snapshot-relative paths that would be packaged. Whether such a path resolves +// depends on the runtime, which the CLI doesn't own, so the warning suggests +// $CODE_SOURCE_PATH and links the docs rather than asserting how the run behaves. +func relativeScriptWarning(cfg *runConfig, snapshotFiles []string) string { + if cfg.Command != nil { + if rel := relativeScriptInCommand(*cfg.Command, snapshotFiles); rel != "" { + return relativeScriptMessage("command", rel) + } + } + for _, c := range cfg.Containers { + if c.Command == nil { + continue + } + if rel := relativeScriptInCommand(*c.Command, snapshotFiles); rel != "" { + return relativeScriptMessage(fmt.Sprintf("containers[%s].command", c.Name), rel) + } + } + return "" +} + +// relativeScriptInCommand returns the first word of command that names a file in +// snapshotFiles, or "". Words are split on whitespace and shell operators, so +// `&&cd` is seen as `cd`. A `--flag=value` word is checked by its value; a +// `NAME=value` word is an environment assignment and skipped. Scanning stops at a +// `#` comment and at a `cd` or `pushd`: once the command changes directory, as in +// `cd "$CODE_SOURCE_PATH" && python train.py`, later relative paths are resolved +// against a directory this check can't know. +func relativeScriptInCommand(command string, snapshotFiles []string) string { + for word := range strings.FieldsFuncSeq(command, isShellWordBreak) { + word = strings.Trim(word, `"'`) + if word == "cd" || word == "pushd" || strings.HasPrefix(word, "#") { + return "" + } + if strings.HasPrefix(word, "-") { + _, word, _ = strings.Cut(word, "=") + word = strings.Trim(word, `"'`) + } else if strings.Contains(word, "=") { + continue + } + if word == "" || strings.Contains(word, "$") || strings.HasPrefix(word, "/") { + continue + } + if slices.Contains(snapshotFiles, path.Clean(word)) { + return word + } + } + return "" +} + +func isShellWordBreak(r rune) bool { + return unicode.IsSpace(r) || strings.ContainsRune(";&|()", r) +} + +func relativeScriptMessage(field, rel string) string { + var b strings.Builder + fmt.Fprintf(&b, "Warning: %s refers to %q, a path relative to code_source.root_path. Consider \"$CODE_SOURCE_PATH/%s\" instead. See how command paths and $CODE_SOURCE_PATH work:", field, rel, path.Clean(rel)) + for _, d := range configDocsBases { + fmt.Fprintf(&b, "\n %-6s %s%s", d.cloud+":", d.base, yamlConfigDocsPath) + } + return b.String() +} + +// yamlConfigDocsPath is the docs page that describes command paths and +// $CODE_SOURCE_PATH; see configDocsBases. +const yamlConfigDocsPath = "/machine-learning/ai-runtime/connecting/cli/yaml-config#command" diff --git a/cmd/air/scriptpathcheck_test.go b/cmd/air/scriptpathcheck_test.go new file mode 100644 index 00000000000..a59ff4dd7a2 --- /dev/null +++ b/cmd/air/scriptpathcheck_test.go @@ -0,0 +1,62 @@ +package aircmd + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestRelativeScriptWarning(t *testing.T) { + snapshot := []string{"train.py", "src/main.py", "configs/base.yaml"} + cases := []struct { + name string + command string + word string // the command word reported, "" when no warning is expected + suggest string // the path suggested under $CODE_SOURCE_PATH + }{ + {"bare script", "python train.py", "train.py", "train.py"}, + {"dot-slash script", "./train.py --epochs 1", "./train.py", "train.py"}, + {"quoted nested script", `torchrun --nproc_per_node=8 "src/main.py"`, "src/main.py", "src/main.py"}, + {"flag value with equals", "python -m mod --config=configs/base.yaml", "configs/base.yaml", "configs/base.yaml"}, + {"flag value with space", "python -m mod --config configs/base.yaml", "configs/base.yaml", "configs/base.yaml"}, + {"quoted flag value with equals", `python -m mod --config="configs/base.yaml"`, "configs/base.yaml", "configs/base.yaml"}, + {"code source path variable", `python "$CODE_SOURCE_PATH/train.py"`, "", ""}, + {"absolute path", "python /opt/train.py", "", ""}, + {"environment assignment", "SCRIPT=train.py python -m mod", "", ""}, + {"not in snapshot", "python other.py", "", ""}, + {"parent directory", "python ../tools/prep.py", "", ""}, + {"directory", "ls src", "", ""}, + {"cd into code source first", `cd "$CODE_SOURCE_PATH" && python train.py`, "", ""}, + {"subshell cd", `(cd "$CODE_SOURCE_PATH" && python train.py --epochs 1)`, "", ""}, + {"pushd", `pushd "$CODE_SOURCE_PATH"; python train.py`, "", ""}, + {"glued cd", `pip install -r "$CODE_SOURCE_PATH/req.txt"&&cd "$CODE_SOURCE_PATH" && python train.py`, "", ""}, + {"comment", `python "$CODE_SOURCE_PATH/train.py" # was train.py`, "", ""}, + {"path before a comment", "python train.py # entrypoint", "train.py", "train.py"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := &runConfig{Command: &tc.command} + got := relativeScriptWarning(cfg, snapshot) + if tc.word == "" { + assert.Empty(t, got) + return + } + assert.Contains(t, got, "Warning: command refers to \""+tc.word+"\"") + assert.Contains(t, got, "Consider \"$CODE_SOURCE_PATH/"+tc.suggest+"\" instead.") + }) + } +} + +func TestRelativeScriptWarningContainers(t *testing.T) { + head := `python "$CODE_SOURCE_PATH/train.py"` + worker := "python train.py" + cfg := &runConfig{Containers: []containerConfig{ + {Name: "head", Command: &head}, + {Name: "worker", Command: &worker}, + }} + got := relativeScriptWarning(cfg, []string{"train.py"}) + assert.Contains(t, got, "Warning: containers[worker].command refers to \"train.py\"") + assert.Contains(t, got, "Consider \"$CODE_SOURCE_PATH/train.py\" instead.") + assert.Contains(t, got, "https://docs.databricks.com/aws/en/machine-learning/ai-runtime/connecting/cli/yaml-config#command") + assert.Contains(t, got, "https://learn.microsoft.com/azure/databricks/machine-learning/ai-runtime/connecting/cli/yaml-config#command") +} diff --git a/cmd/air/snapshot_git.go b/cmd/air/snapshot_git.go index 53d838ef9c0..14792019b7c 100644 --- a/cmd/air/snapshot_git.go +++ b/cmd/air/snapshot_git.go @@ -234,9 +234,9 @@ func (g gitRepo) validateIncludePathsExist(ctx context.Context, commitSHA string return nil } -// countFilesAtCommit returns how many files `git archive` would package from +// listFilesAtCommit returns the files `git archive` would package from // commitSHA, limited to subtreePrefix and includePaths when set. -func (g gitRepo) countFilesAtCommit(ctx context.Context, commitSHA, subtreePrefix string, includePaths []string) (int, error) { +func (g gitRepo) listFilesAtCommit(ctx context.Context, commitSHA, subtreePrefix string, includePaths []string) ([]string, error) { treeish := commitSHA lsTreeGit := g if subtreePrefix != "" { @@ -245,7 +245,7 @@ func (g gitRepo) countFilesAtCommit(ctx context.Context, commitSHA, subtreePrefi // as createGitArchiveSnapshot does. repoRoot, err := g.repositoryRoot(ctx) if err != nil { - return 0, err + return nil, err } lsTreeGit = newGitRepo(repoRoot) treeish = commitSHA + ":" + subtreePrefix @@ -253,9 +253,9 @@ func (g gitRepo) countFilesAtCommit(ctx context.Context, commitSHA, subtreePrefi args := append([]string{"ls-tree", "-r", "-z", "--name-only", treeish, "--"}, includePaths...) out, err := lsTreeGit.runBytes(ctx, args...) if err != nil { - return 0, err + return nil, err } - return bytes.Count(out, []byte{0}), nil + return strings.FieldsFunc(string(out), func(r rune) bool { return r == 0 }), nil } // shortSHA abbreviates a commit SHA to 8 chars for log/error messages, tolerating diff --git a/cmd/air/snapshot_git_test.go b/cmd/air/snapshot_git_test.go index 0c721ec7eb5..764f9272b22 100644 --- a/cmd/air/snapshot_git_test.go +++ b/cmd/air/snapshot_git_test.go @@ -362,7 +362,7 @@ func TestCaptureDirtyDiff_IncludePaths(t *testing.T) { var fixedNow = time.Date(2026, 7, 10, 12, 0, 0, 0, time.UTC) -func TestCountFilesAtCommit(t *testing.T) { +func TestListFilesAtCommit(t *testing.T) { ctx := t.Context() repo := newTestRepo(t) writeRepoFile(t, repo, "README.md", "repo root") @@ -370,21 +370,26 @@ func TestCountFilesAtCommit(t *testing.T) { writeRepoFile(t, repo, "subpkg/nested/util.py", "pass") sha := commitAll(t, repo, "init") - count, err := newGitRepo(repo).countFilesAtCommit(ctx, sha, "", nil) + files, err := newGitRepo(repo).listFilesAtCommit(ctx, sha, "", nil) require.NoError(t, err) - assert.Equal(t, 3, count) + assert.Equal(t, []string{"README.md", "subpkg/nested/util.py", "subpkg/train.py"}, files) - // root_path below the repo root: git runs from the subfolder, and the count + // root_path below the repo root: git runs from the subfolder, and the listing // must still cover the whole subtree, as `git archive` does. subGit := newGitRepo(filepath.Join(repo, "subpkg")) prefix, err := subGit.repoRelativePrefix(ctx) require.NoError(t, err) - count, err = subGit.countFilesAtCommit(ctx, sha, prefix, nil) + files, err = subGit.listFilesAtCommit(ctx, sha, prefix, nil) require.NoError(t, err) - assert.Equal(t, 2, count) + assert.Equal(t, []string{"nested/util.py", "train.py"}, files) - count, err = subGit.countFilesAtCommit(ctx, sha, prefix, []string{"nested"}) + files, err = subGit.listFilesAtCommit(ctx, sha, prefix, []string{"nested"}) require.NoError(t, err) - assert.Equal(t, 1, count) + assert.Equal(t, []string{"nested/util.py"}, files) + + // A selection that matches nothing lists no files rather than one empty name. + files, err = subGit.listFilesAtCommit(ctx, sha, prefix, []string{"missing"}) + require.NoError(t, err) + assert.Empty(t, files) } diff --git a/cmd/air/snapshot_upload.go b/cmd/air/snapshot_upload.go index 209139c4055..6e69f1fbf05 100644 --- a/cmd/air/snapshot_upload.go +++ b/cmd/air/snapshot_upload.go @@ -117,23 +117,31 @@ func uploadSnapshotSidecars(ctx context.Context, sidecarStore filer.Filer, sidec return path.Join(sidecarBase, gitStateName), diffPath } -// countSnapshotFiles runs the snapshot file selection without packaging or +// listSnapshotFiles runs the snapshot file selection without packaging or // uploading, so --dry-run fails on the same selection errors as a submission. -func countSnapshotFiles(ctx context.Context, snap *snapshotSourceConfig, configPath string) (int, error) { +// It returns the snapshot-relative, slash-separated paths that would be packaged. +func listSnapshotFiles(ctx context.Context, snap *snapshotSourceConfig, configPath string) ([]string, error) { repoPath, err := resolveRootPath(ctx, snap.RootPath, filepath.Dir(configPath)) if err != nil { - return 0, err + return nil, err } git := newGitRepo(repoPath) plan, err := resolveSnapshotPlan(ctx, git, snap.Git, snap.IncludePaths) if err != nil { - return 0, err + return nil, err } if plan.mode == modeGitArchive { - return git.countFilesAtCommit(ctx, plan.commitSHA, plan.subtreePrefix, plan.includePaths) + return git.listFilesAtCommit(ctx, plan.commitSHA, plan.subtreePrefix, plan.includePaths) } files, err := snapshotFiles(ctx, repoPath, plan.includePaths, plan.isGitRepo) - return len(files), err + if err != nil { + return nil, err + } + rels := make([]string, len(files)) + for i, f := range files { + rels[i] = filepath.ToSlash(f.rel) + } + return rels, nil } // snapshotTarName resolves the content-addressed upload filename for the snapshot and,