Skip to content

perf(coderd): authorize chat calls from a cached chat RBAC object - #30887

Closed
cstyan wants to merge 2 commits into
mainfrom
callum/chatd-rbac-cache
Closed

cstyan wants to merge 2 commits into
mainfrom
callum/chatd-rbac-cache

Conversation

@cstyan

@cstyan cstyan commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

The change in this PR is to allow reuse of a chat RBAC object by caching it on the Go context object, as we've done in a number of PRs earlier this year for other dbauthz calls. Chat-ID-scoped dbauthz methods read the chat through chats_expanded just ensure proper authorization by the caller, and many of these dbauthz calls execute queries that run under the chat row lock.

Following the pattern from other PRs, we can cache the chat's RBAC object (which only contains ID, owner, org) on the context and authorize against it, falling back to the read on any failure or a different chat ID. Every chat-ID-scoped method whose read only served authorization uses it; UpdateChatACLByID keeps its read because it rejects sub-chats.

ChatMachine.Update caches the object from the lock's own row, the chat HTTP middleware and the worker runner cache it up front, chat creation caches it from the inserted row, and acquisition caches it from the owner and organization GetChatWorkerAcquisitionCandidates now returns. Update callbacks pass tx.Ctx() to the store and helpers so their calls see the cached object.

measurement main this PR percent change
Round trips under lock 180.9 117.9 -35%
Statements under lock 86.1 54.6 -37%
GetChatByID calls under lock 54.1 22.9 -58%
GetChatByID calls total 75.5 27.9 -63%
Statements 235.8 188.0 -20%

Generated by Coder Agents on behalf of @cstyan.

Chat-ID-scoped dbauthz methods read the chat through chats_expanded
only to authorize it, and many of them run under the chat row lock.

Following the workspace RBAC-in-context pattern, cache the chat's RBAC
object (ID, owner, org; never ACLs, which change at runtime) on the
context and authorize against it, falling back to the read on any
failure or a different chat ID. Every chat-ID-scoped method whose read
only served authorization uses it; UpdateChatACLByID keeps its read
because it rejects sub-chats.

ChatMachine.Update caches the object from the lock's own row, the chat
HTTP middleware and the worker runner cache it up front, chat creation
caches it from the inserted row, and acquisition caches it from the
owner and organization GetChatWorkerAcquisitionCandidates now returns.
Update callbacks pass tx.Ctx() to the store and helpers so their calls
see the cached object.

Generated by Coder Agents on behalf of @cstyan.
@linear-code

linear-code Bot commented Oct 29, 2026

Copy link
Copy Markdown

GRU-109

# Conflicts:
#	coderd/database/dbauthz/dbauthz.go
#	coderd/x/chatd/chat_mutations.go
#	coderd/x/chatd/generation.go
#	coderd/x/chatd/worker.go
@cstyan
cstyan temporarily deployed to main November 9, 2026 22:27 — 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 authorizes chat-ID-scoped dbauthz methods from a chat RBAC object cached on the context by ChatMachine.Update, the chat HTTP middleware, the runner, chat creation, and acquisition. Findings: 5 P3, 5 P4.

The measurement table in the PR description does not say which workload produced the numbers, what they are averaged over, or how round trips and statements were counted. Add one line above the table so a reader can rerun it.

Out of scope (needs a ticket or explicit acceptance by a human):

  • coderd/database/dbauthz/dbauthz.go:4394: GetLatestWorkspaceBuildByWorkspaceID, GetWorkspaceAgentByID (:5768), and UpdateWorkspaceAgentMetadata (:9033) authorize against the cached workspace RBAC object without checking that its ID matches the requested workspace or agent, so a context that carries workspace A's object authorizes these calls for workspace B whenever the actor can access A. authorizeChatByID in this PR does check the ID.
  • coderd/database/dbauthz/workspace_rbac_context.go:12: isWorkspaceRBACObjectEmpty returns true for a partly filled object, so its name and its error message describe the rejected input wrongly.
  • coderd/database/dbauthz/dbauthz.go:160: the slow-path line in the authorizeWorkspaceByAgentID doc restates the function body.

