Skip to content

executor: give a partitioned table the online attach's proofs and constraints - #706

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/attach-partitioned-table
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/attach-partitioned-table

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

The online attach's proof and constraint steps now work on a table that is itself partitioned, the first step toward attaching a sub-partitioned table online.

Why

pg-sprite runs ATTACH PARTITION online: before the brief attach, it gives the new table a validated CHECK that proves its rows fit the bound, plus the parent's CHECKs and NOT NULLs, so the attach itself scans nothing. Today every one of those steps accepts only a plain table, so a table that is itself partitioned (for example a year table split by region) cannot be attached online at all. This PR lets the first two steps work on such a table. The attach flow still refuses one until the index and foreign key steps follow in later PRs.

What

  • The proof step accepts a partitioned table. Its ADD CONSTRAINT ... NOT VALID and VALIDATE recurse to every partition. The wait for long-lived lock holders now covers every partition below the table, because the ADD and DROP lock each of them.
  • The constraint step's NOT NULL helper works the same way on a partitioned table. SET NOT NULL recurses, and each partition skips its scan on its copy of the validated helper.
  • On PostgreSQL 18, a NOT VALID not-null constraint on any partition below the table is refused, as one on the table already was, because SET NOT NULL on the table leaves it NOT VALID.
  • errAttachProofNotPlainTable becomes errAttachProofTableKind. It now refuses only relations that are neither plain nor partitioned tables (a view, a foreign table) and keeps the same outcome code.

Before / after

Take payments_2027, partitioned by currency into payments_2027_usd and a DEFAULT partition that is itself split by half year, attached under payments. Before, the proof step refused the table outright. After, the steps give the whole tree what the attach needs, and the attach proves the bound from the validated CHECK instead of scanning any leaf. The flow's own refusal of a partitioned table to attach is unchanged in this PR.

Before
  ensureAttachProof(bound CHECK on payments_2027)
    └─ lock + prove the table: relkind 'p'  ──▶  refused, nothing added
  ATTACH payments_2027 run as written
    └─ scans payments_2027_usd, _other_h1, _other_h2 under ACCESS EXCLUSIVE

After
  ensureAttachProof(bound CHECK on payments_2027)
    ├─ ADD ... NOT VALID: copies reach all four partitions (brief lock on each)
    └─ VALIDATE: scans the three leaves under SHARE UPDATE EXCLUSIVE, writes go on
  ensureAttachConstraints(payments → payments_2027)
    ├─ the parent's two CHECKs: added and validated the same way
    ├─ helper CHECK (id IS NOT NULL AND paid IS NOT NULL): validated once
    ├─ SET NOT NULL id, paid: all 5 tables proved from the helper, none scanned
    └─ helper dropped from all 5 tables
  ATTACH payments_2027
    └─ "partition constraint ... is implied by existing constraints": no leaf scanned

A DEFAULT partition of the parent that is itself partitioned works the same way at the step level: its exclusion proof reaches its leaves, and the attach skips their scan.

The proof and constraint steps of the online attach now act on a table
that is itself partitioned: each CHECK reaches every partition below it,
and SET NOT NULL skips every partition's scan. The flow still refuses a
partitioned table to attach until its index and foreign key steps follow.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 2, 2026 19:09
@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-02T19:09:27.273031Z
We couldn’t complete this review. Comment @codex review to try again.
0686a0f 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.

@aparajon

aparajon commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review 1/2 (correctness) of 0686a0f: 0 blocking, 4 non-blocking.

Inspected the whole change at 0686a0f46a090e2b76b011a0b3717dfbcb25887d: the three production edits (attach_proof.go, attach_constraints.go, the one-line code mapping in code.go), the new attach_partitioned_source_integration_test.go, and the one test it removes, against the flow that calls them (attach_partition_flow.go), the holder-wait code (lock_holder_wait.go) and the proof drop (attach_proof_drop.go). CI at the time of posting: all 18 checks green, including lint, build, unit tests, the PostgreSQL 14 to 18 legs, Supabase compatibility and all-green. The PR has base main; it does not stack on #704 or #705 (partitioned index builds), and it touches none of their files.

