Repository navigation
fix(coderd/database): lock the workspaces row when claiming a prebuild - #31518
Conversation
6e095b7 to
fb5461f
Compare
ClaimPrebuiltWorkspace locked the workspace_prebuilds view with FOR UPDATE ... SKIP LOCKED. The view is built from CTEs, so the lock took no row locks and concurrent claims picked the same prebuild. The losing request failed with 409 "A workspace build is already active." Select the candidate from the workspaces table directly and lock that row with FOR NO KEY UPDATE SKIP LOCKED. Ownership and deletion are checked on the locked row so a prebuild claimed by a just-committed transaction is skipped. The eligibility checks use per-workspace index lookups instead of the views, so skipping a locked row no longer repeats deployment-wide work. Compare with = so the locking subquery runs once, and claim the newest prebuild first because the reconciler deletes the oldest first. Co-authored-by: Kevin Ha <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
fb5461f to
84f50e6
Compare
|
/coder-agents-review Please limit the review to P0, P1, and P2 issues only. |
|
Chat: Review posted | View chat Review history
deep-review v0.13.0 | Round 1 | Last posted: Round 1, 16 findings (1 P2, 8 P3, 4 P4, 3 Nit), COMMENT. Review Finding inventoryFinding inventoryFindings
Contested and acknowledgedLaw analysisNot run. Effective additions 403 (threshold 1000). Round logRound 1Full panel (round 1). Netero first pass: 1 P3, 1 Note, no P0, so panel ran. Panel: Knuckle, Ging-Go, Takumi, Killua, Ryosuke (Go + SQL specialists), Pariston, Mafuuu (core), Bisky (tests), Gon, Leorio (once-per-PR floor), Komugi, Hisoka (pool), Zoro (wildcard). Multi-domain (Go and SQL, concurrency): 13 panel reviewers, size target 9-12 exceeded by 1 because Gon and Leorio default to round 1 alongside the five triggered specialists. Contradiction: Pariston recommends FOR UPDATE; Takumi and Mafuuu argue NO KEY UPDATE avoids a claim/reconciler deadlock; Bisky asks for a behavioral test of NO KEY UPDATE. Posted as CRF-4 (tradeoff) and CRF-5 (test for whichever mode is kept). Gon P2 comment findings downgraded: CRF-12 to Nit (keep-argument: stale rationale in concurrency-critical SQL misleads; drop reason: sentence is true and explains why the views are not locked), CRF-13 to P4 (keep-argument: reader cannot resolve the reference; drop reason: test-only comment, no behavior effect). Result: 1 P2, 8 P3, 4 P4, 3 Nit posted. Reviewed against 1acacc9..84f50e6. About deep-reviewCRF = Coder Review Finding (P0-P4, Nit, Note)
|
BobbyHo
left a comment
There was a problem hiding this comment.
Overall, the code changes LGTM! Just curious if you've considered how TTL interacts with newest-first ordering. If demand stays below the pool size, older prebuilds might never get picked and could end up expiring and being rebuilt unnecessarily. Oldest-first could help avoid this churn, though I understand there's an existing reconciler race.
Just something that came to mind, but not a blocker. I think the changes in this PR look good overall! 🙂
There was a problem hiding this comment.
This PR rewrites ClaimPrebuiltWorkspace to lock the workspaces row with SKIP LOCKED, check eligibility per workspace, and claim newest first. Findings: 1 P2, 8 P3, 4 P4, 3 Nit.
The two comments on prebuilds.sql:77 are linked: one weighs FOR UPDATE against FOR NO KEY UPDATE, and the other asks for a behavioral test of the mode you keep.
Out of scope (needs a ticket or explicit acceptance by a human):
enterprise/coderd/prebuilds/reconcile.go:955:provisionDeletereads the workspace owner without locking the row, so a reconciler delete build can race a claim, and the claim returns 409 when it inserts its build second. The PR description lists this as a follow-up with no linked issue.coderd/database/queries/prebuilds.sql:35: when Postgres rechecks a lockedpwrow, the latest-build join and the preset and agent subqueries keep their statement-snapshot values, so a delete build committed after the snapshot is not seen and the claim hands out a workspace that is being deleted.coderd/database/queries/prebuilds.sql:16: the claim does not check the preset TTL orlast_invalidated_at, so it can take a prebuild the reconciler has classified as expired and is deleting.coderd/database/dbtestutil/db.go:172: test databases run withjit = off, so no test or benchmark can detect a query whose plan cost crossesjit_above_costin production.
Notes:
SKIP LOCKEDalso skips prebuilds locked by other writers such asUpdateWorkspacesTTLByTemplateID; a claim during such a statement getssql.ErrNoRowsand the user gets a new workspace build instead.- The recheck of a locked row relies on READ COMMITTED (
coderd/workspaces.go:712callsInTx(..., nil)); a caller that wraps the claim in REPEATABLE READ would get serialization errors instead of skips. TestClaimPrebuiltWorkspaceClaimsOnecatches a revert toINonly while the planner reruns the subquery per outer row, which it did on Postgres 13.TestClaimPrebuiltWorkspaceRechecksLockedRowpasses the seven query parameters positionally in the generated order (querier_test.go:8096).
🤖 This review was automatically generated with Coder Agents.
…set's template Claim prebuilds oldest first so they are used before they reach the preset TTL. Filter candidates by the preset's template so Postgres can use workspace_template_id_idx and skip other templates' prebuilds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Good call, switched to oldest-first in f509c1b. Newest-first was meant to dodge the reconciler delete race, but with claims down to ~12ms that window is tiny, and the TTL churn you described would be a constant cost on any preset with a TTL. Thanks for flagging it! |
BobbyHo
left a comment
There was a problem hiding this comment.
lgtm. Thanks for addressing my comments.
Emyrk
left a comment
There was a problem hiding this comment.
Review comments from Steven, drafted with Coder Agents. The concurrent-claim lock and oldest-first selection look good; the three inline comments cover the reconciler race, agent nesting, and regression coverage.
| -- NO KEY UPDATE matches the outer UPDATE and, unlike FOR UPDATE, does not block FK checks | ||
| -- from inserts that reference the workspace, such as a reconciler delete build. | ||
| LIMIT 1 | ||
| FOR NO KEY UPDATE OF pw SKIP LOCKED -- Ensure that a concurrent request will not select the same prebuild. |
There was a problem hiding this comment.
This comment is from an agent (Coder Agents generated). The claim-versus-reconciler-delete 409 remains possible with this lock mode, as noted in the description. We should investigate alternatives that coordinate claims and deletion, such as implementing a queue.
There was a problem hiding this comment.
Agreed, this lock mode doesn’t close the claim vs delete race. It’s pre-existing and only ever a 409. I’d like to do the proper coordination as a follow-up rather than in the patch
Emyrk
left a comment
There was a problem hiding this comment.
I am approving the overall idea. I did not look at the new query.
TIL locking a view is a no-op? And postgres just allows that with no error? Feels like an easy mistake to make.
I think we should take step back and re-evaluate the design once we patch this immediate bug. This is my first time looking at this code, but the discussion with an agent suggestions that this code might be kind of fragile?
… claim eligibility Add eligibility cases for a build whose only agent is deleted and for a latest build without a preset after an earlier build had one. Drop the locked-row recheck test and its test-only query export; the concurrent and eligibility tests already fail without the owner_id predicate. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClaimPrebuiltWorkspacelocked theworkspace_prebuildsview withFOR UPDATE ... SKIP LOCKED, but the view is built from CTEs, so nothing got locked. Concurrent claims picked the same prebuild and the losers got a 409 (a customer saw 28 of 30 fail).This locks the
workspacesrow directly (FOR NO KEY UPDATE SKIP LOCKED), rechecks owner and deleted on it, and checks eligibility with per-workspace index lookups instead of the views. It uses=instead ofINso one claim can't take two prebuilds, filters on the preset's template so other templates' prebuilds aren't scanned, and claims oldest first so prebuilds are used before they hit the preset TTL. Query-only, no migration, applies cleanly to release/2.38. Builds on #31468 by Kevin Ha (Canva).Benchmarks (Postgres 17, 20k users, 320k builds, 600 ready prebuilds): ~12 ms per claim (was ~640 ms), and 500 concurrent claims got distinct prebuilds in ~1.5 s.
Known limitations:
deleting_atmarker the claim skips.