Skip to content

perf(coderd/x/chatd): count subagent capacity in one statement and lock per family - #359

Merged
ibetitsmike merged 7 commits into
mainfrom
mike/issue-301-batched-capacity
Nov 16, 2026
Merged

ibetitsmike merged 7 commits into
mainfrom
mike/issue-301-batched-capacity

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

Coder Agents opened this PR on behalf of @ibetitsmike.

Closes #301

What changed

All of this sits behind fork-nested-subagents. Fork logic stays in fork_*.go files. No upstream file gained a hook line.

  • New query GetSubagentCapacityCounts takes candidate_ids uuid[] and an optional root_chat_id. Candidates are the listed IDs plus, when the root is set, every chat of that family. For each candidate it returns the deployment, organization and family active counts. Each count excludes the candidate's own active lineage. awaiting_only limits the rows to candidates that wait for a worker.
  • Removed CountActiveSubagentsForCapacity, GetChatAwaitingWorker and GetFamilySubagentsAwaitingWorker. Nothing else used them.
  • New query AcquireSharedLock (pg_advisory_xact_lock_shared). dbauthz and dbmetrics wrappers were added for both queries.
  • list_agents groups running children by organization. It reads the limits once per organization and runs one batched count.
  • GET /chats/{chat} (ChatQueuedForCapacity) and Admit use the same query with one ID. The family sidebar uses it with the root ID, so the family is filtered in SQL in one statement and the result stays in ID order.
  • Admission lock modes:
    • With only a family limit: first an exclusive per-family capacity lock, then the shared deployment lock. A waiter on the family lock therefore holds no deployment lock and cannot delay an exclusive deployment lock holder such as a lease takeover. The family lock is chatFamilyCapacityLockID(root) (GenLockID("fork_chat_family_capacity:"+root)). Admissions in different families no longer wait for each other. This key is separate from chatFamilyAdmissionLockID, which spawns and resumes hold. Spawns and resumes never change the active count, so Admit does not wait for them. Reusing that key could deadlock: a resume holds it and waits on the sender row (FK insert), a lease takeover holds the sender row and waits on the exclusive deployment lock, and Admit holds the shared deployment lock while it waits on the family lock.
    • With a deployment or organization limit, or on a lease takeover: the exclusive deployment lock, as before. The takeover case keeps the exclusive lock so leaseStaleUnderAdmissionLock never has to upgrade a shared lock.
  • forkValidateSubagentResume sets the same 5 s lock timeout as Admit before it takes the family lock, and resets it to 0 (SET LOCAL lock_timeout) right after the lock is acquired. The rest of the SendMessage transaction, including EditMessage and the later FK and admission waits, waits as before.
  • ARCHITECTURE.md describes the batched statement, the lock modes and the resume lock wait.

Tests I ran

Head fb0072acbd, after the Codex lock order and sidebar fixes (all under flock ~/.fork-go.lock):

  • go test ./coderd/x/chatd/ -count=1 -v: ok. 2560 PASS, 0 FAIL.
  • go test ./coderd/x/chatd/ -run TestForkCapacityAdmissionLockScope -count=5: ok.
  • go test ./coderd/database/forkdb/ ./coderd/database/dbmetrics/ -count=1 -v: ok. 66 PASS, 0 FAIL.
  • go test ./coderd/database/dbauthz/ -run "TestForkQuerier|TestMethodTestSuite" -count=1: ok.
  • go test ./coderd/ -run TestForkChatFamilyCapacity -count=1 -v: 3 PASS, 0 FAIL.
  • go build ./... and go vet ./coderd/x/chatd/: clean. gofmt -l coderd/: clean.
  • golangci-lint run --fix=false --config=.golangci.new-code.yaml --new-from-merge-base=origin/main ./coderd/x/chatd/... ./coderd/database/...: 0 issues.

Head ae328f99fe, after the deadlock fix:

  • go test ./coderd/x/chatd/ ./coderd/database/forkdb/ ./coderd/database/dbmetrics/ -count=1 -v: ok for all 3 packages. 2624 PASS, 0 FAIL.
  • go test ./coderd/ -run TestForkChatFamilyCapacity -count=1 -v: 3 PASS, 0 FAIL.
  • go build ./... and go vet ./coderd/x/chatd/: clean. gofmt -l coderd/: clean.
  • golangci-lint run --fix=false --config=.golangci.new-code.yaml --new-from-merge-base=origin/main ./coderd/x/chatd/... ./coderd/database/...: 0 issues.

Earlier heads:

  • flock ~/.fork-go.lock go test ./coderd/x/chatd/ ./coderd/database/forkdb/ ./coderd/database/dbmetrics/ -count=1 -v: ok for all 3 packages. 2618 PASS, 0 FAIL.
  • flock ~/.fork-go.lock go test ./coderd/database/dbauthz/ -run "TestForkQuerier|TestMethodTestSuite" -count=1: ok.
  • flock ~/.fork-go.lock go test ./coderd/ -run TestForkChatFamilyCapacity -count=1 -v: PASS (Enabled, Disabled).
  • go vet on the touched packages: clean. gofmt -l: clean.
  • golangci-lint run --fix=false --config=.golangci.new-code.yaml --new-from-merge-base=origin/main ./coderd/x/chatd/... ./coderd/database/...: 0 issues.