The change lets the proof step and the NOT NULL helper run on a table that is itself partitioned. Three production edits carry it. The proof's lockedTables now sets descendants: true, so the wait outside the lock queue covers every partition the ADD and DROP lock. The relkind gate accepts p as well as r, under the renamed errAttachProofTableKind. attachColumnSQL looks for a NOT VALID not-null constraint on the table and on every partition below it, matching the partition's column by name. I read each against what PostgreSQL does for ADD ... CHECK ... NOT VALID, VALIDATE CONSTRAINT, SET NOT NULL and DROP CONSTRAINT on a partitioned table (each recurses to every partition, and the CHECK on the parent reads validated only after the recursion has validated every copy), and found nothing wrong. The new path is unreachable from the public attach flow today, which is what the PR says: resolve still refuses a table to attach that is not r, and a DEFAULT partition that is not r, before any proof step runs. So no user-visible behavior changes and the public outcome codes are the same.

Invariants (docs/invariants.md): LK-2 and ST-7 are the entries this touches. The change upholds both in code: the added ADD, DROP and SET NOT NULL locks are still requested after the wait outside the lock queue, and the proof still proves the name resolves to the table the run resolved before it decides. Their wording is now stale; that is finding 2 of comment 2/2.

Non-blocking

  1. The "matched by name, because its attnum may differ" claim in the new column SQL is not pinned: the tests only use partitions whose column has the same attnum as the table's. attachColumnSQL joins the partition's constraint to its attribute and compares names (d.attname = a.attname, #L469-L476), which is right. Every partition in paymentsSubPartitioned is created with PARTITION OF, so it takes the table's column order, and id is attnum 1 on all five tables. A mutant that goes back to the old k.conkey[1] = a.attnum predicate, now over the partition list, matches on every one of them, and the PostgreSQL 18 test still refuses the nested leaf. By reading, nothing fails. The case the comment describes is a leaf created on its own with another column order and then attached to the sub-partitioned table, which PostgreSQL allows. Reasoned from the code, not run here (it needs a live PostgreSQL 18).
Test case: a leaf with another column order (not run here)
// The leaf's id is attnum 2 while the table's is attnum 1; the NOT VALID
// not-null constraint on the leaf must still be found, by name.
func TestEnsureAttachConstraintsRefusesANotValidNotNullOnALeafOfAnotherColumnOrder(t *testing.T) {
	withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) {
		f := newFixture(t)
		if major := f.serverMajor(t); major < 18 {
			t.Skipf("a NOT VALID not-null constraint needs PostgreSQL 18, have %d", major)
		}
		f.exec(t, `
			CREATE TABLE %[1]s.payments (
				id bigint NOT NULL,
				paid date NOT NULL,
				amount integer
			) PARTITION BY RANGE (paid);
			CREATE TABLE %[1]s.payments_2027 (
				id bigint,
				paid date,
				amount integer
			) PARTITION BY LIST (amount);
			CREATE TABLE %[1]s.payments_2027_leaf (
				paid date,
				id bigint,
				amount integer
			);
			ALTER TABLE %[1]s.payments_2027 ATTACH PARTITION %[1]s.payments_2027_leaf FOR VALUES IN (1);
			ALTER TABLE %[1]s.payments_2027_leaf
				ADD CONSTRAINT payments_2027_leaf_id_not_null NOT NULL id NOT VALID`)

		_, err := ensureAttachConstraints(t.Context(), f.pool, f.tableOID(t, "payments"), f.attachTable(t, "payments_2027"),
			attachProofTestBudget, 0, nil, nil)
		require.ErrorIs(t, err, errAttachNotNullNotValid)
	})
}

