Repository navigation
perf(relay): stop indexing the column every control renewal writes - #21286
Conversation
relay_assignment_activity_expiry indexes expires_at on relay_assignment_activity_leases, and expires_at is what every control renewal updates: ~471 calls/s, all of them non-HOT because a changed indexed column forbids HOT. The index has one reader, the 30s expiry sweep, which seq-scans the whole 14.8k-row table in under a millisecond. Drop it, and set fillfactor to 70 so a renewal has room for a second row version on its own page. Measured on postgres:16-alpine over 14.8k rows, WAL bytes per renewal and HOT ratio: index, fillfactor 100 (today) 0% HOT 371 B index, fillfactor 70 0% HOT 246 B no index, fillfactor 100 0.5% HOT 298 B no index, fillfactor 70 100% HOT 80 B Both are needed: the index makes HOT illegal, and the default fillfactor leaves no page space to make it possible. Neither statement can use the catalog pre-check as it stood. DROP INDEX IF EXISTS resolves the name before it locks, so once the index is gone it costs a catalog miss and takes no lock on the table - pinned in the lock-target census as the one exempt statement. ALTER TABLE SET does take a lock, so it gets a new 'reloption' target kind that asks pg_class.reloptions for the name=value pair, keeping the invariant that no lock-taking statement reaches a warm boot unchecked.
|
This run was cancelled 🛑 The workflow was cancelled before completion. Please check the link below for details. |
📝 WalkthroughWalkthroughThe relay schema removes the activity lease expiry index and sets Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Valid semicolon-terminated schema migrations can fail during boot with an unparsed lock-target error. Accept terminal semicolons before merging. 🚥 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 |
…lock timeout The drop had no catalog pre-check, so it was sent on every boot, and a 55P03 from it was fatal: apply-postgres-schema throws on a lock timeout with no retry. On the migration boot that combination is a crash loop. All 28 directors reach the same DROP INDEX at once, it needs ACCESS EXCLUSIVE on a table written ~475/s with lock_timeout at 1s, and a boot that fails restarts the instance to re-queue the same DDL behind the same writers. Two changes: - A new 'index-by-name' lock target. A DROP INDEX names no table, so the existing index check could not serve it; this one resolves by name through the search_path with relkind = 'i', which is how the DROP itself resolves, and skips when absent. DROP INDEX now counts as lock-taking in the census, so it is covered rather than exempt, and IF EXISTS is required the way it is on DROP CONSTRAINT. - A 'schema-deferrable' marker, read from a statement's leading comment. A 55P03 on a marked statement logs orca_relay_postgres_schema_object_deferred and leaves the statement unapplied instead of failing the boot; the next boot re-sends it. Both activity-lease migrations carry it. Everything else keeps the old contract and still fails loudly. SchemaApplySummary gains a deferred count so a boot that skipped work is distinguishable from one with nothing to do. Verified against a real server: with the index present and the table held in ACCESS EXCLUSIVE by another session, both statements defer, the boot completes, nothing is half-applied, and the next boot finishes the job. A warm boot now sends neither statement at all.
|
Addressed the review condition in The drop now has a catalog pre-check ( Proof against a real server, not just unit tests: with the index recreated and the table held in Suites: relay 784 passed with Postgres, postgres-schema 108, push 139, |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Accept a trailing statement terminator. · schema-lock-target.ts:131-137
cloud/packages/postgres-schema/src/schema-lock-target.ts:131-137
🎯 Functional Correctness | 🟠 Major | ⚡ Quick winAccept a trailing statement terminator.
applyPostgresSchemapasses each statement torequireSchemaLockTargetwithout removing semicolons.sqlWithoutCommentsalso preserves them. Therefore,DROP INDEX IF EXISTS i;andALTER TABLE t SET (fillfactor = 70);fail their respective regexes, then matchMUST_PARSEand throwunparsed_schema_lock_target.
relayPostgresSchemaStatementsremoves separators only fromSCHEMA.split(';'). It appendsPOSTGRES_SCHEMA_MIGRATIONSunchanged, so statement splitting does not guarantee that semicolons are absent. Accept an optional terminal semicolon in both patterns and cover both forms in parser tests.Proposed fix
-const DROP_INDEX = new RegExp(`^DROP\\s+INDEX\\s+(?:CONCURRENTLY\\s+)?IF\\s+EXISTS\\s+${QUALIFIED}\\s*$`, 'i') +const DROP_INDEX = new RegExp( + `^DROP\\s+INDEX\\s+(?:CONCURRENTLY\\s+)?IF\\s+EXISTS\\s+${QUALIFIED}\\s*;?\\s*$`, + 'i' +) const SET_RELOPTION = new RegExp( `^ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?${QUALIFIED}\\s+` + - `SET\\s+\\(\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*([A-Za-z0-9_.]+)\\s*\\)\\s*$`, + `SET\\s+\\(\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*([A-Za-z0-9_.]+)\\s*\\)\\s*;?\\s*$`, 'i' )
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 4da1f5bf-daba-41e9-9f3e-7b45a5f3e5d7
📒 Files selected for processing (9)
cloud/apps/relay/src/database.tscloud/apps/relay/src/relay-schema-catalog-precheck-postgres.test.tscloud/apps/relay/src/relay-schema-lock-targets.test.tscloud/packages/postgres-schema/src/apply-postgres-schema.test.tscloud/packages/postgres-schema/src/apply-postgres-schema.tscloud/packages/postgres-schema/src/catalog-object-precheck.tscloud/packages/postgres-schema/src/index.tscloud/packages/postgres-schema/src/schema-lock-target.test.tscloud/packages/postgres-schema/src/schema-lock-target.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- cloud/packages/postgres-schema/src/apply-postgres-schema.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
…tablyai#21286) * perf(relay): stop indexing the column every control renewal writes relay_assignment_activity_expiry indexes expires_at on relay_assignment_activity_leases, and expires_at is what every control renewal updates: ~471 calls/s, all of them non-HOT because a changed indexed column forbids HOT. The index has one reader, the 30s expiry sweep, which seq-scans the whole 14.8k-row table in under a millisecond. Drop it, and set fillfactor to 70 so a renewal has room for a second row version on its own page. Measured on postgres:16-alpine over 14.8k rows, WAL bytes per renewal and HOT ratio: index, fillfactor 100 (today) 0% HOT 371 B index, fillfactor 70 0% HOT 246 B no index, fillfactor 100 0.5% HOT 298 B no index, fillfactor 70 100% HOT 80 B Both are needed: the index makes HOT illegal, and the default fillfactor leaves no page space to make it possible. Neither statement can use the catalog pre-check as it stood. DROP INDEX IF EXISTS resolves the name before it locks, so once the index is gone it costs a catalog miss and takes no lock on the table - pinned in the lock-target census as the one exempt statement. ALTER TABLE SET does take a lock, so it gets a new 'reloption' target kind that asks pg_class.reloptions for the name=value pair, keeping the invariant that no lock-taking statement reaches a warm boot unchecked. * fix(relay): pre-check the activity-expiry drop and let it defer on a lock timeout The drop had no catalog pre-check, so it was sent on every boot, and a 55P03 from it was fatal: apply-postgres-schema throws on a lock timeout with no retry. On the migration boot that combination is a crash loop. All 28 directors reach the same DROP INDEX at once, it needs ACCESS EXCLUSIVE on a table written ~475/s with lock_timeout at 1s, and a boot that fails restarts the instance to re-queue the same DDL behind the same writers. Two changes: - A new 'index-by-name' lock target. A DROP INDEX names no table, so the existing index check could not serve it; this one resolves by name through the search_path with relkind = 'i', which is how the DROP itself resolves, and skips when absent. DROP INDEX now counts as lock-taking in the census, so it is covered rather than exempt, and IF EXISTS is required the way it is on DROP CONSTRAINT. - A 'schema-deferrable' marker, read from a statement's leading comment. A 55P03 on a marked statement logs orca_relay_postgres_schema_object_deferred and leaves the statement unapplied instead of failing the boot; the next boot re-sends it. Both activity-lease migrations carry it. Everything else keeps the old contract and still fails loudly. SchemaApplySummary gains a deferred count so a boot that skipped work is distinguishable from one with nothing to do. Verified against a real server: with the index present and the table held in ACCESS EXCLUSIVE by another session, both statements defer, the boot completes, nothing is half-applied, and the next boot finishes the job. A warm boot now sends neither statement at all.

ELI5
Relay keeps a row for every live connection saying when it expires. Phones refresh that row constantly, about 471 times a second across the fleet. The database also kept a sorted lookup table over the "when does this expire" column, so every single refresh had to update that sorted table too.
Only one thing ever read the sorted table: a cleanup job that runs twice a minute. That job is perfectly happy reading all 14,800 rows directly, which takes less than a millisecond. So we were paying on every refresh to save nothing.
This removes the sorted table, and gives each page of rows a bit of spare room so a refresh can be written in place instead of somewhere new.
What Changed
Nothing changes for anyone using Orca. This is a write-amplification fix inside Relay's database.
Two statements, both in
POSTGRES_SCHEMA_MIGRATIONS:DROP INDEX IF EXISTS relay_assignment_activity_expiryALTER TABLE relay_assignment_activity_leases SET (fillfactor = 70)The mechanism is Postgres's heap-only-tuple (HOT) optimisation. An
UPDATEcan rewrite a row inside its existing page, touching no index at all, but only if two things hold: no indexed column changed, and the page has room for the second version. Renewals broke the first condition, becauseexpires_atwas indexed andexpires_atis exactly what a renewal writes. Removing the index fixes that, but the default fillfactor of 100 leaves a freshly filled page with no free space, so the second condition still failed and the update still moved to a new page.Measured on a fresh
postgres:16-alpineover 14,800 representative rows, updating every row and reading WAL LSN deltas pluspg_stat_user_tables:Dropping the index alone is not the win; it is the precondition for the win. Both statements together take a renewal from 371 to 80 bytes of WAL, a 4.6x reduction on a write path that is roughly 15% of the instance's WAL.
Supporting changes in
@orca-cloud/postgres-schema, both so that neither statement can take a lock on a warm boot or crash an instance on the migration boot:reloptionlock-target kind, so the pre-check can ask whetherfillfactor=70is already set before sending anALTER TABLEthat would take a lock.index-by-namelock-target kind for theDROP INDEX. ADROP INDEXnames no table, so the existing index check could not serve it; this one resolves by name through thesearch_pathwithrelkind = 'i', which is how theDROPitself resolves, and skips when the index is absent.schema-deferrablemarker, read from a statement's leading comment. A lock timeout on a marked statement logsorca_relay_postgres_schema_object_deferredand leaves the statement unapplied rather than failing the boot. Both statements here carry it; everything else keeps the old contract of failing loudly.Why
Why this index can go. I checked every statement in
cloud/apps/relay/srcthat touches this table. Exactly one filters onexpires_atwithout a primary-key prefix: therelease-expired-activity-leasessweep inassignment-store.ts, one of ten cleanup steps the director runs every 30 seconds. Every other reader looks the row up by its primary key, bycell_id, or aggregates the whole table.renewControlActivity, the 471/s path, finds its row by primary key and never consults this index.The sweep's new plan, measured:
469 buffers, all cache hits, 0.7 ms, once every 30 seconds. The sweep also carries two
NOT EXISTSanti-joins, so the index was never the dominant term anyway. The table already gets seq-scanned on operational paths that filter bycell_id, which has no index either.Why fillfactor 70 rather than another value. 70 is where the measurement converges to 100% HOT with margin. A row is ~100 bytes against an 8 KB page, so 30% reserved is several rows of headroom per page. It costs heap size on a table whose indexes (31 MB) already outweigh its heap (7 MB), and in the measurement the table got smaller, not larger, because it stopped bloating.
Why not
DROP INDEX CONCURRENTLY. It would need the schema runner to guarantee no surrounding transaction, and it waits on every transaction that can see the index, which is an unbounded wait on a busy instance. PlainDROP INDEXtakesACCESS EXCLUSIVE, but only to unlink a catalog entry, andPOSTGRES_LOCK_TIMEOUT_MS(1000 ms) already bounds how long boot waits for it. It happens once.Why not keep the index and only change fillfactor. Measured at 0% HOT across four rounds. A changed indexed column forbids HOT no matter how much page space is free.
Why a new pre-check kind instead of letting the
ALTER TABLErun unchecked.relay-schema-lock-targets.test.tsenforces that nothing taking a relation lock reaches a warm boot without a catalog pre-check, andALTER TABLE ... SETdoes take one (SHARE UPDATE EXCLUSIVE). Exempting it would have meant weakening that census. Thereloptionkind compares the wholename=valuepair againstpg_class.reloptions, so changing 70 to some other value re-runs rather than skipping forever.Why the
DROP INDEXneeds its own pre-check and a deferral, not an exemption. It is true that once the index is gone the statement takes no lock, because Postgres resolves the name before it locks andIF EXISTSon a missing name is a notice. But that only describes the steady state. On the one boot that matters the index is still there, all 28 directors reach the statement at once, and it needsACCESS EXCLUSIVEon a table written ~475/s against a 1000 mslock_timeout. The runner throws on a lock timeout with no retry, which is right for a statement the boot depends on and wrong here: a failed boot restarts the instance, which re-queues the same DDL behind the same writers.So the statement is in the census like any other lock-taking statement, with a pre-check that makes it disappear after the first success, and a marker that turns a lost lock race into a logged deferral instead of a restart.
IF EXISTSis required by the parser for the same reason it is onDROP CONSTRAINT: a bareDROPon a missing index is an error the server should raise.Linked Issue
Fixes #
Visual Proof
N/A- a database schema change with no user-visible surface. The measurements above are the evidence.Testing
Ran against a fresh
postgres:16-alpinecontainer, removed afterwards.cloud/apps/relay:pnpm testwithORCA_RELAY_TEST_POSTGRES_URLset. 86 files, 784 passed, 1 skipped. Without a database, 65 files, 671 passed.cloud/apps/push, the other consumer of the schema runner, is 139 passed. The Postgres-backedrelay-schema-catalog-precheck-postgres.test.tsis the one that matters: it asserts a warm boot issues zero lock-taking statements, which only holds if the newreloptionpre-check works.cloud/packages/postgres-schema:pnpm test, 108 passed, up from 87.cloud:pnpm typecheckandpnpm lintclean across all 7 projects.End-to-end boot checks against a real server, beyond the suite:
orca_relay_postgres_schema_object_presentforfillfactor=70and sends noALTER TABLE. Resulting state:reloptions = {fillfactor=70}, and the only index on the table is its primary key.relay_assignment_activity_expiryby hand and reset fillfactor to the default, then booted. The boot dropped the index and set fillfactor, ending atidx=0,reloptions={fillfactor=70}.Two test files failed on a second run against an already-populated database and passed on a fresh one; that is a known property of this suite, not related to this change.
Platforms: the change is server-side SQL, applied by Relay at boot on Linux (Cloud Run). No client, no path handling, no shell.
Added: the concurrent-drop race in the schema runner; the deferral path, including that it fires only on a lock timeout, that an unmarked statement still fails, that the marker is read only from a leading comment, and that the boot keeps going after a deferral so nothing behind it is skipped; the
index-by-nameandreloptiontarget shapes, including a changed fillfactor value, a refused multi-optionSET, a refused multi-indexDROP, and a bareDROPwith noIF EXISTS; and pins in the relay census that exactly these two statements are deferrable and that nothing re-creates an index onexpires_at.The decisive one runs against a real server: with the index recreated and the table held in
ACCESS EXCLUSIVEby another session, both statements defer, the boot completes, the index is verifiably still there, and a second run with the lock released drops it and sets fillfactor.AI Disclosure
Review
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
Rollout and locking. On the migration boot every director sees the index and sends the drop.
ACCESS EXCLUSIVEfor the drop is a catalog unlink, held for microseconds, but the wait for it is the exposure, bounded at 1000 ms by the existinglock_timeout. Three outcomes are now all safe: the winner drops it; a loser that raced past the name resolution gets42704, which the runner treats as already-applied; a loser that cannot get the lock at all gets55P03, which it logs as deferred and carries on, leaving the work for its next boot. Every boot after the first sends neither statement, because both are pre-checked.A stall that keeps the lock unavailable therefore costs one extra boot cycle per director, not a crash loop. Nothing else about the boot changes, and no other statement becomes deferrable.
Fillfactor takes effect gradually. Setting the parameter does not rewrite existing pages. Pages adopt it as they refill, so the table converges over its own renewal cycle, minutes at 471/s. An operator can make it immediate with
pg_repack, but nothing here requires that, and aVACUUM FULLwould takeACCESS EXCLUSIVEfor the length of a table rewrite and should not be used on the live instance.Rollback is re-creating the index with
CREATE INDEX CONCURRENTLYand reverting the commit. TheRULEcomment besideSCHEMAalready forbids adding a brand-new index to the schema without building it out of band first, and that still holds.Backwards compatibility. No wire change, no client change. A director running the previous image against a database where the index is already gone is fine: nothing in the old code names the index, and its sweep just seq-scans.
SQLite. Both statements live in
POSTGRES_SCHEMA_MIGRATIONS, which the SQLite path does not run. TheCREATE INDEXis removed from the sharedSCHEMA, so new SQLite databases simply never create it; an existing local file keeps a harmless leftover.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)