Skip to content

fix(relay): skip boot-time DDL when the catalog already has the object - #21147

Merged
Jinwoo-H merged 7 commits into
mainfrom
relay-schema-precheck
Sep 17, 2026
Merged

Jinwoo-H merged 7 commits into
mainfrom
relay-schema-precheck

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor

ELI5

When a relay director starts up, it re-runs its whole database setup script: create these tables, create these indexes, add these columns. Every statement says "only if it isn't already there," so on a database that has been running for months this is supposed to be a no-op.

It isn't. PostgreSQL takes the lock on the table before it checks whether the index already exists. So a startup that changes nothing still gets in line for a lock on every indexed table. And locks are handed out strictly in the order they were requested, so anything that lines up behind that startup waits too, even though the startup is about to do nothing at all.

Normally the startup is at the front of the line and nobody notices. If a long maintenance job already holds the table, the startup waits, and every ordinary write that arrives after it waits behind the startup. That is how a change-nothing boot takes the service down.

This PR makes startup ask the catalog first, in plain English: "is this index already there?" That question takes no lock on the table. When the answer is yes, the statement is never sent, so the boot never gets in line.

What Changed

Before. Every relay boot against PostgreSQL sent all 74 schema statements, 30 of which take a relation lock. On a healthy database this was invisible. On 2026-09-16 the auth service, which has the same shape, hit a forced anti-wraparound autovacuum holding a large table; its boot queued behind the vacuum, every write queued behind the boot, and the service crash-looped. Relay's relay_control_connection_reservations is 5.1 GB with two indexes in the boot script, and two more relay tables reach their forced freeze around 2026-09-21.

After. A boot on an already-migrated database sends zero lock-taking statements. It reads pg_class/pg_index for each index, pg_attribute for each added column, and pg_constraint for each constraint swap, on the same connection, and skips the statement when the catalog gives the answer that means there is nothing left to do. Measured against a real server: all 30 skipped. Nothing about the SQLite path changed.

