Repository navigation
perf(relay): index and gate the credential cleanup sweeps that seq-scan relay_invites - #21301
Conversation
…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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review. 📝 WalkthroughWalkthroughThe relay cleanup path adds indexes for expiry, reservation, pending authorization, and rate-window scans. Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to 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)
✅ 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: 65bdeec7-af60-4a71-a56a-895a36d0c7fd
📒 Files selected for processing (7)
cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.tscloud/apps/relay/src/credential-store-cleanup.test.tscloud/apps/relay/src/credential-store.tscloud/apps/relay/src/database.tscloud/apps/relay/src/index.tscloud/apps/relay/src/relay-schema-lock-targets.test.tscloud/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.
| SELECT ${address} FROM relay_invites | ||
| WHERE state IN (?, ?, ?) AND updated_at <= ? | ||
| LIMIT ${TERMINAL_INVITE_REAP_BATCH} |
There was a problem hiding this comment.
🚀 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.tsRepository: 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's WHERE clause mathematically implies the partial index'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's value will satisfy the index'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>
Citations:
- 1: https://www.postgresql.org/docs/current/indexes-partial.html
- 2: https://www.postgresql.org/docs/18/indexes-partial.html
- 3: https://www.postgresql.org/docs/19/indexes-partial.html
- 4: https://www.postgresql.org/docs/17/indexes-partial.html
- 5: https://www.postgresql.org/docs/16/indexes-partial.html
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.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
- Partial sweep indexes —
database.tsgainsrelay_invites_sweep_expiry,relay_invites_sweep_reservation,relay_direct_authorizations_pending_deadline(partial) andrelay_rate_windows_started, each marked-- schema-deferrable:for out-of-band builds. - Cleanup gated to the maintenance owner — the credential cleanup timer in
index.tsnow followsroleOwnsAssignmentMaintenance(config.role)andjitteredSweepIntervalMs(30_000), matching the assignment sweep. - Bounded terminal-invite reaper —
reapTerminalInvitesdeletes terminal invites older than 7 days, at most 5,000 per cycle, viactid/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.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ 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 = 1replaces the 6.65M-row composite walk for the sweep, whilerelay_connection_bases_active_deadlineis kept because it is the only index coveringactive = 0for the reaper's range. - Two more bounded reapers —
reapBatchgeneralizes the invite reaper, andreapSettledCredentialsnow also deletesactive = 0 AND deadline <= now - 1dbases andconsumed_at <= now - 1dauthorizations, 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
ctidcycle 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.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
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: 8387a3b0-2f9f-411a-b4d6-884977820be1
📒 Files selected for processing (6)
cloud/apps/relay/src/credential-cleanup-sweep-postgres.test.tscloud/apps/relay/src/credential-store-cleanup.test.tscloud/apps/relay/src/credential-store.tscloud/apps/relay/src/database.tscloud/apps/relay/src/postgres-maintenance-sweep-plans.test.tscloud/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.
| 'consumed_at IS NOT NULL AND consumed_at <= ?', | ||
| [now - INACTIVE_AUTHORIZATION_RETENTION_MS] |
There was a problem hiding this comment.
🚀 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.tsRepository: 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.
There was a problem hiding this comment.
✅ 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.tsnow requires an index scan over eitherrelay_connection_bases_active_deadlineorrelay_connection_bases_live_deadlineinstead of pinning the partial index and forbidding the composite, whilenot.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_authorizationsreaper comment incredential-store.tsrecords that retention is measured onconsumed_at, since consumption can settle a row well before itsdeadline.
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.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…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.
…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.
…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.

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.tsstarted a 30-secondsetIntervalcalling 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:relay_connection_basesexpiryrelay_invitesexpiryrelay_invitesreservation lapserelay_direct_authorizationsexpiryrelay_rate_windowsretentionAt 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_invitesstatements were the first to go long, 1.7 seconds before the fleet-wide pileup.Nothing in any of these tables is ever deleted:
relay_connection_basesrelay_invitesrelay_direct_authorizationsrelay_invitestakes 1.44 inserts a minute against a ten-minute TTL, so its partial indexes stay at one leaf page.Three kinds of change:
The cleanup timer is gated on
roleOwnsAssignmentMaintenance(config.role), the same owner the assignment sweep already uses, and jittered byjitteredSweepIntervalMsso director instances do not land on the same wall-clock second.Bounded reapers for all three growing tables, at most 5,000 rows each per cycle, addressed by
ctidon Postgres androwidon SQLite. Terminal invites are kept 7 days, measured onupdated_at. Settled bases are kept until theirdeadlineis a day past, and consumed authorizations until theirconsumed_atis 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_deadlinestays. It is the only index coveringactive = 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: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 INDEXcarries 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
SCHEMAis 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: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:
reserveCredentialexpires_at <= nowas expired itself, and performs the reserved-to-cooldown transition inlineresolveInviteForMoveexpires_at > nowand a non-terminal state, in its own predicatefailReservationconfirmResumeactive = 1anddeadline >= nowon the basisconfirmation_not_activeeither wayvalidateInstallAuthorization, basis modeactive = 1anddeadline >= nowinvalid_relay_basiseither wayvalidateInstallAuthorization, direct modeconsumed_at IS NULLanddeadline >= nowinvalid_direct_authorizationeither waydeactivateBasisconsumeRateTwo things make the reapers safe rather than merely probable:
now + resumeConfirmationDeadlineMs(30 s) for resume, or the invite reservation lease (at most 15 s) for invite. A direct authorization getsnow + 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.confirmResumeanswers a repeat fromrelay_confirm_results, andinstallCredentialanswers a repeat fromrelay_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_idandrelay_confirmable_splices.basis_conn_idare plain columns, andrelay_confirmable_spliceshas 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 = 1for 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 checkdeadline >= nowindependently 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.
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:
deadlinefor a basis,consumed_atfor an authorization. The audit trail for both lives inrelay_audit_events, which this does not touch.Why
ctidrather 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 forrelay_invitesmeans 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
LIMITthat 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.Without a Postgres URL the suite reports
66 passed | 21 skipped (87); the 21 skipped files are the ones that need a real server.oxlintdoes not cover this code:cloud/**is in the root config'signorePatterns, and the changed-code quality gate reports no changed JavaScript or TypeScript in its scope. The relay package's ownlintscript istsc --noEmit, which passes. No lint suppressions were added.New and changed tests:
credential-cleanup-sweep-postgres.test.tsreads 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 realctid.credential-store-cleanup.test.tscovers 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.tsadds a census asserting everysetIntervalinindex.tsis gated on the maintenance role, so a future ungated sweep fails CI rather than shipping to 23 cells.relay-schema-lock-targets.test.tsupdates the golden lock-target and deferrable-statement lists, and adds a case proving the pre-check parser derives a target for a partial index,WHEREclause and all. It does, with no parser change: the regex reads the name and table from the head of the statement and a trailingWHEREis invisible to it.postgres-maintenance-sweep-plans.test.tsis an existing test that pinned the basis sweep torelay_connection_bases_active_deadlineby 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 isEXPLAIN (ANALYZE, BUFFERS)output with the index present and then dropped.Review
Cross-platform: SQL only, no paths, shells, or processes. The one dialect branch is
ctidversusrowid, and SQLite accepts both the partial indexes and therowidbatch delete; verified directly againstnode:sqlitebefore 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:
SCHEMAis 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
docs/reference/agent-skill-sharing-upstream-boundary.mdand 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 CONCURRENTLYstatements above before this image reaches production. Theschema-deferrablemarkers 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
VACUUMonrelay_connection_basesafterwards to return the 1.5 GB rather than leaving it as reusable free space.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)