Repository navigation
fix(relay): stop taking the fleet-wide cell inventory lock on per-connection paths - #18606
Conversation
…nection paths activateControl, acquireActivity, changeActivity and removeSupersededSameCellControls each adjust exactly one cell's reservation, yet took SELECT * FROM relay_cells FOR UPDATE, so every desktop rebind and phone reconnect in the fleet queued behind every other one and behind placement. They now use the single-row atomic update (or lock only their own cell row), leaving the inventory lock to placement and sweeps. Fleet-wide 55P03 retries ran p50 430 / p99 1320 per five minutes on 2026-09-03, every cell pinned sqlLatencyMsMax at the lock timeout, and the old cell image crashed on the resulting pool timeouts ~every 15 minutes. A real-Postgres test holds another cell's row and asserts a rebind proceeds; re-adding the inventory lock fails it.
…y moves Review found that acquireActivity's existing-lease branch could lock the old lease's cell row (via removeActivityLease) before the new cell's row, which cycles with placement's ascending inventory lock; reproduced on real Postgres as paired 55P03 retries. lockCellRows now takes the one or two rows a per-connection path touches in cell_id order with the 500 ms request bound, and the census fails on any inline relay_cells FOR UPDATE outside the named lock helpers. A three-cell Postgres test moves an activity from the highest cell to a lower one while the target row is held and asserts the mover holds nothing else; five revert-mutants (inventory lock on each path, dropped ordering, dropped ORDER BY) fail it.
|
This run was cancelled 🛑 The workflow was cancelled before completion. Please check the link below for details. |
…ments Review showed two evasions: a FOR UPDATE inside query() and a queryLocked whose FROM relay_cells sat past a fixed line window. The guard now matches every query()/queryLocked() template statement in full; both evasions fail it. Also clears relay_cell_connection_snapshots in the connection- headroom Postgres suite so an aborted run does not poison the next.
📝 WalkthroughWalkthroughRelay assignment paths now use atomic reservation updates and targeted cell-row locks instead of the fleet-wide inventory lock. Multi-cell activity moves lock rows in ascending Merge Risk: 🔵 Low · up to The relay test suite can retain database locks or perform work after teardown, and the lock census can miss future unregistered cell locks. Fix these test safeguards before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides strong implementation, rationale, review, verification, and rollout details. However, it omits the mandatory Linked Issue entry and several required template sections, including Visual Proof, Testing, Agent skill upstream boundary, Notes, and Checklist. Resolution Add the missing required sections. Include a real issue reference after "Fixes #". Add "Visual Proof" with "N/A" and a reason if there is no UI or interaction change. Add a "Testing" section with the required test checklist and platform details. Complete the Agent skill upstream boundary, Notes, and Checklist sections. Keep the existing detailed technical content under the matching template headings, including a separate "Why" section if needed.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: a50540c9-3615-4eac-9186-24fe5aaf25cb
📒 Files selected for processing (4)
cloud/apps/relay/src/assignment-control-supersession-postgres.test.tscloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/cell-inventory-lock-census.test.tscloud/apps/relay/src/control-rebind-inventory-lock-postgres.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| if (!/queryLocked\(/.test(line)) return | ||
| const statement = lines.slice(index, index + 4).join(' ') | ||
| if (!/FROM relay_cells\b/.test(statement)) return |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Scan complete lock calls across both query APIs.
queryLocked adds FOR UPDATE, and query can execute raw FOR UPDATE SQL inside a transaction. The current census contract requires every inline relay_cells lock to be registered. Scan the complete call expression for both APIs, while retaining the named-helper exclusions, so a raw query(...) lock or a multiline call cannot bypass the census.
| const timeout = new Promise<never>((_, reject) => | ||
| setTimeout( | ||
| () => | ||
| void blockedStatement().then((statement) => | ||
| reject(new Error(`rebind on cell A blocked behind cell B's row: ${statement}`)) | ||
| ), | ||
| 2_000 | ||
| ) | ||
| ) | ||
| const rebound = await Promise.race([ | ||
| store.activateControl(identity, { | ||
| cellId: cells[0]!.id, | ||
| assignmentEpoch: assignment.assignmentEpoch, | ||
| generation: 2, | ||
| connectionInclusionWatermark: 11 | ||
| }), | ||
| timeout | ||
| ]) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Clean up the holder and timeout in every race outcome.
When Promise.race rejects, execution skips releaseInventory() and await holder, so the Postgres transaction can keep the relay_cells lock and block teardown. When activation wins, the timer can call blockedStatement() after databases[1] closes and produce an unhandled rejection. Use a timer handle and try/finally to clear it, release the holder, and await holder.
…nection paths (stablyai#18606) * fix(relay): stop taking the fleet-wide cell inventory lock on per-connection paths activateControl, acquireActivity, changeActivity and removeSupersededSameCellControls each adjust exactly one cell's reservation, yet took SELECT * FROM relay_cells FOR UPDATE, so every desktop rebind and phone reconnect in the fleet queued behind every other one and behind placement. They now use the single-row atomic update (or lock only their own cell row), leaving the inventory lock to placement and sweeps. Fleet-wide 55P03 retries ran p50 430 / p99 1320 per five minutes on 2026-09-03, every cell pinned sqlLatencyMsMax at the lock timeout, and the old cell image crashed on the resulting pool timeouts ~every 15 minutes. A real-Postgres test holds another cell's row and asserts a rebind proceeds; re-adding the inventory lock fails it. * fix(relay): lock the touched cell rows in order on cross-cell activity moves Review found that acquireActivity's existing-lease branch could lock the old lease's cell row (via removeActivityLease) before the new cell's row, which cycles with placement's ascending inventory lock; reproduced on real Postgres as paired 55P03 retries. lockCellRows now takes the one or two rows a per-connection path touches in cell_id order with the 500 ms request bound, and the census fails on any inline relay_cells FOR UPDATE outside the named lock helpers. A three-cell Postgres test moves an activity from the highest cell to a lower one while the target row is held and asserts the mover holds nothing else; five revert-mutants (inventory lock on each path, dropped ordering, dropped ORDER BY) fail it. * test(relay): make the inline relay_cells lock census scan whole statements Review showed two evasions: a FOR UPDATE inside query() and a queryLocked whose FROM relay_cells sat past a fixed line window. The guard now matches every query()/queryLocked() template statement in full; both evasions fail it. Also clears relay_cell_connection_snapshots in the connection- headroom Postgres suite so an aborted run does not poison the next.

ELI5
The relay keeps a 23-row table of "how full is each cell". Any time a desktop rebinds its control or a phone reconnects, the code locked all 23 rows until the transaction committed, even though it only changes one cell's number. So every reconnect in the fleet queued behind every other one and behind placement. That is the source of the fleet-wide lock retries (p50 430 / p99 1320 per five minutes on 2026-09-03), the 1 s SQL latency pinned on every cell, the 24 s phone hang that started this investigation, and the pool timeouts that crash the old cell image about every 15 minutes. This PR makes those paths lock only the one or two rows they touch.
What changed
cloud/apps/relay/src/assignment-store.tsactivateControl(fresh control),acquireActivity(existing lease),changeActivity, andremoveSupersededSameCellControlsno longer calllockCellInventory. They use the existing single-row atomic update, orlockCellRows.lockCellRows(cellIds): locks exactly the given rowsORDER BY cell_id ASCwith the 500 ms request bound. Used where a path touches two cells (a client-chosen activity id following a migration) so the order matches placement's ascending inventory lock and no cycle can form.assign*), evacuation, rehome, and sweeps keep the inventory lock unchanged.cloud/apps/relay/src/cell-inventory-lock-census.test.tsFROM relay_cells ... FOR UPDATEoutsidelockCellInventory/lockGeneralCellInventory/lockCellRowsfails until listed. The 12 pre-existing inline sites are enumerated.cloud/apps/relay/src/control-rebind-inventory-lock-postgres.test.ts(new, Postgres-gated)cloud/apps/relay/src/assignment-control-supersession-postgres.test.tsrelay_cell_connection_snapshots; a leftover snapshot from an aborted run made it fail withstale_connection_snapshoton every rerun.Review
Independent adversarial review (Opus) before push found one real defect in the first cut:
acquireActivitylocked the old lease's cell before the new one, which cycles with placement. Reviewer reproduced it on real Postgres as paired 55P03 retries (no 40P01 because lock_timeout equals deadlock_timeout). Fixed bylockCellRows. Reviewer confirmed capacity accounting is unchanged: every writer ofrelay_assignment_activity_leasesthat changes a cell's units takes that cell's row in the same transaction, so the recomputed SUM cannot miss a sibling.Verification
tsc --noEmitclean.--no-file-parallelism: full relay suite green except two files that fail identically on main.removeSupersededSameCellControls; toactivateControl; toacquireActivity;lockCellRowsdropped fromacquireActivity;ORDER BYdropped fromlockCellRows.Rollout
Ships in the next relay image. Director first (
cloud-deploy-relay-production-director), then cells via same-cap roll. The c7 canary on the current image (85bf6799) still shows 55P03 retries and 1.0–1.2 ssqlLatencyMsMaxduring refill, which is the measurement this PR should move. Follow-ups: paced drain on the cell side, monitor bar re-tighten, Terraform exhausted-alert recalibration.