New tests:

  • TestGetSubagentCapacityCounts and TestGetSubagentCapacityCountsAwaitingOnly (forkdb): several candidates across 2 organizations in one call. The second test also selects by root_chat_id and checks it returns the same 3 rows as the explicit IDs, in ID order.
  • TestForkListAgentsCapacityStatements: 50 running children. It counts GetChatOrganizationSubagentLimits plus GetSubagentCapacityCounts through dbmetrics and asserts at most 2.
  • TestForkCapacityAdmissionLockScope:
    • With only a family limit, a family-mode Admit succeeds within the 5 s timeout while another transaction holds chatFamilyAdmissionLockID of its family (the spawn and resume lock).
    • An admission held open in family A does not block family B.
    • A sibling in family A waits on chatFamilyCapacityLockID, and while it waits only 1 transaction holds the deployment lock.
    • A simulated exclusive deployment lock holder blocks family-mode admission.
    • With a deployment limit, family B waits again.
  • TestNestedSubagentResumeLockTimeout: holds the family admission lock in another transaction. A message_agent send fails with "lock timeout" after about 5 s while its context is still live. This uses the real Postgres lock timeout, because mock time cannot shorten a wait inside Postgres. The test takes about 5.2 s.

Negative controls

Each one was a temporary revert, and the code was restored afterwards.

  • With one capacity call per child in list_agents, the statement test fails: 102 statements, not at most 2.
  • With the exclusive deployment lock forced in every mode, the lock scope test fails at the family B admission with a lock timeout after 5.29 s.
  • Without the resume lock timeout, the send blocks until the 15 s context ends. It fails with "canceling statement due to user request", not "lock timeout".
  • With Admit switched back to chatFamilyAdmissionLockID, the lock scope test fails at the new assertion (line 596) with "canceling statement due to lock timeout" after 5.23 s.
  • With the old order (shared deployment lock before the family lock), the lock scope test fails at line 627: 2 holders of the deployment lock, not 1.
  • With the SQL root filter disabled (AND false), TestGetSubagentCapacityCountsAwaitingOnly fails (0 rows, not 3) and TestForkChatFamilyCapacity fails (empty WaitingForCapacity).

Not verified and residual risk

  • make gen stops at helm/ai-gateway/tests because helm is not installed in this workspace. make -k gen produced no diff in the files this PR touches. The forkdb code was generated with coderd/database/forkdb/generate.sh.
  • The resume, takeover and Admit deadlock was found by review and reproduced there as a lock pattern. My test shows that Admit no longer waits on the spawn and resume lock. It does not replay the full three-transaction cycle. I found no other wait in a family-mode admission that could close a cycle with the shared deployment lock, but I did not prove that.
  • No dedicated test asserts that the resume path clears its lock timeout after it takes the family lock.
  • The spawn path still takes the family lock without a lock timeout. This PR does not change that.
  • No UI or end-to-end check on a running server.
  • The diff has about 530 added non-generated lines, and about 290 of them are tests. I kept it as one PR because the query, the callers and the lock change share one contract.

…ck per family

Replace the per-candidate capacity queries with GetSubagentCapacityCounts,
which counts every candidate in one set-based statement. list_agents reads
organization limits once per organization and runs one batched query.

Admission takes the shared deployment lock plus the per-family lock when
only a family limit is configured, so spawns in different families do not
serialize. Resume validation now uses the same 5 s lock timeout as Admit.

