Repository navigation
fix(relay): prune released control-connection reservations in bounded batches - #25352
Conversation
… batches relay_control_connection_reservations was never deleted: 13.8M rows and 9.1 GB in production, 99.999% of them in state 'released' and ~400k more a day. Nothing reads a released row (every reader filters it out by state), but each placement still locks all of its host's rows, ~160 on average. A new director sweep step deletes released rows older than a day. It walks the heap in TID ranges of 16 pages, because without an index on released_at a `LIMIT n` delete plans as a sequential scan from page 0 that gets slower as the head of the heap empties (production EXPLAIN). Each statement selects its rows FOR UPDATE SKIP LOCKED, so a row a request holds is skipped rather than waited on, and deletes them by `ctid = ANY(ARRAY(...))` so the delete is always a TID scan. A tick stops at 400 rows, 128 pages or 250 ms, which drains the backlog over about three days at five directors.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 🧰 Additional context used📚 Code guidelines (1)📝 WalkthroughWalkthroughThe change adds a reaper that removes released control-reservation rows older than 24 hours. PostgreSQL pruning uses bounded heap-page windows and skips locked rows; other database types use a row-limited deletion path. The assignment cleanup sequence now invokes this pruning step. Tests cover retention boundaries, batch limits, backlog draining, wraparound, lock contention, and PostgreSQL query plans. Priority: ➖ Normal Merge Risk: 🔵 Low · up to Pruning can exceed its configured per-tick row limit when a PostgreSQL window contains many eligible reservations. The excess work is bounded to a window, so this is mergeable with owner awareness and a follow-up fix. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The cleanup targets old, released reservations and preserves live reservation states. Its main risk is operational: the stated time and row budgets are checked between database statements, so slow cleanup can delay later maintenance. Page limits, lock skipping and existing database deadlines substantially contain that risk, but production timeout settings remain unconfirmed. Retained concerns
Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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: 1
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
61702f59-c30b-4ccb-bc2a-7ab53f81bde1
📒 Files selected for processing (5)
cloud/apps/relay/src/assignment-cleanup-steps.test.tscloud/apps/relay/src/assignment-cleanup-steps.tscloud/apps/relay/src/assignment-store.tscloud/apps/relay/src/heap-window-reaper.tscloud/apps/relay/src/released-reservation-prune.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| deleted += changes( | ||
| await database.query( | ||
| `DELETE FROM ${this.table} WHERE ctid = ANY(ARRAY( | ||
| SELECT ctid FROM ${this.table} | ||
| WHERE ctid >= CAST(? AS tid) AND ctid < CAST(? AS tid) AND ${this.predicate} | ||
| FOR UPDATE SKIP LOCKED | ||
| ))`, | ||
| [`(${page},0)`, `(${end},0)`, ...params] | ||
| ) | ||
| ) |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '40,78p' cloud/apps/relay/src/heap-window-reaper.ts
sed -n '107,164p' cloud/apps/relay/src/released-reservation-prune.test.tsRepository: stablyai/orca
Length of output: 3846
🏁 Script executed:
set -o pipefail
printf '%s\n' '--- diff base..head ---'
git diff --stat 51fe6f3fbadc7281e42d4974542aba9cd0e4b874 6d3daae376a28764a7db82c216ea7db40d4bb13b -- cloud/apps/relay/src/heap-window-reaper.ts cloud/apps/relay/src/released-reservation-prune.test.ts
git diff --unified=40 51fe6f3fbadc7281e42d4974542aba9cd0e4b874 6d3daae376a28764a7db82c216ea7db40d4bb13b -- cloud/apps/relay/src/heap-window-reaper.ts cloud/apps/relay/src/released-reservation-prune.test.ts
printf '%s\n' '--- reaper file ---'
nl -ba cloud/apps/relay/src/heap-window-reaper.ts | sed -n '1,220p'
printf '%s\n' '--- test references and relevant test blocks ---'
rg -n -F -- 'HeapWindowReaper' cloud/apps/relay/src cloud/apps/relay
rg -n -F -- 'maxRowsPerTick' cloud/apps/relay/src cloud/apps/relay
nl -ba cloud/apps/relay/src/released-reservation-prune.test.ts | sed -n '1,240p'
printf '%s\n' '--- table definition and reservation consumers ---'
rg -n -F -- 'relay_control_connection_reservations' cloud/apps/relay cloud | head -120Repository: stablyai/orca
Length of output: 41621
🏁 Script executed:
printf '%s\n' '--- production reaper configuration and caller ---'
nl -ba cloud/apps/relay/src/assignment-store.ts | sed -n '490,575p'
rg -n -F -- 'pruneReleasedControlReservations' cloud/apps/relay/src/assignment-store.ts cloud/apps/relay/src
rg -n -F -- 'releasedReservationReaper.reap' cloud/apps/relay/src
rg -n -F -- 'releasedReservationReaper' cloud/apps/relay/src/assignment-store.ts
printf '%s\n' '--- reservation table definition and indexes ---'
nl -ba cloud/apps/relay/src/database.ts | sed -n '545,610p'
nl -ba cloud/apps/relay/src/database.ts | sed -n '70,100p'
printf '%s\n' '--- production row-size/retention evidence ---'
rg -n -F -- '13.7M' cloud/apps/relay
rg -n -F -- '9 GB' cloud/apps/relay
rg -n -F -- 'RELEASED_CONTROL_RESERVATION_RETENTION_MS' cloud/apps/relay/srcRepository: stablyai/orca
Length of output: 11630
🏁 Script executed:
nl -ba cloud/apps/relay/src/assignment-cleanup-steps.ts | sed -n '1,60p'
nl -ba cloud/apps/relay/src/assignment-store.ts | sed -n '7174,7188p'Repository: stablyai/orca
Length of output: 3976
Cap the PostgreSQL DELETE by the remaining tick budget.
maxRowsPerTick limits the loop, but the PostgreSQL DELETE has no row limit. If one 16-page window contains more eligible rows than the remaining 400-row budget, the statement deletes every matching row in that window and exceeds the configured tick cap. Limit the selected TIDs to maxRowsPerTick - deleted.
Suggested fix
WHERE ctid >= CAST(? AS tid) AND ctid < CAST(? AS tid) AND ${this.predicate}
+ LIMIT ${this.budget.maxRowsPerTick - deleted}
FOR UPDATE SKIP LOCKED📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| deleted += changes( | |
| await database.query( | |
| `DELETE FROM ${this.table} WHERE ctid = ANY(ARRAY( | |
| SELECT ctid FROM ${this.table} | |
| WHERE ctid >= CAST(? AS tid) AND ctid < CAST(? AS tid) AND ${this.predicate} | |
| FOR UPDATE SKIP LOCKED | |
| ))`, | |
| [`(${page},0)`, `(${end},0)`, ...params] | |
| ) | |
| ) | |
| deleted += changes( | |
| await database.query( | |
| `DELETE FROM ${this.table} WHERE ctid = ANY(ARRAY( | |
| SELECT ctid FROM ${this.table} | |
| WHERE ctid >= CAST(? AS tid) AND ctid < CAST(? AS tid) AND ${this.predicate} | |
| LIMIT ${this.budget.maxRowsPerTick - deleted} | |
| FOR UPDATE SKIP LOCKED | |
| ))`, | |
| [`(${page},0)`, `(${end},0)`, ...params] | |
| ) | |
| ) |
🧰 Tools
🪛 ast-grep (0.45.3)
[error] 59-66: Avoid SQL injection
Context: database.query(
DELETE FROM ${this.table} WHERE ctid = ANY(ARRAY( SELECT ctid FROM ${this.table} WHERE ctid >= CAST(? AS tid) AND ctid < CAST(? AS tid) AND ${this.predicate} FOR UPDATE SKIP LOCKED )),
[(${page},0), (${end},0), ...params]
)
Note: [CWE-89] Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection').
(sql-injection-typescript)
🪛 OpenGrep (1.30.0)
[ERROR] 60-67: SQL query built via string concatenation or template literal passed to query()/execute(). Use parameterized queries instead.
(coderabbit.sql-injection.raw-query-concat-js)
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — relay redesign step 0: a bounded-batch prune of released control-connection reservations.
HeapWindowReaper(new) — walks the Postgres heap in TID ranges of 16 pages per statement withctid = ANY(ARRAY(SELECT ctid ... FOR UPDATE SKIP LOCKED)), a random first page, forward walk that wraps atpages, and per-tick caps of 400 rows / 128 pages / 250ms with the cursor persisted across ticks; SQLite uses arowid IN (SELECT ... LIMIT)batch.pruneReleasedControlReservations— new store method plus the 24h retention constant and reaper budget, wired into the cleanup step list afterrelease-expired-activity-leases.- Tests — the retention predicate (exact remaining rows), the per-tick row cap and multi-tick drain, heap wrap,
SKIP LOCKEDskip-not-wait, and a Postgres plan assertion pinningTid Range Scan/ noSeq Scan.
I verified the PR's safety argument end-to-end: every reader of the table filters out released (headroom query and cell status, inventory snapshot, insert dedup, claim, alreadyClaimed), and the only statement still touching released rows is the per-host lock, whose result is discarded. released is terminal — no writer transitions a released row back to reserved/late-arrival-debt/claimed, and every release stamps released_at — so deleting released rows cannot lose a live transition. The reaper's SKIP LOCKED means it never waits, so it cannot deadlock or invert the documented row-lock order against lockControlConnectionReservations; any residual interaction is bounded under-delete that a later cycle retries. CI sets ORCA_RELAY_TEST_POSTGRES_URL, so the production path is exercised.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

