Skip to content

executor: wait out readers of a table the attach's foreign keys reference - #737

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/attach-fk-referenced-lock-wait
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/attach-fk-referenced-lock-wait

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

The online attach now waits for long readers, not only writers, of every table the parent's foreign keys reference before it runs the ATTACH.

Why

When pg-sprite attaches a partition online, it prepares the new table first and then runs ATTACH PARTITION in one brief transaction. Before that transaction asks for its locks, it waits, outside PostgreSQL's lock queue, for anyone already holding a lock that would conflict with them. For a table the parent's foreign keys reference, such as customers for orders.customer_id, it waited only for writers, on the belief that the ATTACH takes a lock there that readers can share. In fact, when the ATTACH reuses the foreign key the run already built on the new table, which the online attach always does, it takes an exclusive lock on customers. A long report query on customers therefore made the ATTACH queue while it already held the new table and the DEFAULT partition. In that queue it blocked every new reader of customers until the lock budget ran out.

What

  • The waiting step now lists each table a foreign key of the parent references, and every partition of a partitioned one, with read and write lock modes. Tables whose own foreign keys reference the parent keep the writer-only wait: the ATTACH takes at most SHARE ROW EXCLUSIVE on them.
  • Probes on PostgreSQL 14–18 show the lock. Adopting the foreign key takes ACCESS EXCLUSIVE on the referenced table. When the referenced table is partitioned, it is taken on every partition, and on the root too from 15. Creating the foreign key instead takes only SHARE ROW EXCLUSIVE.
  • A new test holds ACCESS SHARE on the referenced table. On PostgreSQL 14, 16, and 18 it checks that progress reports the wait for that reader and that the attach finishes once the reader ends. It fails if the referenced table goes back to the writer-only wait. The two existing waiting tests now share a helper that takes the lock mode.
  • The attach section of the online DDL reference explains the lock, so operators running the attach by hand know about it too.

Before / after

Take orders, with FOREIGN KEY (customer_id) REFERENCES customers, a DEFAULT partition, and orders_2027 already prepared by the run. A dashboard query has been reading customers for two minutes.

Before
  t0  dashboard: SELECT ... FROM customers                (holds ACCESS SHARE)
  t1  waiting step: customers listed for writers only  ──▶  nothing to wait for
  t2  ATTACH: ACCESS EXCLUSIVE on orders_default and orders_2027  (granted)
  t3  ATTACH: adopting orders_2027's foreign key asks ACCESS EXCLUSIVE on customers
        └─ queued behind the dashboard; every new SELECT on customers queues behind it
  t4  lock_timeout ends the ATTACH; reads of customers were stalled from t3 to t4

After
  t0  dashboard: SELECT ... FROM customers                (holds ACCESS SHARE)
  t1  waiting step: customers listed for readers and writers
        └─ waits outside the queue; progress names the dashboard's session
  t2  dashboard ends
  t3  ATTACH takes its locks, adopts the foreign key, commits; no reader of customers waited

A reader that outlasts the holder wait is treated as a long writer is today: the ATTACH then asks for its locks under the lock budget.

…ence

Adopting the table's foreign key at the ATTACH drops that key's triggers on
the referenced table under ACCESS EXCLUSIVE, so a long reader there queued
the ATTACH while it held the table and the DEFAULT partition, and blocked
every new reader of the referenced table until the lock budget ran out.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 4, 2026 16:27
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-12-04T16:27:55.963686Z
We couldn’t complete this review. Comment @codex review to try again.
9e50bc3 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@JashLal

JashLal commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Local review of 9e50bc38d64ea240f2e3888e002cd51444964e3a. The new reader test covers the enforced foreign key on a plain table. I found two cases where the broader wait can spend the holder budget on a reader whose lock is compatible with the attach.

  • [P2] Keep the writer-only wait for NOT ENFORCED foreign keys. PostgreSQL 18 can clone these keys during attach without creating or dropping action triggers, so the referenced table only needs SHARE ROW EXCLUSIVE. The unconditional readAndWriteLockModes() makes a long reader delay the attach anyway. Use fk.notEnforced to choose writer-only modes when every key to that table is unenforced, and preserve the wider modes if any key to it is enforced. The existing NOT ENFORCED attach fixture can also check completion while an ACCESS SHARE holder remains open. attach_partition_ready.go:249
  • [P2] Match the PostgreSQL 14 lock modes for partitioned targets. PostgreSQL 14 puts action triggers on the leaves. The preflight applies the wider mode to the referenced root and all descendants, so a long LOCK TABLE ONLY accounts IN ACCESS SHARE MODE on the root can consume the holder budget even when the leaves are clear. Keep the reader wait on the leaves and use writer-only modes on partitioned nodes for PostgreSQL 14. attach_partition_ready.go:278