Closes #301
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T06:31:38.584751Z fb0072a Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 91b9ec5943

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged main (#351) into the branch so it is not behind. No conflicts. Regenerated forkdb code (no diff). Reran chatd, forkdb, dbmetrics, dbauthz fork and plugins tests: all ok.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 2a61e8a9c0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged main (#357) into the branch so it is not behind. No conflicts. Regenerated forkdb code (no diff). Reran chatd, forkdb, dbmetrics, chatdmig and dbauthz fork tests: all ok.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 8454e6bad5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged main (#360) into the branch so it is not behind. No conflicts. Regenerated forkdb code (no diff). Reran chatd, forkdb, dbmetrics, plugins, enterprise/dbcrypt and dbauthz fork tests: all ok.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: d8ab281370

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

A family-mode Admit held the shared deployment admission lock while it
waited for the family lock that spawns and resumes hold. A resume holds
that lock and waits for a sender row that a lease takeover locks, and the
takeover waits for the exclusive deployment lock, so the three could
deadlock. Admit now takes a separate per-family capacity lock. Spawns and
resumes never change the active count, so Admit need not wait for them.

The resume path also clears its 5 s lock timeout once it holds the family
lock, so EditMessage and the later admission wait as before.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Pushed 1ca9ece to fix a regression found in review. Family-mode Admit now takes its own lock, chatFamilyCapacityLockID(root), instead of the spawn and resume family lock, which could deadlock with a resume and a lease takeover. The resume path also clears its 5 s lock timeout after it takes the family lock. The new test assertion fails with the old key (lock timeout) and passes with the new one. The PR body has the updated test results.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 1ca9ece7fc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged main (54e2b41, after #346, #358 and #361) into the branch. No conflicts. Regenerated forkdb code (no diff). Build ok. chatd, forkdb, dbmetrics: 2626 PASS, 0 FAIL. fork-ci run 43811119490 passed on ae328f9.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ae328f99fe

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/fork_capacity.go Resolved
Comment thread coderd/x/chatd/fork_family.go Resolved
…in SQL

A family-mode admission now takes the family capacity lock before the
shared deployment lock, so admissions that wait for their family do not
hold the shared lock and delay heartbeat renewal.

GetSubagentCapacityCounts takes an optional root_chat_id and selects the
family's candidates itself, so the family sidebar no longer loads every
family chat ID into Go and sends it back.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: fb0072acbd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike
ibetitsmike merged commit d4b1539 into main Nov 16, 2026
10 checks passed
@ibetitsmike
ibetitsmike deleted the mike/issue-301-batched-capacity branch November 16, 2026 06:37
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged at head fb0072acbdf89cfdd1ac324bcfcd727c20bd1b00 as d4b1539, on main 54e2b41bf974e5e2e62a7e405991588bd4cd57cb, with the server running that main.

Gates on this exact head:

  1. The head matched the SHA I verified (--match-head-commit).
  2. Every check run passed. fork-ci run 43815158477 passed on this head.
  3. Codex receipt for this head: perf(coderd/x/chatd): count subagent capacity in one statement and lock per family #359 (comment) ("Didn't find any major issues").
  4. No unresolved review thread. Both Codex P2 findings on ae328f99fe (shared lock held while waiting for the family; family IDs loaded into Go) were regressions of this PR, so they were fixed in fb0072acbd and resolved.
  5. 0 commits behind main.
  6. I ran the tests below on this exact head.

Tests I ran on the PR commit at 8454e6bad5 (detached worktree, under flock ~/.fork-go.lock, Postgres 16 at 127.0.0.1:5432):

  • go test -count=1 -v -run 'Capacity|ListAgents|Subagent|Family|Admission|Resume' ./coderd/x/chatd/: 213 PASS, 0 FAIL.
  • go test -count=1 -v -run 'Capacity|Family' ./coderd/database/forkdb/: 3 PASS, 0 FAIL.
  • go test -count=1 -v -run 'TestForkQuerier|TestMethodTestSuite' ./coderd/database/dbauthz/: 5394 PASS, 0 FAIL.
  • go test -count=1 -v -run TestForkChatFamilyCapacity ./coderd/: 3 PASS, 0 FAIL.
  • Negative control: with the exclusive deployment lock forced in every mode (if true || ... in acquireAdmissionLocks), TestForkCapacityAdmissionLockScope fails after 5.24 s (family B waits for family A). The source was restored after.
    After the deadlock fix (commit 1ca9ece7fc: family capacity admission takes its own advisory key, and the resume path clears its 5 s lock timeout after the family lock), on head 1ca9ece7fc:
  • go test -count=1 -v -run 'TestForkCapacity|TestForkListAgents|TestNestedSubagent|TestForkChatQueuedForCapacity|Capacity|Subagent' ./coderd/x/chatd/: 168 PASS, 0 FAIL.
  • go test -count=1 -v ./coderd/x/chatd/: 2558 PASS, 0 FAIL.
  • Negative control: with Admit switched back to chatFamilyAdmissionLockID, TestForkCapacityAdmissionLockScope fails after 5.13 s with "canceling statement due to lock timeout" (Admit waited on the spawn and resume lock). The source was restored after.
  • An Opus review of the earlier head found the deadlock (family-mode Admit held the shared deployment lock while it waited for the lock that resumes hold; a lease takeover closes the cycle). The fix follows its recommendation.

On the final head fb0072acbd (adds a main merge and fb0072acbd: family capacity lock before the shared deployment lock, and the family filter in SQL through an optional root_chat_id):

  • go test -count=1 -v ./coderd/x/chatd/: 2560 PASS, 0 FAIL.
  • go test -count=1 -v -run 'Capacity|Family' ./coderd/database/forkdb/ and go test -count=1 -v -run TestForkChatFamilyCapacity ./coderd/: 6 PASS, 0 FAIL.
  • Negative control: with the old lock order (shared deployment lock before the family capacity lock), TestForkCapacityAdmissionLockScope fails. The source was restored after.

Lock order after this PR, from an Opus review of 8454e6bad5 and my reading of fb0072acbd: the family capacity lock is held only by family-mode admissions, which take it before the shared deployment lock. Spawns and resumes keep their own family admission lock. Heartbeat renewal and takeovers take only the deployment lock. I found no cycle.

Not exercised: a test that replays the full resume, takeover and admission cycle; a test that the resume path clears its lock timeout; the spawn path's family lock still has no timeout (unchanged); a running server or the UI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

chatd: subagent capacity is counted once per candidate, under a deployment-wide lock

1 participant