Skip to content

Commit 375849c

Browse files
committed
air: bound submission config validation
1 parent 332ed36 commit 375849c

2 files changed

Lines changed: 272 additions & 21 deletions

File tree

‎cmd/air/validateconfig.go‎

Lines changed: 87 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package aircmd
22

33
import (
44
"context"
5+
"crypto/tls"
6+
"encoding/json"
57
"errors"
68
"fmt"
79
"net/http"
@@ -10,11 +12,15 @@ import (
1012
"time"
1113

1214
"github.com/databricks/cli/libs/auth"
15+
"github.com/databricks/cli/libs/cmdio"
1316
"github.com/databricks/databricks-sdk-go"
1417
"github.com/databricks/databricks-sdk-go/apierr"
1518
"github.com/databricks/databricks-sdk-go/client"
19+
"github.com/databricks/databricks-sdk-go/common"
1620
"github.com/databricks/databricks-sdk-go/config"
1721
"github.com/databricks/databricks-sdk-go/httpclient"
22+
"github.com/databricks/databricks-sdk-go/httpclient/traceparent"
23+
"github.com/databricks/databricks-sdk-go/useragent"
1824
)
1925

2026
// validateConfigPath is AiTrainingService's pre-flight: it checks a training
@@ -24,6 +30,8 @@ const validateConfigPath = "/api/2.0/ai-training/config:validate"
2430

2531
const dryRunValidationMaxAttempts = 2
2632

33+
const submissionValidationTimeout = 5 * time.Second
34+
2735
type dryRunValidationAttemptBudgetKey struct{}
2836

2937
func armDryRunValidationAttemptBudget(ctx context.Context) context.Context {
@@ -74,18 +82,88 @@ func validationUnavailable(err error) (*validationUnavailableError, bool) {
7482
// preflightValidate checks the config against the backend before any upload, so
7583
// a bad config fails fast with the server's own field-level errors.
7684
//
77-
// It preserves the existing submission behavior: a missing endpoint or 5xx
78-
// fails open, while other request failures and field errors block.
85+
// Availability failures fail open, while caller failures and field errors block.
7986
func preflightValidate(ctx context.Context, w *databricks.WorkspaceClient, cfg *runConfig, commandPath string, containers []submittedContainer, idempotencyToken string) error {
80-
apiClient, err := client.New(w.Config)
87+
validationCtx, cancel := context.WithTimeout(ctx, submissionValidationTimeout)
88+
defer cancel()
89+
90+
err := validateConfigOnce(validationCtx, w, cfg, commandPath, containers, idempotencyToken)
91+
if unavailable, _ := classifyValidationFailure(err); unavailable {
92+
if cmdio.HasIO(ctx) {
93+
cmdio.LogString(ctx, "Warning: server-side config validation was unavailable; continuing with submission.")
94+
}
95+
return nil
96+
}
97+
return err
98+
}
99+
100+
func validateConfigOnce(ctx context.Context, w *databricks.WorkspaceClient, cfg *runConfig, commandPath string, containers []submittedContainer, idempotencyToken string) error {
101+
clientCfg, err := config.HTTPClientConfigFromConfig(w.Config)
81102
if err != nil {
82103
return fmt.Errorf("failed to create API client: %w", err)
83104
}
84-
err = validateConfig(ctx, apiClient, cfg, commandPath, containers, idempotencyToken)
85-
if endpointUnavailable(err) || serverError(err) {
105+
106+
requestBody, err := common.NewRequestBody(validateConfigRequest(ctx, cfg, commandPath, containers, idempotencyToken))
107+
if err != nil {
108+
return fmt.Errorf("failed to validate config: %w", err)
109+
}
110+
req, err := http.NewRequestWithContext(ctx, http.MethodPost, validateConfigPath, requestBody.Reader)
111+
if err != nil {
112+
return fmt.Errorf("failed to validate config: %w", err)
113+
}
114+
req.Header.Set("Accept", "application/json")
115+
req.Header.Set("Content-Type", requestBody.ContentType)
116+
if clientCfg.AuthVisitor != nil {
117+
if err := clientCfg.AuthVisitor(req); err != nil {
118+
return fmt.Errorf("failed to validate config: %w", err)
119+
}
120+
}
121+
for _, visitor := range clientCfg.Visitors {
122+
if err := visitor(req); err != nil {
123+
return fmt.Errorf("failed to validate config: %w", err)
124+
}
125+
}
126+
for key, value := range auth.WorkspaceIDHeaders(w.Config) {
127+
req.Header.Set(key, value)
128+
}
129+
req.Header.Set("User-Agent", useragent.FromContext(req.Context()))
130+
traceparent.AddTraceparent(req)
131+
132+
transport := clientCfg.Transport
133+
if transport == nil {
134+
defaultTransport := http.DefaultTransport.(*http.Transport).Clone()
135+
if clientCfg.InsecureSkipVerify {
136+
defaultTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
137+
}
138+
transport = defaultTransport
139+
}
140+
resp, err := (&http.Client{Transport: transport}).Do(req)
141+
if err != nil {
142+
return fmt.Errorf("failed to validate config: %w", err)
143+
}
144+
responseBody, err := common.NewResponseWrapper(resp, requestBody)
145+
if err != nil {
146+
err = fmt.Errorf("failed to validate config: %w", err)
147+
if resp.StatusCode >= 400 && resp.StatusCode < 500 &&
148+
resp.StatusCode != http.StatusNotFound &&
149+
resp.StatusCode != http.StatusRequestTimeout &&
150+
resp.StatusCode != http.StatusTooManyRequests {
151+
return err
152+
}
153+
return asValidationUnavailable(err, true)
154+
}
155+
if err := apierr.GetAPIError(ctx, responseBody); err != nil {
156+
return fmt.Errorf("failed to validate config: %w", err)
157+
}
158+
159+
var result validateConfigResponse
160+
if err := json.Unmarshal(responseBody.DebugBytes, &result); err != nil {
161+
return asValidationUnavailable(fmt.Errorf("failed to validate config: %w", err), true)
162+
}
163+
if len(result.Errors) == 0 {
86164
return nil
87165
}
88-
return err
166+
return errors.New(formatConfigErrors(result.Errors))
89167
}
90168

91169
func newDryRunValidationClient(w *databricks.WorkspaceClient) (*client.DatabricksClient, error) {
@@ -145,6 +223,9 @@ func classifyValidationFailure(err error) (unavailable, retryable bool) {
145223
if errors.Is(err, context.Canceled) {
146224
return false, false
147225
}
226+
if unavailable, ok := validationUnavailable(err); ok {
227+
return true, unavailable.retryable
228+
}
148229
if errors.Is(err, context.DeadlineExceeded) {
149230
return true, true
150231
}
@@ -246,21 +327,6 @@ func putOpt[T any](m map[string]any, key string, value *T) {
246327
}
247328
}
248329

249-
// endpointUnavailable reports that the validation endpoint could not answer
250-
// because it is disabled or absent.
251-
func endpointUnavailable(err error) bool {
252-
apiErr, ok := errors.AsType[*apierr.APIError](err)
253-
return ok && (apiErr.ErrorCode == "FEATURE_DISABLED" ||
254-
apiErr.StatusCode == http.StatusNotFound ||
255-
apiErr.StatusCode == http.StatusNotImplemented)
256-
}
257-
258-
// serverError reports a backend 5xx rather than a caller error.
259-
func serverError(err error) bool {
260-
apiErr, ok := errors.AsType[*apierr.APIError](err)
261-
return ok && apiErr.StatusCode >= 500
262-
}
263-
264330
// formatConfigErrors renders the field errors as one message, one problem per
265331
// line, each pointing at the config field the user wrote.
266332
func formatConfigErrors(fieldErrors []configFieldError) string {

‎cmd/air/validateconfig_test.go‎

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,16 @@ import (
44
"context"
55
"encoding/json"
66
"errors"
7+
"io"
78
"net/http"
89
"net/http/httptest"
910
"net/url"
11+
"strings"
12+
"sync/atomic"
1013
"testing"
14+
"time"
1115

16+
"github.com/databricks/cli/libs/cmdio"
1217
"github.com/databricks/databricks-sdk-go"
1318
"github.com/databricks/databricks-sdk-go/apierr"
1419
"github.com/stretchr/testify/assert"
@@ -48,6 +53,38 @@ func validationTestWorkspaceClient(t *testing.T, host string) *databricks.Worksp
4853
return w
4954
}
5055

56+
func validationTestWorkspaceClientWithTransport(t *testing.T, transport validationRoundTripFunc) *databricks.WorkspaceClient {
57+
t.Helper()
58+
w, err := databricks.NewWorkspaceClient(&databricks.Config{
59+
Host: "https://example.test",
60+
Token: "token",
61+
HTTPTransport: transport,
62+
})
63+
require.NoError(t, err)
64+
return w
65+
}
66+
67+
type validationRoundTripFunc func(*http.Request) (*http.Response, error)
68+
69+
func (fn validationRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
70+
return fn(req)
71+
}
72+
73+
type validationErrorReadCloser struct{}
74+
75+
func (validationErrorReadCloser) Read([]byte) (int, error) { return 0, errors.New("body read failed") }
76+
func (validationErrorReadCloser) Close() error { return nil }
77+
78+
type validationContextReadCloser struct {
79+
ctx context.Context
80+
}
81+
82+
func (r validationContextReadCloser) Read([]byte) (int, error) {
83+
<-r.ctx.Done()
84+
return 0, r.ctx.Err()
85+
}
86+
func (validationContextReadCloser) Close() error { return nil }
87+
5188
func TestPreflightValidateFailsOpenWhenBackendUnavailable(t *testing.T) {
5289
tests := []struct {
5390
name string
@@ -67,6 +104,154 @@ func TestPreflightValidateFailsOpenWhenBackendUnavailable(t *testing.T) {
67104
}
68105
}
69106

107+
func TestPreflightValidationUnavailableWarnsWithoutRetry(t *testing.T) {
108+
var requests atomic.Int32
109+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
110+
if r.URL.Path == validateConfigPath {
111+
requests.Add(1)
112+
w.WriteHeader(http.StatusServiceUnavailable)
113+
_, _ = w.Write([]byte(`{"error_code":"TEMPORARILY_UNAVAILABLE","message":"try again"}`))
114+
return
115+
}
116+
_, _ = w.Write([]byte(`{}`))
117+
}))
118+
t.Cleanup(srv.Close)
119+
ctx, stderr := cmdio.NewTestContextWithStderr(t.Context())
120+
121+
err := preflightValidate(ctx, validationTestWorkspaceClient(t, srv.URL), baseRunConfig(), "/Workspace/Users/me/cmd.sh", nil, "token")
122+
require.NoError(t, err)
123+
assert.Equal(t, int32(1), requests.Load())
124+
assert.Equal(t, "Warning: server-side config validation was unavailable; continuing with submission.\n", stderr.String())
125+
}
126+
127+
func TestPreflightValidationDoesNotRetryTransportFailure(t *testing.T) {
128+
var requests atomic.Int32
129+
w := validationTestWorkspaceClientWithTransport(t, func(req *http.Request) (*http.Response, error) {
130+
if req.URL.Path == validateConfigPath {
131+
requests.Add(1)
132+
}
133+
return nil, errors.New("connection failed")
134+
})
135+
136+
err := preflightValidate(t.Context(), w, baseRunConfig(), "/Workspace/Users/me/cmd.sh", nil, "token")
137+
require.NoError(t, err)
138+
assert.Equal(t, int32(1), requests.Load())
139+
}
140+
141+
func TestPreflightValidationFailsOpenOnInvalidSuccessResponse(t *testing.T) {
142+
tests := []struct {
143+
name string
144+
body func() io.ReadCloser
145+
}{
146+
{"body read failure", func() io.ReadCloser { return validationErrorReadCloser{} }},
147+
{"malformed JSON", func() io.ReadCloser { return io.NopCloser(strings.NewReader("{")) }},
148+
}
149+
150+
for _, tt := range tests {
151+
t.Run(tt.name, func(t *testing.T) {
152+
var requests atomic.Int32
153+
w := validationTestWorkspaceClientWithTransport(t, func(req *http.Request) (*http.Response, error) {
154+
body := io.NopCloser(strings.NewReader(`{}`))
155+
if req.URL.Path == validateConfigPath {
156+
requests.Add(1)
157+
body = tt.body()
158+
}
159+
return &http.Response{
160+
StatusCode: http.StatusOK,
161+
Header: http.Header{"Content-Type": []string{"application/json"}},
162+
Body: body,
163+
Request: req,
164+
}, nil
165+
})
166+
167+
err := preflightValidate(t.Context(), w, baseRunConfig(), "/Workspace/Users/me/cmd.sh", nil, "token")
168+
require.NoError(t, err)
169+
assert.Equal(t, int32(1), requests.Load())
170+
})
171+
}
172+
}
173+
174+
func TestPreflightValidationBodyReadFailureOnCallerErrorBlocks(t *testing.T) {
175+
w := validationTestWorkspaceClientWithTransport(t, func(req *http.Request) (*http.Response, error) {
176+
body := io.NopCloser(strings.NewReader(`{}`))
177+
status := http.StatusOK
178+
if req.URL.Path == validateConfigPath {
179+
body = validationErrorReadCloser{}
180+
status = http.StatusUnauthorized
181+
}
182+
return &http.Response{
183+
StatusCode: status,
184+
Header: http.Header{"Content-Type": []string{"application/json"}},
185+
Body: body,
186+
Request: req,
187+
}, nil
188+
})
189+
190+
err := preflightValidate(t.Context(), w, baseRunConfig(), "/Workspace/Users/me/cmd.sh", nil, "token")
191+
require.Error(t, err)
192+
}
193+
194+
func TestPreflightValidationTimeoutFailsOpen(t *testing.T) {
195+
releaseRequest := make(chan struct{})
196+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
197+
if r.URL.Path == validateConfigPath {
198+
<-releaseRequest
199+
return
200+
}
201+
_, _ = w.Write([]byte(`{}`))
202+
}))
203+
t.Cleanup(srv.Close)
204+
205+
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
206+
defer cancel()
207+
started := time.Now()
208+
err := preflightValidate(ctx, validationTestWorkspaceClient(t, srv.URL), baseRunConfig(), "/Workspace/Users/me/cmd.sh", nil, "token")
209+
close(releaseRequest)
210+
require.NoError(t, err)
211+
assert.Less(t, time.Since(started), time.Second)
212+
}
213+
214+
func TestPreflightValidationPropagatesCancellation(t *testing.T) {
215+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
216+
if r.URL.Path == validateConfigPath {
217+
<-r.Context().Done()
218+
return
219+
}
220+
_, _ = w.Write([]byte(`{}`))
221+
}))
222+
t.Cleanup(srv.Close)
223+
224+
ctx, cancel := context.WithCancel(t.Context())
225+
cancel()
226+
err := preflightValidate(ctx, validationTestWorkspaceClient(t, srv.URL), baseRunConfig(), "/Workspace/Users/me/cmd.sh", nil, "token")
227+
require.ErrorIs(t, err, context.Canceled)
228+
}
229+
230+
func TestPreflightValidationPropagatesCancellationWhileReadingResponse(t *testing.T) {
231+
validationStarted := make(chan struct{})
232+
w := validationTestWorkspaceClientWithTransport(t, func(req *http.Request) (*http.Response, error) {
233+
body := io.NopCloser(strings.NewReader(`{}`))
234+
if req.URL.Path == validateConfigPath {
235+
close(validationStarted)
236+
body = validationContextReadCloser{ctx: req.Context()}
237+
}
238+
return &http.Response{
239+
StatusCode: http.StatusOK,
240+
Header: http.Header{"Content-Type": []string{"application/json"}},
241+
Body: body,
242+
Request: req,
243+
}, nil
244+
})
245+
246+
ctx, cancel := context.WithCancel(t.Context())
247+
go func() {
248+
<-validationStarted
249+
cancel()
250+
}()
251+
err := preflightValidate(ctx, w, baseRunConfig(), "/Workspace/Users/me/cmd.sh", nil, "token")
252+
require.ErrorIs(t, err, context.Canceled)
253+
}
254+
70255
func TestPreflightValidateBlocksOnCallerError(t *testing.T) {
71256
for _, status := range []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden} {
72257
t.Run(http.StatusText(status), func(t *testing.T) {

0 commit comments

Comments
 (0)