Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(search): classify client cancellation separately from server errors (MUL-7989) (#9209)
Frezc0a979b1f9c56
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 09da855eb9..8f06cb8c3a 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -1156,6 +1156,9 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {if !includeClosed {resolvedKeys, err := h.terminalIssueStatusKeys(ctx, wsUUID)if err != nil {+ if writeSearchCancellation(w, r, err) {+ return+ }slog.Warn("expand terminal status categories failed", append(logger.RequestAttrs(r), "error", err)...)writeError(w, http.StatusInternalServerError, "failed to resolve status categories")return@@ -1207,6 +1210,9 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {return rows.Err()})if err != nil {+ if writeSearchCancellation(w, r, err) {+ return+ }// Statement-timeout surfaces as SQLSTATE 57014. Return a 503// so the frontend can distinguish a timeout ("try a more// specific query") from a generic 500. This is the fail-fast@@ -1224,6 +1230,9 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to search issues")return}+ if writeSearchCancellation(w, r, ctx.Err()) {+ return+ }prefix := h.getIssuePrefix(ctx, wsUUID)var originals []pgtype.UUID@@ -1257,6 +1266,9 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {resp[i] = sir}+ if writeSearchCancellation(w, r, ctx.Err()) {+ return+ }writeJSON(w, http.StatusOK, map[string]any{"issues": resp,})diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex 942c4995ee..6a6592284a 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -887,6 +887,9 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {return rows.Err()})if err != nil {+ if writeSearchCancellation(w, r, err) {+ return+ }// Statement-timeout surfaces as SQLSTATE 57014 — same// fail-fast contract as SearchIssues (see runSearchQuery).if isSearchStatementTimeout(err) {@@ -901,6 +904,9 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to search projects")return}+ if writeSearchCancellation(w, r, ctx.Err()) {+ return+ }// Batch-fetch issue stats and resource countsstatsMap := make(map[string]db.GetProjectIssueStatsRow)@@ -954,6 +960,9 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {resp[i] = spr}+ if writeSearchCancellation(w, r, ctx.Err()) {+ return+ }writeJSON(w, http.StatusOK, map[string]any{"projects": resp,})diff --git a/server/internal/handler/search.go b/server/internal/handler/search.goindex c2c75350f1..ca2ca80871 100644--- a/server/internal/handler/search.go+++ b/server/internal/handler/search.go@@ -5,6 +5,7 @@ import ("errors""fmt""log/slog"+ "net/http""os""strconv""strings"@@ -12,6 +13,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn"+ "github.com/multica-ai/multica/server/internal/middleware")// searchStatementTimeout bounds every /search request at the Postgres level.@@ -183,3 +185,22 @@ func isSearchStatementTimeout(err error) bool {}return false}++// writeSearchCancellation classifies an abandoned search without counting it as+// a server failure or a successful request. PostgreSQL may surface disconnect+// cancellation as SQLSTATE 57014, so the request context distinguishes it from+// the database's statement timeout. Unrelated database errors remain failures.+// Successful paths pass the context error to catch cancellation after commit+// or during supplementary reads before writing a response.+func writeSearchCancellation(w http.ResponseWriter, r *http.Request, err error) bool {+ if !errors.Is(r.Context().Err(), context.Canceled) {+ return false+ }+ if !errors.Is(err, context.Canceled) && !isSearchStatementTimeout(err) {+ return false+ }+ // The client has disconnected; retain the status for logs and metrics but+ // avoid encoding a response body for a request that no longer needs it.+ w.WriteHeader(middleware.StatusClientClosedRequest)+ return true+}diff --git a/server/internal/handler/search_cancellation_test.go b/server/internal/handler/search_cancellation_test.gonew file mode 100644index 0000000000..29653c2c7e--- /dev/null+++ b/server/internal/handler/search_cancellation_test.go@@ -0,0 +1,323 @@+package handler++import (+ "context"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strconv"+ "strings"+ "testing"+ "time"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// searchFailureTx injects a query failure after the transaction-local settings+// have been applied, including cancellation while the search is in flight.+type searchFailureTx struct {+ pgx.Tx+ err error+ cancel context.CancelFunc+ rows pgx.Rows+ commitErr error+ commitCancel context.CancelFunc+}++func (tx searchFailureTx) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {+ return pgconn.CommandTag{}, nil+}++func (tx searchFailureTx) Query(context.Context, string, ...any) (pgx.Rows, error) {+ if tx.rows != nil {+ return tx.rows, nil+ }+ if tx.cancel != nil {+ tx.cancel()+ }+ return nil, tx.err+}++func (tx searchFailureTx) Rollback(context.Context) error { return nil }++func (tx searchFailureTx) Commit(context.Context) error {+ if tx.commitCancel != nil {+ tx.commitCancel()+ }+ return tx.commitErr+}++type searchFailureTxStarter struct{ tx searchFailureTx }++func (s searchFailureTxStarter) Begin(context.Context) (pgx.Tx, error) { return s.tx, nil }++func TestSearchRequestErrorClassification(t *testing.T) {+ for _, endpoint := range []string{"issues", "projects"} {+ t.Run(endpoint, func(t *testing.T) {+ for _, tc := range []struct {+ name string+ err error+ cancel bool+ wantStatus int+ }{+ {"client cancellation", context.Canceled, true, 499},+ {"wrapped client cancellation", fmt.Errorf("scan: %w", context.Canceled), true, 499},+ {"postgres cancellation after disconnect", &pgconn.PgError{Code: "57014"}, true, 499},+ {"database statement timeout", &pgconn.PgError{Code: "57014"}, false, http.StatusServiceUnavailable},+ {"database failure", &pgconn.PgError{Code: "42P01"}, false, http.StatusInternalServerError},+ {"unexpected cancellation with live request", context.Canceled, false, http.StatusInternalServerError},+ {"database failure concurrent with disconnect", &pgconn.PgError{Code: "42P01"}, true, http.StatusInternalServerError},+ } {+ t.Run(tc.name, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ tx := searchFailureTx{err: tc.err}+ if tc.cancel {+ tx.cancel = cancel+ }+ h := *testHandler+ h.TxStarter = searchFailureTxStarter{tx: tx}+ assertSearchStatus(t, &h, endpoint, ctx, tc.wantStatus)+ })+ }+ })+ }+}++func TestSearchAlreadyCanceledRequest(t *testing.T) {+ for _, tc := range []struct {+ name string+ path string+ handler http.HandlerFunc+ }{+ {"issue status lookup", "/api/issues/search?q=needle", testHandler.SearchIssues},+ {"issue search transaction", "/api/issues/search?q=needle&include_closed=true", testHandler.SearchIssues},+ {"project search transaction", "/api/projects/search?q=needle", testHandler.SearchProjects},+ } {+ t.Run(tc.name, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ response := testutil.Call(t, tc.handler, newRequest(http.MethodGet, tc.path, nil).WithContext(ctx)).Want(499)+ if response.Body.Len() != 0 {+ t.Fatalf("already canceled search wrote a response body: %s", response.Body.String())+ }+ })+ }+}++func assertSearchStatus(t *testing.T, h *Handler, endpoint string, ctx context.Context, status int) {+ t.Helper()+ registry := metrics.NewRegistry(metrics.RegistryOptions{})+ router := chi.NewRouter()+ router.Use(registry.HTTP.Middleware)+ path := "/api/" + endpoint + "/search"+ if endpoint == "issues" {+ router.Get(path, h.SearchIssues)+ } else {+ router.Get(path, h.SearchProjects)+ }+ req := newRequest(http.MethodGet, path+"?q=SearchCancellationEnrichment&include_closed=true", nil).WithContext(ctx)+ response := testutil.Call(t, router.ServeHTTP, req).Want(status)+ if status == 499 && response.Body.Len() != 0 {+ t.Fatalf("disconnected search wrote a response body: %s", response.Body.String())+ }++ rec := httptest.NewRecorder()+ metrics.NewHandler(registry.Gatherer).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))+ body := rec.Body.String()+ want := `multica_http_requests_total{method="GET",route="` + path + `",status="` + strconv.Itoa(status) + `"} 1`+ if !strings.Contains(body, want) {+ t.Fatalf("missing request classification %q in metrics:\n%s", want, body)+ }+ if status == 499 {+ for _, incorrect := range []string{`status="200"`, `status="500"`, `status="503"`} {+ if strings.Contains(body, incorrect) {+ t.Fatalf("canceled search counted as %s:\n%s", incorrect, body)+ }+ }+ }+}++type searchCancellationRows struct {+ pgx.Rows+ cancel context.CancelFunc+ err error+}++func (rows searchCancellationRows) Next() bool {+ if rows.cancel != nil {+ rows.cancel()+ }+ return false+}++func (rows searchCancellationRows) Err() error { return rows.err }+func (rows searchCancellationRows) Close() {}++func TestSearchCancellationAfterQuery(t *testing.T) {+ for _, endpoint := range []string{"issues", "projects"} {+ t.Run(endpoint, func(t *testing.T) {+ for _, stage := range []string{"reading rows", "commit error", "successful commit"} {+ t.Run(stage, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ tx := searchFailureTx{rows: searchCancellationRows{}}+ switch stage {+ case "reading rows":+ tx.rows = searchCancellationRows{cancel: cancel, err: context.Canceled}+ case "commit error":+ tx.commitCancel = cancel+ tx.commitErr = context.Canceled+ case "successful commit":+ tx.commitCancel = cancel+ }+ h := *testHandler+ h.TxStarter = searchFailureTxStarter{tx: tx}+ assertSearchStatus(t, &h, endpoint, ctx, 499)+ })+ }+ })+ }+}++// These wrappers cancel only after a real supplementary read completes. The+// primary search and commit succeed, so their error branches cannot catch it.+type searchEnrichmentDB struct {+ db.DBTX+ cancel context.CancelFunc+ canceled bool+}++func (d *searchEnrichmentDB) stop() {+ d.canceled = true+ d.cancel()+}++func (d *searchEnrichmentDB) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ row := d.DBTX.QueryRow(ctx, sql, args...)+ if strings.HasPrefix(sql, "-- name: GetWorkspace :one") {+ return searchCancelRow{Row: row, cancel: d.stop}+ }+ return row+}++func (d *searchEnrichmentDB) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ rows, err := d.DBTX.Query(ctx, sql, args...)+ if err == nil && strings.HasPrefix(sql, "-- name: GetProjectResourceCounts :many") {+ return searchCancelAfterCloseRows{Rows: rows, cancel: d.stop}, nil+ }+ return rows, err+}++type searchCancelRow struct {+ pgx.Row+ cancel context.CancelFunc+}++func (row searchCancelRow) Scan(dest ...any) error {+ err := row.Row.Scan(dest...)+ if err == nil {+ row.cancel()+ }+ return err+}++type searchCancelAfterCloseRows struct {+ pgx.Rows+ cancel context.CancelFunc+}++func (rows searchCancelAfterCloseRows) Close() {+ rows.Rows.Close()+ rows.cancel()+}++func TestSearchCancellationDuringEnrichment(t *testing.T) {+ for _, endpoint := range []string{"issues", "projects"} {+ t.Run(endpoint, func(t *testing.T) {+ if endpoint == "issues" {+ dbfx.Issue(t, "SearchCancellationEnrichment issue")+ } else {+ dbfx.Project(t, "SearchCancellationEnrichment project")+ }+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ d := &searchEnrichmentDB{DBTX: testPool, cancel: cancel}+ h := *testHandler+ h.Queries = db.New(d)+ assertSearchStatus(t, &h, endpoint, ctx, 499)+ if !d.canceled {+ t.Fatal("search never reached the supplementary read")+ }+ })+ }+}++type searchBlockingTxStarter struct{ txStarter }++func (s searchBlockingTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {+ tx, err := s.txStarter.Begin(ctx)+ if err != nil {+ return nil, err+ }+ return searchBlockingTx{Tx: tx}, nil+}++type searchBlockingTx struct{ pgx.Tx }++const cancellationSleepQuery = "SELECT pg_sleep(10) /* search cancellation regression */"++func (tx searchBlockingTx) Query(ctx context.Context, _ string, _ ...any) (pgx.Rows, error) {+ return tx.Tx.Query(ctx, cancellationSleepQuery)+}++func TestSearchCancellationInFlightPostgres(t *testing.T) {+ for _, endpoint := range []string{"issues", "projects"} {+ t.Run(endpoint, func(t *testing.T) {+ conn, err := testPool.Acquire(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Release()+ pid := conn.Conn().PgConn().PID()+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ watchCtx, stop := context.WithTimeout(context.Background(), 3*time.Second)+ defer stop()+ observed := make(chan error, 1)+ go func() {+ defer cancel()+ ticker := time.NewTicker(10 * time.Millisecond)+ defer ticker.Stop()+ for {+ var running bool+ err := testPool.QueryRow(watchCtx, `SELECT EXISTS (+ SELECT 1 FROM pg_stat_activity WHERE pid = $1 AND state = 'active'+ AND wait_event = 'PgSleep' AND query = $2+ )`, pid, cancellationSleepQuery).Scan(&running)+ if err != nil || running {+ observed <- err+ return+ }+ select {+ case <-ticker.C:+ case <-watchCtx.Done():+ observed <- watchCtx.Err()+ return+ }+ }+ }()+ h := *testHandler+ h.TxStarter = searchBlockingTxStarter{txStarter: conn}+ assertSearchStatus(t, &h, endpoint, ctx, 499)+ if err := <-observed; err != nil {+ t.Fatalf("did not observe a real in-flight PostgreSQL query: %v", err)+ }+ })+ }+}diff --git a/server/internal/middleware/request_logger.go b/server/internal/middleware/request_logger.goindex 98e6be1a27..55cb0a4c1b 100644--- a/server/internal/middleware/request_logger.go+++ b/server/internal/middleware/request_logger.go@@ -110,6 +110,10 @@ var softNotFoundMarkers = []string{"task not found",}+// StatusClientClosedRequest identifies a request abandoned by its client. It is+// distinct from both a successful response and a server-side failure.+const StatusClientClosedRequest = 499+// RequestLogger is a structured HTTP request logger using slog.// It replaces Chi's built-in chimw.Logger with colored, structured output.func RequestLogger(next http.Handler) http.Handler {@@ -164,6 +168,8 @@ func RequestLogger(next http.Handler) http.Handler {switch {case status >= 500:slog.Error("http request", attrs...)+ case status == StatusClientClosedRequest:+ slog.Info("http request", attrs...)case status == http.StatusNotFound && isSoftNotFound(bodyPrefix.Bytes()):// Lifecycle 404 — runtime/task was deleted server-side. The daemon// catches this exact body and triggers its own self-heal, so it isdiff --git a/server/internal/middleware/request_logger_test.go b/server/internal/middleware/request_logger_test.goindex 91e91dc706..5c49992d09 100644--- a/server/internal/middleware/request_logger_test.go+++ b/server/internal/middleware/request_logger_test.go@@ -92,6 +92,14 @@ func TestRequestLogger_500StaysError(t *testing.T) {requireLogLevel(t, logs, "ERROR", "WARN", "INFO")}+func TestRequestLogger_ClientClosedRequestStaysInfo(t *testing.T) {+ logs := runRequestLogger(t, 499, "")+ requireLogLevel(t, logs, "INFO", "WARN", "ERROR")+ if !strings.Contains(logs.String(), "status=499") {+ t.Fatalf("canceled request lost its status: %s", logs.String())+ }+}+func TestRequestLogger_200StaysInfo(t *testing.T) {logs := runRequestLogger(t, http.StatusOK, `{"ok":true}`)requireLogLevel(t, logs, "INFO", "WARN", "ERROR")