GitHub reports passing CI on PostgreSQL 14–18. I reviewed the diff and PostgreSQL source without running the repository tests locally. Builderbot result retrieval was unavailable (DNS lookup failed); this is a local review, not a confirmed Builderbot result.

@aparajon

aparajon commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review of 9e50bc3: no blocking findings, 4 non-blocking

The change does what the description says. attachForeignKeyLockedTables now waits for readers and writers on every table the parent's foreign keys reference, with its partitions when it is partitioned (attach_partition_ready.go#L248-L250), and keeps the writer-only wait for tables whose own foreign keys reference the parent (#L259-L261). The referenced entries are appended first, so the dedupe at #L265-L268 keeps the wider set for a table that is both referenced and referencing. Nothing regresses against main: every table that was waited on for writers still is, and the set only widens. CI is green on PostgreSQL 14 through 18.

Blocking

None.

Non-blocking

1. The doc comment on attachPartitionOnline still says only a writer is waited out on a foreign key table.
attach_partition.go#L199-L202 reads "while a reader or writer holds the table or the DEFAULT partition, or a writer holds a table the ATTACH reaches through a foreign key". The PR updated the INV: LK-2 comment a few lines below (#L271-L276) but not this one, so the two now disagree about the referenced tables. A reader of the function doc would conclude a long report query on a referenced table is not waited for, which is the exact belief the PR corrects.
Suggested fix: say a reader or writer holds a table the parent's foreign keys reference, or a writer holds a table whose foreign keys reference the parent.

2. No test shows the server really conflicts with a reader on the referenced table.
The new test (attach_partition_ready_integration_test.go#L221) proves the wait lists readers. It passes whether or not the ATTACH takes ACCESS EXCLUSIVE on accounts, so if a later PostgreSQL release stopped dropping those triggers under that lock, the wait would silently become needless and nothing would say so. Failure scenario: the lock mode on the referenced table changes in a future server version and the test suite stays green while the comment, the docs table, and the wait all describe behavior that no longer exists. A test with holderWait zero and a short lock budget, where a reader on accounts makes the ATTACH end on its lock budget, pins the claim the whole change rests on, on every server version in the CI matrix.

Test case: a reader on the referenced table makes the ATTACH hit its lock budget (not run; written against the fixtures in this file)
// A reader holds accounts and the step does not wait for it. The ATTACH
// adopts the table's foreign key by dropping that key's triggers on accounts,
// which needs ACCESS EXCLUSIVE there, so it ends on its lock budget and the
// table stays standalone.
func TestAttachPartitionOnlineAReaderOfTheReferencedTableBlocksTheAttach(t *testing.T) {
	withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) {
		f := newFixture(t)
		f.exec(t, eventsWithAccountsParent)
		f.exec(t, events2027AccountsFK)
		target := f.attachTarget(t)
		release, _ := f.holdLock(t, "accounts", "ACCESS SHARE")
		defer release()

		_, err := attachPartitionOnline(t.Context(), f.pool, target,
			Budget{LockTimeout: 200 * time.Millisecond, StatementTimeout: 5 * time.Second}, 0, nil, nil)
		var budgetErr *BudgetError
		require.ErrorAs(t, err, &budgetErr)
		assert.Empty(t, f.partitionBound(t, "events_2027"))
	})
}

3. The partitioned referenced table, the only place descendants matters here, has no test.
descendants: rel.relkind == "p" (attach_partition_ready.go#L278) is what makes a reader on a partition of a partitioned referenced table count, and the description says that is where the lock lands on 14 (partitions only) and from 15 (partitions and root). Both new and existing waiting tests use a plain accounts. Failure scenario: someone changes the descendants expression, and a long report on accounts_2026 goes back to queueing the ATTACH behind it while it holds the table and the DEFAULT partition, with every test green. The test needs the helper to separate the table it holds from the table progress names, because progress reports the referenced table, not the partition.

Test case: a reader on a partition of the referenced table is waited out (not run; needs attachWaitsOutAHolderOn to take a hold table and a reported table)
// A reader holds a partition of accounts, which the parent's foreign key
// references. The ATTACH drops the foreign key's triggers on every partition
// of accounts under ACCESS EXCLUSIVE, so the step waits that reader out and
// progress names accounts.
func TestAttachPartitionOnlineWaitsOutAReaderOnAPartitionOfTheReferencedTable(t *testing.T) {
	withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) {
		f := newFixture(t)
		f.exec(t, `
			CREATE TABLE %[1]s.accounts (
				id bigint PRIMARY KEY
			) PARTITION BY RANGE (id);
			CREATE TABLE %[1]s.accounts_low PARTITION OF %[1]s.accounts FOR VALUES FROM (0) TO (100);
			INSERT INTO %[1]s.accounts VALUES (1), (2), (3);
			CREATE TABLE %[1]s.events (
				id bigint NOT NULL,
				day date NOT NULL,
				account_id bigint REFERENCES %[1]s.accounts (id)
			) PARTITION BY RANGE (day);
			CREATE TABLE %[1]s.events_default PARTITION OF %[1]s.events DEFAULT;
			CREATE TABLE %[1]s.events_2027 (
				account_id bigint,
				id bigint NOT NULL,
				day date NOT NULL
			);
			INSERT INTO %[1]s.events_2027 VALUES (2, 2, '2027-03-01')`)
		f.exec(t, events2027AccountsFK)
		f.attachWaitsOutAHolderOnPartition(t, f.attachTarget(t), "accounts_low", "accounts", "ACCESS SHARE")
	})
}