Mechanism.

  • cloud/packages/postgres-schema gained the lock-target derivation and the pre-check. The classification regexes were start-anchored with \s, which never matches --, so any statement carrying the comment written above it (the schema string is split on ;, so it does) fell out of classification entirely and would have had no pre-check at all. Every comment is now stripped before classification, quote-aware and handling nested block comments, not only the leading block. A comment between two keywords, as in ALTER TABLE t ADD /* note */ COLUMN c TEXT, was invisible to both the parse regexes and the must-parse shapes, so it produced no target and no throw and ran unchecked. The server is always sent the original statement text; only classification reads the stripped copy. A dollar-quoted body, $$...$$ or $tag$...$tag$, is opaque to the stripper and to the comma scanner, so a comment marker, comma, parenthesis or bracket inside one is text. Relay's pg_stat_statements block is the only such statement and survives byte-identical.
  • Object names are folded the way Postgres folds them. An unquoted identifier is stored lower case in relname, attname and conname, so comparing the written case would miss the row and rebuild the object on every boot. A qualified name is tokenised quote-aware, so "a.b" is one identifier rather than two, and the table reference still reaches to_regclass exactly as written.
  • to_regclass is used for the table so a fresh database returns no row rather than erroring. The index is matched inside the table's own namespace and tied to the table with i.indrelid = t.oid. Index names are unique per schema, not per table, so without that condition a name freed on one table and taken on another answers yes and the real index is skipped forever. A PostgreSQL test reproduces exactly that, and fails without the condition.
  • The lock target is refused rather than guessed when a keyword sits in an identifier position. CREATE UNIQUE INDEX CONCURRENTLY ON t(c) otherwise reads CONCURRENTLY as the index name, and ADD COLUMN IF NOT EXISTS with no column reads IF as the column. A wrong target is worse than no target, because the pre-check then asks about something that does not exist and sends the statement anyway, or worse, skips forever. Any index or column statement whose target cannot be read now throws at boot with the statement text instead of falling through to the lock path. Schema-qualified tables, UNIQUE, CONCURRENTLY, IF NOT EXISTS and double-quoted identifiers all derive correctly, with the qualified name used for to_regclass and the bare identifier for relname/attname.
  • Constraint swaps are covered too, with opposite polarities. ADD CONSTRAINT skips when pg_constraint already names it; DROP CONSTRAINT IF EXISTS skips when it does not, because nothing to drop is nothing to do. The match is by name only: the CHECK body is generated from the region list, so comparing it would re-run the swap on every region change, and an ADD CONSTRAINT is the one statement here that scans the table. Changing a definition under the same name therefore does nothing on boot; an operator drops it and the next boot adds the current definition back. The rule comment beside SCHEMA says so, and a PostgreSQL test walks that sequence.
  • A multi-action ALTER TABLE throws at boot rather than pre-checking its first action. ALTER TABLE t ADD COLUMN IF NOT EXISTS a TEXT, ADD COLUMN IF NOT EXISTS b TEXT derives the target for a alone, so once a exists the whole statement is skipped and b is never added. The first subcommand parses, so nothing else here would catch it. Commas inside a parenthesised type, a CHECK body, a quoted default, a comment, or square brackets such as bigint[] DEFAULT ARRAY[1, 2] are unaffected.
  • A bare DROP CONSTRAINT, without IF EXISTS, gets no target and throws at boot. Skipping it when the constraint is absent would swallow the undefined_object the server is supposed to raise.
  • A concurrent-create collision (42P07, 42710, 23505) re-asks the catalog rather than retrying the statement. Another director finishing the same CREATE INDEX a moment earlier used to cost a retry that took SHARE on the table all over again for an object that was already there. A present object now counts as skipped, and the retry only happens when the catalog still says absent.
  • Row presence is the skip condition, not indisvalid. An index left invalid by a cancelled CREATE INDEX CONCURRENTLY is skipped by IF NOT EXISTS today too; treating invalid as absent would newly take the lock for exactly the indexes a failed build left behind. The flag is reported in the skip event so an operator can still see it.
  • 55P03 (lock timeout) is no longer retried by default. With the pre-check ahead of it, a lock timeout means the object really is missing and this boot lost the queue. Retrying re-enters the lock queue and parks every writer behind it again for another timeout. It now fails once and logs which statement could not take its lock. The push gateway has no pre-check, so a lock timeout there still says nothing about whether the object exists; it keeps the old bounded retry behind an explicit retryLockTimeout option.
  • Each skip emits orca_relay_postgres_schema_object_present with kind, table, name and indisvalid, and every boot ends with an ..._applied summary of ran vs skipped.
  • cloud/apps/relay/src/database.ts wires the pre-check into the untimed schema pool, covering POSTGRES_SCHEMA_MIGRATIONS as well as SCHEMA: ALTER TABLE ... ADD COLUMN IF NOT EXISTS takes ACCESS EXCLUSIVE even when the column is already there. POSTGRES_LOCK_TIMEOUT_MS stays at 1 s.

The between-steps rule, added as a comment beside SCHEMA and pinned by a test: no new index, column or constraint on relay_control_connection_reservations, relay_confirm_results, relay_audit_events, relay_connection_bases, or any other large table may be added to SCHEMA or POSTGRES_SCHEMA_MIGRATIONS. The pre-check skips a statement only once the object exists, so a brand-new index reports missing on every director at once and each one runs a non-concurrent build over the whole table. The 1 s timeout bounds how long that build waits for its lock, not how long it holds it. Build it out of band with CREATE INDEX CONCURRENTLY, then add it to SCHEMA, where the pre-check skips it forever after.

Why

The 1 s lock_timeout alone does not fix this. It bounds a single wait; it does not stop the boot from entering the queue, and the shared runner then retried 55P03 for 30 s, so a boot during a forced freeze parked writers for roughly a second per retry and then crash-looped. Raising the timeout makes it worse and lowering it does not help, because the damage is the queue entry, not the wait.

