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/relaunch-probe-overlap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* `air run` relaunches with unchanged launch files reach submit sooner: the CLI checks the remembered launch directory while it confirms the signed-in user, and writes nothing until that confirmation arrives. ([#7891](https://github.com/databricks/cli/pull/7891))
80 changes: 71 additions & 9 deletions cmd/air/runlaunch.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,24 @@ func currentUserEmail(ctx context.Context, w *databricks.WorkspaceClient) (strin
return me.UserName, nil
}

// userWorkspaceDir returns the user's workspace home, honoring the env override.
func userWorkspaceDir(ctx context.Context, w *databricks.WorkspaceClient) (string, error) {
// workspaceDirOverride returns the configured workspace home, or "" when the home
// has to come from the current user.
func workspaceDirOverride(ctx context.Context, w *databricks.WorkspaceClient) (string, error) {
if override := env.Get(ctx, userWorkspaceDirEnv); override != "" {
return override, nil
}
override, err := profileValue(w.Config, "databricks_internal_user_workspace_dir")
if err != nil {
return "", fmt.Errorf("failed to read selected profile: %w", err)
}
if override != "" {
return override, nil
return override, nil
}

// userWorkspaceDir returns the user's workspace home, honoring the env override.
func userWorkspaceDir(ctx context.Context, w *databricks.WorkspaceClient) (string, error) {
override, err := workspaceDirOverride(ctx, w)
if err != nil || override != "" {
return override, err
}
email, err := currentUserEmail(ctx, w)
if err != nil {
Expand All @@ -70,12 +77,17 @@ func prospectiveLaunchPaths(ctx context.Context, w *databricks.WorkspaceClient,
if err != nil {
return "", "", "", err
}
launchDir := launchDirFor(base, cfg)
return base, launchDir, path.Join(launchDir, commandScriptName), nil
}

// launchDirFor returns a new launch dir for cfg under base.
func launchDirFor(base string, cfg *runConfig) string {
runName := ""
if cfg.MLflowRunName != nil {
runName = *cfg.MLflowRunName
}
launchDir := cliLaunchDir(base, cfg.ExperimentName, runName)
return base, launchDir, path.Join(launchDir, commandScriptName), nil
return cliLaunchDir(base, cfg.ExperimentName, runName)
}

// launchIndexComponent names the local cache that maps a staged file set to the
Expand All @@ -85,14 +97,22 @@ const (
launchIndexTTL = 30 * 24 * time.Hour
)

// launchIndexKey identifies a staged file set: the workspace, the user's home it
// is staged under, and a hash of the files' names and bytes.
// launchIndexKey identifies a staged file set: the workspace and a hash of the
// files' names and bytes. The home is not part of the key, because a relaunch
// must find the entry before Me has named the user; launchIndexEntry carries it
// and is checked against Me.
type launchIndexKey struct {
Host string
Base string
Content string
}

// launchIndexEntry records where a staged file set lives and the home it was
// staged under, which Me must confirm before Dir is used.
type launchIndexEntry struct {
Base string
Dir string
}

func newLaunchIndex(ctx context.Context) *cache.Cache {
return cache.NewCache(ctx, launchIndexComponent, launchIndexTTL, nil)
}
Expand Down Expand Up @@ -128,6 +148,48 @@ func launchFilesStaged(ctx context.Context, w *databricks.WorkspaceClient, dir s
return group.Wait() == nil
}

// launchSpeculation holds the read-only checks and the dry-run validation started
// under a remembered launch dir before Me confirms the user name that produced it.
// Nothing here writes: the probes are GETs and validation is a stateless dry run.
// Writes and the submit wait for Me, and a mismatch discards the results.
type launchSpeculation struct {
cancel context.CancelFunc
group *errgroup.Group
staged bool
unavailable bool
workspaceID int64
}

func startLaunchSpeculation(ctx context.Context, w *databricks.WorkspaceClient, cfg *runConfig, items []uploadItem, dir, token string) *launchSpeculation {
specCtx, cancel := context.WithCancel(ctx)
group, groupCtx := errgroup.WithContext(specCtx)
spec := &launchSpeculation{cancel: cancel, group: group}
group.Go(func() error {
var err error
spec.unavailable, err = preflightValidate(groupCtx, w, cfg, path.Join(dir, commandScriptName), submittedContainers(cfg, dir), token)
return err
})
group.Go(func() error {
spec.staged = launchFilesStaged(groupCtx, w, dir, items)
return nil
})
group.Go(func() error {
spec.workspaceID = workspaceIDForRunLink(groupCtx, w)
return nil
})
return spec
}

// abort discards a speculation that Me did not confirm and waits for its requests
// to stop. A nil speculation is a no-op.
func (s *launchSpeculation) abort() {
if s == nil {
return
}
s.cancel()
_ = s.group.Wait()
}

// ensureExperimentDirectory creates experimentDir if it is missing, matching the
// CLI's convention for its other artifact directories. Without this, a missing
// parent surfaces only as a server-side INTERNAL_ERROR after the run is wasted.
Expand Down
247 changes: 247 additions & 0 deletions cmd/air/runlaunch_speculation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
package aircmd

import (
"encoding/json"
"slices"
"strings"
"sync"
"testing"
"time"

"github.com/databricks/cli/libs/testserver"
"github.com/databricks/databricks-sdk-go"
"github.com/databricks/databricks-sdk-go/service/iam"
"github.com/databricks/databricks-sdk-go/service/jobs"
"github.com/databricks/databricks-sdk-go/service/workspace"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// relaunchServer records, in arrival order, the calls that decide whether a
// relaunch may write, and lets a test choose what Me answers.
type relaunchServer struct {
mu sync.Mutex
// userName is what Me returns; meStatus, when set, makes Me fail instead.
userName string
meStatus int
// awaitSpeculation makes Me wait until the speculative probe and validation
// have arrived, so the test sees them before Me, not by scheduling luck.
awaitSpeculation bool
events []string
validateBodies []string
submitPaths []string
}

func (s *relaunchServer) record(event string) {
s.mu.Lock()
defer s.mu.Unlock()
s.events = append(s.events, event)
}

// take returns the events recorded since the last call.
func (s *relaunchServer) take() []string {
s.mu.Lock()
defer s.mu.Unlock()
events := s.events
s.events = nil
return events
}

func (s *relaunchServer) setUser(name string) {
s.mu.Lock()
defer s.mu.Unlock()
s.userName = name
}

func (s *relaunchServer) setMeStatus(status int) {
s.mu.Lock()
defer s.mu.Unlock()
s.meStatus = status
}

func (s *relaunchServer) hasEvent(event string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return slices.Contains(s.events, event)
}

// awaitBeforeMe blocks until the speculative probe and validation have arrived,
// or gives up after a few seconds so a regression fails instead of hanging.
func (s *relaunchServer) awaitBeforeMe() {
s.mu.Lock()
wait := s.awaitSpeculation
s.mu.Unlock()
if !wait {
return
}
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) && (!s.hasEvent("probe") || !s.hasEvent("validate")) {
time.Sleep(time.Millisecond)
}
}

func newRelaunchClient(t *testing.T) (*databricks.WorkspaceClient, *relaunchServer) {
t.Helper()
s := &relaunchServer{userName: "a@example.com"}
server := testserver.New(t)
t.Cleanup(server.Close)

// Register before AddDefaultHandlers: the router is first-wins.
server.Handle("GET", "/api/2.0/preview/scim/v2/Me", func(testserver.Request) any {
s.awaitBeforeMe()
s.mu.Lock()
defer s.mu.Unlock()
s.events = append(s.events, "me")
if s.meStatus != 0 {
return testserver.Response{StatusCode: s.meStatus, Body: `{"error_code":"PERMISSION_DENIED","message":"denied"}`}
}
return iam.User{UserName: s.userName}
})
server.Handle("GET", "/api/2.0/workspace/get-status", func(req testserver.Request) any {
s.record("probe")
return req.Workspace.WorkspaceGetStatus(req.URL.Query().Get("path"), false)
})
server.Handle("POST", "/api/2.0/workspace/mkdirs", func(req testserver.Request) any {
s.record("mkdirs")
var request workspace.Mkdirs
require.NoError(t, json.Unmarshal(req.Body, &request))
req.Workspace.WorkspaceMkdirs(request)
return struct{}{}
})
server.Handle("POST", "/api/2.0/workspace-files/import-file/{path...}", func(req testserver.Request) any {
s.record("import " + req.Vars["path"])
return req.Workspace.WorkspaceFilesImportFile(req.Vars["path"], req.Body, req.URL.Query().Get("overwrite") == "true")
})
server.Handle("POST", validateConfigPath, func(req testserver.Request) any {
s.record("validate")
s.mu.Lock()
s.validateBodies = append(s.validateBodies, string(req.Body))
s.mu.Unlock()
return validateConfigResponse{}
})
server.Handle("POST", "/api/2.2/jobs/runs/submit", func(req testserver.Request) any {
s.record("submit")
var got jobs.SubmitRun
require.NoError(t, json.Unmarshal(req.Body, &got))
s.mu.Lock()
s.submitPaths = append(s.submitPaths, got.Tasks[0].AiRuntimeTask.Deployments[0].CommandPath)
s.mu.Unlock()
return jobs.SubmitRunResponse{RunId: 777}
})
testserver.AddDefaultHandlers(server)

// A fixed workspace ID keeps the run-link lookup from issuing its own Me call.
w, err := databricks.NewWorkspaceClient(&databricks.Config{Host: server.URL, Token: "token", WorkspaceID: "1"})
require.NoError(t, err)
return w, s
}

func submitMinimal(t *testing.T, w *databricks.WorkspaceClient, key string) error {
t.Helper()
cfgPath := writeConfigFile(t, "run.yaml", minimalConfig)
cfg, err := loadRunConfig(cfgPath)
require.NoError(t, err)
_, _, err = submitWorkload(t.Context(), w, cfg, cfgPath, key, false)
return err
}

// A relaunch probes and validates its remembered dir before Me returns, and makes
// no write before Me: nothing is uploaded, and the submit follows Me.
func TestRelaunchSpeculatesBeforeMe(t *testing.T) {
w, s := newRelaunchClient(t)
require.NoError(t, submitMinimal(t, w, "idem-1"))
s.take()

s.mu.Lock()
s.awaitSpeculation = true
s.mu.Unlock()
require.NoError(t, submitMinimal(t, w, "idem-2"))
events := s.take()

me := slices.Index(events, "me")
require.GreaterOrEqual(t, me, 0, events)
assert.Contains(t, events[:me], "probe")
assert.Contains(t, events[:me], "validate")
assert.NotContains(t, events, "mkdirs")
for _, event := range events {
assert.False(t, strings.HasPrefix(event, "import"), "relaunch uploaded: %s", event)
}
assert.Greater(t, slices.Index(events, "submit"), me, events)
s.mu.Lock()
defer s.mu.Unlock()
require.Len(t, s.submitPaths, 2)
assert.Contains(t, s.submitPaths[1], "/Workspace/Users/a@example.com/.air/cli_launch/")
}

// A remembered dir under a different name is discarded once Me answers: the
// speculative reads and validation stay under the old name, every write goes to
// the new home, and the index is re-pointed there.
func TestRelaunchMismatchedUserDiscardsSpeculation(t *testing.T) {
w, s := newRelaunchClient(t)
require.NoError(t, submitMinimal(t, w, "idem-1"))
s.take()

s.setUser("b@example.com")
s.mu.Lock()
s.awaitSpeculation = true
s.mu.Unlock()
require.NoError(t, submitMinimal(t, w, "idem-2"))
events := s.take()

me := slices.Index(events, "me")
require.GreaterOrEqual(t, me, 0, events)
assert.Contains(t, events[:me], "probe")
assert.Contains(t, events[:me], "validate")
var uploads []string
for _, event := range events {
if p, ok := strings.CutPrefix(event, "import "); ok {
uploads = append(uploads, p)
}
}
require.NotEmpty(t, uploads, events)
for _, p := range uploads {
assert.True(t, strings.HasPrefix(p, "Workspace/Users/b@example.com/"), p)
}
assert.Greater(t, slices.Index(events, "submit"), me, events)
// Validation order: the first run, the speculative check under the remembered
// home, then the real check under b.
s.mu.Lock()
require.Len(t, s.validateBodies, 3)
assert.Contains(t, s.validateBodies[1], "/Workspace/Users/a@example.com/", "speculative validation used the remembered home")
assert.Contains(t, s.validateBodies[2], "/Workspace/Users/b@example.com/")
s.mu.Unlock()

// The re-pointed entry now belongs to b, so the next relaunch under b is a hit.
require.NoError(t, submitMinimal(t, w, "idem-3"))
events = s.take()
assert.NotContains(t, events, "mkdirs")
for _, event := range events {
assert.False(t, strings.HasPrefix(event, "import"), "relaunch under b uploaded: %s", event)
}
s.mu.Lock()
defer s.mu.Unlock()
require.Len(t, s.submitPaths, 3)
assert.Contains(t, s.submitPaths[2], "/Workspace/Users/b@example.com/")
}

// A failing Me fails the submission exactly as before, and nothing written or
// submitted follows it.
func TestRelaunchMeFailureWritesNothing(t *testing.T) {
w, s := newRelaunchClient(t)
require.NoError(t, submitMinimal(t, w, "idem-1"))
s.take()

s.setMeStatus(403)
s.mu.Lock()
s.awaitSpeculation = true
s.mu.Unlock()
err := submitMinimal(t, w, "idem-2")
require.Error(t, err)
assert.Contains(t, err.Error(), "failed to resolve current user")
events := s.take()
assert.NotContains(t, events, "submit")
assert.NotContains(t, events, "mkdirs")
for _, event := range events {
assert.False(t, strings.HasPrefix(event, "import"), "wrote after failed Me: %s", event)
}
}
Loading
Loading