Notes:

  • coderd/database/dbauthz/dbauthz.go:184: a user who reaches a chat only through an ACL grant always fails the fast path, so that user gets no read reduction and one extra authorize call per method. The savings in the table apply to owners and chatd.
  • coderd/database/dbauthz/dbauthz.go:184: on the fast path, authorization no longer returns sql.ErrNoRows for a missing chat; the query itself returns no rows or a foreign key violation. This requires DeleteOldChats to delete the chat while a context from ExtractChatParam or runner.bootstrap is still in use.
  • coderd/database/dbauthz/chat_rbac_context.go:13: the fast path is safe only because no query changes chats.owner_id or chats.organization_id. The schema does not enforce this, and a future ownership-transfer query would also have to invalidate objects cached on long-lived contexts such as the runner's r.ctx.
  • coderd/x/chatd/chatstate/machine.go:163: the remaining GetChatByID calls under the lock are data reads. Carrying the row that LockChatAndBumpSnapshotVersion returns on Tx would remove the first loadState read.
  • coderd/x/chatd/chatstate/machine_test.go:376: wantReads counts every GetChatByID call, so adding a needed read to a transition fails these tests even when caching still works.

coderd/x/chatd/chatstate/machine.go:66

P3 [CRF-7] The Tx.Ctx doc says it returns the context the surrounding ChatMachine.Update call is using, but it now returns a derived context that carries the locked chat's RBAC object, and no doc tells callback authors to use it. (Gon, Leorio)

The reason for the ctx to tx.Ctx() conversions is recorded only in the PR description. State on Tx.Ctx that store calls and helpers in the callback must use it, because calls made with the caller's context succeed but read the chat to authorize. Then delete the comment at machine.go:170, which this doc would repeat.

🤖