Not run here (it needs a PostgreSQL 18 container). It should pass at the head, and fail against k.conkey[1] = a.attnum.

  1. The typed refusal the new sentinel's comment promises for a foreign table is untested, and may be pre-empted by the LOCK TABLE just above it. errAttachProofTableKind says it covers "a foreign table, whose CHECK the server does not enforce", but lockAndProveAttachProofTable runs LOCK TABLE ONLY first, and the only error it translates is undefined_table. As I read PostgreSQL's LOCK TABLE, it accepts plain tables, partitioned tables and views, and rejects other kinds with cannot lock relation (wrong_object_type), which would come back as a bare wrapped error, not the typed one, on the versions that reject foreign tables. The replacement test, TestEnsureAttachProofRefusesAView, uses a view, which LOCK does accept (it locks the view's base tables for the transaction, a side effect of the refusal worth knowing). This is pre-existing in shape, and the flow refuses a foreign table before it gets here, so it is reachable only by a direct caller. Either test the foreign table on the CI versions and map the lock error to the same sentinel, or narrow the comment to "a view" and say a foreign table is refused by the lock. I did not run it.

  2. The new comment on lockAndProveAttachProofTable says the ONLY lock excludes every ATTACH, DETACH and CREATE ... PARTITION OF under the table; it excludes those at the first level only. attach_proof.go#L416-L423: LOCK TABLE ONLY takes SHARE UPDATE EXCLUSIVE on the table itself, which conflicts with those commands when they name the table as the parent. A command on a sub-partitioned partition one level down locks that partition, not the table, so it is excluded only once the ADD or VALIDATE statement has taken its own recursive locks on that partition, a moment later in the same transaction. The behavior is safe (the statement recurses under the transaction, and the read-back before the commit checks the result), but the comment reads as a stronger guarantee than the lock gives. Say "directly under it, and, once the statement runs, at every level".

  3. Nothing bounds or exercises the number of partitions. The ADD, DROP and every column's SET NOT NULL now hold ACCESS EXCLUSIVE on every partition of the tree for their transaction, requested one partition at a time under lock_timeout, so the hold grows with the partition count and the worst wait for the locks is the count times lock_timeout, cut short only by the pool's statement_timeout. The wait outside the lock queue now watches every partition (descendants: true, read by lockedRelations), which is the right mitigation, and the tests use five tables. A single test with a few dozen partitions would show the step's duration and lock hold stay brief, which is the property the invariant entry's "catalog-only, brief" wording relies on. Reasoned, not run.

Verified

  • Read the whole diff and the surrounding code at the head. I ran no build or test (no clone was available for this review): every new scenario starts a PostgreSQL container, and the test (PostgreSQL 14) to (PostgreSQL 18, ...) checks at this head passed them.
  • Callers of the renamed sentinel: it appears only in attach_proof.go, code.go, code_internal_test.go and the removed test, all in this PR, so nothing dangles. sentinelCode keeps the same outcome code.
  • The removed test, TestEnsureAttachProofRefusesAPartitionedTable, asserted the old refusal of a partitioned DEFAULT partition; the new TestEnsureAttachProofProvesAPartitionedDefaultPartition covers the replacement behavior, and the flow-level refusal is unchanged.
  • Mutation table (by reading, since the scenarios need a live PostgreSQL):
Mutant Caught by
descendants: true dropped from the proof's lockedTables TestEnsureAttachProofWaitsOutALongReaderOfANestedLeaf: the reader on the leaf is not seen, progress never reports the wait, and require.NotNil(wait) fails after 5 s
relkind gate back to r only the four tests that run a step on a partitioned table fail with errAttachProofTableKind
partition list removed from attachColumnSQL TestEnsureAttachConstraintsRefusesANotValidNotNullOnANestedLeaf (PostgreSQL 18 legs only; skipped before 18)
k.conkey[1] = a.attnum instead of the name match survives: every partition has the table's attnum (finding 1)
UNION SELECT a.attrelid dropped from the list the existing table-level NOT VALID tests

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

@aparajon

aparajon commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review 2/2 (OSS adoption and integration) of 0686a0f: 0 blocking, 2 non-blocking.

Read the change from two seats: a contributor who works on the online attach and relies on docs/invariants.md to say what each step holds and what proves it, and a host or importer of pkg/executor who needs the public surface and outcome codes to stay put. Nothing here is exported: the renamed sentinel, the proof step and the constraint step are unexported, Code and its mapping are unchanged, and the one docs edit is the attach-partition-index-unsupported row of the outcome table in docs/execution-model.md, whose new wording matches the code (the index step refuses a table that is not plain, the proof step a relation that is neither plain nor partitioned).

Non-blocking

  1. LK-2 still says the attach's proof and constraint steps hold ACCESS EXCLUSIVE on "one table only". The entry (docs/invariants.md#L840) says in its paragraph at #L1009-L1015 that a proof's ADD, each column's SET NOT NULL and the DROP hold the lock "on one table only". For a partitioned table, which this PR makes the steps accept, each statement locks every partition at every level (the PR's own new comment says so, attach_proof.go#L268-L271). The public flow cannot reach it yet, so the sentence is still true of everything shipped; it will not be once a later PR in the series lets the flow attach a partitioned table, and the entry is the page a reviewer of that PR will read. One clause ("on that table and, for a partitioned table, on every partition below it, which the wait outside the lock queue also watches") keeps it true. The change upholds LK-2.

  2. ST-7's description of the proof step still says "the plain table", and the entry's test list names none of the new tests. The paragraph at #L1847-L1867 says each step proves under its lock that the name "still resolves to the plain table the run resolved" (#L1851); lockAndProveAttachProofTable now accepts a partitioned table too (attach_proof.go#L442). The same list of enforcing tests, and the LK-2 list at #L1019-L1022, do not name TestEnsureAttachProofWaitsOutALongReaderOfANestedLeaf or the other four scenarios, so a contributor who changes the partition wait and reads LK-2 to find what guards it will not find the test that fails. Change "plain table" to "plain or partitioned table" and add the nested-leaf wait test to the LK-2 list. The change upholds ST-7.

What reads well for adopters

  • The PR body says plainly that the flow's refusal of a partitioned table to attach is unchanged and that this is the first step of a series, and the code agrees: a reviewer can see the new path is reachable only from tests and not from the attach flow.
  • The before/after in the body follows one concrete table (payments_2027 with a nested DEFAULT split by half year) through the proof, the constraint and the attach steps, and names the outcome the attach then reaches ("is implied by existing constraints", no leaf scanned). The new tests assert the same thing with requireNoScan over every leaf.
  • The rename from errAttachProofNotPlainTable to errAttachProofTableKind keeps the outcome code and the code-mapping test case, so a host matching on attach-partition-index-unsupported sees no change, and the doc row says which step reports it.
  • Each new scenario has a comment above it stating what is exercised and what a failure would mean, in the package's usual style, and the new _integration_test.go file runs in the existing per-version legs with no workflow change.

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, 6 non-blocking (see the review comments above).

This stamp was left by Claude Code (claude-sonnet-5-5).

@JashLal

JashLal commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

🤖 Reviewed 0686a0f. The nested-leaf tests cover recursive proof and validation, lock-holder reporting, and the PostgreSQL 18 refusal for an existing NOT VALID not-null constraint.

There is a potential race in setAttachNotNull. The descendant NOT VALID check runs before the helper work and the SET NOT NULL transaction. A concurrent session could add a leaf-local NOT VALID constraint in that interval while the root column is still nullable. Given the PostgreSQL 18 behavior described in this PR, that constraint could remain invalid after the recursive SET NOT NULL. The readback already populates c.notValid and only asserts c.notNull. Please return the typed refusal if c.notValid is true before committing. A regression test that runs the leaf DDL between preflight and SET NOT NULL would exercise this timing.

This was a static review. I ran no tests.

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