Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6310 fix(agent tasks): stop NUL bytes wedging tasks on complete/messages/cancel (#7124)

Bohan Jiangd6301091e07b
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 98e823c267..9a296bffd9 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -3494,6 +3494,30 @@ type TaskCompleteRequest struct {
RetiredSessionID string `json:"retired_session_id,omitempty"`
}
+// sanitizeTaskCompleteRequest / sanitizeTaskFailRequest scrub every
+// caller-supplied string on a terminal task callback. Both request types are
+// flat bags of strings, so this is exhaustive by construction — but that also
+// means a NEW string field must be added here, or it reopens GH #7098 through a
+// fresh door. The task-row columns these feed (error, work_dir, branch_name,
+// session_id) are all TEXT, and result is JSONB; neither tolerates a NUL.
+func sanitizeTaskCompleteRequest(req *TaskCompleteRequest) {
+ req.PRURL = util.SanitizeTextForPostgres(req.PRURL)
+ req.Output = util.SanitizeTextForPostgres(req.Output)
+ req.SessionID = util.SanitizeTextForPostgres(req.SessionID)
+ req.WorkDir = util.SanitizeTextForPostgres(req.WorkDir)
+ req.BranchName = util.SanitizeTextForPostgres(req.BranchName)
+ req.RetiredSessionID = util.SanitizeTextForPostgres(req.RetiredSessionID)
+}
+
+func sanitizeTaskFailRequest(req *TaskFailRequest) {
+ req.Error = util.SanitizeTextForPostgres(req.Error)
+ req.SessionID = util.SanitizeTextForPostgres(req.SessionID)
+ req.WorkDir = util.SanitizeTextForPostgres(req.WorkDir)
+ req.FailureReason = util.SanitizeTextForPostgres(req.FailureReason)
+ req.BranchName = util.SanitizeTextForPostgres(req.BranchName)
+ req.RetiredSessionID = util.SanitizeTextForPostgres(req.RetiredSessionID)
+}
+
func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
taskID := chi.URLParam(r, "taskId")
@@ -3508,6 +3532,15 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
+ // Strip bytes PostgreSQL cannot store BEFORE anything reads this payload
+ // (GH #7098). The whole request is marshalled into agent_task_queue.result,
+ // a JSONB column, and encoding/json renders an embedded NUL as \u0000 —
+ // which JSONB rejects (SQLSTATE 22P05), rolling the completion transaction
+ // back and leaving the task stuck in 'running' forever. Sanitizing here
+ // rather than just before the Marshal is deliberate: the context-exhaustion
+ // re-route below feeds req.Output into the failure classifier, and that
+ // classifier must see exactly the text we are going to persist.
+ sanitizeTaskCompleteRequest(&req)
// GH #6402: a daemon whose backend does not (yet) read the provider's
// structured terminal reason reports a context-exhausted run as a clean
@@ -4203,6 +4236,10 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
+ // TaskService.FailTask normalizes req.Error itself, but every other field
+ // here lands in a TEXT column too and a NUL in any one of them fails the
+ // same transaction (GH #7098).
+ sanitizeTaskFailRequest(&req)
h.failTask(w, r, taskID, workspaceID, req)
}
@@ -4299,6 +4336,23 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
msg.Output = redact.Text(msg.Output)
msg.Input = redact.InputMap(msg.Input)
+ // redact.Text only masks secret-shaped substrings; it has no opinion on
+ // bytes PostgreSQL refuses to store. Tool output is the likeliest
+ // carrier of a stray NUL in the whole system — an agent that cats a
+ // binary, or a Windows tool emitting UTF-16 — and this endpoint has no
+ // retry on the daemon side, so an unsanitized batch is silently lost
+ // (GH #7098). Input is a JSONB column, so it needs the deep walk: the
+ // offending byte can sit at any depth of a tool's arguments.
+ msg.Type = util.SanitizeTextForPostgres(msg.Type)
+ msg.Tool = util.SanitizeTextForPostgres(msg.Tool)
+ msg.Content = util.SanitizeTextForPostgres(msg.Content)
+ msg.Output = util.SanitizeTextForPostgres(msg.Output)
+ if msg.Input != nil {
+ if cleaned, ok := util.SanitizeJSONForPostgres(msg.Input).(map[string]any); ok {
+ msg.Input = cleaned
+ }
+ }
+
var inputJSON []byte
if msg.Input != nil {
inputJSON, _ = json.Marshal(msg.Input)
@@ -4355,6 +4409,13 @@ func (h *Handler) AckTaskCancelled(w http.ResponseWriter, r *http.Request) {
// break the cancellation contract this endpoint exists for.
var req TaskCancelAckRequest
_ = json.NewDecoder(r.Body).Decode(&req)
+ // Same persistence hazard as /fail and /complete: these strings go straight
+ // into TEXT columns, and this endpoint fails LOUD on write errors, so an
+ // unsanitized NUL here turns a cancelled task's only pointer to its work
+ // into an endless 500 retry loop (GH #7098).
+ req.ErrorMessage = util.SanitizeTextForPostgres(req.ErrorMessage)
+ req.FailureReason = util.SanitizeTextForPostgres(req.FailureReason)
+ req.BranchName = util.SanitizeTextForPostgres(req.BranchName)
// Terminal deliveries first, failing LOUD on persistence errors: these
// fields are the only pointer to a cancelled task's work, and the daemon
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index 312745e972..2f3e7ae4d4 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -19,6 +19,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
skillpkg "github.com/multica-ai/multica/server/internal/skill"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
"golang.org/x/sync/errgroup"
@@ -26,16 +27,16 @@ import (
// sanitizeNullBytes makes a string safe for a PostgreSQL TEXT column.
//
-// Two failure modes covered:
-// - Embedded NUL (0x00) — PG rejects with SQLSTATE 22021. Removed.
-// - Other invalid-UTF-8 byte sequences (e.g. 0x91 = Windows-1252 smart
-// quote in imported Windows-encoded prose). `strings.ToValidUTF8` drops
-// them.
+// Thin alias for util.SanitizeTextForPostgres, kept because ~20 call sites
+// spell it this way. The shared helper is the single definition of what
+// "safe to persist" means, so the daemon task endpoints and the
+// comment/skill/property endpoints can no longer drift into storing
+// different text for the same input (GH #7098 review).
//
-// Name is kept for compatibility with the many call sites; the behaviour
-// is a strict superset of the original.
+// One behaviour change came with the move: invalid UTF-8 is now replaced
+// with U+FFFD rather than dropped silently. NUL is still removed outright.
func sanitizeNullBytes(s string) string {
- return strings.ToValidUTF8(strings.ReplaceAll(s, "\x00", ""), "")
+ return util.SanitizeTextForPostgres(s)
}
// --- Response structs ---
diff --git a/server/internal/handler/task_payload_nul_test.go b/server/internal/handler/task_payload_nul_test.go
new file mode 100644
index 0000000000..4cca36b34a
--- /dev/null
+++ b/server/internal/handler/task_payload_nul_test.go
@@ -0,0 +1,260 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// seedNULTask creates an agent with one running task, ready to be driven
+// through a terminal daemon callback.
+func seedNULTask(t *testing.T, label string) (agentID, taskID string) {
+ t.Helper()
+ ctx := context.Background()
+
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id,
+ instructions, custom_env, custom_args)
+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4, '', '{}'::jsonb, '[]'::jsonb)
+ RETURNING id`, testWorkspaceID, label, handlerTestRuntimeID(t), testUserID).Scan(&agentID); err != nil {
+ t.Fatalf("seed agent: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)
+ })
+
+ // The task needs an issue: requireDaemonTaskAccess resolves the workspace
+ // through it, and a task with no issue / chat / autopilot link 404s before
+ // the handler ever reads the body.
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)
+ VALUES ($1, $2, 'in_progress', 'none', $3, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1), 0)
+ RETURNING id`, testWorkspaceID, label+" fixture", testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("seed issue: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at)
+ VALUES ($1, $2, $3, 'running', 0, now())
+ RETURNING id`, agentID, handlerTestRuntimeID(t), issueID).Scan(&taskID); err != nil {
+ t.Fatalf("seed running task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ return agentID, taskID
+}
+
+// daemonTaskRequest builds a daemon-authenticated request with taskId bound as
+// a chi URL param, the way the router does in production.
+func daemonTaskRequest(t *testing.T, path, taskID string, body any) *http.Request {
+ t.Helper()
+ req := newDaemonTokenRequest("POST", path, body, testWorkspaceID, "nul-regression-daemon")
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("taskId", taskID)
+ return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+}
+
+// TestCompleteTaskCallbackWithNULSucceeds is the /complete half of GH #7098,
+// driven through the real handler.
+//
+// The NUL travels the way the report describes: encoding/json escapes it on the
+// wire and the decoder rebuilds it, so the handler sees a genuine 0x00 the way
+// a daemon would deliver it. Going through CompleteTask (rather than calling
+// the sanitizer by hand) is what makes this a regression test for the WIRING —
+// delete the sanitize call in the handler and this fails.
+func TestCompleteTaskCallbackWithNULSucceeds(t *testing.T) {
+ ctx := context.Background()
+ _, taskID := seedNULTask(t, "nul-complete-agent")
+
+ w := httptest.NewRecorder()
+ req := daemonTaskRequest(t, "/api/daemon/tasks/"+taskID+"/complete", taskID, map[string]any{
+ "output": "done\x00 summary text",
+ "work_dir": "/tmp/work\x00dir",
+ "session_id": "sess-nul-complete",
+ })
+
+ testHandler.CompleteTask(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("CompleteTask returned %d, want 200: %s", w.Code, w.Body.String())
+ }
+
+ var (
+ status string
+ completedAt *string
+ storedJSON []byte
+ )
+ if err := testPool.QueryRow(ctx, `
+ SELECT status, completed_at::text, result
+ FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status, &completedAt, &storedJSON); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "completed" {
+ t.Fatalf("status = %q, want completed", status)
+ }
+ if completedAt == nil {
+ t.Fatal("completed_at is NULL, want a terminal timestamp")
+ }
+
+ var stored TaskCompleteRequest
+ if err := json.Unmarshal(storedJSON, &stored); err != nil {
+ t.Fatalf("decode stored result: %v", err)
+ }
+ // Removing rather than rejecting: the readable text survives.
+ if stored.Output != "done summary text" {
+ t.Fatalf("stored output = %q, want %q", stored.Output, "done summary text")
+ }
+ if stored.WorkDir != "/tmp/workdir" {
+ t.Fatalf("stored work_dir = %q, want %q", stored.WorkDir, "/tmp/workdir")
+ }
+}
+
+// TestReportTaskMessagesCallbackWithNULSucceeds covers the /messages entry,
+// again through the real handler.
+//
+// Three poisoned places at once, because they fail for three different reasons:
+// type and output are TEXT columns, and input is JSONB where the offending byte
+// sits two levels down inside a tool's arguments while every top-level string
+// is clean.
+func TestReportTaskMessagesCallbackWithNULSucceeds(t *testing.T) {
+ ctx := context.Background()
+ _, taskID := seedNULTask(t, "nul-messages-agent")
+
+ w := httptest.NewRecorder()
+ req := daemonTaskRequest(t, "/api/daemon/tasks/"+taskID+"/messages", taskID, map[string]any{
+ "messages": []any{
+ map[string]any{
+ "seq": 1,
+ "type": "tool_use\x00",
+ "tool": "Bash\x00",
+ "content": "reading\x00 the binary",
+ "output": "ELF\x00\x00binary",
+ "input": map[string]any{
+ "command": "cat",
+ "args": []any{"-n", "build/app.bin"},
+ "result": map[string]any{
+ "stdout": "ELF\x00\x00binary",
+ },
+ },
+ },
+ },
+ })
+
+ testHandler.ReportTaskMessages(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ReportTaskMessages returned %d, want 200: %s", w.Code, w.Body.String())
+ }
+
+ var (
+ msgType string
+ msgTool string
+ msgContent string
+ msgOutput string
+ msgInput []byte
+ )
+ if err := testPool.QueryRow(ctx, `
+ SELECT type, COALESCE(tool, ''), COALESCE(content, ''), COALESCE(output, ''), input
+ FROM task_message WHERE task_id = $1 AND seq = 1`, taskID).
+ Scan(&msgType, &msgTool, &msgContent, &msgOutput, &msgInput); err != nil {
+ t.Fatalf("read persisted task message: %v", err)
+ }
+
+ if msgType != "tool_use" {
+ t.Fatalf("stored type = %q, want %q", msgType, "tool_use")
+ }
+ if msgTool != "Bash" {
+ t.Fatalf("stored tool = %q, want %q", msgTool, "Bash")
+ }
+ if msgContent != "reading the binary" {
+ t.Fatalf("stored content = %q, want %q", msgContent, "reading the binary")
+ }
+ if msgOutput != "ELFbinary" {
+ t.Fatalf("stored output = %q, want %q", msgOutput, "ELFbinary")
+ }
+
+ var storedInput struct {
+ Result struct {
+ Stdout string `json:"stdout"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(msgInput, &storedInput); err != nil {
+ t.Fatalf("decode stored input: %v", err)
+ }
+ if storedInput.Result.Stdout != "ELFbinary" {
+ t.Fatalf("stored nested stdout = %q, want %q", storedInput.Result.Stdout, "ELFbinary")
+ }
+}
+
+// TestPostgresRejectsUnsanitizedTaskPayloads is the control for both tests
+// above: it proves the database really does refuse these payloads, so the
+// handler tests are demonstrating a fix rather than a no-op. If PostgreSQL ever
+// starts accepting them, this fails and the guards can be reconsidered.
+func TestPostgresRejectsUnsanitizedTaskPayloads(t *testing.T) {
+ ctx := context.Background()
+ _, taskID := seedNULTask(t, "nul-control-agent")
+
+ t.Run("complete result JSONB", func(t *testing.T) {
+ raw, err := json.Marshal(TaskCompleteRequest{Output: "done\x00 summary"})
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if !strings.Contains(string(raw), "\\u0000") {
+ t.Fatalf("premise broken: payload carries no NUL escape: %s", raw)
+ }
+ if _, err := testHandler.Queries.CompleteAgentTask(ctx, db.CompleteAgentTaskParams{
+ ID: util.MustParseUUID(taskID),
+ Result: raw,
+ }); err == nil {
+ t.Fatal("PostgreSQL accepted a JSONB payload containing a NUL escape")
+ }
+
+ // The rejected write rolled back — which is exactly the reported wedge.
+ var status string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "running" {
+ t.Fatalf("status after rejected write = %q, want running", status)
+ }
+ })
+
+ t.Run("task message input JSONB", func(t *testing.T) {
+ raw, err := json.Marshal(map[string]any{
+ "result": map[string]any{"stdout": "ELF\x00binary"},
+ })
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if _, err := testHandler.Queries.CreateTaskMessage(ctx, db.CreateTaskMessageParams{
+ TaskID: util.MustParseUUID(taskID),
+ Seq: 99,
+ Type: "tool_use",
+ Input: raw,
+ }); err == nil {
+ t.Fatal("PostgreSQL accepted nested JSONB containing a NUL escape")
+ }
+ })
+
+ t.Run("task message type TEXT", func(t *testing.T) {
+ if _, err := testHandler.Queries.CreateTaskMessage(ctx, db.CreateTaskMessageParams{
+ TaskID: util.MustParseUUID(taskID),
+ Seq: 98,
+ Type: "tool_use\x00",
+ }); err == nil {
+ t.Fatal("PostgreSQL accepted a TEXT value containing a NUL")
+ }
+ })
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 2f3cc5771a..c92248d31f 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2351,6 +2351,13 @@ func (s *TaskService) CancelTaskWithReason(ctx context.Context, taskID pgtype.UU
// CancelTaskWithResult cancels a single task and returns any chat-specific
// cleanup result needed by user-facing callers.
func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUID, opts CancelTaskOptions) (*CancelTaskResult, error) {
+ // Both fields are persisted onto the cancelled row's TEXT columns below, and
+ // at least one caller interpolates an externally-supplied path into
+ // ErrorMessage. A NUL in either rolls the cancellation back and leaves the
+ // task running — the same wedge as GH #7098 on the fail/complete paths.
+ opts.ErrorMessage = util.SanitizeTextForPostgres(opts.ErrorMessage)
+ opts.FailureReason = util.SanitizeTextForPostgres(opts.FailureReason)
+
var (
task db.AgentTaskQueue
cancelledChatMessage *CancelledChatMessageResult
@@ -3945,10 +3952,6 @@ func (s *TaskService) observeChatOutputLocalPath(task db.AgentTaskQueue, body st
)
}
-func normalizeTaskFailureDiagnostic(errMsg string) string {
- return strings.ReplaceAll(strings.ToValidUTF8(errMsg, "\uFFFD"), "\x00", "")
-}
-
// FailTask marks a task as failed.
// Issue status is NOT changed here — the agent manages it via the CLI.
//
@@ -3966,7 +3969,12 @@ func normalizeTaskFailureDiagnostic(errMsg string) string {
// (via classifyPoisonedError, the timeout / runtime classifier, etc.)
// will have their value preserved untouched.
func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID string) (*db.AgentTaskQueue, error) {
- errMsg = normalizeTaskFailureDiagnostic(errMsg)
+ // Strip bytes PostgreSQL cannot store before anything else reads errMsg, so
+ // the classifier, the transaction and every downstream consumer see the one
+ // text we will actually persist (GH #7098). Kept at the service boundary
+ // rather than only in the /fail handler because failClaimedTaskBeforeLaunch
+ // reaches FailTask without going through request decoding.
+ errMsg = util.SanitizeTextForPostgres(errMsg)
// MUL-2946: synthesise a refined reason from the error text whenever the
// caller didn't supply one. This is the last write-path guard against
diff --git a/server/internal/service/task_failure_diagnostic_test.go b/server/internal/service/task_failure_diagnostic_test.go
index be9e785c0c..5349a306d4 100644
--- a/server/internal/service/task_failure_diagnostic_test.go
+++ b/server/internal/service/task_failure_diagnostic_test.go
@@ -10,43 +10,6 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-func TestNormalizeTaskFailureDiagnostic(t *testing.T) {
- tests := []struct {
- name string
- diagnostic string
- want string
- }{
- {
- name: "valid UTF-8 is unchanged",
- diagnostic: "worker 失败:诊断详情",
- want: "worker 失败:诊断详情",
- },
- {
- name: "embedded NUL is removed",
- diagnostic: "worker failed\x00 diagnostic details",
- want: "worker failed diagnostic details",
- },
- {
- name: "invalid UTF-8 is replaced",
- diagnostic: string([]byte{'b', 'a', 'd', 0xff, 't', 'e', 'x', 't'}),
- want: "bad\uFFFDtext",
- },
- {
- name: "only NUL becomes empty",
- diagnostic: "\x00\x00",
- want: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := normalizeTaskFailureDiagnostic(tt.diagnostic); got != tt.want {
- t.Fatalf("normalizeTaskFailureDiagnostic() = %q, want %q", got, tt.want)
- }
- })
- }
-}
-
func TestFailTaskSanitizesNULDiagnostic(t *testing.T) {
pool := newResolveOriginatorPool(t)
ctx := context.Background()
diff --git a/server/internal/util/text.go b/server/internal/util/text.go
index 00be979a70..ce89ac7767 100644
--- a/server/internal/util/text.go
+++ b/server/internal/util/text.go
@@ -1,6 +1,9 @@
package util
-import "strings"
+import (
+ "strings"
+ "unicode/utf8"
+)
// UnescapeBackslashEscapes decodes the common backslash escape sequences
// (\n, \r, \t, \\) that LLM agents routinely emit as 4-character literals
@@ -46,3 +49,78 @@ func UnescapeBackslashEscapes(s string) string {
}
return b.String()
}
+
+// sanitizeJSONMaxDepth bounds SanitizeJSONForPostgres's recursion. Task tool
+// input is a handful of levels deep in practice; anything past this is either
+// pathological or hostile, and is dropped rather than walked so a deeply
+// nested payload cannot turn a persistence guard into a stack overflow.
+const sanitizeJSONMaxDepth = 32
+
+// SanitizeTextForPostgres makes an arbitrary externally-produced string safe to
+// persist in a PostgreSQL TEXT or JSONB column.
+//
+// Two distinct failure modes, either of which aborts the entire INSERT and
+// rolls the surrounding transaction back:
+//
+// - Embedded NUL (0x00). PostgreSQL rejects it in TEXT with SQLSTATE 22021
+// ("invalid byte sequence for encoding UTF8"), and in JSONB with 22P05
+// ("unsupported Unicode escape sequence") once encoding/json has escaped it.
+// Removed outright: it has no useful rendering, and the caller wants the
+// surrounding diagnostic far more than it wants an invisible byte.
+// - Any other invalid UTF-8 byte sequence — a byte-bounded tail that cut a
+// multi-byte rune in half, a Windows-1252 smart quote, raw binary from a
+// child process that crashed. Replaced with U+FFFD so the text keeps its
+// shape and a reader can see that something was there.
+//
+// IMPORTANT: strings.ToValidUTF8 alone does NOT cover the NUL case — 0x00 is a
+// perfectly valid UTF-8 encoding of U+0000, so it passes through untouched.
+// The explicit ReplaceAll is load-bearing. Do not "simplify" it away; that is
+// exactly the gap that let GH #7098 wedge tasks in 'running'.
+func SanitizeTextForPostgres(s string) string {
+ // Overwhelmingly the common case: leave ordinary text completely alone.
+ if !strings.ContainsRune(s, 0) && utf8.ValidString(s) {
+ return s
+ }
+ return strings.ReplaceAll(strings.ToValidUTF8(s, "\uFFFD"), "\x00", "")
+}
+
+// SanitizeJSONForPostgres walks a decoded JSON value — the `any` tree
+// encoding/json produces — and applies SanitizeTextForPostgres to every string
+// inside it, object keys included: a poisoned key breaks the INSERT exactly
+// like a poisoned value does.
+//
+// This exists because sanitizing only the top-level string fields of a request
+// is not enough when one of those fields is itself a JSONB blob (agent tool
+// input, for instance), where the offending byte can sit at any depth.
+//
+// Subtrees deeper than sanitizeJSONMaxDepth are replaced with nil rather than
+// walked. That is a deliberate, bounded loss: the alternative is letting an
+// adversarial payload dictate our recursion depth.
+func SanitizeJSONForPostgres(v any) any {
+ return sanitizeJSONValue(v, 0)
+}
+
+func sanitizeJSONValue(v any, depth int) any {
+ if depth > sanitizeJSONMaxDepth {
+ return nil
+ }
+ switch t := v.(type) {
+ case string:
+ return SanitizeTextForPostgres(t)
+ case map[string]any:
+ out := make(map[string]any, len(t))
+ for k, val := range t {
+ out[SanitizeTextForPostgres(k)] = sanitizeJSONValue(val, depth+1)
+ }
+ return out
+ case []any:
+ out := make([]any, len(t))
+ for i, val := range t {
+ out[i] = sanitizeJSONValue(val, depth+1)
+ }
+ return out
+ default:
+ // Numbers, bools, nil — nothing a TEXT/JSONB column can choke on.
+ return v
+ }
+}
diff --git a/server/internal/util/text_postgres_test.go b/server/internal/util/text_postgres_test.go
new file mode 100644
index 0000000000..acd7c6722a
--- /dev/null
+++ b/server/internal/util/text_postgres_test.go
@@ -0,0 +1,155 @@
+package util
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestSanitizeTextForPostgres(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want string
+ }{
+ {
+ name: "ordinary text is returned unchanged",
+ in: "worker failed: connection refused",
+ want: "worker failed: connection refused",
+ },
+ {
+ name: "multi-byte text is returned unchanged",
+ in: "任务失败:诊断详情",
+ want: "任务失败:诊断详情",
+ },
+ {
+ name: "embedded NUL is removed and surrounding text kept",
+ in: "worker failed\x00 diagnostic details",
+ want: "worker failed diagnostic details",
+ },
+ {
+ name: "UTF-16-shaped run of NULs is removed",
+ in: "w\x00o\x00r\x00k\x00e\x00r\x00",
+ want: "worker",
+ },
+ {
+ name: "a string of only NULs collapses to empty",
+ in: "\x00\x00\x00",
+ want: "",
+ },
+ {
+ name: "invalid UTF-8 becomes U+FFFD rather than vanishing",
+ in: string([]byte{'b', 'a', 'd', 0xff, 'b', 'y', 't', 'e'}),
+ want: "bad\uFFFDbyte",
+ },
+ {
+ name: "NUL removal and UTF-8 repair compose",
+ in: string([]byte{'a', 0x00, 'b', 0xff, 'c'}),
+ want: "ab\uFFFDc",
+ },
+ {
+ name: "empty stays empty",
+ in: "",
+ want: "",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := SanitizeTextForPostgres(tt.in); got != tt.want {
+ t.Fatalf("SanitizeTextForPostgres(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestSanitizeTextForPostgresToValidUTF8IsNotEnough pins the single fact this
+// whole guard rests on: NUL is VALID UTF-8, so the strings.ToValidUTF8 call on
+// its own lets it straight through to the database. If someone ever
+// "simplifies" SanitizeTextForPostgres down to just ToValidUTF8, this test is
+// what tells them they have reopened GH #7098.
+func TestSanitizeTextForPostgresToValidUTF8IsNotEnough(t *testing.T) {
+ poisoned := "worker failed\x00 diagnostic"
+
+ if !strings.ContainsRune(strings.ToValidUTF8(poisoned, "\uFFFD"), 0) {
+ t.Fatal("premise broken: strings.ToValidUTF8 now strips NUL on its own")
+ }
+ if strings.ContainsRune(SanitizeTextForPostgres(poisoned), 0) {
+ t.Fatal("SanitizeTextForPostgres left a NUL behind")
+ }
+}
+
+func TestSanitizeJSONForPostgres(t *testing.T) {
+ t.Run("cleans strings at every depth, keys included", func(t *testing.T) {
+ in := map[string]any{
+ "cmd\x00": "cat\x00 binary",
+ "args": []any{"-n\x00", "1"},
+ "nested": map[string]any{
+ "deep": []any{map[string]any{"k": "v\x00"}},
+ },
+ "count": float64(3),
+ "ok": true,
+ "null": nil,
+ }
+
+ out, ok := SanitizeJSONForPostgres(in).(map[string]any)
+ if !ok {
+ t.Fatalf("SanitizeJSONForPostgres returned %T, want map[string]any", SanitizeJSONForPostgres(in))
+ }
+
+ encoded, err := json.Marshal(out)
+ if err != nil {
+ t.Fatalf("marshal sanitized value: %v", err)
+ }
+ // The marshalled form is what actually reaches the JSONB column, so
+ // assert on that: encoding/json renders a surviving NUL as an escape,
+ // which is precisely what PostgreSQL rejects with SQLSTATE 22P05.
+ if strings.Contains(string(encoded), "\\u0000") {
+ t.Fatalf("sanitized JSON still carries a NUL escape: %s", encoded)
+ }
+
+ if _, exists := out["cmd"]; !exists {
+ t.Fatalf("poisoned key was not cleaned: %v", out)
+ }
+ if got := out["cmd"]; got != "cat binary" {
+ t.Fatalf("out[cmd] = %v, want %q", got, "cat binary")
+ }
+ if got := out["count"]; got != float64(3) {
+ t.Fatalf("non-string value was mutated: %v", got)
+ }
+ if got := out["ok"]; got != true {
+ t.Fatalf("bool value was mutated: %v", got)
+ }
+ if got, exists := out["null"]; !exists || got != nil {
+ t.Fatalf("null value was mutated: %v", got)
+ }
+ })
+
+ t.Run("stops at the depth limit instead of recursing forever", func(t *testing.T) {
+ // Build a chain deeper than the cap. The point is that this returns at
+ // all rather than blowing the stack on a hostile payload.
+ var deep any = "leaf\x00"
+ for i := 0; i < sanitizeJSONMaxDepth+10; i++ {
+ deep = map[string]any{"next": deep}
+ }
+
+ out := SanitizeJSONForPostgres(deep)
+
+ encoded, err := json.Marshal(out)
+ if err != nil {
+ t.Fatalf("marshal deep value: %v", err)
+ }
+ if strings.Contains(string(encoded), "\\u0000") {
+ t.Fatalf("deep payload still carries a NUL escape: %s", encoded)
+ }
+ })
+
+ t.Run("scalars pass through", func(t *testing.T) {
+ if got := SanitizeJSONForPostgres("plain"); got != "plain" {
+ t.Fatalf("got %v, want plain", got)
+ }
+ if got := SanitizeJSONForPostgres(nil); got != nil {
+ t.Fatalf("got %v, want nil", got)
+ }
+ })
+}