Repository navigation
perf: validate chat transitions from the locked row - #30886
Conversation
ChatMachine.Update seeds the transaction with the row returned by LockChatAndBumpSnapshotVersion plus a queue count taken right after it. Callbacks read it with tx.Current() and the first transition validates against it, so neither re-reads the chat while the row lock is held. ChatMachine.UpdateReturning returns the row Update already reads after the callback for publication. updateChat (send, edit, promote, tool results, interrupt, compact, clear, reconcile), hook failure, family archive, and the worker's generation and task transitions use it instead of reloading the chat under the lock. Generated by Coder Agents on behalf of @cstyan.
|
|
||
| Each transaction that applies one or more transitions advances the `snapshot_version` field on the `chats` table by 1 immediately after locking the chat row and before mutating any tables. This lets us version the chat's execution state. The chat worker and the stream loop rely on it to ensure they do not process outdated or out of order notifications. | ||
|
|
||
| TODO (tx.Current): `ChatMachine.Update` counts queued messages right after the lock and seeds the transaction with the locked row. Callbacks read it with `tx.Current()` and the first transition validates against it, so neither reads the chat again under the lock. Later transitions in the same transaction and the publication read still go to the database. Describe this here. |
There was a problem hiding this comment.
we don't need changes in this file
There was a problem hiding this comment.
You don't want a mention of the new method for passing in the chat row, with the point that its valid only for the at the beginning of the Update call?
There was a problem hiding this comment.
I don't. This document is for describing general architecture, not small changes in interfaces.
| // under the lock. The row is zero if fn or that read failed. It is still | ||
| // set when the commit or publication fails afterwards, so treat it as | ||
| // committed only when err is nil. | ||
| func (m *ChatMachine) UpdateReturning( |
There was a problem hiding this comment.
I'd rather we made Update return a chat instead of adding UpdateReturning.
Update now always returns the published chat row; callers ignore it when they don't need it. Generated by Coder Agents on behalf of @cstyan.
….Current Transitions validate against an optional Snapshot input field and otherwise read the chat. Generated by Coder Agents on behalf of @cstyan.
Generated by Coder Agents on behalf of @cstyan.
# Conflicts: # coderd/x/chatd/chat_mutations.go # coderd/x/chatd/chatstate/machine.go # coderd/x/chatd/chatstate/synthetic_cancellation_test.go # coderd/x/chatd/chatstate/transitions.go # coderd/x/chatd/tasks_test.go # coderd/x/chatd/worker.go
# Conflicts: # coderd/chat_projects_test.go # coderd/exp_chats_chatstate_test.go # coderd/x/chatd/chat_mutations.go # coderd/x/chatd/chatstate/editing_test.go # coderd/x/chatd/chatstate/helpers_test.go # coderd/x/chatd/chatstate/interrupt_unowned_test.go # coderd/x/chatd/chatstate/queue_client_order_test.go # coderd/x/chatd/chatstate/queued_message_link_test.go # coderd/x/chatd/chatstate/synthetic_cancellation_test.go # coderd/x/chatd/chatstate/transitions.go # coderd/x/chatd/chatstate/transitions_test.go # coderd/x/chatd/generation.go # coderd/x/chatd/helpers_test.go
|
/coder-agents-review |
There was a problem hiding this comment.
This PR validates chat transitions against the row LockChatAndBumpSnapshotVersion returns, passed through an optional Snapshot input, and makes ChatMachine.Update return the row it reads for publication. Findings: 13 P3, 3 P4, 2 Nit.
PR text: the title check fails because the scope coderd/x/chatd does not contain coderd/chat_projects_test.go, coderd/exp_chats_chatstate_test.go, and coderd/exp_chats_test.go; use perf(coderd): ... (P3). The description still describes ChatMachine.UpdateReturning, tx.Current(), and a chat cached on Tx, none of which exist at the head; describe ChatSnapshot and the new Update return value instead (P3). The measurement table does not say what workload, unit, or tool produced the numbers, and GetChatByIDunder is missing a space (P4).
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/database/dbauthz/dbauthz.go:7491: dbauthzLockChatAndBumpSnapshotVersionreads the chat withGetChatByIDbefore it locks the row, so everyUpdatethrough a dbauthz-wrapped store still runs one more chat read inside the transaction.
Notes:
coderd/x/chatd/chatstate/machine.go:198:Updatenow runsLoadQueueStateon every call, so a callback that does not pass the snapshot to its transition runs one more query than on main.coderd/database/queries/chats.sql:2752: transitions now validate against the row from the hand-copiedchats_expandedCTE inLockChatAndBumpSnapshotVersion;TestChatMachine_Update_SnapshotMatchesDatabasecompares it withGetChatByIDfor a root chat only, so drift in the parent-chat join would not fail a test.coderd/x/chatd/chatstate/machine.go:213: the publicationreadStateafter the callback is the remaining chat read under the lock on everyUpdate.
coderd/x/chatd/chatstate/transitions.go:607
P4 [CRF-7] Tx.SendMessage calls LoadQueueState even when given a snapshot, so each send reads the queue head twice under the lock. (Netero)
Update already loaded the same QueueState into snapshot.Queue, and from already comes from it through snapshot.State(). Use input.Snapshot.Queue when the snapshot is set.
🤖
coderd/x/chatd/chatstate/machine.go:127
P3 [CRF-14] The requireFromAllowed doc says it "loads the current state" and returns "the loaded chat", which is false when a snapshot is given. (Gon)
The PR added the snapshot parameter without changing the doc, and with a snapshot the function reads nothing. State that it validates t against snapshot, or against a fresh read when snapshot is nil.
🤖
🤖 This review was automatically generated with Coder Agents.
| return xerrors.Errorf("load committed chat: %w", err) | ||
| } | ||
| return nil | ||
| } |
There was a problem hiding this comment.
P4 [CRF-3] RecordGenerationAttempt here still reads the chat and queue head under the lock on every generation attempt that delivers no steer message. (Netero)
beginGenerationAttempt passes the snapshot to the same transition, but here it would be the second transition in the callback, which the ChatSnapshot doc forbids. Every no-delivery path in DeliverSteerMessages returns before it writes (transitions.go:1723-1732), so to remove this read, have DeliverSteerMessages report that it wrote nothing and pass the snapshot only in that case.
🤖
…apshot SendMessage read the queue state again even when given a snapshot, whose queue state Update had already loaded under the lock. Use the snapshot's queue state when set, and correct the requireFromAllowed doc to say it validates against the snapshot when one is given. Generated by Coder Agents on behalf of @cstyan.
Return the row ChatMachine.Update reads from updateChat instead of taking an out-parameter that duplicated it, and use the Update return value in the generation finish paths. Rename the snapshot fence helpers to verifyLockedTaskFence and verifyLockedGenerationFence so errors no longer report a chat read that does not happen. Document that Update returns the row with a commit or publication error so callers can compare it with a fresh read, and cover StartInterrupt and the requires-action cancel with a publish failure after the commit. Update the ChatSnapshot, Tx, Abandon and transition input docs to match the snapshot rules. Generated by Coder Agents on behalf of @cstyan.
…id for EditQueuedMessage now checks archived status on the snapshot and passes it to the transition instead of reading the chat again, and SetFamilyProject passes each member's snapshot to SetProject. SendMessage and EditMessage write the chat before their transition, so they no longer pass the snapshot and the transition reads the chat. Generated by Coder Agents on behalf of @cstyan.
hugodutka
left a comment
There was a problem hiding this comment.
LGTM with some nits. Please address them before merging.
| // messages, by a transition or through the store, makes it stale, so | ||
| // pass it only to the first transition in a callback, and only when the | ||
| // callback has not written before that transition. | ||
| type ChatSnapshot struct { |
There was a problem hiding this comment.
Could you make this comment less verbose and more to the point? Snapshot is an up-to-date state of the chat used as a performance optimization to avoid refetching the chat at the beginning of a transition.
|
|
||
| // Reads under the transition lock directly lengthen lock hold time, so | ||
| // a transition given the snapshot must validate against it. | ||
| func TestChatMachine_Update_ValidatesFromSnapshot(t *testing.T) { |
There was a problem hiding this comment.
This test seems pointless to me.
There was a problem hiding this comment.
this one can be removed 👍
|
|
||
| // A publish failure after the commit must not turn a committed transition | ||
| // into a task failure. | ||
| func TestInterruptTask_PublishFailureAfterCommitSucceeds(t *testing.T) { |
There was a problem hiding this comment.
why are these 2 new tests included in this PR?
There was a problem hiding this comment.
This one covers what I understand to be the contract of the Update function rather than something specific to tasks, so potentially a rename would help here. In this PR we're removing the extra reads for GetChatByID in tasks.go so that those now get the chat row from Update return value directly. IIUC, a task where the commit succeeds but the publish fails is still considered a success, and so the updated row should still be returned from Update in that case. committedStateAfterUpdateError appears to depend on that exact case, if it did not get passed the updated row it would return false.
Update being modified to not return the committed row in this particular error case would cause issues, but we did not need to test for that before since we read via GetChatByID in StartInterrupt and cancelRequiresAction. Modifying the return behaviour would break things, so this test will at least notify us that other code would need to be updated alongside the return value change if we chose to modify the overall success case.
Let me know if a) I've misunderstood something here and b) if you prefer we just remove the test regardless of my understanding.
There was a problem hiding this comment.
Makes sense, let's leave them in. I didn't understand what they were testing initially.
One of the main costs in terms of DB load from chats is extra round trips during transactions. This results in locks being held for longer periods of time -> an increase in lock waits for chats related queries.
One of the opportunities for reducing some of the round trips is to eliminate extra chat row reads after we have just read the row in order to lock it.
In this PR
ChatMachine.Updatenow seeds the transaction struct with the row returned byLockChatAndBumpSnapshotVersion, plus a queue count taken right after it. We can then pass it intoUpdateas an optional parameter validate against it, so neither re-reads the chat row from the database while the row lock is held.updateChat(send, edit, promote, tool results, interrupt, compact, clear, reconcile), hook failure, family archive, and the worker's generation and task transitions use it instead of reloading the chat under the lock.This PR relative to main:
Generated by Coder Agents on behalf of @cstyan.