Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6523: persist task message batches in one statement (#7377)
Multica Eve115bfab7592a
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 9f7622653c..91c09b205b 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -4426,36 +4426,51 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {return}- // Verify the caller owns this task's workspace.- task, ok := h.requireDaemonTaskAccess(w, r, taskID)+ // Verify the caller owns this task's workspace. The access check already+ // resolves the workspace id (it needs it to authorize the daemon), so take+ // it from there instead of re-running GetIssue / GetChatSession: this+ // endpoint fires every 500ms for every running task, and that second+ // lookup was a whole extra query per batch on the hottest write path in+ // the system (MUL-6523).+ task, wsID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)if !ok {return}+ // Broadcast reach is deliberately unchanged: only issue- and chat-backed+ // tasks streamed live messages before, and widening that to autopilot /+ // quick-create tasks is a product decision, not part of this optimization.workspaceID := ""- if task.IssueID.Valid {- if issue, err := h.Queries.GetIssue(r.Context(), task.IssueID); err == nil {- workspaceID = uuidToString(issue.WorkspaceID)- }- }- if workspaceID == "" && task.ChatSessionID.Valid {- if cs, err := h.Queries.GetChatSession(r.Context(), task.ChatSessionID); err == nil {- workspaceID = uuidToString(cs.WorkspaceID)- }- }-- messageIDs := make([]pgtype.UUID, len(req.Messages))- for i := range messageIDs {+ if task.IssueID.Valid || task.ChatSessionID.Valid {+ workspaceID = wsID+ }++ // Column-wise parameters for the single batch insert below. Building them+ // as parallel arrays rather than as one JSON document is deliberate: these+ // strings were just decoded out of the request, and re-encoding content /+ // output into JSON would make the server escape every byte a second time+ // and Postgres parse the envelope back out — measurably worse on exactly+ // the large messages that are already the most expensive (MUL-6523). Empty+ // string means SQL NULL, applied by the query's NULLIF.+ n := len(req.Messages)+ params := db.CreateTaskMessagesParams{+ TaskID: parseUUID(taskID),+ Ids: make([]pgtype.UUID, 0, n),+ Seqs: make([]int32, 0, n),+ Types: make([]string, 0, n),+ Tools: make([]string, 0, n),+ Contents: make([]string, 0, n),+ Inputs: make([]string, 0, n),+ Outputs: make([]string, 0, n),+ }+ for _, msg := range req.Messages {id, err := uuid.NewV7()if err != nil {slog.Error("failed to generate task message id", "task_id", taskID, "error", err)writeError(w, http.StatusInternalServerError, "failed to persist task message")return}- messageIDs[i] = pgtype.UUID{Bytes: [16]byte(id), Valid: true}- }- for i, msg := range req.Messages {// Redact sensitive information before persisting or broadcasting.msg.Content = redact.Text(msg.Content)msg.Output = redact.Text(msg.Output)@@ -4467,7 +4482,9 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {// 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.+ // offending byte can sit at any depth of a tool's arguments. Batching+ // raises the stakes: one bad byte now fails the whole statement rather+ // than a single row, which is inherent to one-statement writes.msg.Type = util.SanitizeTextForPostgres(msg.Type)msg.Tool = util.SanitizeTextForPostgres(msg.Tool)msg.Content = util.SanitizeTextForPostgres(msg.Content)@@ -4478,29 +4495,50 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {}}- var inputJSON []byte+ inputJSON := ""if msg.Input != nil {- inputJSON, _ = json.Marshal(msg.Input)- }- created, createErr := h.Queries.CreateTaskMessage(r.Context(), db.CreateTaskMessageParams{- ID: messageIDs[i],- TaskID: parseUUID(taskID),- Seq: int32(msg.Seq),- Type: msg.Type,- Tool: pgtype.Text{String: msg.Tool, Valid: msg.Tool != ""},- Content: pgtype.Text{String: msg.Content, Valid: msg.Content != ""},- Input: inputJSON,- Output: pgtype.Text{String: msg.Output, Valid: msg.Output != ""},- })- if createErr != nil {- slog.Error("failed to create task message", "task_id", taskID, "seq", msg.Seq, "error", createErr)- writeError(w, http.StatusInternalServerError, "failed to persist task message")- return+ // Fail loud rather than dropping the field: a tool call whose+ // arguments silently vanish is worse than a 500 the daemon logs,+ // because the transcript then shows a tool_use with no input and+ // nothing anywhere records that it was lost.+ encoded, err := json.Marshal(msg.Input)+ if err != nil {+ slog.Error("failed to encode task message input", "task_id", taskID, "seq", msg.Seq, "error", err)+ writeError(w, http.StatusInternalServerError, "failed to persist task message")+ return+ }+ inputJSON = string(encoded)}- if workspaceID != "" {+ params.Ids = append(params.Ids, pgtype.UUID{Bytes: [16]byte(id), Valid: true})+ params.Seqs = append(params.Seqs, int32(msg.Seq))+ params.Types = append(params.Types, msg.Type)+ params.Tools = append(params.Tools, msg.Tool)+ params.Contents = append(params.Contents, msg.Content)+ params.Inputs = append(params.Inputs, inputJSON)+ params.Outputs = append(params.Outputs, msg.Output)+ }++ created, err := h.Queries.CreateTaskMessages(r.Context(), params)+ if err != nil {+ slog.Error("failed to create task messages", "task_id", taskID, "count", n, "error", err)+ writeError(w, http.StatusInternalServerError, "failed to persist task message")+ return+ }++ if workspaceID != "" {+ // CreateTaskMessages orders its result by seq, which is the daemon's+ // own within-batch ordering — so this publishes in the same order the+ // per-message loop did. A bare INSERT ... RETURNING has no row-order+ // guarantee, and subscribers render these events as they arrive, so the+ // ordering lives in the query rather than in the clients.+ for _, m := range created {+ // The ordered CTE makes sqlc name the row type after the query+ // rather than reusing the table model; the columns are the table's,+ // in order, so the conversion is checked by the compiler and breaks+ // loudly if the query ever stops returning the whole row.h.publishTask(protocol.EventTaskMessage, workspaceID, "system", "", taskID,- taskMessageToPayload(created, taskID, uuidToString(task.IssueID)))+ taskMessageToPayload(db.TaskMessage(m), taskID, uuidToString(task.IssueID)))}}diff --git a/server/internal/handler/task_message_batch_test.go b/server/internal/handler/task_message_batch_test.gonew file mode 100644index 0000000000..536f6f0aa3--- /dev/null+++ b/server/internal/handler/task_message_batch_test.go@@ -0,0 +1,220 @@+package handler++import (+ "context"+ "net/http"+ "sync"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+ "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"+)++// seedBatchTask builds the running, issue-backed task the /messages endpoint+// needs: requireDaemonTaskAccess resolves the workspace through the issue, and a+// task with no issue / chat / autopilot link 404s before the body is read.+func seedBatchTask(t *testing.T, label string) string {+ t.Helper()+ agentID := dbfx.Agent(t, label+" agent", handlerTestRuntimeID(t), testutil.Cols{+ "instructions": "",+ "custom_env": testutil.Raw("'{}'::jsonb"),+ "custom_args": testutil.Raw("'[]'::jsonb"),+ })+ issueID := dbfx.Issue(t, label+" fixture", testutil.Cols{"status": "in_progress"})+ return dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": handlerTestRuntimeID(t),+ "issue_id": issueID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })+}++// batchMessagesRequest builds the daemon-authenticated POST the daemon sends,+// with taskId bound as a chi URL param the way the router does in production.+func batchMessagesRequest(t *testing.T, taskID string, messages []any) *http.Request {+ t.Helper()+ req := testutil.JSONRequest(http.MethodPost,+ "/api/daemon/tasks/"+taskID+"/messages", map[string]any{"messages": messages})+ req = testutil.WithURLParams(req, "taskId", taskID)+ return req.WithContext(middleware.WithDaemonContext(+ req.Context(), testWorkspaceID, "batch-messages-daemon"))+}++// TestReportTaskMessagesPersistsWholeBatch covers the multi-message shape of the+// /messages endpoint after it stopped issuing one INSERT per message. The row+// count, the seq values, and the NULL/non-NULL split all have to survive the+// jsonb round trip CreateTaskMessages does: a tool event carries tool + input ++// output, a text event carries only content, and everything the daemon omitted+// must land as SQL NULL rather than an empty string.+func TestReportTaskMessagesPersistsWholeBatch(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ taskID := seedBatchTask(t, "batch-messages")++ testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{+ map[string]any{"seq": 1, "type": "thinking", "content": "planning"},+ map[string]any{+ "seq": 2,+ "type": "tool_use",+ "tool": "fs_read",+ "input": map[string]any{"path": "/etc/hosts", "nested": map[string]any{"depth": 2}},+ "output": "127.0.0.1 localhost",+ },+ map[string]any{"seq": 3, "type": "text", "content": "done"},+ })).Want(http.StatusOK)++ stored, err := testHandler.Queries.ListTaskMessages(ctx, util.MustParseUUID(taskID))+ if err != nil {+ t.Fatalf("list persisted task messages: %v", err)+ }+ if len(stored) != 3 {+ t.Fatalf("persisted %d task messages, want 3", len(stored))+ }+ for i, want := range []int32{1, 2, 3} {+ if stored[i].Seq != want {+ t.Fatalf("row %d seq = %d, want %d", i, stored[i].Seq, want)+ }+ }++ if stored[0].Type != "thinking" || stored[0].Content.String != "planning" {+ t.Fatalf("thinking row = %+v, want type=thinking content=planning", stored[0])+ }+ // Fields the daemon did not send must be NULL, not "".+ if stored[0].Tool.Valid || stored[0].Output.Valid || stored[0].Input != nil {+ t.Fatalf("thinking row should have NULL tool/output/input, got %+v", stored[0])+ }+ if stored[1].Tool.String != "fs_read" {+ t.Fatalf("tool_use row tool = %q, want fs_read", stored[1].Tool.String)+ }+ if stored[1].Output.String != "127.0.0.1 localhost" {+ t.Fatalf("tool_use row output = %q", stored[1].Output.String)+ }+ if stored[1].Content.Valid {+ t.Fatalf("tool_use row content should be NULL, got %q", stored[1].Content.String)+ }+ // The jsonb argument must arrive as an object, not as a string holding JSON,+ // or `input->>'path'` stops resolving for every consumer of this column.+ var inputPath string+ dbfx.QueryRow(t,+ `SELECT input->>'path' FROM task_message WHERE task_id = $1 AND seq = 2`,+ taskID).Scan(&inputPath)+ if inputPath != "/etc/hosts" {+ t.Fatalf("input->>path = %q, want /etc/hosts", inputPath)+ }+ if stored[2].Type != "text" || stored[2].Content.String != "done" {+ t.Fatalf("text row = %+v, want type=text content=done", stored[2])+ }+}++// TestReportTaskMessagesPublishesInSeqOrder pins the realtime ordering the batch+// insert has to preserve. The per-message loop it replaced published in request+// order; `INSERT ... RETURNING` has no row-order guarantee, so the order now+// comes from CreateTaskMessages' ORDER BY seq. Subscribers render these events+// as they arrive, so an out-of-order batch is a visible transcript bug.+//+// The request deliberately lists the messages out of seq order: if the ORDER BY+// were dropped, the events would come back in array order and this fails. That+// also makes seq — the daemon's own counter — the single ordering authority,+// rather than however the rows happen to land.+func TestReportTaskMessagesPublishesInSeqOrder(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ taskID := seedBatchTask(t, "batch-order")++ // The shared bus has no unsubscribe, so a listener registered on it would+ // outlive this test and keep firing for the rest of the package. Swap in a+ // bus of this test's own and put the shared one back afterwards.+ sharedBus := testHandler.Bus+ testHandler.Bus = events.New()+ t.Cleanup(func() { testHandler.Bus = sharedBus })++ var mu sync.Mutex+ var gotSeqs []int+ testHandler.Bus.Subscribe(protocol.EventTaskMessage, func(e events.Event) {+ mu.Lock()+ defer mu.Unlock()+ if e.TaskID != taskID {+ return+ }+ if payload, ok := e.Payload.(protocol.TaskMessagePayload); ok {+ gotSeqs = append(gotSeqs, payload.Seq)+ }+ })++ testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{+ map[string]any{"seq": 3, "type": "text", "content": "third"},+ map[string]any{"seq": 1, "type": "text", "content": "first"},+ map[string]any{"seq": 2, "type": "text", "content": "second"},+ })).Want(http.StatusOK)++ mu.Lock()+ defer mu.Unlock()+ want := []int{1, 2, 3}+ if len(gotSeqs) != len(want) {+ t.Fatalf("published %v task:message events, want seqs %v", gotSeqs, want)+ }+ for i := range want {+ if gotSeqs[i] != want[i] {+ t.Fatalf("published seq order = %v, want %v — subscribers render these "++ "events in arrival order, so the transcript would show the batch scrambled",+ gotSeqs, want)+ }+ }+}++// TestCreateTaskMessagesBatchIsAtomic exercises the production query, not a copy+// of it: a batch that violates the primary key must persist nothing. This is the+// property the single statement buys over the per-message loop, which could+// leave a prefix of the batch behind and no way to complete it (the daemon does+// not retry this endpoint).+//+// Note what this does and does not guarantee: the batch is consistent, not+// complete. A failing batch is now lost whole. Closing that gap needs a retry+// plus a (task_id, seq) uniqueness rule, which is not part of this change.+func TestCreateTaskMessagesBatchIsAtomic(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ taskID := seedBatchTask(t, "batch-atomic")++ // The colliding row is built as a fixture, not through the query under+ // test: test setup that shares code with the code being exercised can pass+ // for the wrong reason.+ const dupID = "018f0000-0000-7000-8000-000000000001"+ dbfx.Insert(t, "task_message", testutil.Cols{+ "id": dupID,+ "task_id": taskID,+ "seq": 1,+ "type": "text",+ "content": "first",+ })++ _, err := testHandler.Queries.CreateTaskMessages(ctx, db.CreateTaskMessagesParams{+ TaskID: util.MustParseUUID(taskID),+ Ids: []pgtype.UUID{util.MustParseUUID("018f0000-0000-7000-8000-000000000002"), util.MustParseUUID(dupID)},+ Seqs: []int32{2, 3},+ Types: []string{"text", "text"},+ Tools: []string{"", ""},+ Contents: []string{"ok", "collides"},+ Inputs: []string{"", ""},+ Outputs: []string{"", ""},+ })+ if err == nil {+ t.Fatal("CreateTaskMessages accepted a batch with a duplicate primary key")+ }++ count := dbfx.Count(t, `SELECT COUNT(*) FROM task_message WHERE task_id = $1`, taskID)+ if count != 1 {+ t.Fatalf("task_message rows after the failed batch = %d, want 1 (only the seeded row) — "++ "the batch persisted a prefix instead of rolling back", count)+ }+}diff --git a/server/pkg/db/generated/task_message.sql.go b/server/pkg/db/generated/task_message.sql.goindex 4e37f1224f..89ce8c3053 100644--- a/server/pkg/db/generated/task_message.sql.go+++ b/server/pkg/db/generated/task_message.sql.go@@ -54,6 +54,139 @@ func (q *Queries) CreateTaskMessage(ctx context.Context, arg CreateTaskMessagePareturn i, err}+const createTaskMessages = `-- name: CreateTaskMessages :many+WITH incoming AS (+ -- Several single-argument unnest calls in one SELECT list expand in+ -- lockstep (PostgreSQL 10+ set-returning-function semantics), which is the+ -- same row-wise zip the multi-argument unnest(a, b, ...) form gives — but+ -- sqlc's analyzer only knows the single-argument signature, so this is the+ -- shape that survives code generation.+ SELECT+ unnest($1::uuid[]) AS id,+ unnest($2::int4[]) AS seq,+ unnest($3::text[]) AS type,+ unnest($4::text[]) AS tool,+ unnest($5::text[]) AS content,+ unnest($6::text[]) AS input,+ unnest($7::text[]) AS output+), inserted AS (+ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output)+ SELECT+ m.id,+ $8::uuid,+ m.seq,+ m.type,+ NULLIF(m.tool, ''),+ NULLIF(m.content, ''),+ NULLIF(m.input, '')::jsonb,+ NULLIF(m.output, '')+ FROM incoming AS m+ RETURNING id, task_id, seq, type, tool, content, input, output, created_at+)+SELECT id, task_id, seq, type, tool, content, input, output, created_at FROM inserted ORDER BY seq ASC+`++type CreateTaskMessagesParams struct {+ Ids []pgtype.UUID `json:"ids"`+ Seqs []int32 `json:"seqs"`+ Types []string `json:"types"`+ Tools []string `json:"tools"`+ Contents []string `json:"contents"`+ Inputs []string `json:"inputs"`+ Outputs []string `json:"outputs"`+ TaskID pgtype.UUID `json:"task_id"`+}++type CreateTaskMessagesRow struct {+ ID pgtype.UUID `json:"id"`+ TaskID pgtype.UUID `json:"task_id"`+ Seq int32 `json:"seq"`+ Type string `json:"type"`+ Tool pgtype.Text `json:"tool"`+ Content pgtype.Text `json:"content"`+ Input []byte `json:"input"`+ Output pgtype.Text `json:"output"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++// Batch variant of CreateTaskMessage: persists a whole daemon-reported batch in+// ONE statement — therefore one round trip and, more importantly, one commit+// instead of one per message. Commit acknowledgement (IO:XactSync) is ~94% of+// this SQL's load in production, so the commit count is the thing being+// optimized; the round trip is a bonus.+//+// The rows arrive as parallel arrays rather than as one jsonb document, even+// though a jsonb document is the tidier Go side. content and output routinely+// carry tens of KB and occasionally megabytes, and wrapping them in JSON makes+// the server escape every byte a second time and Postgres parse the whole+// envelope back out — measured at 1.2x the old per-row insert at 128KB and+// ~1.8x at 1MB, i.e. a regression on exactly the most expensive requests, which+// are also the ones least likely to be batched. Native text[] elements are+// length-prefixed by the wire protocol, so they cost neither pass.+//+// NULLIF is what makes per-row NULL expressible through a non-nullable []string+// (the Go type sqlc gives a text[] parameter): it reproduces, exactly, the+// `pgtype.Text{Valid: x != ""}` mapping the single-row query carries — empty+// string means SQL NULL. input is passed as text and cast here for the same+// reason; it is the one column that genuinely has to be parsed as JSON, because+// it is a jsonb column.+//+// Callers MUST still run the Postgres text sanitizer first. A NUL anywhere in+// the batch fails the whole statement (GH #7098) — that is inherent to batching+// into one statement, not to the parameter shape.+//+// Atomicity is a deliberate side effect, not just a speedup: the per-message+// loop this replaces could persist part of a batch and then fail, leaving the+// transcript with a prefix of the batch and no way to complete it — the daemon+// does not retry this endpoint. One statement makes the batch all-or-nothing,+// which buys consistency; a batch that fails is still lost whole, so closing+// the gap for real needs a retry plus a (task_id, seq) uniqueness rule.+//+// The ORDER BY is a contract, not decoration. A bare `INSERT ... RETURNING`+// has no defined row order, and the caller republishes these rows as realtime+// events in the order they arrive — the per-row loop this replaces implicitly+// published in request order, so the ordering has to be restored explicitly or+// subscribers can see a batch out of order. seq is assigned by the daemon and+// increases within a batch, so it is the request order.+func (q *Queries) CreateTaskMessages(ctx context.Context, arg CreateTaskMessagesParams) ([]CreateTaskMessagesRow, error) {+ rows, err := q.db.Query(ctx, createTaskMessages,+ arg.Ids,+ arg.Seqs,+ arg.Types,+ arg.Tools,+ arg.Contents,+ arg.Inputs,+ arg.Outputs,+ arg.TaskID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []CreateTaskMessagesRow{}+ for rows.Next() {+ var i CreateTaskMessagesRow+ if err := rows.Scan(+ &i.ID,+ &i.TaskID,+ &i.Seq,+ &i.Type,+ &i.Tool,+ &i.Content,+ &i.Input,+ &i.Output,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const deleteTaskMessages = `-- name: DeleteTaskMessages :execDELETE FROM task_messageWHERE task_id = $1diff --git a/server/pkg/db/queries/task_message.sql b/server/pkg/db/queries/task_message.sqlindex 368958dfdb..b664c2ac91 100644--- a/server/pkg/db/queries/task_message.sql+++ b/server/pkg/db/queries/task_message.sql@@ -3,6 +3,76 @@ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output)VALUES ($1, $2, $3, $4, $5, $6, $7, $8)RETURNING *;+-- name: CreateTaskMessages :many+-- Batch variant of CreateTaskMessage: persists a whole daemon-reported batch in+-- ONE statement — therefore one round trip and, more importantly, one commit+-- instead of one per message. Commit acknowledgement (IO:XactSync) is ~94% of+-- this SQL's load in production, so the commit count is the thing being+-- optimized; the round trip is a bonus.+--+-- The rows arrive as parallel arrays rather than as one jsonb document, even+-- though a jsonb document is the tidier Go side. content and output routinely+-- carry tens of KB and occasionally megabytes, and wrapping them in JSON makes+-- the server escape every byte a second time and Postgres parse the whole+-- envelope back out — measured at 1.2x the old per-row insert at 128KB and+-- ~1.8x at 1MB, i.e. a regression on exactly the most expensive requests, which+-- are also the ones least likely to be batched. Native text[] elements are+-- length-prefixed by the wire protocol, so they cost neither pass.+--+-- NULLIF is what makes per-row NULL expressible through a non-nullable []string+-- (the Go type sqlc gives a text[] parameter): it reproduces, exactly, the+-- `pgtype.Text{Valid: x != ""}` mapping the single-row query carries — empty+-- string means SQL NULL. input is passed as text and cast here for the same+-- reason; it is the one column that genuinely has to be parsed as JSON, because+-- it is a jsonb column.+--+-- Callers MUST still run the Postgres text sanitizer first. A NUL anywhere in+-- the batch fails the whole statement (GH #7098) — that is inherent to batching+-- into one statement, not to the parameter shape.+--+-- Atomicity is a deliberate side effect, not just a speedup: the per-message+-- loop this replaces could persist part of a batch and then fail, leaving the+-- transcript with a prefix of the batch and no way to complete it — the daemon+-- does not retry this endpoint. One statement makes the batch all-or-nothing,+-- which buys consistency; a batch that fails is still lost whole, so closing+-- the gap for real needs a retry plus a (task_id, seq) uniqueness rule.+--+-- The ORDER BY is a contract, not decoration. A bare `INSERT ... RETURNING`+-- has no defined row order, and the caller republishes these rows as realtime+-- events in the order they arrive — the per-row loop this replaces implicitly+-- published in request order, so the ordering has to be restored explicitly or+-- subscribers can see a batch out of order. seq is assigned by the daemon and+-- increases within a batch, so it is the request order.+WITH incoming AS (+ -- Several single-argument unnest calls in one SELECT list expand in+ -- lockstep (PostgreSQL 10+ set-returning-function semantics), which is the+ -- same row-wise zip the multi-argument unnest(a, b, ...) form gives — but+ -- sqlc's analyzer only knows the single-argument signature, so this is the+ -- shape that survives code generation.+ SELECT+ unnest(sqlc.arg('ids')::uuid[]) AS id,+ unnest(sqlc.arg('seqs')::int4[]) AS seq,+ unnest(sqlc.arg('types')::text[]) AS type,+ unnest(sqlc.arg('tools')::text[]) AS tool,+ unnest(sqlc.arg('contents')::text[]) AS content,+ unnest(sqlc.arg('inputs')::text[]) AS input,+ unnest(sqlc.arg('outputs')::text[]) AS output+), inserted AS (+ INSERT INTO task_message (id, task_id, seq, type, tool, content, input, output)+ SELECT+ m.id,+ sqlc.arg('task_id')::uuid,+ m.seq,+ m.type,+ NULLIF(m.tool, ''),+ NULLIF(m.content, ''),+ NULLIF(m.input, '')::jsonb,+ NULLIF(m.output, '')+ FROM incoming AS m+ RETURNING *+)+SELECT * FROM inserted ORDER BY seq ASC;+-- name: ListTaskMessages :manySELECT * FROM task_messageWHERE task_id = $1