diff --git a/.nextchanges/air/relaunch-probe-overlap.md b/.nextchanges/air/relaunch-probe-overlap.md new file mode 100644 index 00000000000..c9c60ae6e8b --- /dev/null +++ b/.nextchanges/air/relaunch-probe-overlap.md @@ -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)) diff --git a/cmd/air/runlaunch.go b/cmd/air/runlaunch.go index 550da3a7a4a..d753aff5472 100644 --- a/cmd/air/runlaunch.go +++ b/cmd/air/runlaunch.go @@ -34,8 +34,9 @@ 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 } @@ -43,8 +44,14 @@ func userWorkspaceDir(ctx context.Context, w *databricks.WorkspaceClient) (strin 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 { @@ -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 @@ -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) } @@ -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. diff --git a/cmd/air/runlaunch_speculation_test.go b/cmd/air/runlaunch_speculation_test.go new file mode 100644 index 00000000000..a2591aafb1d --- /dev/null +++ b/cmd/air/runlaunch_speculation_test.go @@ -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) + } +} diff --git a/cmd/air/runsubmit.go b/cmd/air/runsubmit.go index bba27095d7d..5b9937c8d07 100644 --- a/cmd/air/runsubmit.go +++ b/cmd/air/runsubmit.go @@ -345,12 +345,12 @@ func submitWorkload(ctx context.Context, w *databricks.WorkspaceClient, cfg *run var snap snapshotResult defer func() { logRunEvent(ctx, cfg, snap, runID, time.Since(start), err) }() - // Compute and validate the actual submission path before creating artifacts. - base, funcDir, commandPath, err := prospectiveLaunchPaths(ctx, w, cfg) + items, err := buildArtifacts(cfg) if err != nil { return 0, "", err } - items, err := buildArtifacts(cfg) + token := effectiveIdempotencyToken(idempotencyKey, cfg) + override, err := workspaceDirOverride(ctx, w) if err != nil { return 0, "", err } @@ -359,18 +359,43 @@ func submitWorkload(ctx context.Context, w *databricks.WorkspaceClient, cfg *run // takes the unchanged path below, with no extra server call. var indexKey *launchIndexKey launchIndex := newLaunchIndex(ctx) - recorded := false + var remembered *launchIndexEntry if cfg.CodeSource == nil || cfg.CodeSource.Snapshot == nil { - key := launchIndexKey{Host: w.Config.Host, Base: base, Content: launchContentHash(items)} + key := launchIndexKey{Host: w.Config.Host, Content: launchContentHash(items)} indexKey = &key - if dir, ok := cache.Get[string](ctx, launchIndex, key); ok { - funcDir = dir - commandPath = path.Join(funcDir, commandScriptName) - recorded = true + if entry, ok := cache.Get[launchIndexEntry](ctx, launchIndex, key); ok { + remembered = &entry + } + } + + // A remembered dir is probed and validated under the user name that staged it, + // before Me returns. Those are reads and a dry run. Me then confirms the name, + // and every write and the submit wait for that. + var spec *launchSpeculation + if remembered != nil && override == "" { + spec = startLaunchSpeculation(ctx, w, cfg, items, remembered.Dir, token) + // Every return below joins the speculation; abort is idempotent. + defer spec.abort() + } + base := override + if override == "" { + var email string + if email, err = currentUserEmail(ctx, w); err != nil { + return 0, "", err } + base = "/Workspace/Users/" + email + } + recorded := remembered != nil && remembered.Base == base + var funcDir string + if recorded { + funcDir = remembered.Dir + } else { + spec.abort() + spec = nil + funcDir = launchDirFor(base, cfg) } + commandPath := path.Join(funcDir, commandScriptName) containers := submittedContainers(cfg, funcDir) - token := effectiveIdempotencyToken(idempotencyKey, cfg) deps, _ := cfg.inlineDependencies() @@ -399,36 +424,57 @@ func submitWorkload(ctx context.Context, w *databricks.WorkspaceClient, cfg *run // the other side and is the one reported. group, stagingCtx := errgroup.WithContext(ctx) var validationUnavailable, staged bool - group.Go(func() (err error) { - validationUnavailable, err = preflightValidate(stagingCtx, w, cfg, commandPath, containers, token) - return err - }) - group.Go(func() error { - return withSpinner(ctx, showProgress, "Staging run artifacts…", func() error { - // A recorded dir whose files all exist with their local sizes is staged. - // Anything else, including a 404 for a dir that was deleted, uploads into - // funcDir. - staged = recorded && launchFilesStaged(stagingCtx, w, funcDir, items) - if staged { - return nil + var workspaceID int64 + if spec != nil { + // Me confirmed the speculated dir: the probes and validation are already + // done, so join them and upload only if the dir is not fully staged. + group.Go(func() error { + defer spec.cancel() + if err := spec.group.Wait(); err != nil { + return err } - var stageErr error - snap, stageErr = stageRunArtifacts(stagingCtx, fc, items, stageSnapshot) - return stageErr + validationUnavailable, staged, workspaceID = spec.unavailable, spec.staged, spec.workspaceID + return withSpinner(ctx, showProgress, "Staging run artifacts…", func() error { + if staged { + return nil + } + var stageErr error + snap, stageErr = stageRunArtifacts(stagingCtx, fc, items, stageSnapshot) + return stageErr + }) }) - }) - var workspaceID int64 - group.Go(func() error { - workspaceID = workspaceIDForRunLink(stagingCtx, w) - return nil - }) + } else { + group.Go(func() (err error) { + validationUnavailable, err = preflightValidate(stagingCtx, w, cfg, commandPath, containers, token) + return err + }) + group.Go(func() error { + return withSpinner(ctx, showProgress, "Staging run artifacts…", func() error { + // A recorded dir whose files all exist with their local sizes is staged. + // Anything else, including a 404 for a dir that was deleted, uploads into + // funcDir. + staged = recorded && launchFilesStaged(stagingCtx, w, funcDir, items) + if staged { + return nil + } + var stageErr error + snap, stageErr = stageRunArtifacts(stagingCtx, fc, items, stageSnapshot) + return stageErr + }) + }) + group.Go(func() error { + workspaceID = workspaceIDForRunLink(stagingCtx, w) + return nil + }) + } if err := group.Wait(); err != nil { return 0, "", err } // Refresh the entry only after an upload: a probe hit changed nothing, so - // its TTL should keep counting from the upload that created the dir. + // its TTL should keep counting from the upload that created the dir. An + // unconfirmed entry is replaced here too, since its dir was not used. if indexKey != nil && !staged { - cache.Put(ctx, launchIndex, *indexKey, funcDir) + cache.Put(ctx, launchIndex, *indexKey, launchIndexEntry{Base: base, Dir: funcDir}) } // Warn only after staging so the warning doesn't interleave with the spinner. if validationUnavailable && cmdio.HasIO(ctx) {