Skip to content

fix(relay): stop taking the fleet-wide cell inventory lock on per-connection paths - #18606

Merged
Jinwoo-H merged 3 commits into
mainfrom
relay-single-row-reservation
Sep 4, 2026
Merged

Jinwoo-H merged 3 commits into
mainfrom
relay-single-row-reservation

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​337 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​331
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​24 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​16

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.ts

  • activateControl (fresh control), acquireActivity (existing lease), changeActivity, and removeSupersededSameCellControls no longer call lockCellInventory. They use the existing single-row atomic update, or lockCellRows.
  • New lockCellRows(cellIds): locks exactly the given rows ORDER BY cell_id ASC with 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.
  • Placement (assign*), evacuation, rehome, and sweeps keep the inventory lock unchanged.

cloud/apps/relay/src/cell-inventory-lock-census.test.ts

  • Removes the four converted sites from the census.
  • New check: any inline FROM relay_cells ... FOR UPDATE outside lockCellInventory / lockGeneralCellInventory / lockCellRows fails until listed. The 12 pre-existing inline sites are enumerated.

cloud/apps/relay/src/control-rebind-inventory-lock-postgres.test.ts (new, Postgres-gated)

  • Rebind supersedes a control on cell A while another transaction holds cell B's row: must not wait.
  • Three-cell move: activity moves from the highest cell to a lower one while the target row is held; asserts the mover holds no other cell row while waiting, and that accounting matches the SQLite origin-scoped case.

cloud/apps/relay/src/assignment-control-supersession-postgres.test.ts

  • Cleanup now also deletes relay_cell_connection_snapshots; a leftover snapshot from an aborted run made it fail with stale_connection_snapshot on every rerun.

Review

Independent adversarial review (Opus) before push found one real defect in the first cut: acquireActivity locked 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 by lockCellRows. Reviewer confirmed capacity accounting is unchanged: every writer of relay_assignment_activity_leases that changes a cell's units takes that cell's row in the same transaction, so the recomputed SUM cannot miss a sibling.

Verification

  • 480 SQLite unit tests, tsc --noEmit clean.
  • Postgres 17 on 127.0.0.1:55440, --no-file-parallelism: full relay suite green except two files that fail identically on main.
  • Revert-mutants against the new Postgres test, each fails it: inventory lock re-added to removeSupersededSameCellControls; to activateControl; to acquireActivity; lockCellRows dropped from acquireActivity; ORDER BY dropped from lockCellRows.

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 s sqlLatencyMsMax during 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.

…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.
@pullfrog

pullfrog Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

This run was cancelled 🛑

The workflow was cancelled before completion. Please check the link below for details.

Pullfrog  | View workflow run | via Pullfrog | 𝕏

Jinwoo-H added a commit that referenced this pull request Sep 4, 2026
…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.
@Jinwoo-H
Jinwoo-H merged commit 7b108ab into main Sep 4, 2026
24 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 4, 2026
@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Relay 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 cell_id order. PostgreSQL tests cover concurrent control rebinding, activity migration, supersession, and reservation accounting. Census tests track inline cell-row lock sites, and test cleanup removes connection snapshot rows.

Merge Risk: 🔵 Low · up to 65569

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides strong implementation, rationale, review, verification, and rollout details. However, it omits the mandatory Linked Issue entry and several required template sections, includi… 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 det…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: removing the fleet-wide cell inventory lock from per-connection relay paths.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: a50540c9-3615-4eac-9186-24fe5aaf25cb

📥 Commits

Reviewing files that changed from the base of the PR and between 2ee507d and 65569be.

📒 Files selected for processing (4)
  • cloud/apps/relay/src/assignment-control-supersession-postgres.test.ts
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/cell-inventory-lock-census.test.ts
  • cloud/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.

Comment on lines +186 to +188
if (!/queryLocked\(/.test(line)) return
const statement = lines.slice(index, index + 4).join(' ')
if (!/FROM relay_cells\b/.test(statement)) return

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.

🩺 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.

Comment on lines +147 to +164
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
])

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.

🩺 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.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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.

1 participant