Skip to content

Commit e5473e0

Browse files
committed
air: add environment field to config validation
1 parent 7898562 commit e5473e0

4 files changed

Lines changed: 103 additions & 16 deletions

File tree

‎cmd/air/run_test.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,10 @@ func TestRunDryRunValidatesBackendWithoutMutation(t *testing.T) {
200200
}
201201
require.Len(t, validations, 1)
202202
assert.Equal(t, http.MethodPost, validations[0].method)
203-
assert.Len(t, validations[0].body, 2)
203+
assert.Len(t, validations[0].body, 3)
204204
assert.Contains(t, validations[0].body, "task")
205205
assert.Contains(t, validations[0].body, "run_options")
206+
assert.Equal(t, map[string]any{"environment_version": "6"}, validations[0].body["environment"])
206207
task := validations[0].body["task"].(map[string]any)
207208
commandPath := task["deployments"].([]any)[0].(map[string]any)["command_path"].(string)
208209
assert.True(t, strings.HasPrefix(commandPath, "/Workspace/Users/tester@databricks.com/.air/cli_launch/my-run/my-run_"))

‎cmd/air/runsubmit.go‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,19 @@ func dlRuntimeImage(ctx context.Context, runtimeVersion string) string {
4545
return strings.TrimPrefix(img, "CLIENT-GPU-")
4646
}
4747