Dropping the IF NOT EXISTS statements from boot entirely and moving to versioned migrations is the right end state but a much larger change, and it leaves a fresh database with no way to bootstrap.

Asking the catalog first is the smallest change that removes the queue entry: pg_class, pg_index and pg_attribute reads take no lock on the table. It is also self-maintaining, because the lock target is derived from the statement text, so a renamed index cannot drift away from its own pre-check.

The work went into the shared @orca-cloud/postgres-schema package rather than a relay-local copy so relay and auth converge on one implementation instead of three.

The invariant the census now enforces is that every statement taking a relation lock has a pre-check, with no exceptions. That is what lets the warm-boot test assert zero rather than a small number, and it is a much easier property to keep true than a list of tolerated exceptions.

Linked Issue

Fixes #

Visual Proof

N/A. No user-visible interface changed; this is boot-time database behaviour on the relay service.

Testing

Ran locally on macOS against PostgreSQL 17 in a disposable container, on a fresh database.

  • cloud/packages/postgres-schema — pnpm test: 2 files, 85 tests passed.
  • cloud/apps/relay — pnpm test with no database URL: 63 files passed, 21 skipped; 633 tests passed, 110 skipped.
  • cloud/apps/relay — pnpm test with ORCA_RELAY_TEST_POSTGRES_URL set: 84 files passed, 744 tests passed, 1 skipped. The 21 previously skipped files ran.
  • cloud/apps/push — pnpm test against its own fresh database: 29 files, 143 tests passed.
  • cloud — pnpm typecheck and pnpm build pass.

The PostgreSQL test that matters most boots relay twice while a second session holds ACCESS EXCLUSIVE on relay_control_connection_reservations. The boot completes while the lock is held. A companion test proves the lock really does block relay's DDL, so the first test cannot pass vacuously.

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

New tests:

  • schema-lock-target.test.ts — comment-prefixed classification, multi-line and quoted and schema-qualified index and column derivation, constraint derivation in both polarities, the shapes that correctly yield no target, a table of seven malformed shapes that each must throw rather than derive a wrong target, a multi-action ALTER TABLE group covering the two-subcommand shapes and the comma placements that must not throw, a comments-between-keywords group, a catalog-name-folding group, a square-bracket group, and a dollar-quoted-body group.
  • apply-postgres-schema.test.ts — comment-prefixed CREATE INDEX and CREATE TABLE each keep their own collision codes; 55P03 is not retried and names its statement; opt-in retry still works; the pre-check sends nothing when the catalog answers, skips an invalid index, and never probes for a statement that takes no relation lock.
  • relay-schema-lock-targets.test.ts — a golden pin of relay's exact 30 lock-taking statements, a census that every statement in the real schema survives the strict derivation boot uses, a check that every derived name is a bare identifier rather than a keyword or a qualified name, and a check that the one comment-prefixed statement really is there so the census cannot pass vacuously.
  • relay-schema-catalog-precheck-postgres.test.ts — against a real server: cold start then a warm boot issuing zero pre-checkable lock-taking statements, an invalid index skipped rather than rebuilt, a same-named index on a sibling table refusing to answer for this one, a dropped constraint being re-added and then skipped again, a boot completing under a held ACCESS EXCLUSIVE lock, and the negative control for that.

Updated: database-postgres-timeout.test.ts and database-statement-timeout-postgres.test.ts both pinned the old retry-and-queue behaviour and now pin the new one.

AI Disclosure

Review

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

  • Backwards compatibility. applyPostgresSchema now returns a summary instead of void; both existing callers ignored the return value. The pre-check is opt-in per caller, so a consumer that passes no catalog query behaves exactly as before apart from the 55P03 default, which push opts out of explicitly.
  • Cross-platform. Server-side SQL and TypeScript only; no paths, shells or shortcuts.
  • Remote SSH and mobile. Unaffected. Nothing on the client wire changed, and nothing a cell publishes changed.
  • Security. The catalog query binds both the table reference and the object name as parameters; no identifier is interpolated into SQL.
  • Failure direction. Every ambiguity resolves toward failing the boot, never toward skipping a statement. An unreadable target throws, a keyword in an identifier position throws, and only a catalog row the query positively ties to this table counts as present.
  • Performance. A warm boot trades 30 lock-taking DDL statements for 30 catalog reads on one connection, and stops entering the lock queue at all.
  • No Terraform, workflow or cell-image change. The new PostgreSQL test runs in the existing Cloud Verify job, which already sets ORCA_RELAY_TEST_POSTGRES_URL.

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)

