Skip to content

fix(relay): read reconcile's counter units after the cell lock - #25638

Merged
Jinwoo-H merged 1 commit into
mainfrom
relay-reconcile-obs
Oct 5, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
relay-reconcile-obs

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Every relay cell row keeps a counter of how many requests it has promised. A repair job rewrites that counter from the list of live promises. It read the list, then waited for the cell row, then wrote the old list's total. A host placed while it waited lost its promise from the counter.

What Changed

  • reconcileReservationAccounting now reads each cell's lease units with a plain SELECT … GROUP BY cell_id issued after lockCellRows, and writes that total. The per-host counts and the lock order (assignments → leases → cell rows) are unchanged.
  • New Postgres test in postgres-transaction-recovery.test.ts: pauses reconciliation right after its lease read, places a brand-new host on one of the two cells, then lets reconciliation finish.

Before: the cell ends with reserved_requests = 0 and one lease worth 1 unit (the test fails on main with exactly this). After: reserved_requests = 1, matching the lease.

Why

The counter is written as an absolute value, so its inputs have to be read once the row is held. Any lease committed before the lock already bumped the counter and is now counted. Any lease still uncommitted belongs to a transaction that needs this row to bump the counter, so it cannot commit before reconciliation does.

Reconciliation runs only on migration-backed paths: evacuation completion and status, drain-send accounting repair, and supersede. Same-cap rolls use drain-return and create no migrations. In production it has run 0 times since 2026-09-28 (no pg_stat_statements entry for its statements, a window that includes the 10-02 US same-cap wave). So the bug bites only during evacuations, but when it does, a low counter lets a cell be promised past capacity_requests until the next repair.

Alternatives considered:

  • Moving the lease FOR UPDATE after the cell lock would invert the lock order every live writer uses, which risks deadlocks.
  • Re-reading the leases as a second FOR UPDATE adds locks with no benefit; the cell row already fences the writers that matter.

Found by the step-1 correctness review (F1), which reproduced it on local Postgres with the production lock shapes.

Linked Issue

N/A (internal relay fix)

Visual Proof

N/A: server-side accounting fix with no UI.

Testing

  • pnpm typecheck (cloud/apps/relay)

  • New test fails on main (reserved_requests 0 vs lease_units 1) and passes with the fix

  • Full relay suite including the relay-postgres project on a fresh local Postgres 16: 32 Postgres files / 173 tests pass; whole suite 113 files pass

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Review

Ships as a normal director deploy (pause rehome → publish → deploy → monitor → re-enable). Cells are unaffected until their next image; the bug only lives in director-run reconciliation paths.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

No wire, schema or lock-order change.

Cost, measured read-only in production by the reviewer:

  • The new statement is a full sequential scan of relay_assignment_activity_leases, which has no cell_id index (deliberately, see database.ts).
  • That table is 109 MB for ~24k live rows, about 12× bloated.
  • EXPLAIN ANALYZE of the exact statement: 14–16 ms. The same scan shape ran 7 days at a mean of 17.7 ms, with a max of 3.1 s under load.
  • Expect +14–18 ms of hold per reconcile call on the two cell rows, with a tail into seconds under load.
  • At today's frequency (0 calls since 09-28; a handful per source/target pair at the end of an evacuation), the fleet-level added hold is about 0 s/s.

Alternatives the reviewer tested:

  • A cell_id index: 6.5 → 0.5 ms locally, but it costs out-of-band DDL on the shared instance and ~104/s more index writes. Not worth it for a path that ran 0×/week.
  • Delta correction: wrong when an absolute writer commits in the gap.
  • Compacting the bloated table is the real lever for every scan of it. That is a separate ops item.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

reconcileReservationAccounting computed each cell's absolute reserved_requests
from leases read before lockCellRows, so a host placed in that gap lost its
unit: the counter went to 0 with one lease on the cell.

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

✅ No new issues found.

Reviewed changes

  • Read cell lease units after the cell lock: reconcileReservationAccounting now derives relay_cells.reserved_requests from a fresh SELECT cell_id, SUM(request_units) … GROUP BY cell_id WHERE cell_id IN (?, ?) issued after lockCellRows, instead of summing the leases snapshot read before the lock. This closes the window where a placement that committed a new lease while reconciliation waited on the cell rows had its counter bump overwritten away.
  • Regression test: a new relay-postgres test pauses reconciliation right after its lease read, places a brand-new host on one of the two cells, resumes, and asserts reserved_requests == lease_units == 1 with an exact equality — it fails on main and passes with the fix.

The fix is sound: every path that mutates reserved_requests holds the target cell row lock in the same transaction (the adjustCellReservation* helpers and reserveRegionalRehomeTargetRow; the only raw updates in non-test source are the locked rehome statement and this reconcile write), and Postgres transactions run at READ COMMITTED (plain BEGIN), so the post-lock read sees a lease committed during the wait. Lock order and the per-host assignment counts are unchanged.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c8d48504-037b-470b-adc9-e8e89f500e1e
📥 Commits

Reviewing files that changed from the base of the PR and between 2a68ea9 and 158b1b6.

📒 Files selected for processing (2)
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/postgres-transaction-recovery.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

reconcileReservationAccounting now calculates source and target cell reservation totals from activity leases after acquiring the cell locks. A PostgreSQL integration test checks the reservation total when a host assignment commits during reconciliation.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 158b1

The reconciliation change has no confirmed merge-blocking issue; merge after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 158b1

The change addresses a reservation-undercount race without expanding access or authority. Existing capacity checks and transactional rollback remain intact. Residual uncertainty concerns whether deployed database isolation settings match the assumptions behind the fix.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The directly affected state is the reservation accounting of the internally selected source and target cells. Incorrect totals can weaken shared cell-capacity enforcement, but this change does not introduce access to additional cells or data stores.

Trust Boundaries and Controls

  • observed — The inspected public placement route retains authenticated identity matching and per-host admission. The director evacuation-status route remains gated, and none of these caller controls changes in the PR.

Resilience and Maintainability Implications

  • inferred — Reconciliation's counter writes remain inside one transaction. Errors roll back partial updates, transient failures retry the operation, and repeated reconciliation recomputes absolute totals rather than accumulating duplicate reservations. This preserves failure containment, subject to the database isolation assumption.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 2…
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.
Title check ✅ Passed The title clearly and concisely describes the main change: reading reconciliation counter units after acquiring the cell lock.
Description check ✅ Passed The description covers the required sections, explains the change and rationale, links testing results, and marks the visual proof as not applicable because there is no UI change. The internal-contrib…
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@Jinwoo-H
Jinwoo-H merged commit 17ecee6 into main Oct 5, 2026
24 checks passed
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