Skip to content

executor: give a partitioned table to attach the parent's keys - #714

Open
Kiran01bm wants to merge 1 commit into
kiran01bm/attach-partitioned-indexesfrom
kiran01bm/attach-partitioned-keys
Open

Kiran01bm wants to merge 1 commit into
kiran01bm/attach-partitioned-indexesfrom
kiran01bm/attach-partitioned-keys

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

The online attach's index step now gives a table that is itself partitioned the parent's primary key and unique constraints, built concurrently, so the attach adopts them and builds no index.

Why

A partitioned parent's primary key or unique constraint must also exist on every partition. When pg-sprite attaches a partitioned table online, the ATTACH looks for a matching key on that table to adopt. Without one, it builds the key's index on every partition of the table while it blocks them all. The previous PR gave such a table the parent's plain indexes ahead of time but refused the parent's keys. This PR builds the keys too, so only foreign keys stand between a sub-partitioned table and an online attach.

What

  • For a parent key nothing on the table pairs with, the step runs the existing partitioned key build on the table itself, under the derived name <constraint>_p<table oid>. Each leaf's unique index is built concurrently and given the constraint, then the table's own ADD CONSTRAINT adopts them in one brief transaction that builds nothing. A rerun finds the key.
  • A key the table already has, of the parent key's columns, is taken as it stands, as before.
  • The checks the plain-table path makes before building a key (not DEFERRABLE, a plain unique btree index on its columns) move into one helper, attachKeySpec, that both paths share.
  • The partitioned key build's refusals reach the step. A table whose partition is itself partitioned is refused with ErrPartitionedKeySubPartitioned until that build takes nested trees.

Before / after

Take visits with PRIMARY KEY (id, day, region), and visits_2027, partitioned by region into visits_2027_eu and visits_2027_us, with no key. The index step runs on visits_2027 before the attach. Before, it refused the parent's key; after, it builds the key without blocking writes, and the ATTACH adopts it.

Before
  ensureAttachIndexes(visits → visits_2027)
    └─ visits_pkey: visits_2027 is partitioned  ──▶  refused, nothing built
  ATTACH visits_2027 run as written
    └─ builds the key's unique index on _eu and _us under ACCESS EXCLUSIVE

After
  ensureAttachIndexes(visits → visits_2027)
    └─ visits_pkey  ──▶  partitioned key build of visits_pkey_p<oid> on visits_2027
          ├─ CREATE UNIQUE INDEX CONCURRENTLY on _eu and _us, then ADD CONSTRAINT ... USING INDEX on each
          └─ ALTER TABLE visits_2027 ADD CONSTRAINT visits_pkey_p<oid> PRIMARY KEY: adopts both, builds nothing
  ATTACH visits_2027
    └─ visits_pkey adopts visits_pkey_p<oid>; the 3 indexes in the tree are the ones the step built

The attach index step now gives a table that is itself partitioned the key
constraint a parent PRIMARY KEY or UNIQUE constraint adopts at the attach,
by running the partitioned key build on it, so the ATTACH builds no index.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 4, 2026 03:48
@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-04T03:48:11.197639Z
We couldn’t complete this review. Comment @codex review to try again.
1539478 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 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review 1/2 (correctness) of 1539478: 0 blocking, 3 non-blocking.

Inspected the whole diff at head 153947899b4ab50aa4bc1705124cbe44c9e9b49d, plus the surrounding code it leans on (partitioned_key_flow.go, attach_index_pairing.go, attach_partition.go, the derived-name helper) and docs/invariants.md. CI is green on all of PostgreSQL 14 to 18. I did not build or run anything locally, so the proposed tests below are marked "not run here".

Relation to #713. This PR's base is exactly #713's head (e06c45b), so it is a stack on it and shares no hunk with it: the diff here deletes the one #713 test that pinned the old refusal (TestEnsureAttachIndexesGivesAPartitionedTableOnlyAKeyItHas) and replaces it. It depends on #713 for ensureAttachPartitionedIndex, the subPartitioned branch of the step, and the partitioned-table pairing, so it cannot merge first. It does not conflict with it.

