Adds the backend-only seam that lets a later `Publish` operation admit an automation message inside chatd's existing create-chat and send-message transactions, and the guard that drops stale automation input when the queue promotes it. Only Go test callbacks use the seam in this PR, so ordinary chat behavior does not change. Closes CODAGT-1208 Part of CODAGT-1135 > Stack: PR 2, on top of #30085 (schema, RBAC resource, and audit entries). No migration changes; this PR adds and extends sqlc queries only. ARCHITECTURE.md prose was drafted by an agent at the user's request; the user will review it. ## Changes - **Admission seam.** `chatstate.AdmitFunc` is a nil-default `AdmitInTx` field on `chatd.CreateOptions`, `chatd.SendMessageOptions`, `chatstate.CreateChatInput`, and `chatstate.SendMessageInput`. `CreateChat` runs it after inserting the chat and before the initial history, and requires exactly one initial user message. `SendMessage` runs it on the locked chat before any write. The callback returns an `AutomationProvenance` (automation ID, input ID, queue generation), which is validated and stamped on the message. A callback error rolls back the whole transaction, so no chat, message, or queue row survives. `Server.CreateChat` and `Server.SendMessage` keep their signatures. - **Provenance.** `chatstate.Message.Automation` is written to queued rows (`automation_id`, `input_id`, `queue_generation`) and history rows (`automation_id`, `input_id`). `InsertChatMessages` and `InsertChatQueuedMessageWithCreator` gain the matching parameters, and `messageFromQueuedRow` copies them on promotion. - **Promotion guard.** `chatstate.LockAutomations` is the only way to lock automation rows: it locks them `FOR UPDATE` in ascending ID order, running as chatd. The chatd subject gains read on `chat_automation`. A queued automation row passes only if its automation exists, is enabled, and has the row's `queue_generation`. Two helpers apply the check: - `nextPromotableQueueHead` serves `sendMessageE1`, `FinishTurn`, and `FinishInterruption`. A head without an automation costs no extra query. Otherwise it locks every automation in the queue up front, deletes failing heads until one passes, and leaves rows behind that head alone. If the queue empties, `FinishTurn` and `FinishInterruption` land in `waiting`, as from `R0` and `I0`. - `guardQueuedRows` serves explicit `PromoteQueuedMessage`. A failing row is deleted and the transition returns `Rejected` without an error, so the delete commits. `Server.PromoteQueued` then returns `ErrQueuedMessageNotFound` (HTTP 404) without reordering, substituting a message, or changing status. - The steer paths (`DeliverSteerMessages` and the steer batches from #30073/#30074) add one `guardQueuedRows` call each, whichever PR lands second. - **Deadlocks.** `database.IsDeadlockError` is new. `ChatMachine.Update` reruns the transaction, at most 3 attempts with a fresh publish buffer each, only when an attempt that took automation locks hit a deadlock abort. Attempts without automation locks, and nested Updates, never retry. The `SendMessage` and `PromoteQueued` closures reset their results so a rerun is safe. - **Transition matrix.** Adds the outputs the guard can produce, such as `R1 -> FinishTurn -> W` and `E1 -> SendMessage -> R0`. - **`ARCHITECTURE.md`.** Describes the admission seam, provenance, the queue promotion guard, the lock order, and the deadlock retry, and adds the guard's outcomes to the state diagram. ## Validation - Go tests on real PostgreSQL cover the ticket's checks: - A callback error leaves no chat, message, or queue row. - A guard rejection deletes only the rejected heads, on every promotion path and for each failure reason (missing, disabled, disabled with the same generation, generation mismatch). - Explicit promotion of a failing row returns not found, and the delete is committed. - Provenance round-trips through queue and history. - `LockAutomations` works through dbauthz. - `Update` retries only when an attempt that took automation locks hits a deadlock. - A concurrency test of acceptance, promotion, and disable across mixed automation IDs sees zero deadlock aborts. - Mutation checks confirmed that the guard, retry, and permission tests fail when their behavior is removed. - Remote dogfood UAT passed on a real dev instance: sending, queueing, head and explicit promotion, interrupting, and deleting queued messages all behaved as before. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
79 lines
1.5 KiB
SQL
79 lines
1.5 KiB
SQL
-- name: InsertChatAutomation :one
|
|
INSERT INTO chat_automations (
|
|
id,
|
|
organization_id,
|
|
owner_id,
|
|
name,
|
|
created_by_chat_id,
|
|
kind,
|
|
enabled,
|
|
target_mode,
|
|
target_chat_id,
|
|
new_chat_model_config_id,
|
|
reasoning_effort,
|
|
when_busy,
|
|
webhook_use,
|
|
webhook_secret_hash,
|
|
webhook_secret_version,
|
|
prompt,
|
|
schedule_cron,
|
|
schedule_time_zone,
|
|
schedule_next_run_at,
|
|
created_at,
|
|
updated_at
|
|
) VALUES (
|
|
@id,
|
|
@organization_id,
|
|
@owner_id,
|
|
@name,
|
|
@created_by_chat_id,
|
|
@kind,
|
|
@enabled,
|
|
@target_mode,
|
|
@target_chat_id,
|
|
@new_chat_model_config_id,
|
|
@reasoning_effort,
|
|
@when_busy,
|
|
@webhook_use,
|
|
-- A nil []byte is sent as an empty bytea, not NULL. Store NULL so
|
|
-- automations without a secret satisfy chat_automations_kind_shape.
|
|
NULLIF(@webhook_secret_hash::bytea, ''::bytea),
|
|
@webhook_secret_version,
|
|
@prompt,
|
|
@schedule_cron,
|
|
@schedule_time_zone,
|
|
@schedule_next_run_at,
|
|
@created_at,
|
|
@updated_at
|
|
)
|
|
RETURNING
|
|
*;
|
|
|
|
-- name: GetChatAutomationByID :one
|
|
SELECT
|
|
*
|
|
FROM
|
|
chat_automations
|
|
WHERE
|
|
id = @id::uuid;
|
|
|
|
-- name: DeleteChatAutomationByID :exec
|
|
DELETE FROM
|
|
chat_automations
|
|
WHERE
|
|
id = @id::uuid;
|
|
|
|
-- name: GetChatAutomationsByIDsForUpdate :many
|
|
-- Locks the given automations in ascending id order so concurrent
|
|
-- lockers always acquire automation row locks in the same order.
|
|
-- Missing ids are not returned.
|
|
SELECT
|
|
*
|
|
FROM
|
|
chat_automations
|
|
WHERE
|
|
id = ANY(@ids::uuid[])
|
|
ORDER BY
|
|
id
|
|
FOR UPDATE;
|