refactor(coderd/x/chatd): insert chats directly as pending on creation (#23888)

Previously, `CreateChat` inserted the `chats` row with the DB default
status (`waiting`), then updated it to `pending` in the same transaction
via `setChatPendingWithStore`. This wasted two extra queries per chat
creation (`GetChatByID` + `UpdateChatStatus`) and rewrote the same row
immediately after inserting it.

Now `CreateChat` passes the status directly to `InsertChat`, so the row
is written once in its final create-time state. The
`setChatPendingWithStore` helper is removed entirely. `InsertChat` now
requires an explicit `status` parameter at all callsites instead of
relying on a DB column default.

## Motivation

On an experimental branch we're trialing firing all chatd notifications
from plpgsql triggers. The old two-step insert made that awkward: in an
`AFTER INSERT` trigger, `NEW` only contained the insert-time row
(`waiting`), not the final committed state (`pending`). To emit the
correct event payload the trigger had to be deferred and re-read the row
from `chats` at commit time.

With this change, `NEW` already contains the correct row to publish — no
deferred trigger, no extra `SELECT`, simpler and cheaper trigger logic.

That said, this seems like a worthwhile change regardless of the trigger
experiment: writing the final row state once removes unnecessary DB work
on every chat creation and makes the create path easier to reason about.
This commit is contained in:
Ethan
2026-04-02 14:13:51 +11:00
committed by GitHub
parent fc1e0beb3b
commit 7757cd8e08
12 changed files with 78 additions and 35 deletions
+6 -2
View File
@@ -5707,6 +5707,7 @@ INSERT INTO chats (
last_model_config_id,
title,
mode,
status,
mcp_server_ids,
labels
) VALUES (
@@ -5719,8 +5720,9 @@ INSERT INTO chats (
$7::uuid,
$8::text,
$9::chat_mode,
COALESCE($10::uuid[], '{}'::uuid[]),
COALESCE($11::jsonb, '{}'::jsonb)
$10::chat_status,
COALESCE($11::uuid[], '{}'::uuid[]),
COALESCE($12::jsonb, '{}'::jsonb)
)
RETURNING
id, owner_id, workspace_id, title, status, worker_id, started_at, heartbeat_at, created_at, updated_at, parent_chat_id, root_chat_id, last_model_config_id, archived, last_error, mode, mcp_server_ids, labels, build_id, agent_id, pin_order, last_read_message_id, last_injected_context
@@ -5736,6 +5738,7 @@ type InsertChatParams struct {
LastModelConfigID uuid.UUID `db:"last_model_config_id" json:"last_model_config_id"`
Title string `db:"title" json:"title"`
Mode NullChatMode `db:"mode" json:"mode"`
Status ChatStatus `db:"status" json:"status"`
MCPServerIDs []uuid.UUID `db:"mcp_server_ids" json:"mcp_server_ids"`
Labels pqtype.NullRawMessage `db:"labels" json:"labels"`
}
@@ -5751,6 +5754,7 @@ func (q *sqlQuerier) InsertChat(ctx context.Context, arg InsertChatParams) (Chat
arg.LastModelConfigID,
arg.Title,
arg.Mode,
arg.Status,
pq.Array(arg.MCPServerIDs),
arg.Labels,
)