What the PR does, and whether it is right. For a parent PRIMARY KEY or UNIQUE constraint with nothing on a partitioned table to pair with, ensureAttachPartitionedKey (attach_index_partitioned.go#L38-L73) runs the existing partitioned key build on the table under the derived name <constraint>_p<oid>. The checks the plain path made (not DEFERRABLE, a plain unique btree index on the key columns) moved unchanged into attachKeySpec (attach_index.go#L323-L348), which both paths now call before anything is built. I found no correctness defect.

Why it holds:

  • Pairing and adoption. The pairing already accepts a partitioned key index of the same definition and, from PostgreSQL 17, the same constraint type (attachTakes, attach_index_pairing.go#L81-L106). The key the build leaves is a valid partitioned key index, so the attach adopts it. The step's closing read re-pairs and refuses with errAttachIndexIncomplete unless every parent index pairs with the reported table index (attachIndexesComplete, L112-L127 of the same file), and the ATTACH step itself refuses with errAttachIndexNotReady rather than build under its lock (attach_partition.go#L53-L56). So a step that is wrong fails closed, not into a build under ACCESS EXCLUSIVE.
  • Locks. The table is a standalone node, so only direct writers to it are affected. Each leaf takes ACCESS EXCLUSIVE only for ADD CONSTRAINT ... USING INDEX on an index already built concurrently, and the table's own ADD CONSTRAINT takes it on the table and every leaf in one brief transaction under lock_timeout (LK-2's description of the build, docs/invariants.md L954-L979). Nothing new is held across a build.
  • Naming. The table's constraint takes derivedPartitionIndexName(constraint, table.oid) (attach_index_partitioned.go#L47) and each leaf derives again from that, so a name over 63 bytes is cut with a digest rather than silently truncated, and a rerun finds every name.
  • Failure midway. The build resumes from what an earlier run left (checkParent reports a finished parent key as done, ParentAdded false, which the step maps to attachIndexFound, L68-L71), and an invalid concurrent index is debris the leaf step removes under proof. A run that stops after some leaves leaves their constraints and indexes in place, by design (AddPartitionedKey's own doc says so); there is no half-adopted state, because the table's constraint is added only after every leaf has one.
  • Refusals. A different primary key on the table, a nullable primary key column, a foreign table, a pending detach, and a nested tree all arrive as the build's typed errors, still matchable with errors.Is through the two %w wraps (attach_index.go#L143, attach_index_partitioned.go#L56).

Invariants: ST-7 extends (the table is proved before the build at L51 and again, in the same read as the key lookup, at L60); CO-9 upholds (attachKeyIndexSQL is pg_catalog-qualified, L77-L80); LK-2 extends (the same bounded, brief windows, now reached for a partitioned table); LK-1 is unchanged (see non-blocking 2).

Non-blocking

1. A refusal for a nested tree comes after earlier parent indexes have been built. ensureAttachIndexes walks the parent's indexes in OID order (attach_index.go#L124-L146, ORDER BY c.oid at L374) and builds each as it goes. The nested-tree refusal (refuseKeyTree, partitioned_key_flow.go#L178, refuseSubPartitioned L208) fires only when the key's turn comes. A parent whose primary key was added after a plain index (so the plain index has the lower OID) therefore gets that index built across the whole table's tree, potentially for hours, and then the step fails on the key. Earlier indexes staying is the documented contract, and the same ordering held before this PR, so this is not a regression. But the refusal is now a known, static property of the tree, and it can be checked up front for any parent that has a key constraint, before the first build. The new test asserts nothing was built only because its parent has no other index.

Test case (not run here: no local Postgres or build)
func TestEnsureAttachIndexesRefusesANestedTreeBeforeBuildingAnyIndex(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.visits (
				id bigint NOT NULL, day date NOT NULL, region text NOT NULL
			) PARTITION BY RANGE (day);
			CREATE INDEX visits_region_idx ON %[1]s.visits (region);
			ALTER TABLE %[1]s.visits ADD CONSTRAINT visits_pkey PRIMARY KEY (id, day, region);
			CREATE TABLE %[1]s.visits_2027 (
				id bigint NOT NULL, day date NOT NULL, region text NOT NULL
			) PARTITION BY LIST (region);
			CREATE TABLE %[1]s.visits_2027_eu PARTITION OF %[1]s.visits_2027 FOR VALUES IN ('eu');
			CREATE TABLE %[1]s.visits_2027_us PARTITION OF %[1]s.visits_2027
				FOR VALUES IN ('us') PARTITION BY RANGE (id);
			CREATE TABLE %[1]s.visits_2027_us_low PARTITION OF %[1]s.visits_2027_us
				FOR VALUES FROM (0) TO (100)`)

		_, err := ensureAttachIndexes(t.Context(), f.pool, f.parentOID(t, "visits"), f.standalonePartitioned(t, "visits_2027"), attachIndexBudget, nil, 0, nil)
		require.ErrorIs(t, err, ErrPartitionedKeySubPartitioned)
		for _, rel := range []string{"visits_2027", "visits_2027_eu", "visits_2027_us", "visits_2027_us_low"} {
			assert.Empty(t, f.tableIndexes(t, rel), rel)
		}
	})
}

Expected to fail on 1539478: visits_region_idx has the lower OID, so its derived index is built on every relation of the tree before the key's turn.

2. The build resolves the table by name and does not hold the table's own lock; the proof is before and after, not around. partitionedKeyRequest carries only schema and table names, and the build resolves them in resolveTarget (partitioned_key_flow.go#L89-L113). proveAttachNode runs before it (attach_index_partitioned.go#L51) and the read at L59-L64 after, so a table swapped under the name between the two would have its leaves keyed and a constraint added before the later read refuses. The step is fail-closed afterwards and the swap needs a concurrent rename of a standalone table, so I am not calling it blocking, and it is the same shape the partitioned index step accepted in #713. A key is a heavier thing to land on the wrong table than an index (a primary key can set NOT NULL on a leaf). Carrying table.oid in the request and comparing it in resolveTarget would close it. Related: the attach holds the parent's advisory lock (header of ensureAttachIndexes, L82-L83), while AddPartitionedKey takes the lock of the table it keys; this path does not, so a direct AddPartitionedKey on the same standalone table could run alongside. That too fails closed (a second primary key is refused by the server and by checkParent), and every earlier attach step has the same property.

3. The tests pin PRIMARY KEY on a fresh two-leaf table, and little else of the new branch. Not covered: a parent UNIQUE constraint (the partitionedUniqueKey kind through attachKeySpec, L324-L330), a resume where the leaves have their constraints but the table has none (the keyed report with Leaves found), a parent with a plain index and a key together, and the derived constraint and index names on the leaves. The rerun assertion only covers the finished case.

Test case for a parent UNIQUE constraint (not run here: no local Postgres or build)
func TestEnsureAttachIndexesGivesAPartitionedTableTheUniqueKey(t *testing.T) {
	withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) {
		f := newFixture(t)
		f.exec(t, strings.Replace(keyedVisits,
			"CONSTRAINT visits_pkey PRIMARY KEY (id, day, region)",
			"CONSTRAINT visits_uniq UNIQUE (id, day, region)", 1))
		parent, table := f.parentOID(t, "visits"), f.standalonePartitioned(t, "visits_2027")
		name := derivedPartitionIndexName("visits_uniq", table.oid)

		results, err := ensureAttachIndexes(t.Context(), f.pool, parent, table, attachIndexBudget, nil, 0, nil)
		require.NoError(t, err)
		require.Len(t, results, 1)
		assert.Equal(t, attachIndexKeyed, results[0].action)
		assert.Equal(t, name, results[0].index)

		f.attach(t, attachVisits2027)
		assert.Equal(t, []tableKey{{name: name, adopted: true}}, f.tableKeys(t, "visits_2027"))
	})
}

Needs strings imported. Expected to pass on 1539478 if the unique path behaves as the primary key one does; it is the gap in coverage rather than a known failure.

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

@aparajon

aparajon commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review 2/2 (OSS adoption and integration ease) of 1539478: 0 blocking, 3 non-blocking.

Same head, 153947899b4ab50aa4bc1705124cbe44c9e9b49d. This read looks at what an adopter of the CLI sees, and what a program that imports pkg/executor (a schema change orchestrator, say) has to handle. Correctness is in the first comment.

For adopters. The change removes a dead end: attaching a partitioned table under a parent with a primary key or unique constraint used to be refused unless the table already carried a matching key, and now the step builds it online and the ATTACH changes only the catalog. The PR description's before/after is accurate against the code and the new test (the three indexes in the tree are the ones the step built; the attach builds none). For a caller, a refusal now arrives as a typed, exported error (ErrPartitionedKeySubPartitioned and the build's other refusals) rather than the unexported errAttachIndexUnsupported the old branch returned, so an importer can errors.Is on it through both wraps. That is an improvement.

Non-blocking

1. The invariants registry still describes the step as it was. docs/invariants.md ST-7 says the attach index step proves "the table to attach still that plain table" (L1808-L1812), and LK-2 says the leaf key step is "also reached through the attach index step ... for a table to attach" (L954-L956). With #713 and this PR a partitioned table to attach is also proved (proveAttachNode at attach_index_partitioned.go#L51 and proveNodeIn at L60), and the whole partitioned key build, with its brief ACCESS EXCLUSIVE window on the table and every leaf, is reached through the step. The registry is what reviewers trust, so both entries should name the partitioned path and the tests that pin it (TestEnsureAttachIndexesGivesAPartitionedTableThePrimaryKey, TestEnsureAttachIndexesRefusesAKeyOnATwoLevelPartitionedTable). The docs guards are green, so nothing enforces this. The leftovers of an attach an operator abandons after the step (a key constraint and unique index on each leaf and on the table, under derived names) are also not described anywhere an adopter would look; one sentence in the step's header comment would do.

2. The error text names a constraint the adopter never wrote. A nested tree under a parent visits_pkey surfaces as give s.visits_2027 the index of visits_pkey: build the key constraint visits_pkey_p<oid> of s.visits_2027: ... (attach_index.go#L143 wrapping attach_index_partitioned.go#L56, which formats spec.name, already the derived name). The outer wrap does name visits_pkey, so it is traceable, but the inner half reads like an object the adopter should go look for. Formatting pi.constraint at L56 (the parent's name) and leaving the derived name to the debugging detail would read better. Separately, an importer cannot tell before running the attach that a nested tree will be refused for a keyed parent; a refusal ahead of the first build (first comment, finding 1) would also let a planner report it up front rather than after a build.

3. The table's key keeps an OID-derived name after the attach. As for the leaf path and the index step, the constraint is <parent constraint>_p<table oid> and its leaves derive again from that, so the same logical partition carries a different constraint name in each environment (OIDs differ). That is deliberate so a rerun finds its own work, and it is stated in the PR. For a declarative tool it means the end-state name is not the one a hand-written desired schema would use (visits_2027_pkey); I did not check how the diff or rename logic treats such a name on the next plan, so this is a question rather than a defect. If it matters, renaming the constraint after the ATTACH commits would settle names, and could be a follow-up.

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 across the two review comments above (3 correctness, 3 OSS adoption and integration).

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

@JashLal

JashLal commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Static review of 153947899b4ab50aa4bc1705124cbe44c9e9b49d.

I checked the shared key eligibility checks, the post-build lookup scoped to the candidate table’s OID, and the final pairing. The new integration test records all three index OIDs before ATTACH and verifies adoption of those same indexes, so it would catch rebuilding them under the attach lock. I found no additional issue beyond the existing review. This PR is stacked on #713. GitHub CI reports success on PostgreSQL 14–18. I did not run tests locally.

The automated review result was unavailable. No local tests were run.

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