Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .nextchanges/air/dry-run-relative-script-warning.md
Original file line number Diff line number Diff line change
@@ -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/<file>` and links the docs for command paths. ([#7865](https://github.com/databricks/cli/pull/7865))
2 changes: 1 addition & 1 deletion acceptance/air/run/non-git-subdir.yaml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
9 changes: 9 additions & 0 deletions acceptance/air/run/output.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions acceptance/air/run/relative-script.yaml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions acceptance/air/run/script
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions acceptance/air/run/script-src/train.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print("hello")
6 changes: 5 additions & 1 deletion cmd/air/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
78 changes: 78 additions & 0 deletions cmd/air/scriptpathcheck.go
Original file line number Diff line number Diff line change
@@ -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)
Comment thread
vinchenzo-db marked this conversation as resolved.
Resolved
}
}
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, "#") {
Comment thread
vinchenzo-db marked this conversation as resolved.
Resolved
return ""
}
if strings.HasPrefix(word, "-") {
_, word, _ = strings.Cut(word, "=")
Comment thread
vinchenzo-db marked this conversation as resolved.
Resolved
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"
62 changes: 62 additions & 0 deletions cmd/air/scriptpathcheck_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
10 changes: 5 additions & 5 deletions cmd/air/snapshot_git.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 != "" {
Expand All @@ -245,17 +245,17 @@ 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
}
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
Expand Down
21 changes: 13 additions & 8 deletions cmd/air/snapshot_git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,29 +362,34 @@ 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")
writeRepoFile(t, repo, "subpkg/train.py", "print()")
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)
}
20 changes: 14 additions & 6 deletions cmd/air/snapshot_upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading