diff --git a/acceptance/acceptance_test.go b/acceptance/acceptance_test.go index 664964eb30b..b232befc18c 100644 --- a/acceptance/acceptance_test.go +++ b/acceptance/acceptance_test.go @@ -32,6 +32,7 @@ import ( "github.com/databricks/cli/internal/build" "github.com/databricks/cli/internal/testutil" "github.com/databricks/cli/libs/auth" + "github.com/databricks/cli/libs/retry" "github.com/databricks/cli/libs/testdiff" "github.com/databricks/cli/libs/testserver" "github.com/stretchr/testify/require" @@ -86,6 +87,8 @@ func init() { flag.BoolVar(&WorkspaceTmpDir, "workspace-tmp-dir", false, "Run tests on the workspace file system (For DBR testing).") flag.BoolVar(&OnlyOutTestToml, "only-out-test-toml", false, "Only regenerate out.test.toml files without running tests") flag.BoolVar(&Subset, "subset", false, "Select a subset of EnvMatrix variants that cover all output files. Auto-enabled on -update (unless -run specifies a variant with '=').") + flag.StringVar(&internal.FaultPlanPath, "faultplan", "", "Fail one request per test as planned in this JSON file and skip the tests it does not list (see acceptance/internal/request_fault.go, tools/fault_sweep.py)") + flag.StringVar(&internal.FaultLogPath, "faultlog", "", "Append each test's request count and injected fault to this file as JSON lines") flag.BoolVar(&DebugSandbox, "debugsandbox", false, "Use a per-test blocking proxy instead of a shared one; shows exactly which test caused unexpected internet access (slower)") } @@ -245,6 +248,14 @@ func testAccept(t *testing.T, inprocessMode bool, selectedTests []string, skipTo Subset = true } + if internal.FaultMode() { + // Outputs under injected faults must not become goldens, and a real workspace cannot be + // made to fail a chosen request. + require.False(t, testdiff.OverwriteMode, "-faultplan and -faultlog cannot be combined with -update") + require.Empty(t, os.Getenv("CLOUD_ENV"), "-faultplan and -faultlog only work against the local testserver") + require.NoError(t, internal.LoadFaultPlan()) + } + repls := testdiff.ReplacementsContext{} cwd, err := os.Getwd() require.NoError(t, err) @@ -890,6 +901,10 @@ func runTest(t *testing.T, testEnv := buildTestEnv(config.Env, customEnv) checkEnvFilters(t, testEnv, envFilters) + if reason := internal.FaultPlanSkipReason(t); reason != "" { + t.Skip(reason) + } + if LogConfig { configBytes, err := json.MarshalIndent(config, "", " ") require.NoError(t, err) @@ -1067,6 +1082,11 @@ func runTest(t *testing.T, cmd.Env = append(cmd.Env, "GIT_CONFIG_GLOBAL="+os.DevNull) cmd.Env = append(cmd.Env, "GIT_CONFIG_SYSTEM="+os.DevNull) + if _, ok := internal.FaultPlanned(t); ok { + // The CLI's own retries (libs/retry) pause 15s; a test's Env can still override this. + cmd.Env = append(cmd.Env, retry.IntervalMsVariable+"=100") + } + for _, kv := range testEnv { key, value, _ := strings.Cut(kv, "=") // Only add replacement by default if value is part of EnvMatrix with more than 1 option and length is 4 or more chars diff --git a/acceptance/internal/prepare_server.go b/acceptance/internal/prepare_server.go index 57904951238..df881e4d5ae 100644 --- a/acceptance/internal/prepare_server.go +++ b/acceptance/internal/prepare_server.go @@ -198,7 +198,7 @@ func PrepareServerAndClient(t *testing.T, config TestConfig, logRequests bool, o // If we are not recording requests, and no custom server stubs are configured, // use the default shared server. - if len(config.Server) == 0 && !recordRequests { + if len(config.Server) == 0 && !recordRequests && !FaultMode() { cfg := &sdkconfig.Config{ Host: env.Get(t.Context(), "DATABRICKS_DEFAULT_HOST"), Token: token, @@ -225,6 +225,10 @@ type requestRecorder struct { t *testing.T includeHeaders []string outputDir string + // onlyInjected treats only requests failed by a planned request fault as failed attempts, + // not every transient status: a testserver stub that answers with an error does so on + // purpose, and its goldens show every attempt. + onlyInjected bool mu sync.Mutex // entries holds what was written for requests still waiting for a response; nil unless @@ -354,8 +358,9 @@ func isTransientStatus(status int) bool { // not repeated stays recorded. Before it repeats a failed create, the CLI reads the resource to // see whether the request created it anyway; a read answered with 404 is dropped with the failed // attempt. A read that finds the resource stays recorded, since no repeat follows, and ends the -// recovery. Only the proxy uses this: the testserver answers with an error only when a test -// injects one, and its goldens show that. +// recovery. The proxy uses this, and so does the testserver when a planned request fault (see +// request_fault.go) fails a request: otherwise the testserver answers with an error only when a +// test injects one, and its goldens show that. func (r *requestRecorder) noteResponse(request *testserver.Request, response *testserver.EncodedResponse) { r.mu.Lock() defer r.mu.Unlock() @@ -365,7 +370,11 @@ func (r *requestRecorder) noteResponse(request *testserver.Request, response *te if !ok { return } - if isTransientStatus(response.StatusCode) { + failed := isTransientStatus(response.StatusCode) + if r.onlyInjected { + failed = request.InjectedFault != "" + } + if failed { r.failed[entry]++ if request.Method == http.MethodPost { // The id of the resource a create names travels in a query parameter such as project_id. @@ -424,15 +433,37 @@ func startLocalServer(t *testing.T, ) string { s := testserver.New(t) + var planned *PlannedFault + if FaultMode() { + planned = setupRequestFault(t, s) + } + + var responseCallbacks []func(request *testserver.Request, response *testserver.EncodedResponse) + // Record API requests in out.requests.txt if RecordRequests is true // in test.toml if recordRequests { - s.RequestCallback = newRequestRecorder(t, includeHeaders, outputDir, false).record + // With a fault planned, the CLI repeats the failed request, and the failed attempt is + // dropped from out.requests.txt as on cloud, so the test's goldens still apply. + recorder := newRequestRecorder(t, includeHeaders, outputDir, planned != nil) + s.RequestCallback = recorder.record + if planned != nil { + recorder.onlyInjected = true + responseCallbacks = append(responseCallbacks, recorder.noteResponse) + } } // Log API responses if the -logrequests flag is set. if logRequests { - s.ResponseCallback = logResponseCallback(t) + responseCallbacks = append(responseCallbacks, logResponseCallback(t)) + } + + if len(responseCallbacks) > 0 { + s.ResponseCallback = func(request *testserver.Request, response *testserver.EncodedResponse) { + for _, callback := range responseCallbacks { + callback(request, response) + } + } } for ind := range stubs { diff --git a/acceptance/internal/request_fault.go b/acceptance/internal/request_fault.go new file mode 100644 index 00000000000..9eff56086ae --- /dev/null +++ b/acceptance/internal/request_fault.go @@ -0,0 +1,133 @@ +package internal + +import ( + "encoding/json" + "fmt" + "os" + "sync" + "testing" + + "github.com/databricks/cli/libs/testserver" + "github.com/stretchr/testify/require" +) + +// Request fault mode checks that the CLI and the tests survive a single backend error: each +// planned test gets one request failed (see testserver.SetRequestFault), and the test must +// still pass. tools/fault_sweep.py drives it: it learns each test's request count from runs +// with only -faultlog, then picks a request and a fault kind per test. + +// FaultPlanPath is the -faultplan flag: a JSON object mapping a test name (as go test prints it) +// to the fault to inject, e.g. {"TestAccept/bundle/deploy/basic": {"at": 3, "kind": "503"}}. +// Tests not in the plan are skipped. +var FaultPlanPath string + +// FaultLogPath is the -faultlog flag: a file each test run against the testserver appends a +// FaultLogEntry line to. Setting it alone runs the tests unchanged and records request counts. +var FaultLogPath string + +// PlannedFault is one -faultplan entry. +type PlannedFault struct { + At int `json:"at"` + Kind string `json:"kind"` +} + +// FaultLogEntry is one line of the -faultlog file. +type FaultLogEntry struct { + Test string `json:"test"` + Requests int `json:"requests"` + Planned *PlannedFault `json:"planned,omitempty"` + Fired *testserver.FiredRequestFault `json:"fired,omitempty"` + Failed bool `json:"failed"` + Skipped bool `json:"skipped"` +} + +var ( + faultPlan map[string]PlannedFault + faultLogLock sync.Mutex +) + +// LoadFaultPlan reads -faultplan, if set. It must run before any test starts. +func LoadFaultPlan() error { + if FaultPlanPath == "" { + return nil + } + data, err := os.ReadFile(FaultPlanPath) + if err != nil { + return err + } + if err := json.Unmarshal(data, &faultPlan); err != nil { + return fmt.Errorf("%s: %w", FaultPlanPath, err) + } + if faultPlan == nil { + faultPlan = map[string]PlannedFault{} + } + return nil +} + +// FaultMode reports whether -faultplan or -faultlog is set. In this mode every test gets its +// own testserver, so its requests can be counted and failed. +func FaultMode() bool { + return FaultPlanPath != "" || FaultLogPath != "" +} + +// FaultPlanned returns the fault planned for the test and whether -faultplan lists it. +func FaultPlanned(t *testing.T) (PlannedFault, bool) { + fault, ok := faultPlan[t.Name()] + return fault, ok +} + +// FaultPlanSkipReason returns why the test is skipped under -faultplan, or "". +func FaultPlanSkipReason(t *testing.T) string { + if FaultPlanPath == "" { + return "" + } + if _, ok := FaultPlanned(t); ok { + return "" + } + return "not in -faultplan" +} + +// setupRequestFault arms the test's planned fault on s and logs the outcome when the test ends. +// It returns the planned fault, or nil. +func setupRequestFault(t *testing.T, s *testserver.Server) *PlannedFault { + var planned *PlannedFault + if fault, ok := FaultPlanned(t); ok { + require.NoError(t, s.SetRequestFault(fault.At, fault.Kind)) + planned = &fault + } + if FaultLogPath != "" { + t.Cleanup(func() { + appendFaultLog(t, FaultLogEntry{ + Test: t.Name(), + Requests: s.RequestCount(), + Planned: planned, + Fired: s.FiredRequestFault(), + Failed: t.Failed(), + Skipped: t.Skipped(), + }) + }) + } + if planned != nil { + t.Cleanup(func() { + if fired := s.FiredRequestFault(); fired != nil { + t.Logf("Injected fault %s into request %d: %s %s", fired.Kind, fired.At, fired.Method, fired.Path) + } else { + t.Logf("Planned fault %s at request %d did not fire: the test made %d requests", planned.Kind, planned.At, s.RequestCount()) + } + }) + } + return planned +} + +func appendFaultLog(t *testing.T, entry FaultLogEntry) { + line, err := json.Marshal(entry) + require.NoError(t, err) + + faultLogLock.Lock() + defer faultLogLock.Unlock() + f, err := os.OpenFile(FaultLogPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + require.NoError(t, err) + defer f.Close() + _, err = f.Write(append(line, '\n')) + require.NoError(t, err) +} diff --git a/acceptance/internal/request_fault_test.go b/acceptance/internal/request_fault_test.go new file mode 100644 index 00000000000..986957b0cc2 --- /dev/null +++ b/acceptance/internal/request_fault_test.go @@ -0,0 +1,60 @@ +package internal + +import ( + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/databricks/cli/libs/testserver" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// planFault plans a fault for the running test, as -faultplan would. +func planFault(t *testing.T, fault PlannedFault) { + oldPath, oldPlan := FaultPlanPath, faultPlan + t.Cleanup(func() { FaultPlanPath, faultPlan = oldPath, oldPlan }) + FaultPlanPath = "plan.json" + faultPlan = map[string]PlannedFault{t.Name(): fault} +} + +func get(t *testing.T, url string) int { + resp, err := http.Get(url) + require.NoError(t, err) + resp.Body.Close() + return resp.StatusCode +} + +func TestRequestFaultDropsRetriedAttempt(t *testing.T) { + planFault(t, PlannedFault{At: 2, Kind: testserver.FaultUnavailable}) + outputDir := t.TempDir() + stubs := []ServerStub{ + {Pattern: "GET /api/2.0/ok", Response: testserver.Response{Body: "{}"}}, + // A stub answering with an error keeps every attempt recorded, fault or not. + {Pattern: "GET /api/2.0/stub-error", Response: testserver.Response{StatusCode: 503, Body: "{}"}}, + } + url := startLocalServer(t, stubs, true, false, nil, outputDir) + + assert.Equal(t, 200, get(t, url+"/api/2.0/ok")) + assert.Equal(t, 503, get(t, url+"/api/2.0/ok")) + assert.Equal(t, 200, get(t, url+"/api/2.0/ok")) + assert.Equal(t, 503, get(t, url+"/api/2.0/stub-error")) + assert.Equal(t, 503, get(t, url+"/api/2.0/stub-error")) + + data, err := os.ReadFile(filepath.Join(outputDir, "out.requests.txt")) + require.NoError(t, err) + assert.Equal(t, 2, strings.Count(string(data), `"path": "/api/2.0/ok"`)) + assert.Equal(t, 2, strings.Count(string(data), `"path": "/api/2.0/stub-error"`)) +} + +func TestFaultPlanSkipReason(t *testing.T) { + assert.Empty(t, FaultPlanSkipReason(t)) + + planFault(t, PlannedFault{At: 1, Kind: testserver.FaultUnavailable}) + assert.Empty(t, FaultPlanSkipReason(t)) + + faultPlan = map[string]PlannedFault{"TestAccept/other": {At: 1, Kind: testserver.FaultUnavailable}} + assert.Equal(t, "not in -faultplan", FaultPlanSkipReason(t)) +} diff --git a/libs/testserver/request_fault.go b/libs/testserver/request_fault.go new file mode 100644 index 00000000000..611e0ad6200 --- /dev/null +++ b/libs/testserver/request_fault.go @@ -0,0 +1,205 @@ +package testserver + +import ( + "fmt" + "net" + "net/http" + "slices" + "strconv" + "strings" + "sync" +) + +// Request fault kinds, each a backend failure we have seen from a real workspace. Status kinds +// answer instead of the handler, so the request has no effect. Kinds ending in "-after" run the +// handler first and lose its response, as when a gateway times out or a connection drops after +// the backend applied the request. +const ( + FaultTooManyRequests = "429" + FaultInternalError = "500" + FaultBadGateway = "502" + FaultUnavailable = "503" + FaultGatewayTimeout = "504" + FaultGatewayTimeoutLate = "504-after" + FaultReset = "reset" + FaultResetLate = "reset-after" + FaultTruncatedLate = "eof-after" +) + +// RequestFaultKinds lists every kind SetRequestFault accepts. +var RequestFaultKinds = []string{ + FaultTooManyRequests, + FaultInternalError, + FaultBadGateway, + FaultUnavailable, + FaultGatewayTimeout, + FaultGatewayTimeoutLate, + FaultReset, + FaultResetLate, + FaultTruncatedLate, +} + +// faultStatusResponses are the responses of the status kinds. The bodies match what the workspace +// API (JSON) and its Envoy gateway (plain text) send. +var faultStatusResponses = map[string]EncodedResponse{ + FaultTooManyRequests: jsonFaultResponse(http.StatusTooManyRequests, "REQUEST_LIMIT_EXCEEDED", "Injected fault: too many requests."), + FaultInternalError: jsonFaultResponse(http.StatusInternalServerError, "INTERNAL_ERROR", "Injected fault: internal error."), + FaultBadGateway: textFaultResponse(http.StatusBadGateway, "upstream connect error or disconnect/reset before headers. reset reason: connection termination"), + FaultUnavailable: jsonFaultResponse(http.StatusServiceUnavailable, "TEMPORARILY_UNAVAILABLE", "Injected fault: service unavailable."), + FaultGatewayTimeout: textFaultResponse(http.StatusGatewayTimeout, "upstream request timeout"), +} + +func jsonFaultResponse(status int, errorCode, message string) EncodedResponse { + return EncodedResponse{ + StatusCode: status, + Headers: getJsonHeaders(), + Body: fmt.Appendf(nil, `{"error_code": %q, "message": %q}`, errorCode, message), + } +} + +func textFaultResponse(status int, body string) EncodedResponse { + return EncodedResponse{ + StatusCode: status, + Headers: http.Header{"Content-Type": {"text/plain"}}, + Body: []byte(body), + } +} + +// FiredRequestFault describes the request a fault was injected into. +type FiredRequestFault struct { + At int `json:"at"` + Kind string `json:"kind"` + Method string `json:"method"` + Path string `json:"path"` +} + +// requestFault fails the at-th request the server receives (1-based) with the given kind. With at +// set to 0 it only counts requests. +type requestFault struct { + mu sync.Mutex + count int + at int + kind string + fired *FiredRequestFault +} + +// next counts a request and returns the fault kind to inject into it, or "" for none. +func (f *requestFault) next(method, path string) string { + // Scripts set up kill and fault rules through these; they are not CLI traffic. + if strings.HasPrefix(path, "/__testserver/") { + return "" + } + f.mu.Lock() + defer f.mu.Unlock() + f.count++ + if f.at == 0 || f.count != f.at { + return "" + } + f.fired = &FiredRequestFault{At: f.at, Kind: f.kind, Method: method, Path: path} + return f.kind +} + +// SetRequestFault makes the server fail the at-th request it receives (1-based) with kind, one +// of RequestFaultKinds. Requests to /__testserver/ endpoints are not counted. +func (s *Server) SetRequestFault(at int, kind string) error { + if at < 1 { + return fmt.Errorf("request number must be at least 1, got %d", at) + } + if !slices.Contains(RequestFaultKinds, kind) { + return fmt.Errorf("unknown request fault kind %q, expected one of %s", kind, strings.Join(RequestFaultKinds, ", ")) + } + s.requestFault.mu.Lock() + defer s.requestFault.mu.Unlock() + s.requestFault.at = at + s.requestFault.kind = kind + return nil +} + +// RequestCount returns the number of requests the server received, not counting requests to +// /__testserver/ endpoints. +func (s *Server) RequestCount() int { + s.requestFault.mu.Lock() + defer s.requestFault.mu.Unlock() + return s.requestFault.count +} + +// FiredRequestFault returns the request the fault set with SetRequestFault was injected into, or +// nil if the server has not received that many requests. +func (s *Server) FiredRequestFault() *FiredRequestFault { + s.requestFault.mu.Lock() + defer s.requestFault.mu.Unlock() + return s.requestFault.fired +} + +// faultRunsHandler reports whether the handler applies the request before the fault is injected. +func faultRunsHandler(kind string) bool { + return strings.HasSuffix(kind, "-after") +} + +// writeRequestFault sends the fault of the given kind instead of resp, the handler's response for +// the kinds that run it. +func (s *Server) writeRequestFault(w http.ResponseWriter, request *Request, kind string, resp EncodedResponse) { + switch kind { + case FaultGatewayTimeoutLate: + s.writeResponse(w, request, faultStatusResponses[FaultGatewayTimeout]) + case FaultReset, FaultResetLate: + s.notifyResponse(request, EncodedResponse{}) + conn := s.hijack(w) + if conn == nil { + return + } + // A zero linger makes Close send RST instead of FIN, so the client reads + // "connection reset by peer". + if tcp, ok := conn.(*net.TCPConn); ok { + _ = tcp.SetLinger(0) + } + _ = conn.Close() + case FaultTruncatedLate: + if !responseHasBody(request.Method, resp.StatusCode) { + // The client would not read the body, so cut the connection instead. + s.writeRequestFault(w, request, FaultResetLate, resp) + return + } + s.notifyResponse(request, EncodedResponse{}) + conn := s.hijack(w) + if conn == nil { + return + } + // Promise more bytes than are sent, so the client reads "unexpected EOF" in the body. + sent := resp.Body[:len(resp.Body)/2] + var head strings.Builder + fmt.Fprintf(&head, "HTTP/1.1 %d %s\r\n", resp.StatusCode, http.StatusText(resp.StatusCode)) + for key, values := range resp.Headers { + if http.CanonicalHeaderKey(key) == "Content-Length" { + continue + } + for _, value := range values { + fmt.Fprintf(&head, "%s: %s\r\n", key, value) + } + } + head.WriteString("Content-Length: " + strconv.Itoa(len(resp.Body)+1) + "\r\n\r\n") + _, _ = conn.Write(append([]byte(head.String()), sent...)) + _ = conn.Close() + default: + s.writeResponse(w, request, faultStatusResponses[kind]) + } +} + +// responseHasBody reports whether an HTTP client reads a body for this response. +func responseHasBody(method string, status int) bool { + return method != http.MethodHead && status != http.StatusNoContent && status != http.StatusNotModified +} + +func (s *Server) hijack(w http.ResponseWriter) net.Conn { + hijacker, ok := w.(http.Hijacker) + if !ok { + s.t.Errorf("request fault: response writer does not support hijacking") + return nil + } + conn, _, err := hijacker.Hijack() + if err != nil { + s.t.Errorf("request fault: hijack failed: %s", err) + return nil + } + return conn +} diff --git a/libs/testserver/request_fault_test.go b/libs/testserver/request_fault_test.go new file mode 100644 index 00000000000..c144e675543 --- /dev/null +++ b/libs/testserver/request_fault_test.go @@ -0,0 +1,142 @@ +package testserver_test + +import ( + "io" + "net/http" + "strings" + "testing" + + "github.com/databricks/cli/libs/testserver" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// newCountingServer returns a server whose handler counts the requests it applied. +func newCountingServer(t *testing.T) (*testserver.Server, *int) { + s := testserver.New(t) + applied := 0 + s.Handle("POST", "/api/2.0/things", func(req testserver.Request) any { + applied++ + return map[string]string{"id": "thing-with-a-long-enough-id"} + }) + return s, &applied +} + +// postThing returns the status of the response, after reading its body. +func postThing(s *testserver.Server) (int, error) { + // A fresh connection per request, so a fault on one does not affect the next. + client := &http.Client{Transport: &http.Transport{DisableKeepAlives: true}} + resp, err := client.Post(s.URL+"/api/2.0/things", "application/json", strings.NewReader("{}")) + if err != nil { + return 0, err + } + defer resp.Body.Close() + _, err = io.ReadAll(resp.Body) + return resp.StatusCode, err +} + +func TestRequestFaultStatusKinds(t *testing.T) { + for kind, wantStatus := range map[string]int{ + testserver.FaultTooManyRequests: 429, + testserver.FaultInternalError: 500, + testserver.FaultBadGateway: 502, + testserver.FaultUnavailable: 503, + testserver.FaultGatewayTimeout: 504, + testserver.FaultGatewayTimeoutLate: 504, + } { + t.Run(kind, func(t *testing.T) { + s, applied := newCountingServer(t) + require.NoError(t, s.SetRequestFault(2, kind)) + + status, err := postThing(s) + require.NoError(t, err) + assert.Equal(t, 200, status) + + status, err = postThing(s) + require.NoError(t, err) + assert.Equal(t, wantStatus, status) + + status, err = postThing(s) + require.NoError(t, err) + assert.Equal(t, 200, status) + + // Only the -after kind lets the handler apply the failed request. + wantApplied := 2 + if kind == testserver.FaultGatewayTimeoutLate { + wantApplied = 3 + } + assert.Equal(t, wantApplied, *applied) + assert.Equal(t, 3, s.RequestCount()) + assert.Equal(t, &testserver.FiredRequestFault{At: 2, Kind: kind, Method: "POST", Path: "/api/2.0/things"}, s.FiredRequestFault()) + }) + } +} + +func TestRequestFaultConnectionKinds(t *testing.T) { + for kind, wantErr := range map[string]string{ + testserver.FaultReset: "connection reset by peer", + testserver.FaultResetLate: "connection reset by peer", + testserver.FaultTruncatedLate: "unexpected EOF", + } { + t.Run(kind, func(t *testing.T) { + s, applied := newCountingServer(t) + require.NoError(t, s.SetRequestFault(1, kind)) + + _, err := postThing(s) + require.Error(t, err) + // Depending on timing, a reset surfaces as EOF when the client had not started reading. + if kind == testserver.FaultTruncatedLate { + assert.ErrorContains(t, err, wantErr) + } else { + assert.Regexp(t, wantErr+"|EOF", err.Error()) + } + + status, err := postThing(s) + require.NoError(t, err) + assert.Equal(t, 200, status) + + wantApplied := 1 + if kind != testserver.FaultReset { + wantApplied = 2 + } + assert.Equal(t, wantApplied, *applied) + }) + } +} + +func TestRequestFaultSkipsTestserverEndpoints(t *testing.T) { + s, _ := newCountingServer(t) + require.NoError(t, s.SetRequestFault(1, testserver.FaultUnavailable)) + + resp, err := http.Post(s.URL+"/__testserver/kill", "application/json", strings.NewReader(`{"pattern": "GET /none", "times": 0}`)) + require.NoError(t, err) + resp.Body.Close() + assert.Equal(t, 200, resp.StatusCode) + assert.Equal(t, 0, s.RequestCount()) + assert.Nil(t, s.FiredRequestFault()) + + status, err := postThing(s) + require.NoError(t, err) + assert.Equal(t, 503, status) +} + +func TestSetRequestFaultValidates(t *testing.T) { + s := testserver.New(t) + assert.ErrorContains(t, s.SetRequestFault(0, testserver.FaultUnavailable), "at least 1") + assert.ErrorContains(t, s.SetRequestFault(1, "418"), `unknown request fault kind "418"`) +} + +func TestRequestFaultTruncatedWithoutBodyResets(t *testing.T) { + s := testserver.New(t) + s.Handle("HEAD", "/api/2.0/things", func(req testserver.Request) any { + return testserver.Response{StatusCode: 200} + }) + require.NoError(t, s.SetRequestFault(1, testserver.FaultTruncatedLate)) + + client := &http.Client{Transport: &http.Transport{DisableKeepAlives: true}} + resp, err := client.Head(s.URL + "/api/2.0/things") + if err == nil { + resp.Body.Close() + } + require.Error(t, err) +} diff --git a/libs/testserver/server.go b/libs/testserver/server.go index a1aeeac4f0f..197e5826dc8 100644 --- a/libs/testserver/server.go +++ b/libs/testserver/server.go @@ -66,8 +66,9 @@ type Server struct { fakeOidc *FakeOidc mu sync.Mutex - kills *killRules - faults *FaultRules + kills *killRules + faults *FaultRules + requestFault requestFault sqlHandler *testsql.Handler @@ -84,6 +85,9 @@ type Request struct { Workspace *FakeWorkspace Context context.Context Token string + + // InjectedFault is the kind of the fault set with SetRequestFault that this request gets, or "". + InjectedFault string } type Response struct { @@ -366,11 +370,17 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, handler HandlerFu request := NewRequest(s.t, r, fakeWorkspace) request.Vars = vars request.Token = token + request.InjectedFault = s.requestFault.next(r.Method, r.URL.Path) if s.RequestCallback != nil { s.RequestCallback(&request) } + if request.InjectedFault != "" && !faultRunsHandler(request.InjectedFault) { + s.writeRequestFault(w, &request, request.InjectedFault, EncodedResponse{}) + return + } + var resp EncodedResponse fault := s.faults.Check(r.Method, r.URL.Path, token, request.Body) @@ -398,13 +408,20 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, handler HandlerFu } } + if request.InjectedFault != "" { + s.writeRequestFault(w, &request, request.InjectedFault, resp) + return + } + + s.writeResponse(w, &request, resp) +} + +func (s *Server) writeResponse(w http.ResponseWriter, request *Request, resp EncodedResponse) { maps.Copy(w.Header(), resp.Headers) w.WriteHeader(resp.StatusCode) - if s.ResponseCallback != nil { - s.ResponseCallback(&request, &resp) - } + s.notifyResponse(request, resp) if _, err := w.Write(resp.Body); err != nil { s.t.Errorf("Failed to write response: %s", err) @@ -412,6 +429,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, handler HandlerFu } } +func (s *Server) notifyResponse(request *Request, resp EncodedResponse) { + if s.ResponseCallback != nil { + s.ResponseCallback(request, &resp) + } +} + func getToken(r *http.Request) string { header := r.Header.Get("Authorization") prefix := "Bearer " diff --git a/tools/fault_sweep.py b/tools/fault_sweep.py new file mode 100755 index 00000000000..3ab17154e46 --- /dev/null +++ b/tools/fault_sweep.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +"""Check that acceptance tests and the CLI survive a single backend error. + +1. Runs the selected tests --count-runs times with -faultlog to learn how many requests each + one makes (the max over the runs). Tests that fail in any of these runs, or make no + requests, are left out. +2. Each round picks, for every remaining test, a random request number up to that max and a + random fault kind, and runs the tests with that -faultplan. A test that passes is run again + with the same fault, so a pass is not luck of timing. The CLI should retry the failed + request, and the test should pass unchanged: retry warnings are suppressed by + SuppressLines.warn_retry and the failed attempt is dropped from out.requests.txt. +3. Writes results.jsonl, logs of the failures and summary.md to --out. + +Example: + tools/fault_sweep.py --run 'TestAccept/bundle/resources/jobs' --rounds 2 --out /tmp/sweep +""" + +import argparse +import collections +import json +import random +import re +import subprocess +import sys +import time +from pathlib import Path + +# Keep in sync with RequestFaultKinds in libs/testserver/request_fault.go. +KINDS = ["429", "500", "502", "503", "504", "504-after", "reset", "reset-after", "eof-after"] + +REPO = Path(__file__).resolve().parent.parent + + +def go_test(args, run, faultlog, faultplan, json_out): + cmd = [ + "go", + "test", + "./acceptance", + "-count=1", + "-json", + "-timeout", + args.timeout, + "-run", + run, + "-faultlog", + str(faultlog), + ] + if faultplan: + cmd += ["-faultplan", str(faultplan)] + cmd += args.go_args + # The runner appends to -faultlog; start fresh so a reused --out does not mix in old runs. + faultlog.unlink(missing_ok=True) + print("+ " + " ".join(cmd), file=sys.stderr, flush=True) + start = time.time() + with open(json_out, "w") as f: + subprocess.run(cmd, cwd=REPO, stdout=f, stderr=subprocess.STDOUT, check=False) + print(f" took {time.time() - start:.0f}s", file=sys.stderr, flush=True) + return read_jsonl(faultlog) + + +def read_jsonl(path): + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text().splitlines() if line.strip()] + + +def test_outputs(json_out): + """Return the go test output of each test, from a -json run.""" + outputs = collections.defaultdict(list) + for line in Path(json_out).read_text().splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if event.get("Action") == "output" and event.get("Test"): + outputs[event["Test"]].append(event["Output"]) + return {name: "".join(lines) for name, lines in outputs.items()} + + +def failure_snippet(output): + """Pick the lines of a failed test's log that say what broke.""" + lines = [line.strip() for line in output.splitlines()] + diff = [ + line + for line in lines + if line[:1] in ("+", "-") + and line not in ("+", "-") + and not line.startswith(("+++", "---", "--- FAIL", "--- PASS", "--- SKIP")) + ] + if diff: + return " | ".join(diff[:4]) + errors = [line for line in lines if "Error" in line or "error" in line] + return " | ".join(errors[:3]) + + +ID_SEGMENT = re.compile(r"^(\d+|[0-9a-f]{16,}|[0-9a-f-]{36})$") + + +def endpoint(method, path): + """Generalize a request path so faults in the same API group together.""" + if "/Workspace/" in path: + path = path[: path.index("/Workspace/")] + "/Workspace/..." + segments = ["{id}" if ID_SEGMENT.match(s) else s for s in path.split("/")] + return method + " " + "/".join(segments) + + +def sanitize(name): + return re.sub(r"[^A-Za-z0-9_.=-]+", "_", name) + + +def count_requests(args, out): + """Return {test: max requests} for tests that passed every counting run, and the exclusions.""" + max_requests = {} + failed = set() + for i in range(args.count_runs): + entries = go_test(args, args.run, out / f"count-{i}.jsonl", None, out / f"count-{i}.json") + for e in entries: + if e["skipped"]: + continue + if e["failed"]: + failed.add(e["test"]) + max_requests[e["test"]] = max(max_requests.get(e["test"], 0), e["requests"]) + if not max_requests: + sys.exit(f"No test ran; see the go test output in {out}/count-0.json") + no_requests = {t for t, n in max_requests.items() if n == 0} + eligible = {t: n for t, n in max_requests.items() if t not in failed and n > 0} + return eligible, sorted(failed), sorted(no_requests) + + +def run_round(args, out, rnd, eligible, rng): + plan = {test: {"at": rng.randint(1, n), "kind": rng.choice(args.kinds)} for test, n in sorted(eligible.items())} + results = {} + passed = set() + for attempt in (1, 2): + if attempt == 2: + plan = {t: f for t, f in plan.items() if t in passed} + if not plan: + break + tag = f"round-{rnd}-run-{attempt}" + plan_path = out / f"{tag}.plan.json" + plan_path.write_text(json.dumps(plan, indent=1)) + json_out = out / f"{tag}.json" + entries = go_test(args, args.run, out / f"{tag}.jsonl", plan_path, json_out) + outputs = None + seen = set() + for e in entries: + test = e["test"] + if test not in plan: + continue + seen.add(test) + fired = e.get("fired") + result = results.setdefault( + test, + {"test": test, "round": rnd, "planned": plan[test], "fired": fired, "requests": e["requests"]}, + ) + if not fired: + result["outcome"] = "not-fired" if attempt == 1 else "not-fired-on-rerun" + continue + if e["failed"]: + if outputs is None: + outputs = test_outputs(json_out) + log = outputs.get(test, "") + log_path = out / "logs" / f"{tag}.{sanitize(test)}.txt" + log_path.parent.mkdir(exist_ok=True) + log_path.write_text(log) + result["outcome"] = "fail" if attempt == 1 else "fail-on-rerun" + result["fired"] = fired or result["fired"] + result["snippet"] = failure_snippet(log) + result["log"] = str(log_path.relative_to(out)) + elif attempt == 1: + passed.add(test) + result["outcome"] = "pass-once" + else: + result["outcome"] = "pass" + for test in set(plan) - seen: + # No log entry: the run was cut short, e.g. by -timeout. + results.setdefault(test, {"test": test, "round": rnd, "planned": plan[test]})["outcome"] = "no-result" + return list(results.values()) + + +def write_summary(args, out, eligible, baseline_failed, no_requests, results): + by_kind = collections.defaultdict(collections.Counter) + for r in results: + by_kind[r["planned"]["kind"]][r["outcome"]] += 1 + + failures = [r for r in results if r["outcome"].startswith("fail")] + by_endpoint = collections.defaultdict(list) + for r in failures: + f = r["fired"] + by_endpoint[(endpoint(f["method"], f["path"]), r["planned"]["kind"])].append(r) + + lines = [ + "# Fault sweep summary", + "", + f"Selection: `-run {args.run}`, {args.count_runs} counting runs, {args.rounds} round(s), seed {args.seed}.", + "", + f"- Tests with requests that passed every counting run: {len(eligible)}", + f"- Left out, failed a counting run (flaky or broken without faults): {len(baseline_failed)}", + f"- Left out, made no requests: {len(no_requests)}", + "", + "Outcomes: `pass` passed twice with the fault, `fail` failed with it, `fail-on-rerun` passed once and", + "failed the second time, `not-fired` made fewer requests than the chosen number (`not-fired-on-rerun`: on the second run),", + "`no-result` was cut short.", + "", + "| Kind | Injected | pass | fail | fail-on-rerun | not-fired | no-result |", + "|---|---|---|---|---|---|---|", + ] + total = collections.Counter() + for kind in args.kinds: + c = by_kind[kind] + total.update(c) + injected = sum(c.values()) - c["not-fired"] + lines.append( + f"| {kind} | {injected} | {c['pass']} | {c['fail']} | {c['fail-on-rerun']} | {c['not-fired']} | {c['no-result']} |" + ) + injected = sum(total.values()) - total["not-fired"] + lines.append( + f"| **all** | {injected} | {total['pass']} | {total['fail']} | {total['fail-on-rerun']} | {total['not-fired']} | {total['no-result']} |" + ) + + lines += [ + "", + "## Failures by endpoint and kind", + "", + "| Endpoint | Kind | Failures | Example test |", + "|---|---|---|---|", + ] + for (ep, kind), rs in sorted(by_endpoint.items(), key=lambda item: (-len(item[1]), item[0])): + lines.append(f"| `{ep}` | {kind} | {len(rs)} | {rs[0]['test']} |") + + lines += ["", "## Failures", "", "| Test | Kind | Request | Outcome | Snippet |", "|---|---|---|---|---|"] + for r in sorted(failures, key=lambda r: r["test"]): + f = r["fired"] + snippet = r.get("snippet", "").replace("|", "\\|")[:300] + lines.append( + f"| {r['test']} | {f['kind']} | {f['at']} `{f['method']} {f['path']}` | {r['outcome']} | `{snippet}` |" + ) + + if baseline_failed: + lines += ["", "## Left out: failed a counting run", ""] + lines += [f"- {t}" for t in baseline_failed] + + path = out / "summary.md" + path.write_text("\n".join(lines) + "\n") + return path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--run", default="^TestAccept$", help="go test -run selection (default: every acceptance test)") + parser.add_argument("--count-runs", type=int, default=3, help="runs to learn request counts (default: 3)") + parser.add_argument("--rounds", type=int, default=1, help="rounds of injection per test (default: 1)") + parser.add_argument("--kinds", default=",".join(KINDS), help="comma-separated fault kinds (default: all)") + parser.add_argument("--seed", type=int, default=None, help="random seed (default: random)") + parser.add_argument("--timeout", default="4h", help="go test -timeout for each run (default: 4h)") + parser.add_argument("--out", required=True, type=Path, help="directory for logs, results.jsonl and summary.md") + parser.add_argument("go_args", nargs="*", help="extra go test arguments, after --") + args = parser.parse_args() + + args.kinds = args.kinds.split(",") + unknown = set(args.kinds) - set(KINDS) + if unknown: + parser.error(f"unknown kinds {sorted(unknown)}, expected some of {KINDS}") + if args.seed is None: + args.seed = random.randrange(1 << 32) + rng = random.Random(args.seed) + args.out.mkdir(parents=True, exist_ok=True) + + eligible, baseline_failed, no_requests = count_requests(args, args.out) + print( + f"{len(eligible)} tests to inject into; left out {len(baseline_failed)} failing, {len(no_requests)} without requests", + file=sys.stderr, + ) + + results = [] + for rnd in range(1, args.rounds + 1): + results += run_round(args, args.out, rnd, eligible, rng) + + with open(args.out / "results.jsonl", "w") as f: + f.writelines(json.dumps(r) + "\n" for r in results) + print(write_summary(args, args.out, eligible, baseline_failed, no_requests, results)) + + +if __name__ == "__main__": + main()