4. A NOT ENFORCED foreign key on the parent is waited on for readers although the ATTACH adopts nothing for it.
The loop at attach_partition_ready.go#L248-L250 gives every parent foreign key the reader-and-writer set, but the new comment's reason, "the online attach adopts every one", does not hold for a PostgreSQL 18 NOT ENFORCED key: readiness leaves it out (#L144) and the existing test says the attach clones it without a scan. I did not verify which lock the server takes on the referenced table in that case, and I expect it is not ACCESS EXCLUSIVE, since no triggers are dropped. The cost is small: the attach step ignores the wait's outcome (attach_partition.go#L282), so a long reader delays the step by at most HolderWait and does not fail it. If a probe confirms it, using writeLockModes() for fk.notEnforced keeps the wait exact.

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon

aparajon commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 What I verified on 9e50bc3

The lock claim. Adopting a table's existing foreign key makes the server drop that key's own action triggers on the referenced table, and dropping a trigger opens its table ACCESS EXCLUSIVE. That conflicts with ACCESS SHARE and ROW SHARE as well as ROW EXCLUSIVE, so a writers-only wait left the ATTACH queued behind a long reader of the referenced table while it already held the new table and the DEFAULT partition. The readiness check (requireReady, attach_partition_ready.go#L144) refuses any table without a validated foreign key to adopt for each enforced foreign key of the parent, so on the online path every enforced key is adopted and every enforced key's referenced table needs the wider wait. The SHARE ROW EXCLUSIVE side, for tables whose own foreign keys reference the parent, is unchanged and still writers-only.

Cases checked in the diff and the code around it

  • Which modes reach the wait: readAndWriteLockModes() is AccessShareLock, RowShareLock, RowExclusiveLock, the three modes that conflict with ACCESS EXCLUSIVE among those application reads and writes take (lock_holder_wait.go). conflictingLockHolders filters granted locks by each relation's own modes, so the referencing tables stay writers-only.
  • A table both referenced by the parent and referencing it, including a self-referencing parent: the referenced entries are appended first, so the seen dedupe keeps the wide set. The map in waitOutsideLockQueue is last-write-wins per relation OID, so I checked the self-referencing parent: its partitions, the DEFAULT partition included, get the same reader-and-writer modes the proof entry has, so nothing is narrowed.
  • A partitioned referenced table: descendants is set for relkind == "p", and lockedRelations walks pg_inherits recursively, so nested partitions are covered. On PostgreSQL 14, where the lock lands on the partitions only, the root is waited on too, which is the safe direction.
  • A referenced table dropped between the read and the wait is skipped (!found), as before; the in-transaction lockOnly and the final readiness read still decide under the locks.
  • The wait's outcome is ignored by the attach step, so a reader that outlasts HolderWait leads to the ATTACH requesting its locks under its own lock budget, as for a long writer before. The reader wait therefore adds at most HolderWait and cannot turn a previously working attach into a failure.
  • The new test and the refactored helper (attachWaitsOutAHolderOn, with the mode as a parameter) assert the holder's PID and the referenced table's name from progress, then that the step attaches once the holder ends. The writer test keeps ROW EXCLUSIVE, the new one holds ACCESS SHARE; the referencing-table test is unchanged in behavior.
  • Docs: the paragraph added to docs/postgres-online-ddl-reference.md matches the code, including the PostgreSQL 14 versus 15 difference. The invariants registry's LK-2 entry names the wait generically, so it needs no change.
  • CI: all checks pass, including the PostgreSQL 14 to 18 integration jobs, so the new test passes on every version in the matrix.

Why it is complete. Every table the ATTACH locks ACCESS EXCLUSIVE through foreign keys is now in the reader-and-writer set, and the one narrower set that remains (referencing tables) is exactly the one the ATTACH locks at SHARE ROW EXCLUSIVE. The remaining items are the four non-blocking notes above: a stale function comment, two missing tests that would pin the server behavior and the partitioned case, and an over-wait for NOT ENFORCED keys that costs at most HolderWait.

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon aparajon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Stamping with comments: 0 blocking, 4 non-blocking (see the review comments above).

This review was generated by Claude Code (claude-sonnet-5-5).

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.

3 participants