Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(chat): a predecessor's reply must not seal the next message out of its own batch (#6611)
Xichang(Seacen) Zhaof3a7fce8d8e7
diff --git a/server/internal/handler/chat_channel_debounce_boundary_test.go b/server/internal/handler/chat_channel_debounce_boundary_test.gonew file mode 100644index 0000000000..72bbc07d7d--- /dev/null+++ b/server/internal/handler/chat_channel_debounce_boundary_test.go@@ -0,0 +1,146 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http/httptest"+ "testing"++ "github.com/go-chi/chi/v5"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// appendChannelUserMessage writes an inbound channel message the way+// ChatSession.AppendUserMessage does: durable, unowned, and stamped with the+// immutable channel_ingested provenance. The 3s debounced flush is what later+// creates the task and seals this row into its input batch.+func appendChannelUserMessage(t *testing.T, ctx context.Context, sessionID, body string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, channel_ingested)+ VALUES ($1, 'user', $2, TRUE)+ RETURNING id+ `, sessionID, body).Scan(&id); err != nil {+ t.Fatalf("append channel user message %q: %v", body, err)+ }+ return id+}++// flushChannelChatRun is the debounced run trigger: it creates the task and+// seals the session's waiting input batch into it, exactly as Router's batcher+// does when the silence window expires.+func flushChannelChatRun(t *testing.T, ctx context.Context, sessionID string) db.AgentTaskQueue {+ t.Helper()+ sess, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))+ if err != nil {+ t.Fatalf("load chat session: %v", err)+ }+ task, err := testHandler.TaskService.EnqueueChatTask(ctx, sess, parseUUID(testUserID), false)+ if err != nil {+ t.Fatalf("EnqueueChatTask: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID) })+ return task+}++// claimResult is a claim attempt that does not assume success, so a failing+// claim reports the status and body the daemon actually received.+type claimResult struct {+ code int+ body string+ task *claimRuntimeGuardTask+}++func claimTaskRaw(t *testing.T, runtimeID, daemonID string) claimResult {+ t.Helper()+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,+ testWorkspaceID, daemonID)+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("runtimeId", runtimeID)+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))++ testHandler.ClaimTaskByRuntime(w, req)+ out := claimResult{code: w.Code, body: w.Body.String()}+ if w.Code == 200 {+ var resp struct {+ Task *claimRuntimeGuardTask `json:"task"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode claim response: %v", err)+ }+ out.task = resp.Task+ }+ return out+}++// TestChannelChat_ReplyLandingInsideDebounceWindowStillAnswersTheNextMessage+// reproduces the lost turn seen on a self-hosted WeCom tenant, end to end.+//+// A message arrived while the previous agent turn was finishing:+//+// 18:31:17.7 chat_message "挺好的 正常了" -> task_id NULL, waiting out the 3s window+// 18:31:20.2 the previous task completes -> assistant row, NEWER than that message+// 18:31:20.7 the debounce fires -> task bdc0947e, chat_input_task_id = itself+// 18:31:20.7 ERR chat claim: task-owned direct task has no user input; cancelling+// task_id=bdc0947e chat_session_id=2fccd3c9 chat_input_task_id=bdc0947e+//+// In the database afterwards, that user row still had task_id = NULL while every+// other message in the session had one, and the task owned zero user messages.+// The user saw their message accepted, a task appear and vanish, and no reply.+//+// The batch seal skipped the message because a non-user row existed after it —+// but that row was the PREDECESSOR's reply to an already-sealed batch, not an+// answer to this message. The claim guard is correct to fail closed on an empty+// input batch; the batch should never have been empty.+func TestChannelChat_ReplyLandingInsideDebounceWindowStillAnswersTheNextMessage(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ _, sessionID, runtimeID, daemonID := setupDirectChatSession(t, ctx, "channel debounce boundary")++ // Turn 1: message in, window expires, task claimed and running.+ appendChannelUserMessage(t, ctx, sessionID, "测试下")+ first := flushChannelChatRun(t, ctx, sessionID)+ claimed := claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if claimed.ChatMessage != "测试下" {+ t.Fatalf("first claim delivered %q, want the first message", claimed.ChatMessage)+ }+ markTaskRunning(t, ctx, uuidToString(first.ID))++ // The user sends again while turn 1 is still running. The row is durable and+ // unowned; the batcher re-arms its 3s window.+ stranded := appendChannelUserMessage(t, ctx, sessionID, "挺好的 正常了")++ // Turn 1 finishes inside that window and writes its reply.+ if _, err := testHandler.TaskService.CompleteTask(ctx, first.ID, completeResult(t, "通了。"), "", "", false, ""); err != nil {+ t.Fatalf("complete turn 1: %v", err)+ }++ // The window expires and the next turn is created. The daemon must receive+ // the waiting message, rather than the claim cancelling the task for having+ // nothing to answer.+ next := flushChannelChatRun(t, ctx, sessionID)+ res := claimTaskRaw(t, runtimeID, daemonID)+ if res.code != 200 || res.task == nil || res.task.ChatMessage != "挺好的 正常了" {+ var status string+ var ownedInput int+ _ = testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, next.ID).Scan(&status)+ _ = testPool.QueryRow(ctx, `SELECT count(*) FROM chat_message WHERE task_id = $1 AND role = 'user'`,+ next.ID).Scan(&ownedInput)+ t.Fatalf("claim = %d %s (task %+v); task %s owns %d user messages and is now %q. "++ "The user's message was accepted and never answered.",+ res.code, res.body, res.task, uuidToString(next.ID), ownedInput, status)+ }++ // The waiting row belongs to that turn, not to nothing.+ var owner *string+ if err := testPool.QueryRow(ctx, `SELECT task_id::text FROM chat_message WHERE id = $1`, stranded).Scan(&owner); err != nil {+ t.Fatalf("load the waiting message: %v", err)+ }+ if owner == nil || *owner != uuidToString(next.ID) {+ t.Fatalf("waiting message task_id = %v, want the new turn %s", owner, uuidToString(next.ID))+ }+}diff --git a/server/internal/service/task_channel_seal_race_test.go b/server/internal/service/task_channel_seal_race_test.gonew file mode 100644index 0000000000..d5c689b6a3--- /dev/null+++ b/server/internal/service/task_channel_seal_race_test.go@@ -0,0 +1,270 @@+package service++import (+ "context"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestEnqueueChatTaskSealsMessageStrandedByPredecessorReply reproduces the+// lost-turn window observed on a self-hosted tenant:+//+// 18:31:17.7 the user's next message lands -> chat_message, task_id NULL+// 18:31:20.2 the PREVIOUS turn completes -> assistant row, newer than it+// 18:31:20.7 the 3s debounce fires -> EnqueueChatTask seals NOTHING+// 18:31:20.7 chat claim: task-owned direct task has no user input; cancelling+//+// The race is the debounce window itself: the message waits ~3s unowned, and+// whether it is ever answered depends on whether the predecessor's completion+// lands inside that wait. The two transactions cannot interleave more finely+// than this — CompleteTask takes chat_session FOR UPDATE and the task INSERT+// takes the FK's FOR KEY SHARE on the same row — so "predecessor commits, then+// the flush runs" IS the reachable interleaving, and it is what the tenant hit.+//+// The seal excluded the message because a non-user row existed after it, even+// though that row was the predecessor's reply to an OLDER, already-sealed+// batch. The new task then owned an empty input batch, and the claim guard+// cancelled it: the message was accepted and never answered.+func TestEnqueueChatTaskSealsMessageStrandedByPredecessorReply(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)+ chatSessionID := seedChannelChatSession(t, ctx, pool, workspaceID, agentID, userID)++ session := db.ChatSession{ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID)}+ initiator := util.MustParseUUID(userID)+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}++ // Turn 1: an inbound channel message lands unowned; the debounce fires and+ // EnqueueChatTask seals it into its own task, which then starts running.+ appendChannelUserMessage(t, ctx, pool, chatSessionID, "测试下")+ first, err := svc.EnqueueChatTask(ctx, session, initiator, false)+ if err != nil {+ t.Fatalf("EnqueueChatTask (turn 1): %v", err)+ }+ if got := sealedInputCount(t, ctx, pool, first.ID); got != 1 {+ t.Fatalf("turn 1 sealed %d user messages, want 1", got)+ }+ markChannelTaskRunning(t, ctx, pool, first.ID)++ // The user's next message arrives WHILE turn 1 is still running, so it waits+ // out the debounce window unowned.+ stranded := appendChannelUserMessage(t, ctx, pool, chatSessionID, "挺好的 正常了")++ // Turn 1 completes inside that window: its reply row is NEWER than the+ // waiting message, but it answers turn 1's batch, not this message.+ if _, err := svc.CompleteTask(ctx, first.ID, []byte(`{"output":"通了。"}`), "", "", false, ""); err != nil {+ t.Fatalf("complete turn 1: %v", err)+ }++ // The debounce fires.+ next, err := svc.EnqueueChatTask(ctx, session, initiator, false)+ if err != nil {+ t.Fatalf("EnqueueChatTask (turn 2): %v", err)+ }++ var owner pgtype.UUID+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, stranded).Scan(&owner); err != nil {+ t.Fatalf("load waiting message: %v", err)+ }+ if !owner.Valid || owner.Bytes != next.ID.Bytes {+ t.Fatalf("waiting user message task_id = %q, want the new turn %q — a predecessor reply that landed after the message must not seal it out",+ util.UUIDToString(owner), util.UUIDToString(next.ID))+ }+ if got := sealedInputCount(t, ctx, pool, next.ID); got != 1 {+ t.Fatalf("turn 2 owns %d user messages, want 1 — an empty input batch is what the claim guard cancels", got)+ }+ // Sealing is not retroactive: turn 1 keeps exactly the batch it ran on.+ if got := sealedInputCount(t, ctx, pool, first.ID); got != 1 {+ t.Fatalf("turn 1 batch now holds %d user messages, want its original 1", got)+ }+}++// TestEnqueueChatTaskSealsMessageWhenReplyCommitsDuringEnqueue closes the same+// boundary one level tighter: the predecessor's reply row commits on another+// connection AFTER the enqueue transaction has begun, so the seal statement's+// READ COMMITTED snapshot is the first thing in that transaction to see it.+// Same prior art as the media-deferral race above.+func TestEnqueueChatTaskSealsMessageWhenReplyCommitsDuringEnqueue(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)+ chatSessionID := seedChannelChatSession(t, ctx, pool, workspaceID, agentID, userID)++ session := db.ChatSession{ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID)}+ initiator := util.MustParseUUID(userID)+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}++ appendChannelUserMessage(t, ctx, pool, chatSessionID, "测试下")+ first, err := svc.EnqueueChatTask(ctx, session, initiator, false)+ if err != nil {+ t.Fatalf("EnqueueChatTask (turn 1): %v", err)+ }+ markChannelTaskRunning(t, ctx, pool, first.ID)+ stranded := appendChannelUserMessage(t, ctx, pool, chatSessionID, "挺好的 正常了")++ injected := false+ racing := &TaskService{+ Queries: q,+ Bus: events.New(),+ TxStarter: &raceInjectTxStarter{pool: pool, inject: func() {+ // Turn 1's reply row, committed by a concurrent completion.+ if _, err := pool.Exec(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, task_id)+ VALUES ($1, 'assistant', '通了。', $2)`, chatSessionID, first.ID); err != nil {+ t.Errorf("inject predecessor reply: %v", err)+ return+ }+ injected = true+ }},+ }+ next, err := racing.EnqueueChatTask(ctx, session, initiator, false)+ if err != nil {+ t.Fatalf("EnqueueChatTask (turn 2): %v", err)+ }+ if !injected {+ t.Fatal("race injection did not run")+ }++ var owner pgtype.UUID+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, stranded).Scan(&owner); err != nil {+ t.Fatalf("load waiting message: %v", err)+ }+ if !owner.Valid || owner.Bytes != next.ID.Bytes {+ t.Fatalf("waiting user message task_id = %q, want the new turn %q",+ util.UUIDToString(owner), util.UUIDToString(next.ID))+ }+}++// TestEnqueueChatTaskLeavesAlreadyPassedMessagesUnowned is the other half of+// the boundary, and the reason the fix qualifies the reply instead of dropping+// the check. Two shapes of old unowned row must stay out of a new batch:+//+// - an orphan the pre-fix seal skipped, which later turns have already run+// and replied past. Resurrecting it minutes or hours later would replay a+// message the conversation has moved on from.+// - a pre-ownership transcript, whose replies carry no task at all. Sweeping+// those would hand the agent the whole history as fresh input.+func TestEnqueueChatTaskLeavesAlreadyPassedMessagesUnowned(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)+ chatSessionID := seedChannelChatSession(t, ctx, pool, workspaceID, agentID, userID)++ // A pre-ownership pair: user row and reply, neither carrying a task.+ legacy := appendChannelUserMessage(t, ctx, pool, chatSessionID, "老消息")+ if _, err := pool.Exec(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content)+ VALUES ($1, 'assistant', '老回复')`, chatSessionID); err != nil {+ t.Fatalf("seed pre-ownership reply: %v", err)+ }++ // The orphan the pre-fix seal stranded, then a later turn (created after it)+ // that ran on its own input and replied.+ orphan := appendChannelUserMessage(t, ctx, pool, chatSessionID, "被漏掉的")+ var laterTurn pgtype.UUID+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority, completed_at)+ SELECT id, runtime_id, $2, 'completed', 2, now() FROM agent WHERE id = $1+ RETURNING id`, agentID, chatSessionID).Scan(&laterTurn); err != nil {+ t.Fatalf("seed later turn: %v", err)+ }+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1`, laterTurn); err != nil {+ t.Fatalf("stamp later turn input owner: %v", err)+ }+ if _, err := pool.Exec(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, task_id)+ VALUES ($1, 'user', '后一条', $2), ($1, 'assistant', '后一条的回复', $2)`,+ chatSessionID, laterTurn); err != nil {+ t.Fatalf("seed later turn transcript: %v", err)+ }++ session := db.ChatSession{ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID)}+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}+ fresh := appendChannelUserMessage(t, ctx, pool, chatSessionID, "新消息")+ task, err := svc.EnqueueChatTask(ctx, session, util.MustParseUUID(userID), false)+ if err != nil {+ t.Fatalf("EnqueueChatTask: %v", err)+ }++ for _, tc := range []struct{ label, id string }{+ {"a pre-ownership message whose reply carries no task", legacy},+ {"an orphan a later turn has already replied past", orphan},+ } {+ var owner pgtype.UUID+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, tc.id).Scan(&owner); err != nil {+ t.Fatalf("load %s: %v", tc.label, err)+ }+ if owner.Valid {+ t.Fatalf("%s was swept into task %s; it must stay out of the new batch",+ tc.label, util.UUIDToString(owner))+ }+ }+ var freshOwner pgtype.UUID+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, fresh).Scan(&freshOwner); err != nil {+ t.Fatalf("load fresh message: %v", err)+ }+ if !freshOwner.Valid || freshOwner.Bytes != task.ID.Bytes {+ t.Fatalf("fresh message task_id = %q, want %q", util.UUIDToString(freshOwner), util.UUIDToString(task.ID))+ }+ if got := sealedInputCount(t, ctx, pool, task.ID); got != 1 {+ t.Fatalf("new turn owns %d user messages, want only the fresh one", got)+ }+}++func seedChannelChatSession(t *testing.T, ctx context.Context, pool *pgxpool.Pool, workspaceID, agentID, userID string) string {+ t.Helper()+ var id string+ if err := pool.QueryRow(ctx, `+ INSERT INTO chat_session (workspace_id, agent_id, creator_id)+ VALUES ($1, $2, $3) RETURNING id`, workspaceID, agentID, userID).Scan(&id); err != nil {+ t.Fatalf("seed chat session: %v", err)+ }+ t.Cleanup(func() {+ _, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, id)+ })+ return id+}++// appendChannelUserMessage writes an inbound channel message the way+// ChatSession.AppendUserMessage does: durable, unowned, and stamped with the+// immutable channel_ingested provenance. The debounced flush is what later+// seals it to a task.+func appendChannelUserMessage(t *testing.T, ctx context.Context, pool *pgxpool.Pool, chatSessionID, body string) string {+ t.Helper()+ var id string+ if err := pool.QueryRow(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, channel_ingested)+ VALUES ($1, 'user', $2, TRUE) RETURNING id`, chatSessionID, body).Scan(&id); err != nil {+ t.Fatalf("append channel user message %q: %v", body, err)+ }+ return id+}++func markChannelTaskRunning(t *testing.T, ctx context.Context, pool *pgxpool.Pool, taskID pgtype.UUID) {+ t.Helper()+ if _, err := pool.Exec(ctx, `+ UPDATE agent_task_queue SET status = 'running', dispatched_at = now(), started_at = now()+ WHERE id = $1`, taskID); err != nil {+ t.Fatalf("mark task running: %v", err)+ }+}++func sealedInputCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, taskID pgtype.UUID) int {+ t.Helper()+ var n int+ if err := pool.QueryRow(ctx, `+ SELECT count(*) FROM chat_message WHERE task_id = $1 AND role = 'user'`, taskID).Scan(&n); err != nil {+ t.Fatalf("count sealed input: %v", err)+ }+ return n+}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 4949181f4e..18d5121b9a 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -1254,9 +1254,14 @@ WHERE message.chat_session_id = $2AND NOT EXISTS (SELECT 1FROM chat_message AS prior+ LEFT JOIN agent_task_queue AS prior_turn+ ON prior_turn.id = prior.task_id+ LEFT JOIN agent_task_queue AS prior_batch+ ON prior_batch.id = COALESCE(prior_turn.chat_input_task_id, prior_turn.id)WHERE prior.chat_session_id = $2AND prior.role != 'user'AND (prior.created_at, prior.id) > (message.created_at, message.id)+ AND (prior_batch.id IS NULL OR prior_batch.created_at > message.created_at))`@@ -1271,6 +1276,23 @@ type LinkUnownedChannelChatMessagesToTaskParams struct {// channel_command turns were already handled synchronously by Router. They stay// durable for channel orchestration but remain unowned and absent from public// Chat projections, preventing both immediate and delayed re-execution.+//+// The boundary is "already answered", not "something newer exists". A reply can+// only be a reply TO this message if the turn that wrote it started AFTER the+// message arrived; a turn already running when the message landed had sealed+// its own input batch before the message existed, so its reply — however late+// it lands — answers an earlier batch and must not become a boundary. Without+// that qualifier, a predecessor completing inside the debounce window (message+// at 18:31:17.7, predecessor reply at 18:31:20.2, seal at 18:31:20.7) sealed+// ZERO rows: the new task owned an empty input batch and the claim path+// cancelled it, losing the user's message with no reply (GH #6591).+//+// The reply's turn is compared through COALESCE(chat_input_task_id, id): an+// auto-retry clone gets a fresh id while inheriting the root's batch, and it is+// the ROOT's creation time that says which messages that batch could contain.+// A non-user row with no task (or whose task row is gone) still counts as a+// boundary — unattributable output is treated as possibly answering, so the+// pre-ownership rows of a legacy session are never swept into a new batch.func (q *Queries) LinkUnownedChannelChatMessagesToTask(ctx context.Context, arg LinkUnownedChannelChatMessagesToTaskParams) error {_, err := q.db.Exec(ctx, linkUnownedChannelChatMessagesToTask, arg.TaskID, arg.ChatSessionID)return errdiff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 24b26fe651..d6940ba282 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -479,6 +479,23 @@ WHERE id = $1 AND role = 'user';-- channel_command turns were already handled synchronously by Router. They stay-- durable for channel orchestration but remain unowned and absent from public-- Chat projections, preventing both immediate and delayed re-execution.+--+-- The boundary is "already answered", not "something newer exists". A reply can+-- only be a reply TO this message if the turn that wrote it started AFTER the+-- message arrived; a turn already running when the message landed had sealed+-- its own input batch before the message existed, so its reply — however late+-- it lands — answers an earlier batch and must not become a boundary. Without+-- that qualifier, a predecessor completing inside the debounce window (message+-- at 18:31:17.7, predecessor reply at 18:31:20.2, seal at 18:31:20.7) sealed+-- ZERO rows: the new task owned an empty input batch and the claim path+-- cancelled it, losing the user's message with no reply (GH #6591).+--+-- The reply's turn is compared through COALESCE(chat_input_task_id, id): an+-- auto-retry clone gets a fresh id while inheriting the root's batch, and it is+-- the ROOT's creation time that says which messages that batch could contain.+-- A non-user row with no task (or whose task row is gone) still counts as a+-- boundary — unattributable output is treated as possibly answering, so the+-- pre-ownership rows of a legacy session are never swept into a new batch.UPDATE chat_message AS messageSET task_id = @task_idWHERE message.chat_session_id = @chat_session_id@@ -488,9 +505,14 @@ WHERE message.chat_session_id = @chat_session_idAND NOT EXISTS (SELECT 1FROM chat_message AS prior+ LEFT JOIN agent_task_queue AS prior_turn+ ON prior_turn.id = prior.task_id+ LEFT JOIN agent_task_queue AS prior_batch+ ON prior_batch.id = COALESCE(prior_turn.chat_input_task_id, prior_turn.id)WHERE prior.chat_session_id = @chat_session_idAND prior.role != 'user'AND (prior.created_at, prior.id) > (message.created_at, message.id)+ AND (prior_batch.id IS NULL OR prior_batch.created_at > message.created_at));-- name: DeferChatTaskForSealedPendingMedia :one