Skip to content

fix(relay): prune released control-connection reservations in bounded batches - #25352

Merged
Jinwoo-H merged 1 commit into
mainfrom
relay-step0-reservation-prune
Oct 5, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
relay-step0-reservation-prune

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​238 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​238
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​122 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​120

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

  • New director sweep step prune-released-control-reservations. It runs after release-expired-activity-leases, every ~30 s per director.
  • It deletes rows with state = 'released' AND released_at <= now - 24h. No other state is touched.
  • New HeapWindowReaper (heap-window-reaper.ts). It walks the table's heap in TID ranges of 16 pages per statement:
    DELETE FROM t WHERE ctid = ANY(ARRAY(
      SELECT ctid FROM t WHERE ctid >= $from AND ctid < $to AND <predicate>
      FOR UPDATE SKIP LOCKED))
  • Per tick it stops at 400 rows, 128 pages (1 MB) or 250 ms, whichever comes first. Each director starts its walk at a random page and wraps around at the end of the heap. SQLite (dev and tests) uses a plain rowid batch.

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_reservations filters by state and excludes released:

  • headroom (assignment-connection-headroom-query.ts, assignment-store.ts cell status): state IN ('reserved','late-arrival-debt','claimed');
  • the inventory snapshot: same filter;
  • claim and insert: reserved or late-arrival-debt;
  • the already-claimed check: state <> 'released';
  • duplicate-debt release: 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_key is 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):

  • 13,782,770 released, 34 reserved, 129 late-arrival-debt, 25 claimed.
  • 1% sample: ~97% of released rows are older than 1 day.
  • ~400k new rows a day.
  • n_tup_del = 0.

Why TID windows rather than LIMIT. There is no index on released_at, and new indexes on this table are forbidden without an out-of-band concurrent build (RULE beside SCHEMA). Production EXPLAIN of ... WHERE cell_id = ? AND state = 'released' AND released_at <= ? LIMIT 500 picks 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 a Tid Range Scan whatever the table holds: confirmed by production EXPLAIN, and pinned by a Postgres plan test.

Why = ANY(ARRAY(...)) rather than IN (...). 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 a Tid 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.

  • Per tick: at most ~430 row locks for a few milliseconds, and ~30 KB of WAL. The relay currently writes ~0.6 MB/s of WAL.
  • In steady state, a walk that finds nothing reads ≤ 1 MB per tick.

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. No relay_cells lock is taken.

Alternatives considered:

  • A partial index on released_at WHERE state = 'released'. It needs a production CREATE INDEX CONCURRENTLY first, and it adds an index write to every release.
  • Per-cell LIMIT batches on the (cell_id, state) index. The planner still chose a seq scan in production EXPLAIN.
  • A one-off bulk 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

  • Automated tests added/updated
  • released-reservation-prune.test.ts, run on SQLite and local Postgres 16 (port 55440):
    • Only released rows at or past 24 h are deleted. Fresh released, reserved, debt and claimed rows stay, including a claimed row with an old released_at.
    • A tick stops at its row cap, and the backlog drains over later ticks.
    • The walk wraps from the last page to page 0.
    • A row another transaction holds FOR UPDATE is skipped, and the statement does not wait.
    • The statement plans as Tid Range Scan plus Tid Scan, never Seq Scan.
  • assignment-cleanup-steps.test.ts covers the new step's order.
  • From cloud/apps/relay: pnpm typecheck passes, and the full relay suite with Postgres passes.

Review

Notes

  • Disk space. Deleted space is reused by new rows after autovacuum. Table and index files do not shrink without a VACUUM FULL or pg_repack, which is a separate operator decision.
  • Autovacuum. Default scale factor is 0.2, so it runs a few times on this table while the backlog drains, as it already does for its update churn.
  • Backwards compatible. No schema change. Mixed director versions are fine: older directors simply do not prune.
  • Security, cross-platform, SSH, mobile: not affected.

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

🧰 Additional context used
📚 Code guidelines (1)
AGENTS.md — auto-discovered
📝 Walkthrough

Walkthrough

The 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 6d3da

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 Review

Security architecture risk: 🔵 Low · up to 6d3da

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

  • Low · reliability · inferred: The new pruning step relies on shared database deadlines, rather than its 250 ms threshold, to contain slow statements. Because cleanup steps are awaited serially, slow pruning can delay subsequent activity expiry, preference expiry and dead-cell evacuation. The 16-page statement bound, SKIP LOCKED and default database deadlines limit this exposure; production timeout overrides and aggregate director load remain unconfirmed.
Security review details

Security Blast Radius

  • observed — The deletion predicate has no user, host or cell restriction: maintenance can remove eligible released history across the reservation table. Its authority is therefore table-wide, although the state-and-age controls restrict deletion to old released records.

Trust Boundaries and Controls

  • observed — The inspected production caller supplies a fixed table, fixed predicate and fixed budget; the cutoff is passed as a query parameter derived from the store clock. Although the helper interpolates table and predicate strings, this call path does not expose them as client-selected SQL inputs.

Resilience and Maintainability Implications

  • observed — Existing serving-pool statement and lock deadlines constrain pruning queries, and SKIP LOCKED avoids waiting for request-held reservation tuples. Test source checks contention and the intended TID-range plan, but it is conditional on a PostgreSQL test URL and was not executed in this review. These controls limit the maintenance-containment concern without establishing production latency.

Hardening Proposals

  • proposed — If 250 ms is intended as a strict failure-containment boundary, consider a cleanup-specific database deadline rather than relying solely on elapsed-time checks between statements. Validate that deadline against production timeout settings and expose cleanup duration and backlog progress before expanding throughput.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
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 10 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: bounded pruning of released control-connection reservations.
Description check ✅ Passed The description covers the change, rationale, linked-issue context, visual-proof exception, and testing. It also explains operational impact and compatibility. The blank Review section and unchecked c…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 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.

@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: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 61702f59-c30b-4ccb-bc2a-7ab53f81bde1
📥 Commits

Reviewing files that changed from the base of the PR and between 0a8c572 and 6d3daae.

📒 Files selected for processing (5)
  • cloud/apps/relay/src/assignment-cleanup-steps.test.ts
  • cloud/apps/relay/src/assignment-cleanup-steps.ts
  • cloud/apps/relay/src/assignment-store.ts
  • cloud/apps/relay/src/heap-window-reaper.ts
  • cloud/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.

Comment on lines +59 to +68
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]
)
)

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.

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

Repository: 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 -120

Repository: 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/src

Repository: 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.

Suggested change
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)

@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 — 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 with ctid = ANY(ARRAY(SELECT ctid ... FOR UPDATE SKIP LOCKED)), a random first page, forward walk that wraps at pages, and per-tick caps of 400 rows / 128 pages / 250ms with the cursor persisted across ticks; SQLite uses a rowid IN (SELECT ... LIMIT) batch.
  • pruneReleasedControlReservations — new store method plus the 24h retention constant and reaper budget, wired into the cleanup step list after release-expired-activity-leases.
  • Tests — the retention predicate (exact remaining rows), the per-tick row cap and multi-tick drain, heap wrap, SKIP LOCKED skip-not-wait, and a Postgres plan assertion pinning Tid Range Scan / no Seq 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.

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

@Jinwoo-H
Jinwoo-H merged commit e9daf9b 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