CREATE INDEX IF NOT EXISTS and ALTER TABLE ADD COLUMN IF NOT EXISTS take
their relation lock before the server evaluates the existence test, so a
boot on an already-migrated database still joins the lock queue. Relation
locks are granted in queue order, so every writer queues behind it.

The shared runner now asks pg_catalog whether the index or column is
already there and skips the statement when a row comes back, and 55P03
is no longer retried by default: with the pre-check ahead of it, a lock
timeout means the object is genuinely missing and each retry re-enters
the queue. Push keeps the old retry behind an explicit option.
…dable target

Three defects found in review of the auth reference implementation:

- The catalog query matched an index by name inside the table's namespace
  without checking it belonged to that table. Index names are unique per
  schema, not per table, so a same-named index on a sibling table answered
  yes and the real index was skipped forever. Added i.indrelid = t.oid.
- Lock-target derivation read a keyword sitting in an identifier position as
  the object name: CREATE UNIQUE INDEX CONCURRENTLY ON t(c) yielded the name
  CONCURRENTLY, and ADD COLUMN IF NOT EXISTS with no column yielded IF. A
  wrong target is worse than none, so keywords are now excluded and an index
  or column statement whose target cannot be read throws at boot with the
  statement text instead of falling through to the lock path.
- A concurrent-create collision retried the CREATE INDEX, taking SHARE on the
  table again for an object another director had just finished creating. The
  catalog is re-asked instead and a present object counts as skipped.
… all

The two ALTER TABLE constraint statements were the last lock-taking
statements without a pre-check, so every boot still took ACCESS EXCLUSIVE
on relay_region_rehome_attempts twice.

A lock target now carries the catalog answer that means there is nothing
left to do. ADD CONSTRAINT skips when pg_constraint already names it; DROP
CONSTRAINT IF EXISTS is the inverse and skips when it does not, because
nothing to drop is nothing to do. The match is by name only: the CHECK body
is generated from RELAY_REGIONS, so comparing it would re-run the swap on
every region change. Changing a definition under the same name is an
operator migration, and the rule comment beside SCHEMA says so.

A bare DROP CONSTRAINT gets no target and throws at boot, because skipping
it would swallow the undefined_object the server is supposed to raise.

The census invariant is now that every lock-taking statement has a
pre-check, with no exceptions, and the warm-boot Postgres test asserts zero
statements sent rather than two.
… its first action

`ALTER TABLE t ADD COLUMN IF NOT EXISTS a TEXT, ADD COLUMN IF NOT EXISTS b
TEXT` derived the target for `a` alone, so once `a` existed the whole
statement was skipped and `b` was never added. The first subcommand parses,
so neither the parse throw nor the census caught it.

A lock-taking ALTER TABLE with a comma outside parentheses, quotes and
comments now throws at boot. One action per statement, or no pre-check is
possible. Commas inside a parenthesised type, a CHECK body, a quoted
default or a comment are unaffected, and push's 18 statements still parse.
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review September 17, 2026 04:28

@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 — two parser edge cases inline, plus one compatibility-note nitpick.

Reviewed changes

  • Catalog pre-check wired into relay boot — @orca-cloud/postgres-schema derives each lock-taking statement's target from its own text and asks pg_catalog before sending it, so a warm boot on a migrated database issues zero lock-taking DDL.
  • Classification fix for comment-prefixed statements — leading --//* */ comments are stripped before classification, so the commented CREATE INDEX on relay_connection_bases keeps both its pre-check and its collision handling.
  • Index/constraint identity — the index pre-check is tied to its table (i.indrelid = t.oid) inside the table's namespace; constraint swaps are matched by name with opposite polarities (ADD skips present, DROP ... IF EXISTS skips absent).
  • Retry policy — 55P03 is no longer retried by default (relay fails the boot and names the statement); push opts back in with retryLockTimeout: true, having no pre-check. A concurrent-create collision re-asks the catalog instead of retrying the statement.
  • Tests — derivation/classification/pre-check unit tests, a relay golden census of the 30 lock-taking statements, and a real-PostgreSQL differential test (warm boot completes under a held ACCESS EXCLUSIVE; a negative control shows the same boot fails 55P03 without the pre-check).

ℹ️ Nitpicks

  • requireSchemaLockTarget runs for every caller, including one that passes no catalogQuery (push). The PR note says a no-catalog caller "behaves exactly as before apart from the 55P03 default", but an auto-named CREATE INDEX, a multi-action ALTER TABLE, or a bare DROP CONSTRAINT now fails that caller's boot too. Push's current statements all parse, so this is a documentation mismatch rather than a live bug.

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

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The PostgreSQL schema package now supports lock-target parsing, catalog pre-checks, structured results, and bounded retries. Relay startup uses these features to avoid unnecessary lock-taking DDL and validates its schema statements. Relay tests cover catalog behavior, lock targets, concurrent DDL, and timeout handling. Push explicitly enables lock-timeout retries because it does not use catalog pre-checks. The package test command now runs Vitest.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to f5ce0

Valid schema statements can miss catalog objects or bypass pre-checking, potentially retaining an obsolete constraint or re-entering lock queues. These parser gaps should be fixed before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 12 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, compatibility, and checklist. However, the required Linked Issue section is incomplete because it contains only Fixes # without… Add the complete linked issue reference after Fixes #, such as Fixes #1234``.
✅ Passed checks (3 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 and concisely describes the main change: skipping boot-time PostgreSQL DDL when the catalog already contains the object.
Full details: Docstring Coverage

Explanation

Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 12 files. (1 skipped: 1 unsupported.)

Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, compatibility, and checklist. However, the required Linked Issue section is incomplete because it contains only Fixes # without an issue number or link.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2e71d4e1-71fc-4b50-8d7c-b9022eed4ff6

📥 Commits

Reviewing files that changed from the base of the PR and between fbe7b19 and f5ce025.

📒 Files selected for processing (13)
  • cloud/apps/push/src/push-database.ts
  • cloud/apps/relay/src/database-postgres-timeout.test.ts
  • cloud/apps/relay/src/database-statement-timeout-postgres.test.ts
  • cloud/apps/relay/src/database.ts
  • cloud/apps/relay/src/relay-schema-catalog-precheck-postgres.test.ts
  • cloud/apps/relay/src/relay-schema-lock-targets.test.ts
  • cloud/packages/postgres-schema/package.json
  • cloud/packages/postgres-schema/src/apply-postgres-schema.test.ts
  • cloud/packages/postgres-schema/src/apply-postgres-schema.ts
  • cloud/packages/postgres-schema/src/catalog-object-precheck.ts
  • cloud/packages/postgres-schema/src/index.ts
  • cloud/packages/postgres-schema/src/schema-lock-target.test.ts
  • cloud/packages/postgres-schema/src/schema-lock-target.ts

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

…s, count brackets

Four findings from the bot reviews on #21147:

- A comment between two keywords (ALTER TABLE t ADD /* note */ COLUMN c
  TEXT) was invisible to both the classification regexes and the must-parse
  shapes, so the statement got no target AND no throw and ran with no
  pre-check. Every comment is now stripped quote-aware before classification,
  nested block comments included. The server is still sent the original text.
- hasTopLevelComma counted parentheses but not square brackets, so
  ADD COLUMN c bigint[] DEFAULT ARRAY[1, 2] read as two subcommands and
  failed the boot.
- bareIdentifier split a qualified name on '.' regardless of quoting, so
  "a.b" became b", and it kept the written case while Postgres folds an
  unquoted identifier to lower case before storing it in relname, attname
  and conname. The name is now tokenised quote-aware and folded, with the
  qualified table text still passed to to_regclass as written.
- sqlWithoutLeadingComments is renamed sqlWithoutComments to match.

Relay's 74 statements and push's 18 all still parse, and no relay target
name changed: every identifier there was already lower case.
A comment marker, comma, parenthesis or bracket inside `$$...$$` or
`$tag$...$tag$` is text. The closing delimiter has to match the opening tag
exactly, so an inner `$$` inside a `$tag$` body is more text rather than the
end, and a tag cannot start with a digit, which keeps a `$1` placeholder
from reading as an opener.

Relay's pg_stat_statements DO block is the only dollar-quoted statement in
the schema, and it now survives the stripper byte-identical. A test asserts
that against the real statement.

@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

  • Comment stripping made complete and quote-aware — sqlWithoutComments replaces the leading-only stripper with a single pass that honours '/" quoting (doubled-quote escapes included) and nested block comments, replacing each comment with a space. Classification now sees ALTER TABLE t ADD /* note */ COLUMN c, which previously yielded no target and no throw and so sent the DDL unchecked; the server still receives the original text, pinned by a new test.
  • Catalog names tokenised and folded like Postgres — bareIdentifier is replaced by qualifiedParts/catalogName: dots split only between identifiers ("a.b" stays one name), "" unescapes to ", and unquoted names lower-case to the form stored in relname/attname/conname. Previously a quoted dot or a mixed-case name would miss the catalog row and rebuild the object on every boot.
  • Square-bracket depth in the multi-action guard — hasTopLevelComma counts [/], so bigint[] and DEFAULT ARRAY[1, 2] no longer read as a second ALTER TABLE subcommand, while a genuine second subcommand after an array default is still caught.
  • Regression tests — comment-between-keywords derivation, catalog name folding (dot-in-quotes, case folding, doubled quotes, qualified tables), square brackets in both directions, and a test pinning the original comment-bearing statement text as what reaches the server.

Both prior inline threads are addressed by a479d1d and resolved.

Pullfrog  | 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.

Reviewed changes

  • Dollar-quoted bodies made opaque to both scanners — dollarQuoteEnd recognises $$...$$ and $tag$...$tag$ (the optional tag cannot start with a digit, so $1 placeholders are untouched) and both sqlWithoutComments and hasTopLevelComma copy the region through verbatim. A comment marker, comma, parenthesis or bracket inside a PL/pgSQL body is now text, closing the last place where the classification text could diverge from what the server parses.
  • Tests — a unit group for dollar-quoted defaults (comment marker and comma treated as text, a tagged body with an inner $$, numbered placeholders, an unterminated quote, and a genuine second subcommand after a dollar-quoted default still caught), plus a census test proving relay's real DO $relay_statement_stats$ migration survives sqlWithoutComments byte-identical.

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

@Jinwoo-H
Jinwoo-H merged commit 0699d73 into main Sep 17, 2026
24 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
stablyai#21147)

* fix(relay): skip boot-time DDL when the catalog already has the object

CREATE INDEX IF NOT EXISTS and ALTER TABLE ADD COLUMN IF NOT EXISTS take
their relation lock before the server evaluates the existence test, so a
boot on an already-migrated database still joins the lock queue. Relation
locks are granted in queue order, so every writer queues behind it.

The shared runner now asks pg_catalog whether the index or column is
already there and skips the statement when a row comes back, and 55P03
is no longer retried by default: with the pre-check ahead of it, a lock
timeout means the object is genuinely missing and each retry re-enters
the queue. Push keeps the old retry behind an explicit option.

* fix(relay): tie the index pre-check to its table and fail on an unreadable target

Three defects found in review of the auth reference implementation:

- The catalog query matched an index by name inside the table's namespace
  without checking it belonged to that table. Index names are unique per
  schema, not per table, so a same-named index on a sibling table answered
  yes and the real index was skipped forever. Added i.indrelid = t.oid.
- Lock-target derivation read a keyword sitting in an identifier position as
  the object name: CREATE UNIQUE INDEX CONCURRENTLY ON t(c) yielded the name
  CONCURRENTLY, and ADD COLUMN IF NOT EXISTS with no column yielded IF. A
  wrong target is worse than none, so keywords are now excluded and an index
  or column statement whose target cannot be read throws at boot with the
  statement text instead of falling through to the lock path.
- A concurrent-create collision retried the CREATE INDEX, taking SHARE on the
  table again for an object another director had just finished creating. The
  catalog is re-asked instead and a present object counts as skipped.

* fix(relay): pre-check constraint swaps so a warm boot sends no DDL at all

The two ALTER TABLE constraint statements were the last lock-taking
statements without a pre-check, so every boot still took ACCESS EXCLUSIVE
on relay_region_rehome_attempts twice.

A lock target now carries the catalog answer that means there is nothing
left to do. ADD CONSTRAINT skips when pg_constraint already names it; DROP
CONSTRAINT IF EXISTS is the inverse and skips when it does not, because
nothing to drop is nothing to do. The match is by name only: the CHECK body
is generated from RELAY_REGIONS, so comparing it would re-run the swap on
every region change. Changing a definition under the same name is an
operator migration, and the rule comment beside SCHEMA says so.

A bare DROP CONSTRAINT gets no target and throws at boot, because skipping
it would swallow the undefined_object the server is supposed to raise.

The census invariant is now that every lock-taking statement has a
pre-check, with no exceptions, and the warm-boot Postgres test asserts zero
statements sent rather than two.

* fix(relay): refuse a multi-action ALTER TABLE instead of pre-checking its first action

`ALTER TABLE t ADD COLUMN IF NOT EXISTS a TEXT, ADD COLUMN IF NOT EXISTS b
TEXT` derived the target for `a` alone, so once `a` existed the whole
statement was skipped and `b` was never added. The first subcommand parses,
so neither the parse throw nor the census caught it.

A lock-taking ALTER TABLE with a comma outside parentheses, quotes and
comments now throws at boot. One action per statement, or no pre-check is
possible. Commas inside a parenthesised type, a CHECK body, a quoted
default or a comment are unaffected, and push's 18 statements still parse.

* fix(relay): strip every comment before classifying, fold catalog names, count brackets

Four findings from the bot reviews on stablyai#21147:

- A comment between two keywords (ALTER TABLE t ADD /* note */ COLUMN c
  TEXT) was invisible to both the classification regexes and the must-parse
  shapes, so the statement got no target AND no throw and ran with no
  pre-check. Every comment is now stripped quote-aware before classification,
  nested block comments included. The server is still sent the original text.
- hasTopLevelComma counted parentheses but not square brackets, so
  ADD COLUMN c bigint[] DEFAULT ARRAY[1, 2] read as two subcommands and
  failed the boot.
- bareIdentifier split a qualified name on '.' regardless of quoting, so
  "a.b" became b", and it kept the written case while Postgres folds an
  unquoted identifier to lower case before storing it in relname, attname
  and conname. The name is now tokenised quote-aware and folded, with the
  qualified table text still passed to to_regclass as written.
- sqlWithoutLeadingComments is renamed sqlWithoutComments to match.

Relay's 74 statements and push's 18 all still parse, and no relay target
name changed: every identifier there was already lower case.

* fix(relay): treat a dollar-quoted body as opaque in both scanners

A comment marker, comma, parenthesis or bracket inside `$$...$$` or
`$tag$...$tag$` is text. The closing delimiter has to match the opening tag
exactly, so an inner `$$` inside a `$tag$` body is more text rather than the
end, and a tag cannot start with a digit, which keeps a `$1` placeholder
from reading as an opener.

Relay's pg_stat_statements DO block is the only dollar-quoted statement in
the schema, and it now survives the stripper byte-identical. A test asserts
that against the real statement.
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