🤖 This review was automatically generated with Coder Agents.

)
refreshed, err := p.updateChat(ctx, opts.ChatID, "send", func(tx *chatstate.Tx, store database.Store, _ *database.Chat) error {
lockedChat, err := store.GetChatByID(ctx, opts.ChatID)
lockedChat, err := store.GetChatByID(tx.Ctx(), opts.ChatID)

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.

P3 [CRF-1] No test fails if an Update callback goes back to passing the outer ctx instead of tx.Ctx(). (Netero)

A revert compiles and authorizes; it only adds back a GetChatByID read under the row lock. The read-count tests cover ChatMachine.Update, CreateChat, and acquireCandidate, but not SendMessage, EditMessage, commitGenerationStep, StartInterrupt, handleAPIDispatchError, or the other converted callbacks. Add one read-count test that runs a server-level path such as SendMessage through a dbauthz-wrapped counting store, or make the callback signature change suggested on machine.go:172, which removes the need for per-site tests.

🤖

Comment thread coderd/x/chatd/runner.go
}
// Every transition this runner performs derives from r.ctx, so they
// all authorize against this cached object instead of reading the chat.
if rbacCtx, err := dbauthz.WithChatRBAC(r.ctx, dbauthz.CacheableChatRBAC(chat)); err == 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.

P3 [CRF-2] No test checks that runner.bootstrap puts the chat RBAC object on r.ctx. (Netero)

If this block is removed, every Update that the runner's tasks start reads the chat again to authorize the lock, and no test fails. Assert dbauthz.ChatRBACFromContext(r.ctx) after bootstrap, or count reads for one runner-driven transition.

🤖

Comment thread coderd/x/chatd/worker.go
// Lets the lock authorize without reading the chat; owner and
// organization never change.
updateCtx := ctx
if rbacCtx, err := dbauthz.WithChatRBAC(ctx, dbauthz.CacheableChatRBAC(database.Chat{

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] acquireCandidate discards the WithChatRBAC error, and so do chatparam.go:63, runner.go:114, and transitions.go:181, while machine.go:172 returns it. (Netero)

The error occurs only for a zero ID, owner, or organization, so a malformed row, for example a candidate row without OwnerID, turns the cache off with no error and no log line, and every acquisition reads the chat under the lock again. Use one rule at all five call sites: return the error as machine.go does, or log it.

🤖


// countingChatReadStore counts GetChatByID calls, including those inside
// transactions.
type countingChatReadStore struct {

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-4] countingChatReadStore is a copy of chatReadCountingStore in chatstate/machine_test.go:339 with a different name and counter type. (Netero)

Both wrap database.Store, re-wrap the store inside InTx, and count GetChatByID, so another read-count test would add a third copy. Put one exported helper in a shared test package such as coderd/database/dbtestutil and use it in both tests.

🤖

// CacheableChatRBAC returns the chat's RBAC object without ACLs. ID,
// owner, and organization never change for a chat, so the object is safe
// to cache; ACLs are left out because sharing changes at runtime.
func CacheableChatRBAC(chat database.Chat) rbac.Object {

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-5] CacheableChatRBAC repeats the first three builder calls of database.Chat.RBACObject (coderd/database/modelmethods.go:248-252). (Netero)

If Chat.RBACObject gets a new non-ACL field that narrows access, the cached object will not have it, and the fast path will allow what the slow path denies, because only a denial falls back to the read. Build the cached object from chat.RBACObject() with the ACL lists cleared so the object has one definition.

🤖

}
// Lets dbauthz authorize the transition's chat reads and writes
// without reading the chat again under the lock.
txCtx, err := dbauthz.WithChatRBAC(ctx, dbauthz.CacheableChatRBAC(locked))

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.

P3 [CRF-6] Only tx.Ctx() carries the cached chat RBAC object, but every Update callback still has the outer ctx in scope, so each of the roughly 30 converted call sites depends on the author picking tx.Ctx(). (Meruem, Bisky)

A callback that passes the outer ctx compiles, passes every test, and adds one GetChatByID read under the row lock per chat-scoped call. Change the callback type to func(ctx context.Context, tx *Tx, store database.Store) error so the parameter shadows the outer ctx. Another option: have the per-transaction querier that querier.InTx builds (dbauthz.go:1396) store the RBAC object of the chat that LockChatAndBumpSnapshotVersion locked, so calls on the transaction store authorize from it whatever context they receive.

🤖

Groups: []string{orgID.String()},
Scope: rbac.ScopeAll,
}
allowAll := &coderdtest.RecordingAuthorizer{

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.

P3 [CRF-8] The fast-path tests do not check which action or object the cached path authorizes, so a fast path that authorizes against the wrong object passes them. (Meruem, Bisky)

CachedSkipsRead records calls with RecordingAuthorizer but never asserts them, and the real-RBAC tests in machine_test.go and worker_internal_test.go run as AsChatd, which has site-wide chat permissions, so the cached owner and organization are never evaluated. Changing dbauthz.go:186 to q.authorizeContext(ctx, policy.ActionRead, rbacObj.WithOwner("not-the-owner")) leaves TestChatAuthorization_CachedRBAC, TestChatMachine_Update_AuthorizesFromCachedChatRBAC, and TestCreateChat_AuthorizesFromInsertedChat passing. Assert the recorded action and CacheableChatRBAC(chat) pairs in CachedSkipsRead, and add a real-authorizer case with a member actor: the chat owner succeeds with zero reads, and a non-owner without an ACL grant is denied.

🤖

// WithChatRBAC attaches a chat RBAC object to the context so chat-scoped
// dbauthz methods can authorize without reading the chat. The object must
// carry the chat ID, owner, and organization, and must not carry ACLs.
func WithChatRBAC(ctx context.Context, rbacObj rbac.Object) (context.Context, error) {

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-9] WithChatRBAC accepts any rbac.Object, so it checks for a wrong type and for ACLs that its only producer, CacheableChatRBAC, cannot create. (Meruem, Bisky)

Every caller writes WithChatRBAC(ctx, CacheableChatRBAC(x)), and worker.go:248 builds a partial database.Chat only to call the builder. Change the signature to WithChatRBAC(ctx context.Context, chatID, ownerID, orgID uuid.UUID) and build the object inside, so the type and ACL rules hold by construction and the RejectsWrongType and RejectsACLs subtests can be deleted.

🤖

InOrg(chat.OrganizationID)
}

func isChatRBACObjectEmpty(rbacObj rbac.Object) bool {

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-10] isChatRBACObjectEmpty returns true when any one of ID, owner, or organization is missing, so its name and the error "cannot attach empty chat RBAC object" call a partly filled object empty. (Gon)

Rename it to isChatRBACObjectIncomplete and change the error to say that the object must carry ID, owner, and organization.

🤖

@github-actions github-actions Bot added the stale This issue is like stale bread. label Nov 18, 2026
@github-actions github-actions Bot closed this Nov 22, 2026

This branch was previously deployed

1 inactive deployment
main — fca4caec Deployed Nov 9, 2026 by cstyan via cla #252913
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale This issue is like stale bread.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant