Skip to content

perf: validate chat transitions from the locked row - #30886

Merged
cstyan merged 11 commits into
mainfrom
callum/chatd-tx-current
Nov 13, 2026
Merged

cstyan merged 11 commits into
mainfrom
callum/chatd-tx-current

Conversation

@cstyan

@cstyan cstyan commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

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.Update now seeds the transaction struct with the row returned by LockChatAndBumpSnapshotVersion, plus a queue count taken right after it. We can then pass it into Update as 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:

measurement main this PR percent change
Round trips under lock 180.9 142.0 -39%
Statements under lock 86.1 66.6 -23%
GetChatByID under lock 54.1 35.8 -34%
GetChatByID total 75.5 57.1 -25%
Statements 235.8 216.2 -8%

Generated by Coder Agents on behalf of @cstyan.

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.
Comment thread coderd/x/chatd/ARCHITECTURE.md Outdated

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't need changes in this file

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@hugodutka hugodutka Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't. This document is for describing general architecture, not small changes in interfaces.

Comment thread coderd/x/chatd/chatstate/machine.go Outdated
// 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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather we made Update return a chat instead of adding UpdateReturning.

Comment thread coderd/x/chatd/chatstate/machine.go Resolved
@linear-code

linear-code Bot commented Oct 29, 2026

Copy link
Copy Markdown

GRU-108

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.
# 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
@cstyan
cstyan temporarily deployed to main November 9, 2026 22:01 — with GitHub Actions Inactive
@cstyan

cstyan commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: dbauthz LockChatAndBumpSnapshotVersion reads the chat with GetChatByID before it locks the row, so every Update through a dbauthz-wrapped store still runs one more chat read inside the transaction.

Notes:

  • coderd/x/chatd/chatstate/machine.go:198: Update now runs LoadQueueState on 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-copied chats_expanded CTE in LockChatAndBumpSnapshotVersion; TestChatMachine_Update_SnapshotMatchesDatabase compares it with GetChatByID for a root chat only, so drift in the parent-chat join would not fail a test.
  • coderd/x/chatd/chatstate/machine.go:213: the publication readState after the callback is the remaining chat read under the lock on every Update.

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.

Comment thread coderd/x/chatd/chat_mutations.go Resolved
Comment thread coderd/x/chatd/chatstate/family.go Resolved
return xerrors.Errorf("load committed chat: %w", err)
}
return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

🤖

Comment thread coderd/x/chatd/chat_mutations.go Resolved
Comment thread coderd/x/chatd/chatstate/transitions.go Resolved
Comment thread coderd/x/chatd/tasks.go Resolved
Comment thread coderd/x/chatd/chatstate/machine.go Resolved
Comment thread coderd/x/chatd/chatstate/transitions.go Resolved
Comment thread coderd/x/chatd/chatstate/machine.go Resolved
Comment thread coderd/x/chatd/chatstate/machine.go Resolved
@cstyan cstyan changed the title perf(coderd/x/chatd): validate chat transitions from the locked row perf: validate chat transitions from the locked row Nov 10, 2026
@cstyan
cstyan temporarily deployed to main November 10, 2026 01:17 — with GitHub Actions Inactive
@cstyan
cstyan temporarily deployed to main November 10, 2026 01:18 — with GitHub Actions Inactive
@cstyan
cstyan temporarily deployed to main November 10, 2026 01:19 — with GitHub Actions Inactive
@cstyan
cstyan temporarily deployed to main November 10, 2026 01:27 — with GitHub Actions Inactive
…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.
@cstyan
cstyan temporarily deployed to main November 11, 2026 04:17 — with GitHub Actions Inactive
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.
@cstyan
cstyan temporarily deployed to main November 11, 2026 05:25 — with GitHub Actions Inactive
@cstyan
cstyan requested a review from hugodutka November 11, 2026 05:57
…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.
@cstyan
cstyan temporarily deployed to main November 11, 2026 06:17 — with GitHub Actions Inactive

@hugodutka hugodutka left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread coderd/x/chatd/chat_mutations.go Resolved
Comment thread coderd/x/chatd/chat_mutations.go Resolved

// 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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test seems pointless to me.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are these 2 new tests included in this PR?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, let's leave them in. I didn't understand what they were testing initially.

@cstyan
cstyan temporarily deployed to main November 13, 2026 03:34 — with GitHub Actions Inactive
@cstyan
cstyan merged commit d412c38 into main Nov 13, 2026
29 checks passed
@cstyan
cstyan deleted the callum/chatd-tx-current branch November 13, 2026 16:59
@cstyan
cstyan temporarily deployed to docs-preview November 13, 2026 16:59 — with GitHub Actions Inactive
@cstyan
cstyan temporarily deployed to main November 13, 2026 16:59 — with GitHub Actions Inactive
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 13, 2026

This branch was previously deployed

2 inactive deployments
docs-preview — 200ea581 Deployed Nov 13, 2026 by cstyan via cleanup #46
main — 200ea581 Deployed Nov 13, 2026 by cstyan via cla #256783
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants