Skip to content

perf(relay): index and gate the credential cleanup sweeps that seq-scan relay_invites - #21301

Merged
Jinwoo-H merged 3 commits into
mainfrom
relay-invite-sweep-index
Sep 17, 2026
Merged

Jinwoo-H merged 3 commits into
mainfrom
relay-invite-sweep-index

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​660 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​656
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​93 $\color{#cf222e}{\Huge{\mathbf{−}}}$​10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​83

ELI5

A relay housekeeping job ran every 30 seconds on all 23 machines at once. To find the handful of rows that had gone stale, it read enormous amounts of data: one table it read end to end, and another it read through an index covering 6.6 million rows to find a few hundred. Neither table ever deleted anything, so both just kept growing. While that job ran it held up everyone else's database work, which users saw as the whole service freezing for several seconds. This gives each part of the job an index that goes straight to the rows it wants, runs the job on one machine instead of 23, and throws away rows that finished their work over a day ago.

What Changed

Before. Users saw the whole relay fleet stall for 5 to 12 seconds roughly every 10 minutes: phones stopped connecting, pairing hung, and hosts already connected went quiet until it cleared. Nothing was down, so the stall looked random.

After. Every statement in the sweep is an index lookup over the rows it can actually act on, the sweep runs on one process instead of 28, and the two unbounded tables stop growing.

Mechanism. cloud/apps/relay/src/index.ts started a 30-second setInterval calling the credential store's cleanup in every relay process, cells included. That cleanup opens one transaction and runs five statements. Measured in production the night of 2026-09-17, the transaction averages 268 ms:

Statement Time Problem
relay_connection_bases expiry 195 ms index spans all 6.65M rows to find a few hundred
relay_invites expiry 44 ms sequential scan
relay_invites reservation lapse 23 ms sequential scan
relay_direct_authorizations expiry 5.5 ms sequential scan, primary key only
relay_rate_windows retention 0.6 ms sequential scan

At 268 ms across 28 processes twice a minute, the sweep alone consumes about 15 seconds of database time per minute. At the 21:57:05Z stall onset the relay_invites statements were the first to go long, 1.7 seconds before the fleet-wide pileup.

Nothing in any of these tables is ever deleted:

Table Rows Size Live rows
relay_connection_bases 6,655,761 1.5 GB heap + 283 MB index a few hundred active
relay_invites 124,062 30.2 MB 2 (1 available, 1 cooldown)
relay_direct_authorizations 37,646 — mostly consumed

relay_invites takes 1.44 inserts a minute against a ten-minute TTL, so its partial indexes stay at one leaf page.

Three kinds of change:

  1. Five partial indexes, one per sweep predicate, each holding only the rows its sweep can act on:
relay_invites_sweep_expiry                    ON relay_invites(expires_at)                 WHERE state IN ('available','reserved','cooldown')
relay_invites_sweep_reservation               ON relay_invites(reservation_expires_at)      WHERE state = 'reserved'
relay_connection_bases_live_deadline          ON relay_connection_bases(deadline)          WHERE active = 1
relay_direct_authorizations_pending_deadline  ON relay_direct_authorizations(deadline)      WHERE consumed_at IS NULL
relay_rate_windows_started                    ON relay_rate_windows(window_started_at)
  1. The cleanup timer is gated on roleOwnsAssignmentMaintenance(config.role), the same owner the assignment sweep already uses, and jittered by jitteredSweepIntervalMs so director instances do not land on the same wall-clock second.

  2. Bounded reapers for all three growing tables, at most 5,000 rows each per cycle, addressed by ctid on Postgres and rowid on SQLite. Terminal invites are kept 7 days, measured on updated_at. Settled bases are kept until their deadline is a day past, and consumed authorizations until their consumed_at is a day past: consumption is what settles an authorization and it can happen well before the deadline, so measuring from it retains the row for the full window either way.

relay_connection_bases_active_deadline stays. It is the only index covering active = 0, so it is what lets the drained reaper learn there is nothing left to do from the index rather than the heap. Measured on a real server at 200,000 rows with nothing matching:

Composite index Buffers Time
Present 5 0.037 ms
Dropped 1,274 4.930 ms

It can be dropped later, but only once the 6.65M-row backlog has drained and the heap is small enough that a bounded scan is cheap.

Every new CREATE INDEX carries the -- schema-deferrable: marker, so a boot that cannot take the lock defers the statement instead of crash-looping.

Operator commands, to run before this deploys

The rule beside SCHEMA is that boot must never build a new index on a large table: the catalog pre-check skips a lock-taking statement only once the object exists, so a brand-new one reports missing on all 28 directors at once and each runs a non-concurrent build over the whole table. Build them out of band first, and every later boot skips them forever:

CREATE INDEX CONCURRENTLY IF NOT EXISTS relay_invites_sweep_expiry ON relay_invites(expires_at) WHERE state IN ('available','reserved','cooldown');
CREATE INDEX CONCURRENTLY IF NOT EXISTS relay_invites_sweep_reservation ON relay_invites(reservation_expires_at) WHERE state = 'reserved';
CREATE INDEX CONCURRENTLY IF NOT EXISTS relay_connection_bases_live_deadline ON relay_connection_bases(deadline) WHERE active = 1;
CREATE INDEX CONCURRENTLY IF NOT EXISTS relay_direct_authorizations_pending_deadline ON relay_direct_authorizations(deadline) WHERE consumed_at IS NULL;
CREATE INDEX CONCURRENTLY IF NOT EXISTS relay_rate_windows_started ON relay_rate_windows(window_started_at);

Why

Is the gating safe? Can the reapers delete something still in use? Both questions come down to one reader audit, which I did before touching either. No reader of any of these tables depends on the sweep, and every one of them re-checks freshness itself:

Reader What it requires Effect of a missing row
reserveCredential re-reads the invite, treats expires_at <= now as expired itself, and performs the reserved-to-cooldown transition inline identical rejection
resolveInviteForMove expires_at > now and a non-terminal state, in its own predicate identical rejection
failReservation matches on the reservation id, not on state freshness no-op
confirmResume active = 1 and deadline >= now on the basis confirmation_not_active either way
validateInstallAuthorization, basis mode active = 1 and deadline >= now invalid_relay_basis either way
validateInstallAuthorization, direct mode consumed_at IS NULL and deadline >= now invalid_direct_authorization either way
deactivateBasis addresses one row by id, fire-and-forget no-op
consumeRate exact primary key on the rate window retention delete is pure garbage collection

Two things make the reapers safe rather than merely probable:

  • Every deadline is set at most 30 seconds past insert. A basis gets now + resumeConfirmationDeadlineMs (30 s) for resume, or the invite reservation lease (at most 15 s) for invite. A direct authorization gets now + resumeConfirmationDeadlineMs (30 s). So "deadline more than a day past" is, in practice, "created more than a day ago", and retention is roughly 2,880x the longest window in which any reader would have accepted the row.
  • Idempotent replay does not read these tables. confirmResume answers a repeat from relay_confirm_results, and installCredential answers a repeat from relay_install_results. Both are keyed by request id and neither joins to the row being reaped, so deleting a settled basis or authorization cannot break a retry.

There are no foreign keys on basis_conn_id: the three in the schema are all on cell-fence and drain tables. relay_confirm_results.basis_conn_id and relay_confirmable_splices.basis_conn_id are plain columns, and relay_confirmable_splices has no reader in the source at all.

One case worth naming, because it looks alarming and is not. A long-lived splice keeps its basis active = 1 for hours past the 30-second deadline it was created with. The sweep deactivates it, and the reaper can then take it in the same cycle if that deadline is already over a day old. That is safe precisely because no reader would have accepted it since the moment its deadline passed: both check deadline >= now independently of the active flag. There is a test for exactly this row.

Why all three kinds of change and not one? Each alone leaves a real gap.

  • Indexes only. Fixes the per-call cost but leaves the same transaction running 56 times a minute across the fleet, and leaves two tables growing forever, so the next table this pattern reaches repeats the incident.
  • Gating only. Cuts 15 seconds of database time per minute to about half a second, but the director still walks 283 MB of index and 30 MB of heap every 30 seconds, and that is what went to 57 seconds at the tail. Frequency was not the root cause.
  • Reapers only. Shrinks the tables but leaves four of the five statements planning as sequential scans, so any traffic growth walks straight back into the same stall.

Why 7 days for invites and 1 day for authorizations? Different rationales, so they are different named constants. A terminal invite is the only one of the three a human is likely to ask about after the fact ("why did my pairing fail yesterday"), so it gets a week. A settled basis or authorization is machine-only bookkeeping whose functional lifetime is 30 seconds, so a day is already pure forensic margin. Each is measured from the column that actually settles the row: deadline for a basis, consumed_at for an authorization. The audit trail for both lives in relay_audit_events, which this does not touch.

Why ctid rather than the primary key? The physical row address lets the delete re-find exactly the batch the bounded subquery already located, rather than re-matching the predicate per row, which for relay_invites means four text columns.

One honest limitation. The invite reaper's batch subquery has no index behind it, so it is a sequential scan with a LIMIT that stops as soon as it finds its batch. While the backlog drains that stops almost immediately. In steady state at 7-day retention the table settles to roughly 14,500 rows and 430 pages, a twelfth of today's size, so the scan is a few milliseconds on the director only. A sixth index would remove even that, but it would cover nearly every row in the table, and buying a 430-page scan is not worth the write amplification on every invite state transition. The basis and authorization reapers do not have this problem: the composite index covers the first, and the second is a 37,646-row table where a bounded scan costs about as much as the sweep it replaces.

Linked Issue

Fixes #

Visual Proof

N/A — server-side database work with no UI surface. The user-visible effect is the absence of the periodic stall, which a screenshot cannot show.

Testing

Ran from cloud/ against PostgreSQL 16 in a container, on a fresh database each time, since the relay Postgres suite leaves state behind and fails on a re-used one.

pnpm -F @orca-cloud/relay test
 Test Files  88 passed (88)
      Tests  815 passed | 1 skipped (816)
pnpm typecheck    # all 7 workspace projects, clean
pnpm build        # clean
pnpm test         # full cloud workspace, 0 failures:
                  #   relay 815, relay-ops 132, push 139, postgres-schema 108,
                  #   relay-contract 35, push-contract 30, fence-broker 16,
                  #   plus 606 and 156 node --test cases

Without a Postgres URL the suite reports 66 passed | 21 skipped (87); the 21 skipped files are the ones that need a real server.

oxlint does not cover this code: cloud/** is in the root config's ignorePatterns, and the changed-code quality gate reports no changed JavaScript or TypeScript in its scope. The relay package's own lint script is tsc --noEmit, which passes. No lint suppressions were added.

New and changed tests:

  • credential-cleanup-sweep-postgres.test.ts reads the real planner. It asserts no sweep plans a sequential scan and each uses its partial index, on tables seeded to production's ratio (20,000 settled to a few dozen live). It pins that the basis sweep now uses the partial index and not the composite one, that the drained reaper still uses the composite one, and it exercises all three reapers through real ctid.
  • credential-store-cleanup.test.ts covers the reapers on SQLite: rows past retention deleted, rows inside retention kept, rows a reader could still accept never deleted however old, the 5,000 batch bound per table with the remainder draining on the next cycle, and all five original sweep transitions still firing on exactly the rows past their deadline.
  • relay-sweep-schedule.test.ts adds a census asserting every setInterval in index.ts is gated on the maintenance role, so a future ungated sweep fails CI rather than shipping to 23 cells.
  • relay-schema-lock-targets.test.ts updates the golden lock-target and deferrable-statement lists, and adds a case proving the pre-check parser derives a target for a partial index, WHERE clause and all. It does, with no parser change: the regex reads the name and table from the head of the statement and a trailing WHERE is invisible to it.
  • postgres-maintenance-sweep-plans.test.ts is an existing test that pinned the basis sweep to relay_connection_bases_active_deadline by name. The planner now picks the cheaper partial index, which is the improvement this PR is for, so the assertion is widened to either index while the invariant it guards, no sequential scan, stays exact.

I verified the before-picture rather than assuming it. On a scratch schema with the pre-change index set, both invite sweeps plan as Seq Scan, so the new assertions are not vacuous. I also measured the composite index's value to the drained reaper directly, both ways, rather than reasoning about it: the 5-versus-1,274-buffer table above is EXPLAIN (ANALYZE, BUFFERS) output with the index present and then dropped.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

Cross-platform: SQL only, no paths, shells, or processes. The one dialect branch is ctid versus rowid, and SQLite accepts both the partial indexes and the rowid batch delete; verified directly against node:sqlite before writing the schema. SSH and mobile are unaffected: no wire field, stream opcode, or published content changes, so a mixed-version fleet sees no difference. Backwards compatible in both directions. An old process against the new schema ignores the indexes and keeps its own sweep, and a new process against a database without the indexes behaves exactly as today, only slowly. Security is unchanged: the reapers delete only rows that every read path already rejects, and deleting one produces the identical error the inactive row did.

One landmine worth naming for the next person: SCHEMA is split on ;, including semicolons inside comments. My first draft put one in a -- schema-deferrable: line and it silently cut four statements in half, failing all 266 tests that open a database.

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

Deploy order matters: run the five CREATE INDEX CONCURRENTLY statements above before this image reaches production. The schema-deferrable markers mean a boot that finds an index missing and cannot take the lock defers it and retries on the next boot rather than crash-looping, but a boot that can take the lock will build it non-concurrently on all directors at once. Building out of band first is what makes the pre-check skip them forever after.

Expect the first cleanup cycles after deploy to be write-heavy while the reapers drain 6.65M bases and 124k invites at 5,000 rows per table per cycle. That is roughly 1,330 cycles for the bases, so about 11 hours at one director on a 30-second tick. Worth watching WAL and autovacuum over that window, and worth a manual VACUUM on relay_connection_bases afterwards to return the 1.5 GB rather than leaving it as reusable free space.

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)

…an relay_invites

The credential cleanup ran every 30s in all 23 cells as well as the
director. Both of its relay_invites passes matched columns no index
covered, so each one seq-scanned the whole table inside the maintenance
transaction: 56 calls/min fleet-wide, 129ms and 63ms typical and 57s at
the tail, to return about one row every nine minutes.

Adds partial indexes matching each sweep predicate, gives the cleanup the
same owner as the assignment sweep, and reaps terminal invites after
seven days so the table stops growing for the life of the database.

Every index carries the schema-deferrable marker: an operator builds them
with CREATE INDEX CONCURRENTLY, and the catalog pre-check skips them from
then on.
@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

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: 6730a90e-fa28-437e-8803-d3a680c685b0

📥 Commits

Reviewing files that changed from the base of the PR and between 1cef578 and 0acb133.

📒 Files selected for processing (2)
  • cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.ts
  • cloud/apps/relay/src/credential-store.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • cloud/apps/relay/src/credential-store.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

The relay cleanup path adds indexes for expiry, reservation, pending authorization, and rate-window scans. cleanup() reaps terminal invites, inactive connection bases, and consumed direct authorizations in batches of up to 5,000 rows after the sweep. Unit and PostgreSQL tests cover retention, batching, state transitions, and query plans. The cleanup timer uses jittered scheduling and runs only for roles that own assignment maintenance.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 0acb1

Cleanup may continue imposing substantial database load as credential tables grow, undermining the PR’s goal of preventing recurring maintenance stalls; the missing indexes should be addressed before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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 identifies the main performance changes: adding indexes and gating credential cleanup sweeps. It is concise and specific, although it does not mention the new bounded reapers.
Description check ✅ Passed The description is detailed and covers the change, rationale, testing, deployment order, compatibility, and checklist. The Linked Issue section remains incomplete because it contains only Fixes #, b…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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: 65bdeec7-af60-4a71-a56a-895a36d0c7fd

📥 Commits

Reviewing files that changed from the base of the PR and between 0371418 and 7443fba.

📒 Files selected for processing (7)
  • cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.ts
  • cloud/apps/relay/src/credential-store-cleanup.test.ts
  • cloud/apps/relay/src/credential-store.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/index.ts
  • cloud/apps/relay/src/relay-schema-lock-targets.test.ts
  • cloud/apps/relay/src/relay-sweep-schedule.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +665 to +667
SELECT ${address} FROM relay_invites
WHERE state IN (?, ?, ?) AND updated_at <= ?
LIMIT ${TERMINAL_INVITE_REAP_BATCH}

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 | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- credential-store.ts reaper ---'
sed -n '620,690p' cloud/apps/relay/src/credential-store.ts
printf '%s\n' '--- database.ts schema/indexes ---'
sed -n '70,125p' cloud/apps/relay/src/database.ts
printf '%s\n' '--- PostgreSQL plan/cleanup tests ---'
sed -n '70,210p' cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.ts
printf '%s\n' '--- schema-lock constraints ---'
sed -n '180,320p' cloud/apps/relay/src/relay-schema-lock-targets.test.ts
printf '%s\n' '--- parameter binding references ---'
rg -n -C 3 'question.?mark|node-postgres|prepared|parameter|query\\(' cloud/apps/relay/src/database.ts cloud/apps/relay/src/credential-store.ts

Repository: stablyai/orca

Length of output: 16055


🌐 Web query:

site:postgresql.org/docs partial indexes parameterized query clauses do not work with a partial index planning

💡 Result:

<search_synthesis>
In PostgreSQL, partial indexes cannot be used with parameterized queries because the planner determines index applicability at planning time, rather than at execution time [1][2]. For a partial index to be utilized, the PostgreSQL query planner must be able to prove that the query&#39;s WHERE clause mathematically implies the partial index&#39;s predicate [1][3]. PostgreSQL does not employ a sophisticated theorem prover to analyze the relationship between these clauses; instead, it requires the conditions to either be simple, recognizable inequality implications (e.g., x < 1 implies x < 2) or to match exactly [1][4]. When a query uses parameters (such as in a prepared statement with a WHERE clause like x <?), the planner cannot determine if the parameter&#39;s value will satisfy the index&#39;s predicate for all possible inputs [1][5]. Because the matching process occurs during the planning phase and cannot account for the unknown values of parameters at that time, the system cannot safely confirm that the partial index is applicable, and therefore it will not be used [1][2].
</search_synthesis>

<source_evidence>

<title>PostgreSQL: Documentation: 18: 11.8. Partial Indexes</title> https://www.postgresql.org/docs/current/indexes-partial.html Example 11.2 also illustrates that the indexed column and the column used in the predicate do not need to match. PostgreSQL supports partial indexes with arbitrary predicates, so long as only columns of the table being indexed are involved. However, keep in mind that the predicate must match the conditions used in the queries that are supposed to benefit from the index. To be precise, a partial index can be used in a query only if the system can recognize that the `WHERE` condition of the query mathematically implies the predicate of the index. PostgreSQL does not have a sophisticated theorem prover that can recognize mathematically equivalent expressions that are written in different forms. (Not only is such a general theorem prover extremely difficult to create, it would probably be too slow to be of any real use.) The system can recognize simple inequality implications, for example “ x < 1” implies “ x < 2”; otherwise the predicate condition must exactly match part of the query&`#39`;s `WHERE` condition or the index will not be recognized as usable. Matching takes place at query planning time, not at run time. As a result, parameterized query clauses do not work with a partial index. For example a prepared query with a parameter might specify “ x < ?” which will never imply “ x < 2” for all possible values of the parameter. ... Finally, a partial index can also be used to override the system&`#39`;s query plan choices. Also, data sets with peculiar distributions might cause the system to use an index when it really should not. In that case the index can be set up so that it is not available for the offending query. Normally, PostgreSQL makes reasonable choices about index usage (e.g., it avoids them when retrieving common values, so the earlier example really only saves index size, it is not required to avoid index usage), and grossly incorrect plan choices are cause for a bug report. ... Keep in mind ... setting up a partial index indicates that you know at least as much ... when an index might be profitable. Forming ... understanding of how indexes ... . In most cases, the advantage of a partial index over ... regular index will be minimal. There are cases where ... productive, as in Example 11. ... (Put the category column first, for the reasons described in Section 11.3.) While a search in this larger index might have to descend through a couple more tree levels than a search in a smaller index, that&`#39`;s almost certainly going to be cheaper than the planner effort needed to select the appropriate one of the partial indexes. The core of the problem is that the system does not understand the relationship among the partial indexes, and will laboriously test each one to see if it&`#39`;s applicable to the current query. <title>PostgreSQL: Documentation: 18: 11.8. Partial Indexes</title> https://www.postgresql.org/docs/18/indexes-partial.html Example 11.2 also illustrates that the indexed column and the column used in the predicate do not need to match. PostgreSQL supports partial indexes with arbitrary predicates, so long as only columns of the table being indexed are involved. However, keep in mind that the predicate must match the conditions used in the queries that are supposed to benefit from the index. To be precise, a partial index can be used in a query only if the system can recognize that the`WHERE` condition of the query mathematically implies the predicate of the index. PostgreSQL does not have a sophisticated theorem prover that can recognize mathematically equivalent expressions that are written in different forms. (Not only is such a general theorem prover extremely difficult to create, it would probably be too slow to be of any real use.) The system can recognize simple inequality implications, for example “x < 1” implies “x < 2”; otherwise the predicate condition must exactly match part of the query&`#39`;s`WHERE` condition or the index will not be recognized as usable. Matching takes place at query planning time, not at run time. As a result, parameterized query clauses do not work with a partial index. For example a prepared query with a parameter might specify “x < ?” which will never imply “x < 2” for all possible values of the parameter. ... Finally, a partial index can also be used to override the system&`#39`;s query plan choices. Also, data sets with peculiar distributions might cause the system to use an index when it really should not. In that case the index can be set up so that it is not available for the offending query. Normally, PostgreSQL makes reasonable choices about index usage (e.g., it avoids them when retrieving common values, so the earlier example really only saves index size, it is not required to avoid index usage), and grossly incorrect plan choices are cause for a bug report. ... Keep in mind that setting up a partial index indicates that you know at least as much ... knows, in particular you know when an index might be profitable. Forming ... knowledge requires experience and understanding of how indexes in PostgreSQL work. In most cases, the advantage of a partial index over a regular index will be minimal. There are cases where they are quite counterproductive, as in Example 11.4 ... (Put the category column first, for the reasons described in Section 11.3.) While a search in this larger index might have to descend through a couple more tree levels than a search in a smaller index, ... &`#39`;s almost certainly going to be cheaper than the planner effort needed to select the appropriate one of the partial indexes. The core of the problem is that the system does not understand ... the partial indexes, and will laboriously test each one to see if ... &`#39`;s applicable to the current query. <title>PostgreSQL: Documentation: 19: 11.8. Partial Indexes</title> https://www.postgresql.org/docs/19/indexes-partial.html Example 11.2 also illustrates that the indexed column and the column used in the predicate do not need to match. PostgreSQL supports partial indexes with arbitrary predicates, so long as only columns of the table being indexed are involved. However, keep in mind that the predicate must match the conditions used in the queries that are supposed to benefit from the index. To be precise, a partial index can be used in a query only if the system can recognize that the`WHERE` condition of the query mathematically implies the predicate of the index. PostgreSQL does not have a sophisticated theorem prover that can recognize mathematically equivalent expressions that are written in different forms. (Not only is such a general theorem prover extremely difficult to create, it would probably be too slow to be of any real use.) The system can recognize simple inequality implications, for example “x < 1” implies “x < 2”; otherwise the predicate condition must exactly match part of the query&`#39`;s`WHERE` condition or the index will not be recognized as usable. Matching takes place at query planning time, not at run time. As a result, parameterized query clauses do not work with a partial index. For example a prepared query with a parameter might specify “x < ?” which will never imply “x < 2” for all possible values of the parameter. ... Finally, a partial index can also be used to override the system&`#39`;s query plan choices. Also, data sets with peculiar distributions might cause the system to use an index when it really should not. In that case the index can be set up so that it is not available for the offending query. Normally, PostgreSQL makes reasonable choices about index usage (e.g., it avoids them when retrieving common values, so the earlier example really only saves index size, it is not required to avoid index usage), and grossly incorrect plan choices are cause for a bug report. ... Keep in mind that setting up a partial index indicates that you know at least as much ... the query planner knows, in particular you know when an index might be profitable. Forming ... knowledge requires experience and understanding of how indexes in PostgreSQL work. In most cases, the advantage of a partial index over a regular index will be minimal. There are cases where they are quite counterproductive, as in Example 11.4 ... (Put the category column first, for the reasons described in Section 11.3.) While a search in this larger index might have to descend through a couple more tree levels than a search in a smaller index, that&`#39`;s almost certainly going to be cheaper than the planner effort needed to select the appropriate one of the partial indexes. The core of the problem is that the system does not understand the relationship among the partial indexes, and will laboriously test each one to see if it&`#39`;s applicable to the current query. <title>PostgreSQL: Documentation: 17: 11.8. Partial Indexes</title> https://www.postgresql.org/docs/17/indexes-partial.html Example 11.2 also illustrates that the indexed column and the column used in the predicate do not need to match. PostgreSQL supports partial indexes with arbitrary predicates, so long as only columns of the table being indexed are involved. However, keep in mind that the predicate must match the conditions used in the queries that are supposed to benefit from the index. To be precise, a partial index can be used in a query only if the system can recognize that the `WHERE` condition of the query mathematically implies the predicate of the index. PostgreSQL does not have a sophisticated theorem prover that can recognize mathematically equivalent expressions that are written in different forms. (Not only is such a general theorem prover extremely difficult to create, it would probably be too slow to be of any real use.) The system can recognize simple inequality implications, for example “ x < 1” implies “ x < 2”; otherwise the predicate condition must exactly match part of the query&`#39`;s `WHERE` condition or the index will not be recognized as usable. Matching takes place at query planning time, not at run time. As a result, parameterized query clauses do not work with a partial index. For example a prepared query with a parameter might specify “ x < ?” which will never imply “ x < 2” for all possible values of the parameter. ... Finally, a partial index can also be used to override the system&`#39`;s query plan choices. Also, data sets with peculiar distributions might cause the system to use an index when it really should not. In that case the index can be set up so that it is not available for the offending query. Normally, PostgreSQL makes reasonable choices about index usage (e.g., it avoids them when retrieving common values, so the earlier example really only saves index size, it is not required to avoid index usage), and grossly incorrect plan choices are cause for a bug report. ... Keep in mind ... setting up a partial index ... that you know at least as much ... particular you know when ... index might be profitable. Forming ... experience and understanding of how indexes ... most cases, ... advantage of a partial index ... a regular index will ... . There are cases where they ... as in Example 11 ... (Put the category column first, for the reasons described in Section 11.3.) While a search in this larger index might have to descend through a couple more tree levels than a search in a smaller index, that&`#39`;s almost certainly going to be cheaper than the planner effort needed to select the appropriate one of the partial indexes. The core of the problem is that the system does not understand the relationship among the partial indexes, and will laboriously test each one to see if it&`#39`;s applicable to the current query. <title>PostgreSQL: Documentation: 16: 11.8. Partial Indexes</title> https://www.postgresql.org/docs/16/indexes-partial.html Example 11.2 also illustrates that the indexed column and the column used in the predicate do not need to match. PostgreSQL supports partial indexes with arbitrary predicates, so long as only columns of the table being indexed are involved. However, keep in mind that the predicate must match the conditions used in the queries that are supposed to benefit from the index. To be precise, a partial index can be used in a query only if the system can recognize that the`WHERE` condition of the query mathematically implies the predicate of the index. PostgreSQL does not have a sophisticated theorem prover that can recognize mathematically equivalent expressions that are written in different forms. (Not only is such a general theorem prover extremely difficult to create, it would probably be too slow to be of any real use.) The system can recognize simple inequality implications, for example “x < 1” implies “x < 2”; otherwise the predicate condition must exactly match part of the query&`#39`;s`WHERE` condition or the index will not be recognized as usable. Matching takes place at query planning time, not at run time. As a result, parameterized query clauses do not work with a partial index. For example a prepared query with a parameter might specify “x < ?” which will never imply “x < 2” for all possible values of the parameter. ... Finally, a partial index can also be used to override the system&`#39`;s query plan choices. Also, data sets with peculiar distributions might cause the system to use an index when it really should not. In that case the index can be set up so that it is not available for the offending query. Normally, PostgreSQL makes reasonable choices about index usage (e.g., it avoids them when retrieving common values, so the earlier example really only saves index size, it is not required to avoid index usage), and grossly incorrect plan choices are cause for a bug report. ... Keep in mind that setting up a partial index indicates that you know at least as much as the query planner knows, in particular you know when an index might be profitable. Forming this knowledge requires experience and understanding of how indexes in PostgreSQL work. In most cases, the advantage of a partial index over a regular index will be minimal. There are cases where they are quite counterproductive, as in Example 11.4. ... (Put the category column first, for the reasons described in Section 11.3.) While a search in this larger index might have to descend through a couple more tree levels than a search in a smaller index, that&`#39`;s almost certainly going to be cheaper than the planner effort needed to select the appropriate one of the partial indexes. The core of the problem is that the system does not understand the relationship among the partial indexes, and will laboriously test each one to see if it&`#39`;s applicable to the current query.

Citations:


Make the terminal retention predicate indexable.

The subquery has no supporting terminal-state updated_at index, so its LIMIT 5000 does not bound the scan. PostgreSQL also cannot match a partial index when the state predicate remains parameterized. Add the index, use SQL literals for the fixed terminal states, and assert with EXPLAIN that this query uses the index. Build the index concurrently before registering it in the schema.

-         WHERE state IN (?, ?, ?) AND updated_at <= ?
+         WHERE state IN ('expired', 'consumed', 'invalidated') AND updated_at <= ?
          LIMIT ${TERMINAL_INVITE_REAP_BATCH}
        )`,
-      ['expired', 'consumed', 'invalidated', cutoff]
+      [cutoff]

Add relay_invites_terminal_retention on updated_at with the same terminal-state predicate, then run the plan assertion against this exact query shape.

🧰 Tools
🪛 ast-grep (0.45.3)

[error] 662-669: Avoid SQL injection
Context: this.database.query(
DELETE FROM relay_invites WHERE ${address} IN ( SELECT ${address} FROM relay_invites WHERE state IN (?, ?, ?) AND updated_at <= ? LIMIT ${TERMINAL_INVITE_REAP_BATCH} ),
['expired', 'consumed', 'invalidated', cutoff]
)
Note: [CWE-89] Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection').

(sql-injection-typescript)

🪛 OpenGrep (1.29.0)

[ERROR] 663-670: SQL query built via string concatenation or template literal passed to query()/execute(). Use parameterized queries instead.

(coderabbit.sql-injection.raw-query-concat-js)

relay_connection_bases is the dominant cost in the cleanup transaction:
195 ms of the 268 ms average, with ~5,800 shared buffer hits per call
even though it already uses relay_connection_bases_active_deadline. That
index spans all 6.65M rows, and only a few hundred are ever active.

Adds a partial index on the live rows alone, and reaps settled rows from
relay_connection_bases and relay_direct_authorizations once their deadline
is more than a day past. Both readers of either table require the row
active/unconsumed and inside its deadline, and every deadline is set at
most 30s past insert, so a settled row can never authorize anything again.

The composite index stays: it is the only one covering active = 0, and it
is what lets the drained reaper learn there is nothing to do from the index
rather than the 1.5 GB heap. Measured at 200k rows, 5 buffers with it and
1,274 without.
@Jinwoo-H Jinwoo-H closed this Sep 17, 2026
@Jinwoo-H Jinwoo-H reopened this Sep 17, 2026

@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 critical issues — one minor suggestion inline.

Reviewed changes

  • Partial sweep indexes — database.ts gains relay_invites_sweep_expiry, relay_invites_sweep_reservation, relay_direct_authorizations_pending_deadline (partial) and relay_rate_windows_started, each marked -- schema-deferrable: for out-of-band builds.
  • Cleanup gated to the maintenance owner — the credential cleanup timer in index.ts now follows roleOwnsAssignmentMaintenance(config.role) and jitteredSweepIntervalMs(30_000), matching the assignment sweep.
  • Bounded terminal-invite reaper — reapTerminalInvites deletes terminal invites older than 7 days, at most 5,000 per cycle, via ctid/rowid, and runs outside the sweep transaction.
  • Coverage — SQLite retention/batch unit tests, a Postgres planner test asserting the partial indexes replace the seq scans, and updated schema-lock-target/deferrable goldens.

I verified the gating is safe for every reader of relay_invites, relay_connection_bases, relay_direct_authorizations, and relay_rate_windows (each re-checks state/expiry/deadline at read time), and confirmed on PostgreSQL 16.15 that the two sweep UPDATEs do plan as index scans over the partial indexes.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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 — the second commit is a clean extension of the first, and I retracted my earlier inline note after re-testing it at production scale.

Reviewed changes

Since the prior review, commit 1cef578285 ("index live bases and reap settled connection authorizations") adds:

  • Live-basis partial index — relay_connection_bases_live_deadline ON relay_connection_bases(deadline) WHERE active = 1 replaces the 6.65M-row composite walk for the sweep, while relay_connection_bases_active_deadline is kept because it is the only index covering active = 0 for the reaper's range.
  • Two more bounded reapers — reapBatch generalizes the invite reaper, and reapSettledCredentials now also deletes active = 0 AND deadline <= now - 1d bases and consumed_at <= now - 1d authorizations, 5,000 per table per cycle.
  • Coverage — planner tests for the live-basis sweep (partial over composite) and the drained-basis reaper (composite, no seq scan), SQLite retention/batch tests for both new tables, a Postgres ctid cycle test, and the schema-lock/deferrable goldens plus the partial-index parser expectation updated.

I re-verified the safety claims independently: both relay_connection_bases readers require active = 1 AND deadline >= now, direct-mode validateInstallAuthorization rejects consumed authorizations, idempotent replay is answered from relay_confirm_results/relay_install_results rather than the reaped rows, and relay_confirmable_splices has no reader — so deleting a settled basis leaves no dangling reference, and every reaped row is one no reader would have accepted.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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: 8387a3b0-2f9f-411a-b4d6-884977820be1

📥 Commits

Reviewing files that changed from the base of the PR and between 7443fba and 1cef578.

📒 Files selected for processing (6)
  • cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.ts
  • cloud/apps/relay/src/credential-store-cleanup.test.ts
  • cloud/apps/relay/src/credential-store.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/postgres-maintenance-sweep-plans.test.ts
  • cloud/apps/relay/src/relay-schema-lock-targets.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Comment on lines +678 to +679
'consumed_at IS NOT NULL AND consumed_at <= ?',
[now - INACTIVE_AUTHORIZATION_RETENTION_MS]

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 | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '630,710p' cloud/apps/relay/src/credential-store.ts
rg -n -C 4 'relay_direct_authorizations|consumed_at|direct_authorizations' cloud/apps/relay/src/database.ts cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.ts cloud/apps/relay/src/relay-schema-lock-targets.test.ts

Repository: stablyai/orca

Length of output: 17009


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- database schema and dialect references ---'
rg -n -C 8 'relay_direct_authorizations|CREATE INDEX|dialect|rowid|ctid' cloud/apps/relay/src/database.ts
printf '%s\n' '--- cleanup plan test structure ---'
sed -n '1,280p' cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.ts
printf '%s\n' '--- lock target definitions and schema assertions ---'
sed -n '1,80p' cloud/apps/relay/src/relay-schema-lock-targets.test.ts
sed -n '220,305p' cloud/apps/relay/src/relay-schema-lock-targets.test.ts
printf '%s\n' '--- all direct-authorization references ---'
rg -n -C 3 'relay_direct_authorizations|consumed_at' cloud/apps/relay/src --glob '*.ts'

Repository: stablyai/orca

Length of output: 50369


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 18383


Add a partial index for consumed direct authorizations.

The table has no index on consumed_at. The existing relay_direct_authorizations_pending_deadline index contains only consumed_at IS NULL rows, so it cannot support the reaper predicate consumed_at IS NOT NULL AND consumed_at <= ?. The bounded ctid/rowid selection can therefore scan the accumulated table before finding 5,000 rows.

Add a partial (consumed_at) index for consumed_at IS NOT NULL. Build it concurrently out of band on PostgreSQL before adding it to the shared schema, register its lock target, and add an EXPLAIN assertion for the reaper query.

The negative assertion pinned a planner choice rather than the invariant:
either index keeps the sweep off the 1.5 GB heap, and which one wins on
cost is not something the test should fix. Matches how the same file
already handles the two invite sweep indexes.

Also names the column the authorization reaper actually measures, which
is consumed_at rather than deadline.

@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

Since the prior pullfrog review, commit 0acb133a9b ("test(relay): accept either bases index in the sweep plan assertion") makes two changes:

  • Live-basis plan assertion relaxed to the invariant — credential-cleanup-sweep-postgres.test.ts now requires an index scan over either relay_connection_bases_active_deadline or relay_connection_bases_live_deadline instead of pinning the partial index and forbidding the composite, while not.toContain('Seq Scan on relay_connection_bases') stays exact. This is the right call: at the test's 20k-row seed the composite is the cheaper plan, so pinning the partial index asserted a planner choice that costs, not the invariant the PR is about.
  • Comment names the settling column — the relay_direct_authorizations reaper comment in credential-store.ts records that retention is measured on consumed_at, since consumption can settle a row well before its deadline.

I verified the relaxed assertion still fails when the sweep plans a sequential scan or neither index is chosen. The new partial index's existence remains pinned by the schema-lock-target and deferrable goldens even though its selection at test scale is no longer asserted, so this delta does not leave the index free to disappear silently. The only prior Pullfrog thread (the ctid IN seq-scan note) is already retracted and resolved.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit cbd0470 into main Sep 17, 2026
25 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 17, 2026
…r picks (#21305)

Added in #21301 on the reasoning that the composite (active, deadline)
index spans all 6.65M rows to find a few hundred live ones. Measured
post-merge against production-shaped history, that reasoning does not
hold: a basis is inserted active and flipped to 0, so the partial index
accumulates one dead entry per deactivation exactly as the composite one
does. Scan buffers are identical to composite-only in every state, 11,099
cold, 2,522 warm, 9 after VACUUM, and the planner picks the composite
index throughout. The extra index costs ~65 bytes of WAL per basis insert,
about 22% more.

The relief is the reaper plus vacuum, which #21301 already ships. Removes
the statement from SCHEMA, restores the plan test to pinning the composite
index by name, and records why a narrower index is not the cure so the
next reader does not re-derive it.
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…an relay_invites (stablyai#21301)

* perf(relay): index and gate the credential cleanup sweeps that seq-scan relay_invites

The credential cleanup ran every 30s in all 23 cells as well as the
director. Both of its relay_invites passes matched columns no index
covered, so each one seq-scanned the whole table inside the maintenance
transaction: 56 calls/min fleet-wide, 129ms and 63ms typical and 57s at
the tail, to return about one row every nine minutes.

Adds partial indexes matching each sweep predicate, gives the cleanup the
same owner as the assignment sweep, and reaps terminal invites after
seven days so the table stops growing for the life of the database.

Every index carries the schema-deferrable marker: an operator builds them
with CREATE INDEX CONCURRENTLY, and the catalog pre-check skips them from
then on.

* perf(relay): index live bases and reap settled connection authorizations

relay_connection_bases is the dominant cost in the cleanup transaction:
195 ms of the 268 ms average, with ~5,800 shared buffer hits per call
even though it already uses relay_connection_bases_active_deadline. That
index spans all 6.65M rows, and only a few hundred are ever active.

Adds a partial index on the live rows alone, and reaps settled rows from
relay_connection_bases and relay_direct_authorizations once their deadline
is more than a day past. Both readers of either table require the row
active/unconsumed and inside its deadline, and every deadline is set at
most 30s past insert, so a settled row can never authorize anything again.

The composite index stays: it is the only one covering active = 0, and it
is what lets the drained reaper learn there is nothing to do from the index
rather than the 1.5 GB heap. Measured at 200k rows, 5 buffers with it and
1,274 without.

* test(relay): accept either bases index in the sweep plan assertion

The negative assertion pinned a planner choice rather than the invariant:
either index keeps the sweep off the 1.5 GB heap, and which one wins on
cost is not something the test should fix. Matches how the same file
already handles the two invite sweep indexes.

Also names the column the authorization reaper actually measures, which
is consumed_at rather than deadline.
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…r picks (stablyai#21305)

Added in stablyai#21301 on the reasoning that the composite (active, deadline)
index spans all 6.65M rows to find a few hundred live ones. Measured
post-merge against production-shaped history, that reasoning does not
hold: a basis is inserted active and flipped to 0, so the partial index
accumulates one dead entry per deactivation exactly as the composite one
does. Scan buffers are identical to composite-only in every state, 11,099
cold, 2,522 warm, 9 after VACUUM, and the planner picks the composite
index throughout. The extra index costs ~65 bytes of WAL per basis insert,
about 22% more.

The relief is the reaper plus vacuum, which stablyai#21301 already ships. Removes
the statement from SCHEMA, restores the plan test to pinning the composite
index by name, and records why a narrower index is not the cure so the
next reader does not re-derive it.
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