48+
func buildRunEnvironment(dlImage string, deps []string) *compute.Environment {
49+
environment := &compute.Environment{}
50+
if strings.HasPrefix(dlImage, databricksAIPrefix) {
51+
environment.BaseEnvironment = "workspace-base-environments/" + dlImage
52+
} else {
53+
environment.EnvironmentVersion = dlImage
54+
}
55+
if len(deps) > 0 {
56+
environment.Dependencies = deps
57+
}
58+
return environment
59+
}
60+
4861
// buildSubmitPayload assembles the runs/submit payload. commandPath is the
4962
// workspace path of the uploaded command.sh; dlImage is the runtime channel;
5063
// usagePolicyID is the already-resolved policy id ("" when the run has none);
@@ -98,15 +111,7 @@ func buildSubmitPayload(cfg *runConfig, commandPath, dlImage, usagePolicyID stri
98111
// Carry the user's declared deps inline on spec.dependencies; the AI Runtime
99112
// backend installs them via --deps-config. The SDK marshaler drops nil and empty
100113
// slices, so a no-deps run omits the key.
101-
envSpec := &compute.Environment{}
102-
if strings.HasPrefix(dlImage, databricksAIPrefix) {
103-
envSpec.BaseEnvironment = "workspace-base-environments/" + dlImage
104-
} else {
105-
envSpec.EnvironmentVersion = dlImage
106-
}
107-
if len(deps) > 0 {
108-
envSpec.Dependencies = deps
109-
}
114+
envSpec := buildRunEnvironment(dlImage, deps)
110115

111116
return jobs.SubmitRun{
112117
RunName: cfg.ExperimentName,

‎cmd/air/validateconfig.go‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,17 +63,22 @@ func preflightValidate(ctx context.Context, w *databricks.WorkspaceClient, cfg *
6363
return err
6464
}
6565

66-
// validateConfig performs the current backend validation without client-side
67-
// availability fallbacks. The legacy response reports field errors only; it
68-
// cannot yet distinguish complete success from skipped backend dependencies.
66+
// validateConfig performs backend validation without submission's fail-open
67+
// behavior. One exact old-backend parse error triggers a legacy-body retry.
6968
func validateConfig(ctx context.Context, w *databricks.WorkspaceClient, cfg *runConfig, commandPath string, containers []submittedContainer, idempotencyToken string) error {
7069
apiClient, err := client.New(w.Config)
7170
if err != nil {
7271
return fmt.Errorf("failed to create API client: %w", err)
7372
}
7473

74+
request := validateConfigRequest(ctx, cfg, commandPath, containers, idempotencyToken)
7575
var resp validateConfigResponse
76-
err = apiClient.Do(ctx, http.MethodPost, validateConfigPath, auth.WorkspaceIDHeaders(w.Config), nil, validateConfigRequest(cfg, commandPath, containers, idempotencyToken), &resp)
76+
err = apiClient.Do(ctx, http.MethodPost, validateConfigPath, auth.WorkspaceIDHeaders(w.Config), nil, request, &resp)
77+
if rejectsValidateConfigEnvironment(err) {
78+
delete(request, "environment")
79+
resp = validateConfigResponse{}
80+
err = apiClient.Do(ctx, http.MethodPost, validateConfigPath, auth.WorkspaceIDHeaders(w.Config), nil, request, &resp)
81+
}
7782
if err != nil {
7883
validationErr := fmt.Errorf("failed to validate config: %w", err)
7984
if unavailable, retryable := classifyValidationFailure(err); unavailable {
@@ -87,6 +92,18 @@ func validateConfig(ctx context.Context, w *databricks.WorkspaceClient, cfg *run
8792
return errors.New(formatConfigErrors(resp.Errors))
8893
}
8994

95+
const unsupportedEnvironmentMessage = "Cannot find field: environment in message databricks.aicomputemanager.ValidateConfigRequest"
96+
97+
// rejectsValidateConfigEnvironment identifies the one old-backend response for
98+
// which retrying without the additive environment field is safe.
99+
func rejectsValidateConfigEnvironment(err error) bool {
100+
apiErr, ok := errors.AsType[*apierr.APIError](err)
101+
return ok &&
102+
apiErr.StatusCode == http.StatusBadRequest &&
103+
apiErr.ErrorCode == "MALFORMED_REQUEST" &&
104+
apiErr.Message == unsupportedEnvironmentMessage
105+
}
106+
90107
// classifyValidationFailure separates service failures from caller errors and
91108
// reports whether retrying the same request may succeed.
92109
func classifyValidationFailure(err error) (unavailable, retryable bool) {
@@ -113,11 +130,11 @@ func classifyValidationFailure(err error) (unavailable, retryable bool) {
113130
return false, false
114131
}
115132

116-
// validateConfigRequest builds the {task, run_options} body from the user's config. commandPath is
133+
// validateConfigRequest builds the {task, run_options, environment} body from the user's config. commandPath is
117134
// the workspace path where the command script will be uploaded; the caller computes it before this
118135
// call so the server can validate the real path. `parameters` is intentionally omitted: it is
119136
// free-form nested hyperparameters uploaded as a YAML file at submit, not the proto's string map.
120-
func validateConfigRequest(cfg *runConfig, commandPath string, containers []submittedContainer, idempotencyToken string) map[string]any {
137+
func validateConfigRequest(ctx context.Context, cfg *runConfig, commandPath string, containers []submittedContainer, idempotencyToken string) map[string]any {
121138
compute := map[string]any{}
122139
if cfg.Compute != nil {
123140
compute["accelerator_type"] = cfg.Compute.AcceleratorType
@@ -156,10 +173,13 @@ func validateConfigRequest(cfg *runConfig, commandPath string, containers []subm
156173
if image := cfg.unityCatalogImagePath(); image != "" {
157174
task["unity_catalog_image_path"] = image
158175
}
176+
runtimeVersion, _ := cfg.runtimeVersion()
177+
dependencies, _ := cfg.inlineDependencies()
159178

160179
return map[string]any{
161180
"task": task,
162181
"run_options": validateConfigRunOptions(cfg, idempotencyToken),
182+
"environment": buildRunEnvironment(dlRuntimeImage(ctx, runtimeVersion), dependencies),
163183
}
164184
}
165185

‎cmd/air/validateconfig_test.go‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,64 @@ func TestValidateConfigRequestOmitsUnsetOptions(t *testing.T) {
159159
_, hasMlflowRun := task["mlflow_run"]
160160
assert.False(t, hasMlflowRun)
161161
}
162+
163+
func TestValidateConfigRetriesWithoutEnvironmentForExactCompatibilityError(t *testing.T) {
164+
var requests []map[string]any
165+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
166+
if r.URL.Path != validateConfigPath {
167+
_, _ = w.Write([]byte(`{}`))
168+
return
169+
}
170+
var body map[string]any
171+
if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) {
172+
return
173+
}
174+
requests = append(requests, body)
175+
if len(requests) == 1 {
176+
w.WriteHeader(http.StatusBadRequest)
177+
_, _ = w.Write([]byte(`{"error_code":"MALFORMED_REQUEST","message":"` + unsupportedEnvironmentMessage + `"}`))
178+
return
179+
}
180+
_, _ = w.Write([]byte(`{}`))
181+
}))
182+
t.Cleanup(srv.Close)
183+
184+
err := validateConfig(t.Context(), validationTestWorkspaceClient(t, srv.URL), baseRunConfig(), "/Workspace/Users/me/cmd.sh", nil, "token")
185+
require.NoError(t, err)
186+
require.Len(t, requests, 2)
187+
assert.Contains(t, requests[0], "environment")
188+
delete(requests[0], "environment")
189+
assert.Equal(t, requests[0], requests[1])
190+
}
191+
192+
func TestRejectsValidateConfigEnvironment(t *testing.T) {
193+
tests := []struct {
194+
name string
195+
err error
196+
want bool
197+
}{
198+
{"exact compatibility error", &apierr.APIError{StatusCode: http.StatusBadRequest, ErrorCode: "MALFORMED_REQUEST", Message: unsupportedEnvironmentMessage}, true},
199+
{"wrong status", &apierr.APIError{StatusCode: http.StatusForbidden, ErrorCode: "MALFORMED_REQUEST", Message: unsupportedEnvironmentMessage}, false},
200+
{"wrong code", &apierr.APIError{StatusCode: http.StatusBadRequest, ErrorCode: "INVALID_PARAMETER_VALUE", Message: unsupportedEnvironmentMessage}, false},
201+
{"wrong message", &apierr.APIError{StatusCode: http.StatusBadRequest, ErrorCode: "MALFORMED_REQUEST", Message: "bad request"}, false},
202+
}
203+
204+
for _, tt := range tests {
205+
t.Run(tt.name, func(t *testing.T) {
206+
assert.Equal(t, tt.want, rejectsValidateConfigEnvironment(tt.err))
207+
})
208+
}
209+
}
210+
211+
func TestValidateConfigRequestCarriesEnvironment(t *testing.T) {
212+
cfg := baseRunConfig()
213+
cfg.Environment = &environmentConfig{
214+
Version: stringOrInt{set: true, raw: "databricks_ai_v6"},
215+
Dependencies: dependencies{set: true, list: []string{"torch==2.3.0", "numpy"}},
216+
}
217+
218+
request := validateConfigRequest(t.Context(), cfg, "/Workspace/Users/me/cmd.sh", nil, "token")
219+
raw, err := json.Marshal(request["environment"])
220+
require.NoError(t, err)
221+
assert.JSONEq(t, `{"base_environment":"workspace-base-environments/databricks_ai_v6","dependencies":["torch==2.3.0","numpy"]}`, string(raw))
222+
}

0 commit comments

Comments
 (0)