ELI5
Each time a desktop connects, the relay writes a small "seat reservation" row. When that connection ends, the row is marked "released", and nothing ever looks at it again. But it is never deleted. Production now holds 13.8 million of these rows (9 GB), and every new connection still locks all of its host's old rows. This change slowly deletes released rows once they are a day old.
What Changed
prune-released-control-reservations. It runs afterrelease-expired-activity-leases, every ~30 s per director.state = 'released' AND released_at <= now - 24h. No other state is touched.HeapWindowReaper(heap-window-reaper.ts). It walks the table's heap in TID ranges of 16 pages per statement:rowidbatch.Nothing changes for users. Placement, headroom and the inventory snapshot already ignore released rows.
Why
What is safe to delete. Every reader of
relay_control_connection_reservationsfilters by state and excludesreleased:assignment-connection-headroom-query.ts,assignment-store.tscell status):state IN ('reserved','late-arrival-debt','claimed');reservedorlate-arrival-debt;state <> 'released';late-arrival-debt.The only statement that still touches released rows is the tier-3 per-host lock (
lockControlConnectionReservations). It locks all of a host's rows, which today is ~160 rows per host on average.idempotency_keyis a fresh UUID per row and is never read. The 24 h window is margin for forensics only. It is far beyond the 10-minute late-arrival-debt window, the 10 s attach deadline and the 30 s orphan grace.Production evidence (read-only session, 2026-10-04/05):
n_tup_del = 0.Why TID windows rather than
LIMIT. There is no index onreleased_at, and new indexes on this table are forbidden without an out-of-band concurrent build (RULE besideSCHEMA). ProductionEXPLAINof... WHERE cell_id = ? AND state = 'released' AND released_at <= ? LIMIT 500picks a Seq Scan from page 0. Each tick that scan would reread the already-emptied head of a 501k-page heap, getting slower as the prune progresses. A TID range is aTid Range Scanwhatever the table holds: confirmed by productionEXPLAIN, and pinned by a Postgres plan test.Why
= ANY(ARRAY(...))rather thanIN (...). With realistic row estimates,ctid IN (subquery)can plan as a hash join over a sequential scan of the whole table. The local Postgres test caught exactly that. An array of TIDs is always aTid Scan.Pacing. At ~9 director ticks a minute (5 directors, 30 s plus jitter), 400 rows a tick is ~5M rows a day. The backlog drains over about three days. With up to 12 directors, it is about 1.2 days.
Contention with placement. The inner select uses
FOR UPDATE SKIP LOCKED, so a row a placement holds is skipped, never waited on. A placement whose host has a row in the batch being deleted waits for that one statement, a few milliseconds. Norelay_cellslock is taken.Alternatives considered:
released_at WHERE state = 'released'. It needs a productionCREATE INDEX CONCURRENTLYfirst, and it adds an index write to every release.LIMITbatches on the(cell_id, state)index. The planner still chose a seq scan in productionEXPLAIN.DELETE. That is the burst this avoids.Linked Issue
N/A. Relay redesign step 0 (internal).
Visual Proof
N/A. Database maintenance only; there is no UI or client-visible change.
Testing
released-reservation-prune.test.ts, run on SQLite and local Postgres 16 (port 55440):released_at.FOR UPDATEis skipped, and the statement does not wait.Tid Range ScanplusTid Scan, neverSeq Scan.assignment-cleanup-steps.test.tscovers the new step's order.cloud/apps/relay:pnpm typecheckpasses, and the full relay suite with Postgres passes.Review
Notes
VACUUM FULLorpg_repack, which is a separate operator decision.