Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(http): handle canceled read requests consistently (#10432)
Frezcb57d74717005
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 4a6ce95bed..48028c13e2 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -3023,6 +3023,9 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {PageLimit: int32(limit + 1),})if err != nil {+ if writeQueryCancellation(w, r, err) {+ return+ }writeError(w, http.StatusInternalServerError, "failed to list agent tasks")return}@@ -3045,12 +3048,18 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {}}if err := h.redactForeignChatTaskContent(r.Context(), requestUserID(r), tasks, resp); err != nil {+ if writeQueryCancellation(w, r, err) {+ return+ }slog.Warn("list agent tasks: resolve chat owners failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)writeError(w, http.StatusInternalServerError, "failed to list agent tasks")return}h.hydrateTaskSupplementMetadata(r.Context(), r, agent.WorkspaceID, tasks, resp)if err := h.redactHiddenProjectTasks(r, workspaceID, tasks, resp); err != nil {+ if writeQueryCancellation(w, r, err) {+ return+ }slog.Warn("list agent tasks: resolve project access failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)writeError(w, http.StatusInternalServerError, "failed to list agent tasks")return@@ -3058,12 +3067,18 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))if includeUsage {if err := h.hydrateAgentTaskUsage(r.Context(), agent.ID, taskIDs, resp); err != nil {+ if writeQueryCancellation(w, r, err) {+ return+ }slog.Warn("list agent task usage failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)writeError(w, http.StatusInternalServerError, "failed to list agent task usage")return}}+ if writeQueryCancellation(w, r, r.Context().Err()) {+ return+ }if nextCursor != "" {w.Header().Set(HeaderAgentTasksNextCursor, nextCursor)}diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 4541c2c4a1..424dee27c4 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -6,12 +6,14 @@ import ("fmt""io""log/slog"+ "net""net/http""net/netip""net/url""path""strconv""strings"+ "syscall""time""github.com/go-chi/chi/v5"@@ -19,7 +21,6 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/imagemetadata"- "github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -583,7 +584,7 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {}link, err := h.Storage.Upload(r.Context(), key, data, contentType, header.Filename)if err != nil {- if writeUploadCancellation(w, r, err) {+ if writeRequestCancellation(w, r, err) {return}slog.Error("file upload failed", "error", err)@@ -613,7 +614,7 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {})}if err != nil {- if writeUploadCancellation(w, r, err) {+ if writeRequestCancellation(w, r, err) {// The record write may have committed. Deleting uploaded bytes// could leave a committed attachment pointing at a missing object.return@@ -656,7 +657,7 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {// No workspace context (e.g. avatar upload) — upload directly.link, err := h.Storage.Upload(r.Context(), key, data, contentType, header.Filename)if err != nil {- if writeUploadCancellation(w, r, err) {+ if writeRequestCancellation(w, r, err) {return}slog.Error("file upload failed", "error", err)@@ -1059,11 +1060,17 @@ func shouldProxyAttachmentURL(rawURL string) bool {func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Request, att db.Attachment, key string, forceAttachment bool) {reader, err := h.Storage.GetReader(r.Context(), key)if err != nil {+ if writeRequestCancellation(w, r, err) {+ return+ }slog.Error("failed to open attachment for download", "id", uuidToString(att.ID), "key", key, "error", err)writeError(w, http.StatusNotFound, "attachment object not found")return}defer reader.Close()+ if writeRequestCancellation(w, r, r.Context().Err()) {+ return+ }if att.ContentType != "" {w.Header().Set("Content-Type", att.ContentType)@@ -1096,6 +1103,22 @@ func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Requesth.serveProxyRange(w, r, att, reader)}+// A socket write can report a closed connection instead of context.Canceled.+// Preserve unrelated write errors and distinguish them from storage reads.+type attachmentStreamWriter struct {+ http.ResponseWriter+ request *http.Request+}++func (w attachmentStreamWriter) Write(data []byte) (int, error) {+ n, err := w.ResponseWriter.Write(data)+ if errors.Is(w.request.Context().Err(), context.Canceled) &&+ (errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, net.ErrClosed)) {+ err = errors.Join(context.Canceled, err)+ }+ return n, err+}+// serveProxyRange streams a (possibly partial) attachment body from a// forward-only reader. It always advertises Accept-Ranges: bytes and, when the// request carries a satisfiable single-range `Range` header, replies 206 +@@ -1140,10 +1163,18 @@ func (h *Handler) serveProxyRange(w http.ResponseWriter, r *http.Request, att db}if serveFull {+ if writeRequestCancellation(w, r, r.Context().Err()) {+ return+ }if total >= 0 {w.Header().Set("Content-Length", strconv.FormatInt(total, 10))}- if _, err := io.Copy(w, reader); err != nil {+ w.WriteHeader(http.StatusOK)+ if _, err := io.Copy(attachmentStreamWriter{ResponseWriter: w, request: r}, reader); err != nil {+ if isRequestCancellation(r, err) {+ slog.Info("attachment download cancelled", "id", uuidToString(att.ID))+ return+ }slog.Error("failed to stream attachment download", "id", uuidToString(att.ID), "error", err)}return@@ -1155,6 +1186,9 @@ func (h *Handler) serveProxyRange(w http.ResponseWriter, r *http.Request, att db// ServeContent path above).if start > 0 {if _, err := io.CopyN(io.Discard, reader, start); err != nil {+ if writeRequestCancellation(w, r, err) {+ return+ }// The skip failed BEFORE any response header was written. We must send// an explicit error status here: a bare `return` would let net/http// emit its default 200 OK + empty body, which a resuming client reads@@ -1171,7 +1205,11 @@ func (h *Handler) serveProxyRange(w http.ResponseWriter, r *http.Request, att dbw.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, start+length-1, total))w.Header().Set("Content-Length", strconv.FormatInt(length, 10))w.WriteHeader(http.StatusPartialContent)- if _, err := io.CopyN(w, reader, length); err != nil {+ if _, err := io.CopyN(attachmentStreamWriter{ResponseWriter: w, request: r}, reader, length); err != nil {+ if isRequestCancellation(r, err) {+ slog.Info("attachment range download cancelled", "id", uuidToString(att.ID))+ return+ }slog.Error("failed to stream attachment range", "id", uuidToString(att.ID), "error", err)}}@@ -1631,11 +1669,3 @@ func (h *Handler) deleteS3Objects(ctx context.Context, urls []string) {}h.Storage.DeleteKeys(ctx, keys)}--func writeUploadCancellation(w http.ResponseWriter, r *http.Request, err error) bool {- if !errors.Is(r.Context().Err(), context.Canceled) || !errors.Is(err, context.Canceled) {- return false- }- w.WriteHeader(middleware.StatusClientClosedRequest)- return true-}diff --git a/server/internal/handler/file_download_stream_cancellation_test.go b/server/internal/handler/file_download_stream_cancellation_test.gonew file mode 100644index 0000000000..9ddecbc588--- /dev/null+++ b/server/internal/handler/file_download_stream_cancellation_test.go@@ -0,0 +1,238 @@+package handler++import (+ "bytes"+ "context"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net"+ "net/http"+ "net/http/httptest"+ "strings"+ "syscall"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type cancellationStreamReader struct {+ io.Reader+ closed bool+}++type disconnectedDownloadWriter struct {+ *httptest.ResponseRecorder+ cancel context.CancelFunc+ err error+}++func (w disconnectedDownloadWriter) Write([]byte) (int, error) {+ if w.cancel != nil {+ w.cancel()+ }+ return 0, w.err+}++func (w disconnectedDownloadWriter) WriteString(data string) (int, error) {+ return w.Write([]byte(data))+}++func TestDownloadDisconnectedClientWrite(t *testing.T) {+ for _, tc := range []struct {+ name string+ err error+ disconnect bool+ }{+ {"broken pipe", syscall.EPIPE, true},+ {"connection reset", fmt.Errorf("write: %w", syscall.ECONNRESET), true},+ {"closed connection", net.ErrClosed, true},+ {"content length mismatch", http.ErrContentLength, false},+ {"write deadline", context.DeadlineExceeded, false},+ {"unrelated failure", errors.New("response writer failed"), false},+ } {+ for _, ranged := range []bool{false, true} {+ for _, cancelled := range []bool{false, true} {+ t.Run(fmt.Sprintf("%s/range=%v/cancelled=%v", tc.name, ranged, cancelled), func(t *testing.T) {+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ writer := disconnectedDownloadWriter{ResponseRecorder: httptest.NewRecorder(), err: tc.err}+ if cancelled {+ writer.cancel = cancel+ }+ var logs bytes.Buffer+ previous := slog.Default()+ slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil)))+ t.Cleanup(func() { slog.SetDefault(previous) })+ req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/download", nil)+ status := 200+ if ranged {+ req.Header.Set("Range", "bytes=0-2")+ status = 206+ }+ testHandler.serveProxyRange(writer, req, db.Attachment{SizeBytes: 3}, strings.NewReader("abc"))+ if writer.Code != status || strings.Contains(logs.String(), `"level":"ERROR"`) == (cancelled && tc.disconnect) {+ t.Fatal("client write failure changed the committed status or had the wrong log level")+ }+ })+ }+ }+ }+}++type observedDownloadWriter struct {+ http.ResponseWriter+ err error+}++func (w *observedDownloadWriter) Write(data []byte) (int, error) {+ n, err := w.ResponseWriter.Write(data)+ w.err = err+ return n, err+}++type waitForDownloadDisconnect struct {+ ctx context.Context+ ready chan struct{}+}++func (r waitForDownloadDisconnect) Read([]byte) (int, error) {+ close(r.ready)+ select {+ case <-r.ctx.Done():+ return 0, io.EOF+ case <-time.After(3 * time.Second):+ return 0, context.DeadlineExceeded+ }+}++func TestDownloadDisconnectPreservesHTTPContentLengthError(t *testing.T) {+ type result struct {+ err, contextErr error+ logs string+ }+ ready := make(chan struct{})+ results := make(chan result, 1)+ var logs bytes.Buffer+ previous := slog.Default()+ slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil)))+ t.Cleanup(func() { slog.SetDefault(previous) })+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ writer := &observedDownloadWriter{ResponseWriter: w}+ reader := io.MultiReader(waitForDownloadDisconnect{ctx: r.Context(), ready: ready}, strings.NewReader("oversized object"))+ testHandler.serveProxyRange(writer, r, db.Attachment{SizeBytes: 1}, reader)+ results <- result{writer.err, r.Context().Err(), logs.String()}+ }))+ t.Cleanup(server.Close)+ client, err := net.DialTimeout("tcp", server.Listener.Addr().String(), time.Second)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { client.Close() })+ if _, err := io.WriteString(client, "GET / HTTP/1.1\r\nHost: example\r\n\r\n"); err != nil {+ t.Fatal(err)+ }+ select {+ case <-ready:+ case <-time.After(3 * time.Second):+ t.Fatal("HTTP handler did not start reading")+ }+ client.Close()+ select {+ case got := <-results:+ if !errors.Is(got.err, http.ErrContentLength) || !errors.Is(got.contextErr, context.Canceled) {+ t.Fatalf("did not reach Content-Length failure after disconnect: %+v", got)+ }+ if !strings.Contains(got.logs, `"level":"ERROR"`) {+ t.Fatal("Content-Length failure lost its error log after disconnect")+ }+ case <-time.After(4 * time.Second):+ t.Fatal("HTTP handler did not finish")+ }+}++func (r *cancellationStreamReader) Close() error { r.closed = true; return nil }++type cancellationStreamStorage struct {+ mockStorage+ reader *cancellationStreamReader+}++func (s *cancellationStreamStorage) GetReader(context.Context, string) (io.ReadCloser, error) {+ return s.reader, nil+}++func TestDownloadStreamCancellation(t *testing.T) {+ for _, stage := range []string{"full stream", "range skip", "range stream"} {+ for _, tc := range []struct {+ name string+ cancel bool+ err error+ }{+ {"client cancellation", true, context.Canceled},+ {"independent cancellation", false, context.Canceled},+ {"independent deadline", false, context.DeadlineExceeded},+ {"unrelated failure after disconnect", true, errors.New("storage failure")},+ } {+ t.Run(stage+"/"+tc.name, func(t *testing.T) {+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ failure := &cancellationReadFailure{err: tc.err}+ if tc.cancel {+ failure.cancel = cancel+ }+ prefix := "abc"+ if stage == "range skip" {+ prefix = ""+ }+ reader := &cancellationStreamReader{Reader: io.MultiReader(strings.NewReader(prefix), failure)}+ h := *testHandler+ h.Storage = &cancellationStreamStorage{reader: reader}+ var logs bytes.Buffer+ previous := slog.Default()+ slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil)))+ t.Cleanup(func() { slog.SetDefault(previous) })+ req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/download", nil)+ status := http.StatusOK+ if stage != "full stream" {+ req.Header.Set("Range", "bytes=3-9")+ status = http.StatusPartialContent+ }+ cancelled := tc.cancel && errors.Is(tc.err, context.Canceled)+ if stage == "range skip" {+ status = http.StatusBadGateway+ if cancelled {+ status = 499+ }+ }+ response := testutil.Call(t, func(w http.ResponseWriter, r *http.Request) {+ h.proxyAttachmentDownload(w, r, db.Attachment{SizeBytes: 10, Filename: "example.txt"}, "example", false)+ }, req).Want(status)+ if !reader.closed {+ t.Fatal("stream reader was not closed")+ }+ if strings.Contains(logs.String(), `"level":"ERROR"`) == cancelled {+ t.Fatal("stream cancellation or real failure had the wrong log level")+ }+ if status == 499 && response.Body.Len() != 0 {+ t.Fatal("cancelled range skip returned a body")+ }+ })+ }+ }+}++type cancellationReadFailure struct {+ cancel context.CancelFunc+ err error+}++func (r *cancellationReadFailure) Read([]byte) (int, error) {+ if r.cancel != nil {+ r.cancel()+ }+ return 0, r.err+}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 7741b07078..530f529cd4 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -1037,6 +1037,9 @@ func (h *Handler) requireWorkspaceMember(w http.ResponseWriter, r *http.Request,member, err := h.getWorkspaceMember(r.Context(), userID, workspaceID)if err != nil {+ if writeQueryCancellation(w, r, err) {+ return db.Member{}, false+ }writeError(w, http.StatusNotFound, notFoundMsg)return db.Member{}, false}@@ -1096,7 +1099,11 @@ func (h *Handler) loadIssueForUser(w http.ResponseWriter, r *http.Request, issue// Try identifier format first (e.g., "JIA-42"). resolveIssueByIdentifier// silently returns false for non-identifier strings, falling through to// the UUID path below.- if issue, ok := h.resolveIssueByIdentifier(r.Context(), issueID, workspaceID); ok {+ issue, found, err := h.resolveIssueByIdentifier(r.Context(), issueID, workspaceID)+ if writeQueryCancellation(w, r, err) {+ return db.Issue{}, false+ }+ if found {if !h.requireProjectVisible(w, r, workspaceID, issue.ProjectID, http.StatusNotFound, "issue not found") {return db.Issue{}, false}@@ -1115,11 +1122,14 @@ func (h *Handler) loadIssueForUser(w http.ResponseWriter, r *http.Request, issuewriteError(w, http.StatusBadRequest, "invalid workspace_id")return db.Issue{}, false}- issue, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{+ issue, err = h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: issueUUID,WorkspaceID: wsUUID,})if err != nil {+ if writeQueryCancellation(w, r, err) {+ return db.Issue{}, false+ }writeError(w, http.StatusNotFound, "issue not found")return db.Issue{}, false}@@ -1138,31 +1148,35 @@ func (h *Handler) loadIssueForUser(w http.ResponseWriter, r *http.Request, issue// resolved to the same issue number, so `FOO-134` and `TRS-134` were// interchangeable — which makes the identifier URL `/{ws}/issues/{key}`// unusable as a canonical link.-func (h *Handler) resolveIssueByIdentifier(ctx context.Context, id, workspaceID string) (db.Issue, bool) {+func (h *Handler) resolveIssueByIdentifier(ctx context.Context, id, workspaceID string) (db.Issue, bool, error) {parts := splitIdentifier(id)if parts == nil {- return db.Issue{}, false+ return db.Issue{}, false, nil}if workspaceID == "" {- return db.Issue{}, false+ return db.Issue{}, false, nil}wsUUID, err := util.ParseUUID(workspaceID)if err != nil {- return db.Issue{}, false+ return db.Issue{}, false, nil}// Case-insensitive: a hand-typed `trs-134` should open `TRS-134`.- prefix := h.getIssuePrefix(ctx, wsUUID)+ workspace, err := h.Queries.GetWorkspace(ctx, wsUUID)+ if err != nil {+ return db.Issue{}, false, err+ }+ prefix := issuePrefixForWorkspace(workspace)if prefix == "" || !strings.EqualFold(parts.prefix, prefix) {- return db.Issue{}, false+ return db.Issue{}, false, nil}issue, err := h.Queries.GetIssueByNumber(ctx, db.GetIssueByNumberParams{WorkspaceID: wsUUID,Number: parts.number,})if err != nil {- return db.Issue{}, false+ return db.Issue{}, false, err}- return issue, true+ return issue, true, nil}type identifierParts struct {@@ -1255,6 +1269,9 @@ func (h *Handler) loadAgentForUser(w http.ResponseWriter, r *http.Request, agentWorkspaceID: wsUUID,})if err != nil {+ if writeQueryCancellation(w, r, err) {+ return db.Agent{}, false+ }writeError(w, http.StatusNotFound, "agent not found")return db.Agent{}, false}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex c88434ae5a..4d8b366527 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -1201,7 +1201,7 @@ 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) {+ if writeQueryCancellation(w, r, err) {return}slog.Warn("expand terminal status categories failed", append(logger.RequestAttrs(r), "error", err)...)@@ -1260,7 +1260,7 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {return rows.Err()})if err != nil {- if writeSearchCancellation(w, r, err) {+ if writeQueryCancellation(w, r, err) {return}// Statement-timeout surfaces as SQLSTATE 57014. Return a 503@@ -1280,7 +1280,7 @@ 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()) {+ if writeQueryCancellation(w, r, ctx.Err()) {return}@@ -1316,7 +1316,7 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {resp[i] = sir}- if writeSearchCancellation(w, r, ctx.Err()) {+ if writeQueryCancellation(w, r, ctx.Err()) {return}writeJSON(w, http.StatusOK, map[string]any{@@ -2594,6 +2594,9 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {// Fetch issue reactions.reactions, err := h.Queries.ListIssueReactions(r.Context(), issue.ID)+ if writeQueryCancellation(w, r, err) {+ return+ }if err == nil && len(reactions) > 0 {resp.Reactions = make([]IssueReactionResponse, len(reactions))for i, rx := range reactions {@@ -2606,6 +2609,9 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {IssueID: issue.ID,WorkspaceID: issue.WorkspaceID,})+ if writeQueryCancellation(w, r, err) {+ return+ }if err == nil && len(attachments) > 0 {mode := attachmentURLModeFromRequest(r)resp.Attachments = make([]AttachmentResponse, len(attachments))@@ -2617,6 +2623,9 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {if sourceContext, err := h.issueSourceContextDetail(r.Context(), issue, hidden); err == nil {resp.SourceContext = sourceContext} else if !errors.Is(err, pgx.ErrNoRows) {+ if writeQueryCancellation(w, r, err) {+ return+ }slog.Warn("load issue source context failed", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "error", err)...)// The frozen context is part of the issue's execution contract, not an// optional decoration. Returning a successful detail response without it@@ -2625,6 +2634,9 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {return}+ if writeQueryCancellation(w, r, r.Context().Err()) {+ return+ }writeJSON(w, http.StatusOK, resp)}diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.goindex dd59f7ad5c..72c556f861 100644--- a/server/internal/handler/plugin_action.go+++ b/server/internal/handler/plugin_action.go@@ -249,7 +249,7 @@ func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, cal// pluginCaller, so this is exactly the reach the caller already has.func (h *Handler) resolvePluginIssue(r *http.Request, caller service.PluginActionCaller, issueID string) (db.Issue, bool) {workspaceID := uuidToString(caller.WorkspaceID)- if issue, ok := h.resolveIssueByIdentifier(r.Context(), issueID, workspaceID); ok {+ if issue, ok, _ := h.resolveIssueByIdentifier(r.Context(), issueID, workspaceID); ok {return issue, true}parsed, err := util.ParseUUID(issueID)diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex f036e721cd..4f89f504fc 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -1053,7 +1053,7 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {return rows.Err()})if err != nil {- if writeSearchCancellation(w, r, err) {+ if writeQueryCancellation(w, r, err) {return}// Statement-timeout surfaces as SQLSTATE 57014 — same@@ -1070,7 +1070,7 @@ 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()) {+ if writeQueryCancellation(w, r, ctx.Err()) {return}@@ -1126,7 +1126,7 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {resp[i] = spr}- if writeSearchCancellation(w, r, ctx.Err()) {+ if writeQueryCancellation(w, r, ctx.Err()) {return}writeJSON(w, http.StatusOK, map[string]any{diff --git a/server/internal/handler/project_access.go b/server/internal/handler/project_access.goindex f60026843f..6a2528412a 100644--- a/server/internal/handler/project_access.go+++ b/server/internal/handler/project_access.go@@ -10,7 +10,6 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger"- "github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/projectaccess""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -72,8 +71,7 @@ func (h *Handler) hiddenProjectsForAgentRun(ctx context.Context, workspaceID pgtfunc (h *Handler) requestHiddenProjects(w http.ResponseWriter, r *http.Request, workspaceID string) (projectaccess.Hidden, bool) {hidden, err := h.hiddenProjects(r, workspaceID)if err != nil {- if errors.Is(r.Context().Err(), context.Canceled) && errors.Is(err, context.Canceled) {- w.WriteHeader(middleware.StatusClientClosedRequest)+ if writeQueryCancellation(w, r, err) {return projectaccess.Hidden{}, false}slog.Warn("resolve project access failed", append(logger.RequestAttrs(r), "workspace_id", workspaceID, "error", err)...)diff --git a/server/internal/handler/request_cancellation.go b/server/internal/handler/request_cancellation.gonew file mode 100644index 0000000000..9e81c2511a--- /dev/null+++ b/server/internal/handler/request_cancellation.go@@ -0,0 +1,38 @@+package handler++import (+ "context"+ "errors"+ "net/http"++ "github.com/multica-ai/multica/server/internal/middleware"+)++// A cancelled operation is a client cancellation only when its parent request+// is cancelled too. Independent cancellation, deadlines and unrelated failures+// keep their existing error handling.+func isRequestCancellation(r *http.Request, err error) bool {+ return errors.Is(r.Context().Err(), context.Canceled) && errors.Is(err, context.Canceled)+}++func writeRequestCancellation(w http.ResponseWriter, r *http.Request, err error) bool {+ if !isRequestCancellation(r, err) {+ return false+ }+ w.WriteHeader(middleware.StatusClientClosedRequest)+ return true+}++// SQLSTATE 57014 also describes a database statement timeout. The parent+// request must be cancelled before treating it as an abandoned query.+// Successful reads may pass r.Context().Err() before writing their response.+func writeQueryCancellation(w http.ResponseWriter, r *http.Request, err error) bool {+ if writeRequestCancellation(w, r, err) {+ return true+ }+ if !errors.Is(r.Context().Err(), context.Canceled) || !isSearchStatementTimeout(err) {+ return false+ }+ w.WriteHeader(middleware.StatusClientClosedRequest)+ return true+}diff --git a/server/internal/handler/request_cancellation_test.go b/server/internal/handler/request_cancellation_test.gonew file mode 100644index 0000000000..4056ad6495--- /dev/null+++ b/server/internal/handler/request_cancellation_test.go@@ -0,0 +1,314 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "strings"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Inject faults at an actual SQL call, after the preceding access checks have+// used the real database. Successful scans can also cancel just before return.+type requestCancellationDB struct {+ db.DBTX+ query string+ err error+ cancel context.CancelFunc+ after bool+}++func (d requestCancellationDB) matches(sql string) bool {+ return strings.HasPrefix(sql, "-- name: "+d.query+" :")+}++func (d requestCancellationDB) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ if !d.matches(sql) {+ return d.DBTX.Query(ctx, sql, args...)+ }+ if !d.after {+ if d.cancel != nil {+ d.cancel()+ }+ return nil, d.err+ }+ rows, err := d.DBTX.Query(ctx, sql, args...)+ if err != nil {+ return nil, err+ }+ return searchCancelAfterCloseRows{Rows: rows, cancel: d.cancel}, nil+}++func (d requestCancellationDB) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ if !d.matches(sql) {+ return d.DBTX.QueryRow(ctx, sql, args...)+ }+ if !d.after {+ if d.cancel != nil {+ d.cancel()+ }+ return requestCancellationRow{err: d.err}+ }+ return searchCancelRow{Row: d.DBTX.QueryRow(ctx, sql, args...), cancel: d.cancel}+}++type requestCancellationRow struct{ err error }++func (r requestCancellationRow) Scan(...any) error { return r.err }++type requestCancellationCase struct {+ name string+ err error+ cancel bool+ after bool+ status int+}++func requestCancellationCases(failureStatus int) []requestCancellationCase {+ return []requestCancellationCase{+ {"cancelled operation", fmt.Errorf("query: %w", context.Canceled), true, false, 499},+ {"postgres cancellation", &pgconn.PgError{Code: "57014"}, true, false, 499},+ {"cancelled after successful read", nil, true, true, 499},+ {"independent cancellation", context.Canceled, false, false, failureStatus},+ {"independent deadline", context.DeadlineExceeded, false, false, failureStatus},+ {"deadline concurrent with disconnect", context.DeadlineExceeded, true, false, failureStatus},+ {"failure concurrent with disconnect", errors.New("database unavailable"), true, false, failureStatus},+ }+}++func assertRequestCancellationStatus(t *testing.T, call http.HandlerFunc, req *http.Request, status int) {+ t.Helper()+ response := testutil.Call(t, call, req).Want(status)+ if status == 499 && (response.Body.Len() != 0 || response.Header().Get("Retry-After") != "") {+ t.Fatalf("cancelled request returned a body or retry instruction: %s", response.Body.String())+ }+}++func TestCancellableReadEndpoints(t *testing.T) {+ issueID := dbfx.Issue(t, "Cancelled detail")+ issue, err := testHandler.Queries.GetIssue(t.Context(), parseUUID(issueID))+ if err != nil {+ t.Fatal(err)+ }+ identifier := fmt.Sprintf("%s-%d", testHandler.getIssuePrefix(t.Context(), issue.WorkspaceID), issue.Number)+ runtimeID := dbfx.Runtime(t, "Cancelled discovery", testutil.Cols{"status": "online", "owner_id": testUserID, "visibility": "public"})+ agentID := dbfx.Agent(t, "Cancelled history", runtimeID)+ for _, endpoint := range []struct {+ name, query string+ status int+ request *http.Request+ call func(*Handler, http.ResponseWriter, *http.Request)+ }{+ {"issue lookup", "GetIssueInWorkspace", 404, withURLParam(newRequest(http.MethodGet, "/issues/"+issueID, nil), "id", issueID), (*Handler).GetIssue},+ {"identifier workspace", "GetWorkspace", 404, withURLParam(newRequest(http.MethodGet, "/issues/"+identifier, nil), "id", identifier), (*Handler).GetIssue},+ {"identifier issue", "GetIssueByNumber", 404, withURLParam(newRequest(http.MethodGet, "/issues/"+identifier, nil), "id", identifier), (*Handler).GetIssue},+ {"issue attachments", "ListAttachmentsByIssue", 200, withURLParam(newRequest(http.MethodGet, "/issues/"+issueID, nil), "id", issueID), (*Handler).GetIssue},+ {"agent lookup", "GetAgentInWorkspace", 404, withURLParam(newRequest(http.MethodGet, "/agents/"+agentID+"/tasks", nil), "id", agentID), (*Handler).ListAgentTasks},+ {"agent history", "ListAgentTasks", 500, withURLParam(newRequest(http.MethodGet, "/agents/"+agentID+"/tasks", nil), "id", agentID), (*Handler).ListAgentTasks},+ {"runtime lookup", "GetAgentRuntime", 404, withURLParam(newRequest(http.MethodPost, "/runtimes/"+runtimeID+"/local-skills", nil), "runtimeId", runtimeID), (*Handler).InitiateListLocalSkills},+ {"workspace membership", "GetMemberByUserAndWorkspace", 404, withURLParam(newRequest(http.MethodPost, "/runtimes/"+runtimeID+"/local-skills", nil), "runtimeId", runtimeID), (*Handler).InitiateListLocalSkills},+ } {+ t.Run(endpoint.name, func(t *testing.T) {+ cases := requestCancellationCases(endpoint.status)+ if endpoint.status == 404 {+ cases = append(cases, requestCancellationCase{"missing row after disconnect", pgx.ErrNoRows, true, false, 404})+ }+ for _, tc := range cases {+ if endpoint.query == "ListAttachmentsByIssue" && (!tc.cancel || tc.err != nil && !errors.Is(tc.err, context.Canceled) && !tc.after) {+ continue+ }+ t.Run(tc.name, func(t *testing.T) {+ ctx, cancel := context.WithCancel(endpoint.request.Context())+ defer cancel()+ h := *testHandler+ fault := requestCancellationDB{DBTX: testPool, query: endpoint.query, err: tc.err, after: tc.after}+ if tc.cancel {+ fault.cancel = cancel+ }+ h.Queries = db.New(fault)+ assertRequestCancellationStatus(t, func(w http.ResponseWriter, r *http.Request) { endpoint.call(&h, w, r) }, endpoint.request.WithContext(ctx), tc.status)+ if tc.cancel && ctx.Err() != context.Canceled {+ t.Fatal("request did not reach the named SQL cancellation")+ }+ })+ }+ })+ }+}++type requestCancellationTxStarter struct {+ txStarter+ fault requestCancellationDB+ afterCommit context.CancelFunc+}++func (s requestCancellationTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {+ tx, err := s.txStarter.Begin(ctx)+ if err != nil {+ return nil, err+ }+ s.fault.DBTX = tx+ return requestCancellationTx{Tx: tx, fault: s.fault, afterCommit: s.afterCommit}, nil+}++type requestCancellationTx struct {+ pgx.Tx+ fault requestCancellationDB+ afterCommit context.CancelFunc+}++func (tx requestCancellationTx) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ return tx.fault.Query(ctx, sql, args...)+}++func (tx requestCancellationTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ return tx.fault.QueryRow(ctx, sql, args...)+}++func (tx requestCancellationTx) Commit(ctx context.Context) error {+ err := tx.Tx.Commit(ctx)+ if err == nil && tx.afterCommit != nil {+ tx.afterCommit()+ }+ return err+}++func TestSearchIndexRequestCancellation(t *testing.T) {+ cursor := searchIndexManifest(t, testWorkspaceID).Cursor+ for _, endpoint := range []struct {+ name string+ query string+ call func(*Handler, http.ResponseWriter, *http.Request)+ }{+ {"manifest", "GetSearchIndexManifest", (*Handler).GetSearchIndexManifest},+ {"snapshot", "ListSearchIndexIssuesPage", (*Handler).GetSearchIndexSnapshot},+ {"changes", "SearchIndexSinceIsPruned", (*Handler).ListSearchIndexChanges},+ } {+ t.Run(endpoint.name, func(t *testing.T) {+ cases := append(requestCancellationCases(500), requestCancellationCase{"live statement timeout", &pgconn.PgError{Code: "57014"}, false, false, 503})+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ h := *testHandler+ fault := requestCancellationDB{query: endpoint.query, err: tc.err}+ starter := requestCancellationTxStarter{txStarter: testPool, fault: fault}+ if tc.after {+ starter.fault.query = ""+ starter.afterCommit = cancel+ } else if tc.cancel {+ starter.fault.cancel = cancel+ }+ h.TxStarter = starter+ req := newRequest(http.MethodGet, "/search-index/"+endpoint.name, nil)+ if endpoint.name == "changes" {+ req = newRequest(http.MethodPost, "/search-index/changes", map[string]any{"cursor": cursor})+ }+ assertRequestCancellationStatus(t, func(w http.ResponseWriter, r *http.Request) { endpoint.call(&h, w, r) }, req.WithContext(ctx), tc.status)+ })+ }+ })+ }+}++func TestSearchIndexCancellationWhileWaitingForSlot(t *testing.T) {+ previous := searchIndexBootstrapSlots+ searchIndexBootstrapSlots = make(chan struct{}, 1)+ searchIndexBootstrapSlots <- struct{}{}+ t.Cleanup(func() { searchIndexBootstrapSlots = previous })+ for _, call := range []http.HandlerFunc{testHandler.GetSearchIndexManifest, testHandler.GetSearchIndexSnapshot} {+ ctx, cancel := context.WithCancel(t.Context())+ cancel()+ assertRequestCancellationStatus(t, call, newRequest(http.MethodGet, "/search-index", nil).WithContext(ctx), 499)+ }+}++type cancellationLocalSkillStore struct {+ LocalSkillListStore+ cancel context.CancelFunc+ err error+ after bool+}++func (s cancellationLocalSkillStore) Create(ctx context.Context, runtimeID string) (*RuntimeLocalSkillListRequest, error) {+ if !s.after {+ if s.cancel != nil {+ s.cancel()+ }+ return nil, s.err+ }+ req, err := s.LocalSkillListStore.Create(ctx, runtimeID)+ s.cancel()+ return req, err+}++func (s cancellationLocalSkillStore) Get(ctx context.Context, id string) (*RuntimeLocalSkillListRequest, error) {+ if !s.after {+ if s.cancel != nil {+ s.cancel()+ }+ return nil, s.err+ }+ req, err := s.LocalSkillListStore.Get(ctx, id)+ s.cancel()+ return req, err+}++func TestLocalSkillDiscoveryRequestCancellation(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "Cancellation native skills", testutil.Cols{"status": "online", "owner_id": testUserID, "visibility": "public"})+ for _, operation := range []string{"create", "get"} {+ for _, tc := range []requestCancellationCase{+ {"cancelled", context.Canceled, true, false, 499},+ {"independent cancellation", context.Canceled, false, false, 500},+ {"independent deadline", context.DeadlineExceeded, false, false, 500},+ {"unrelated failure", errors.New("store unavailable"), true, false, 500},+ {"cancelled after acceptance", nil, true, true, 499},+ } {+ t.Run(operation+"/"+tc.name, func(t *testing.T) {+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ store := NewInMemoryLocalSkillListStore()+ h := *testHandler+ recorder := &runtimeLocalSkillPendingWorkRecorder{}+ h.DaemonPendingWork = recorder+ fault := cancellationLocalSkillStore{LocalSkillListStore: store, err: tc.err, after: tc.after}+ if tc.cancel {+ fault.cancel = cancel+ }+ h.LocalSkillListStore = fault+ req := withURLParam(newRequest(http.MethodPost, "/skills", map[string]any{"requestId": uuid.NewString()}), "runtimeId", runtimeID)+ call := h.InitiateListLocalSkills+ if operation == "get" {+ created, err := store.Create(t.Context(), runtimeID)+ if err != nil {+ t.Fatal(err)+ }+ req = withURLParams(newRequest(http.MethodGet, "/skills/"+created.ID, nil), "runtimeId", runtimeID, "requestId", created.ID)+ call = h.GetLocalSkillListRequest+ }+ if operation == "get" {+ req = withURLParams(req.WithContext(ctx), "runtimeId", runtimeID, "requestId", strings.TrimPrefix(req.URL.Path, "/skills/"))+ } else {+ req = withURLParam(req.WithContext(ctx), "runtimeId", runtimeID)+ }+ assertRequestCancellationStatus(t, call, req, tc.status)+ if operation == "create" {+ if (len(recorder.hints) == 1) != tc.after {+ t.Fatal("accepted discovery did not retain its wakeup")+ }+ pending, err := store.HasPending(t.Context(), runtimeID)+ if err != nil || pending != tc.after {+ t.Fatalf("cancellation changed accepted discovery: pending=%v, err=%v", pending, err)+ }+ }+ })+ }+ }+}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 9352eaa37a..f3d9a3dde3 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -884,6 +884,9 @@ func (h *Handler) requireRuntimeReadAccess(w http.ResponseWriter, r *http.Requesrt, err := h.getAgentRuntime(r.Context(), source, runtimeUUID)if err != nil {+ if writeQueryCancellation(w, r, err) {+ return db.AgentRuntime{}, db.Member{}, false+ }writeError(w, http.StatusNotFound, "runtime not found")return db.AgentRuntime{}, db.Member{}, false}diff --git a/server/internal/handler/runtime_local_skills.go b/server/internal/handler/runtime_local_skills.goindex ee690c0e09..aa56f013aa 100644--- a/server/internal/handler/runtime_local_skills.go+++ b/server/internal/handler/runtime_local_skills.go@@ -605,11 +605,17 @@ func (h *Handler) InitiateListLocalSkills(w http.ResponseWriter, r *http.Requestreq, err := h.LocalSkillListStore.Create(r.Context(), rt.runtimeID)if err != nil {+ if writeRequestCancellation(w, r, err) {+ return+ }slog.Warn("enqueue local skills request failed", append(logger.RequestAttrs(r), "error", err)...)writeError(w, http.StatusInternalServerError, "failed to enqueue local skills request")return}h.requestDaemonPendingWork(rt.runtimeID, protocol.PendingWorkKindLocalSkills)+ if writeRequestCancellation(w, r, r.Context().Err()) {+ return+ }writeJSON(w, http.StatusOK, req)}@@ -623,6 +629,9 @@ func (h *Handler) GetLocalSkillListRequest(w http.ResponseWriter, r *http.RequesrequestID := chi.URLParam(r, "requestId")req, err := h.LocalSkillListStore.Get(r.Context(), requestID)if err != nil {+ if writeRequestCancellation(w, r, err) {+ return+ }slog.Warn("load request failed", append(logger.RequestAttrs(r), "error", err)...)writeError(w, http.StatusInternalServerError, "failed to load request")return@@ -632,6 +641,9 @@ func (h *Handler) GetLocalSkillListRequest(w http.ResponseWriter, r *http.Requesreturn}+ if writeRequestCancellation(w, r, r.Context().Err()) {+ return+ }writeJSON(w, http.StatusOK, req)}diff --git a/server/internal/handler/search.go b/server/internal/handler/search.goindex ca2ca80871..c2c75350f1 100644--- a/server/internal/handler/search.go+++ b/server/internal/handler/search.go@@ -5,7 +5,6 @@ import ("errors""fmt""log/slog"- "net/http""os""strconv""strings"@@ -13,7 +12,6 @@ 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.@@ -185,22 +183,3 @@ 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_index.go b/server/internal/handler/search_index.goindex 62a687de9a..d44a9c43fb 100644--- a/server/internal/handler/search_index.go+++ b/server/internal/handler/search_index.go@@ -269,6 +269,9 @@ func (h *Handler) runSearchIndexRead(ctx context.Context, fn func(q *db.Queries)}func (h *Handler) writeSearchIndexError(w http.ResponseWriter, r *http.Request, op string, err error) {+ if writeQueryCancellation(w, r, err) {+ return+ }if isSearchStatementTimeout(err) {writeError(w, http.StatusServiceUnavailable, "search index read timed out; please retry")return@@ -286,6 +289,9 @@ func (h *Handler) GetSearchIndexManifest(w http.ResponseWriter, r *http.Request)}release, ok := acquireSearchIndexBootstrapSlot(r.Context())if !ok {+ if writeRequestCancellation(w, r, r.Context().Err()) {+ return+ }writeSearchIndexBusy(w)return}@@ -300,6 +306,9 @@ func (h *Handler) GetSearchIndexManifest(w http.ResponseWriter, r *http.Request)h.writeSearchIndexError(w, r, "manifest", err)return}+ if writeQueryCancellation(w, r, r.Context().Err()) {+ return+ }writeJSON(w, http.StatusOK, SearchIndexManifestResponse{Cursor: encodeSearchIndexCursor(searchIndexCursor{Since: row.Snapshot}),IssueCount: row.IssueCount,@@ -337,6 +346,9 @@ func (h *Handler) GetSearchIndexSnapshot(w http.ResponseWriter, r *http.Request)}release, ok := acquireSearchIndexBootstrapSlot(ctx)if !ok {+ if writeRequestCancellation(w, r, r.Context().Err()) {+ return+ }writeSearchIndexBusy(w)return}@@ -409,6 +421,9 @@ func (h *Handler) GetSearchIndexSnapshot(w http.ResponseWriter, r *http.Request)}resp.Comments = append(resp.Comments, searchIndexComment(c.ID, c.IssueID, c.Content, c.CreatedAt))}+ if writeQueryCancellation(w, r, r.Context().Err()) {+ return+ }writeJSON(w, http.StatusOK, resp)}@@ -427,6 +442,9 @@ func (h *Handler) ListSearchIndexChanges(w http.ResponseWriter, r *http.Request)Limit int `json:"limit"`}if err := json.NewDecoder(io.LimitReader(r.Body, searchIndexCursorMaxBytes+1024)).Decode(&req); err != nil {+ if writeRequestCancellation(w, r, err) {+ return+ }writeError(w, http.StatusBadRequest, "invalid request body")return}@@ -607,6 +625,9 @@ func (h *Handler) ListSearchIndexChanges(w http.ResponseWriter, r *http.Request)} else {resp.Cursor = encodeSearchIndexCursor(searchIndexCursor{Since: target})}+ if writeQueryCancellation(w, r, r.Context().Err()) {+ return+ }writeJSON(w, http.StatusOK, resp)}