Skip to content

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

Open
Kiran01bm wants to merge 1 commit into
kiran01bm/attach-partitioned-keysfrom
kiran01bm/attach-partitioned-fks
Open

Kiran01bm wants to merge 1 commit into
kiran01bm/attach-partitioned-keysfrom
kiran01bm/attach-partitioned-fks

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

The online attach's foreign key step now gives a table that is itself partitioned the parent's foreign keys, validated while writes go on, so the attach adopts them and validates nothing.

Why

A partitioned parent's foreign key must hold on every partition. When pg-sprite attaches a partitioned table online, the ATTACH adopts a validated foreign key of the same definition on that table. Without one, it creates the foreign key on every partition of the table and checks every row against the referenced table while it blocks them all. Until now the foreign key step refused a partitioned table. This PR builds those foreign keys ahead of time, which is the last step the online attach needs before it can take a partitioned table.

What

  • Before PostgreSQL 18, which refuses ADD FOREIGN KEY ... NOT VALID on a partitioned table, the step runs the existing partitioned foreign key build on the table under the derived name <fk>_p<table oid>. Each leaf's foreign key is added NOT VALID and validated, then the table's own ADD FOREIGN KEY adopts them in one brief transaction that scans nothing.
  • From PostgreSQL 18 the existing leaf step also takes a standalone partitioned table: its ADD ... NOT VALID reaches every partition at every level, and its VALIDATE validates each one.
  • Probes on PostgreSQL 16 and 18 confirm that the ATTACH then adopts the table's foreign key and scans neither the table's leaves nor the referenced table.
  • Before 18, a table whose partition is itself partitioned is refused with ErrPartitionedForeignKeySubPartitioned until that build takes nested trees.

Before / after

Take payments with FOREIGN KEY (account_id) REFERENCES accounts, and payments_2027, partitioned by region into payments_2027_eu and payments_2027_us, with no foreign key. The step runs on payments_2027 before the attach. Before, it refused the table; after, it validates the foreign key without blocking writes, and the ATTACH adopts it.

Before
  ensureAttachForeignKeys(payments → payments_2027)
    └─ payments_2027 is of kind 'p'  ──▶  refused, nothing added
  ATTACH payments_2027 run as written
    └─ creates the foreign key on _eu and _us and checks every row, under ACCESS EXCLUSIVE

After, PostgreSQL 14–17
  ensureAttachForeignKeys(payments → payments_2027)
    └─ partitioned foreign key build of payments_account_fk_p<oid> on payments_2027
          ├─ ADD ... NOT VALID, then VALIDATE, on _eu and on _us (writes go on)
          └─ ALTER TABLE payments_2027 ADD CONSTRAINT ...: adopts both, scans nothing

After, PostgreSQL 18
  ensureAttachForeignKeys(payments → payments_2027)
    ├─ ALTER TABLE payments_2027 ADD CONSTRAINT ... NOT VALID: copies on _eu and _us
    └─ VALIDATE: checks _eu and _us under SHARE UPDATE EXCLUSIVE (writes go on)

  ATTACH payments_2027
    └─ payments_account_fk adopts the table's foreign key; no row is checked

The attach foreign key step now gives a table that is itself partitioned a
validated foreign key of each of the parent's, so the ATTACH adopts it and
validates nothing: through the partitioned foreign key build before
PostgreSQL 18, and the table's own NOT VALID foreign key from 18.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 4, 2026 04:21
@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-04T04:21:56.388864Z
We couldn’t complete this review. Comment @codex review to try again.
7c8e368 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 7c8e368: 0 blocking, 5 non-blocking.

Inspected the full diff at head 7c8e368 (stacked on #714, base kiran01bm/attach-partitioned-keys) and the code it calls: the partitioned foreign key build (partitioned_fk_flow.go, partitioned_fk_parent.go, partitioned_fk_catalog.go), the leaf step, the attach flow, and docs/invariants.md. Nothing was built or run here (no clone, no containers); CI is green on the PostgreSQL 14, 15, 16, 17 and 18 test jobs.

The change is correct as far as I can trace it. ensureAttachForeignKeys now takes a standalone partitioned table. On 14 to 17 it runs the existing build on the table under the derived name, so each leaf's foreign key is added NOT VALID and validated, and the table's own ADD FOREIGN KEY adopts them in one brief transaction that proves each leaf's recorded OID and reads it back (adoptLeafFKs, readBackParentFK). On 18 it reuses the leaf step, which the new leafFKStepTakes gate admits only for a standalone partitioned table on a server that takes NOT VALID there; every other combination still fails closed. A failure midway leaves nothing half-validated that a rerun cannot resume (see Verified). The step is not yet reachable from AttachPartitionOnline: the flow still refuses a table that is not plain (attach_partition_flow.go#L457) and builds its node with standaloneTable (#L551), so this is groundwork and the new branch runs only in tests until a later PR opens the flow.

Invariants (from docs/invariants.md): ST-7 extends (the new step proves the table by identity before and after the build; see finding 4 for the by-name window), LK-2 extends (every statement is still in a brief transaction or a bounded VALIDATE; see finding 3), LK-1 upholds (the flow holds the parent's advisory lock, runUnderParentLock in attachPartitionAt).

Blocking

None.

Non-blocking

1. On PostgreSQL 14 to 17, a partitioned table that already carries a matching validated foreign key under another name is refused; on 18, and for a plain table, it is found.
ensureAttachPartitionedFK (attach_foreign_key_partitioned.go#L38-L62) hands the table to the build, whose decideParentFK accepts only the derived name and returns ErrPartitionedForeignKeyParentConflict ("already has the requested foreign key as X") for the same definition under any other name (partitioned_fk_flow.go#L176-L190). The leaf step the 18 path uses, and the plain-table path, take "one validated foreign key of the definition, under any name" as it stands, and the key step's paired shortcut does the same for keys. A realistic way to hit it: PostgreSQL keeps a detached partition's foreign keys as its own constraints under the parent's names, so a rotated-out partitioned table re-attached to the same or a sibling parent has exactly this foreign key. The result is that the same re-attach works on 18 and is refused on 17, and the refusal text blames a conflict where the table is simply ready. It fails closed (no data risk), hence non-blocking. Suggested fix: on the build route, when the table has one validated, unattached foreign key of the requested definition, adopted on every partition (requireAdoptedFKEverywhere already proves that), return it as found instead of refusing.

Test case (not run here: no clone or containers available to this review)
func TestEnsureAttachForeignKeysTakesAPartitionedTablesOwnForeignKeyUnderAnotherName(t *testing.T) {
	withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) {
		f := newFixture(t)
		f.exec(t, paymentsFKByRegion)
		f.exec(t, `ALTER TABLE %[1]s.payments_2027
			ADD CONSTRAINT my_account_fk FOREIGN KEY (account_id)
			REFERENCES %[1]s.accounts (id) ON DELETE CASCADE`)
		table := f.standalonePartitioned(t, "payments_2027")

		results, err := ensureAttachForeignKeys(t.Context(), f.pool, f.parentOID(t, "payments"), table, attachProofTestBudget, nil, 0, nil)
		require.NoError(t, err)
		require.Len(t, results, 1)
		assert.Equal(t, leafFKFound, results[0].action)
		assert.Equal(t, "my_account_fk", results[0].constraint)
		assert.Equal(t, []string{"my_account_fk"}, slices.Collect(maps.Keys(f.tableFKs(t, "payments_2027"))))
	})
}

Expected: passes on 18 (the leaf step finds it) and fails on 14 to 17 with ErrPartitionedForeignKeyParentConflict from decideParentFK. Read from the code, not run.

2. The partitioned-table tests do not pin several behaviors the PR text claims.

  • TestEnsureAttachForeignKeysFailsTypedOnARowOfAPartition loops over the table's foreign keys and asserts none is validated. Before 18 the table has no foreign key after the failure (the parent's step never ran), so the loop body never executes and the test asserts nothing about state on 14 to 17. Its comment says "so the attach still refuses to adopt one", which is not asserted anywhere.
  • No partitioned-table test reruns after the violating row is removed, though the plain-table tests do (...StopsOnAnOrphanRowAndResumes). That resume is the property that makes a mid-way failure safe.
  • Every call passes nil, 0 for tracker, runStep, so the build's progress reporting through the new parameters, the one plumbing change in attach_partition_flow.go, is never exercised.
  • No partitioned test captures the statements (the plain tests collect them through started), so the derived-name ADD, the per-leaf VALIDATE, and the table's ADD are asserted only through their end state.
  • Nothing covers a table that already has its own foreign key (validated or NOT VALID) or a parent with two foreign keys on this path.
Test case (not run here: no clone or containers available to this review)
func TestEnsureAttachForeignKeysResumesAPartitionedTableAfterAViolationIsFixed(t *testing.T) {
	withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) {
		f := newFixture(t)
		f.exec(t, paymentsFKByRegion)
		f.exec(t, `INSERT INTO %[1]s.payments_2027 VALUES (3, '2027-05-01', 'us', 99)`)
		parent, table := f.parentOID(t, "payments"), f.standalonePartitioned(t, "payments_2027")

		_, err := ensureAttachForeignKeys(t.Context(), f.pool, parent, table, attachProofTestBudget, nil, 0, nil)
		require.ErrorIs(t, err, ErrPartitionedForeignKeyViolation)
		usFKs := f.tableFKs(t, "payments_2027_us")
		require.Len(t, usFKs, 1, "the leaf holding the bad row keeps the foreign key the step added")
		for _, fk := range usFKs {
			assert.False(t, fk.validated)
		}

		f.exec(t, `DELETE FROM %[1]s.payments_2027 WHERE id = 3`)
		results, err := ensureAttachForeignKeys(t.Context(), f.pool, parent, table, attachProofTestBudget, nil, 0, nil)
		require.NoError(t, err)
		require.Len(t, results, 1)
		for _, rel := range []string{"payments_2027", "payments_2027_eu", "payments_2027_us"} {
			fks := f.tableFKs(t, rel)
			require.Len(t, fks, 1, rel)
			for _, fk := range fks {
				assert.True(t, fk.validated, "%s's foreign key is validated after the rerun", rel)
			}
		}
	})
}

Expected to pass on 14 to 18 at this head; read from the code, not run. It would catch a resume that re-adds a foreign key or leaves a leaf NOT VALID.

3. On PostgreSQL 18 the cost model differs from the one the comments describe.
The new doc text says "Each VALIDATE is bounded by b" (attach_foreign_key.go#L55) and the build's comment says "Each leaf's VALIDATE is bounded by b". Before 18 that is per leaf and each leaf commits on its own, so a rerun keeps the finished leaves. From 18 the table's VALIDATE CONSTRAINT is one statement under one StatementTimeout: b.Overall (partitioned_fk_leaf.go#L446) that validates every partition below the table, so Overall bounds the whole tree, and a cancel rolls back every partition's progress together. A tree whose partitions each validate within Overall but whose total does not will never converge: each rerun does the same work and is cancelled at the same point. Likewise addLeafForeignKey's comment and its INV: LK-2 (#L374) describe one leaf's brief transaction; on a partitioned table the server's ADD recurses and takes the same SHARE ROW EXCLUSIVE on every partition, so the hold grows with the partition count (each wait still bounded by lock_timeout). Suggested fix: say so in the comments and the ValidateBudget doc ("on 18, Overall bounds the whole tree"), and consider a test with a small Overall over several partitions that pins the typed timeout. No test case: it needs data sized to the budget.

4. The build still resolves the table by name, and the error text still names an OID-derived constraint (repeats of #714 notes).
runPartitionedFK is handed table.schema and table.name and resolves the table itself; the before and after proveAttachNode reads (attach_foreign_key_partitioned.go#L47, #L54) detect a swap, but only after the build has run: if the name is repointed between the first proof and the build's own resolve, foreign keys are added to the other table and the second proof fails afterwards. This is the same window the sibling index and key steps accept, so it is consistent, not new; passing the proved OID into partitionedFKRequest so the build refuses a different table would close it for all three. The build's error wrap (#L52) names spec.name, the _p<table oid> form, next to the outer wrap that names the parent's foreign key (attach_foreign_key.go#L111), so one failure prints both names and an operator cannot map the OID form back to anything in the parent. Name the parent's foreign key (fk.spec.name) in the inner wrap.

5. docs/invariants.md is not updated, and the code cites ST-7 from a file the registry does not name.
The new file carries INV: ST-7 (attach_foreign_key_partitioned.go#L43), but the ST-7 Enforced: text names the attach index step (attach_index.go, "the table to attach still that plain table") and nothing for the attach foreign key step, attach_foreign_key.go, or this file, and its description of the table to attach is "plain" where this PR admits a partitioned one. The LK-2 Enforced: text lists the attach foreign key step's ADD ... NOT VALID but says nothing of the partitioned build running inside the attach. The PR touches no docs. Update the two entries in this PR or the next in the series, and ask whether each Enforced: pointer still names where the rule is enforced.

Verified

  • Dispatch: attachFKNeedsBuild (attach_foreign_key_partitioned.go#L26) is true only for a partitioned node on a server before 18, and the leaf step's leafFKStepTakes (partitioned_fk_leaf.go#L310) is its exact complement for partitioned nodes, plus a standalone check, so no combination reaches the wrong step.
  • Definition match: the foreign key the build gives each leaf and the table is rendered from the parent's spec (referenced table and columns, MATCH, ON UPDATE, ON DELETE with its column list, deferrability), and sameDefinition compares exactly those, so what the ATTACH adopts is what was built. A parent's foreign key to a partitioned table is refused by resolveFKReference (plain referenced table only), and a referenced table that is itself a partition of the new table is refused by refuseFKTree on 14 to 17. Self-references fall under the first.
  • Failure midway, 14 to 17: a violating leaf keeps its NOT VALID foreign key (enforced for new rows, as the leaf step documents), earlier leaves are validated, and the table has no foreign key until the parent's transaction, which proves every leaf's recorded OID before and after the ADD. A rerun finds each foreign key under any name and resumes.
  • Failure midway, 18: the ADD ... NOT VALID is its own brief transaction and the VALIDATE is one statement, so a violation rolls the whole validation back and leaves the table and every copy NOT VALID; the rerun finds that state and validates.
  • The two-level test pins the pre-18 typed refusal (ErrPartitionedForeignKeySubPartitioned, raised from readTree before any leaf is touched, so nothing is added) and the 18 success.
  • Mutation testing: not run here (no clone, no containers).

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 7c8e368: 0 blocking, 1 non-blocking.

Same head, 7c8e368, read through the eyes of someone adopting pg-sprite for the first time, and of a host that imports the executor (schemabot is one) and has to turn each outcome into something an operator can act on. The correctness review is the comment above.

Blocking

None.

Non-blocking

1. The behavior now differs by server major, and nothing user-facing says so.
For a partitioned table to attach, a host will see three outcomes depending on the server: on 18 a table with sub-partitions is validated; on 14 to 17 it is refused with ErrPartitionedForeignKeySubPartitioned; and on 14 to 17 a table that already has its own foreign key under another name is refused with ErrPartitionedForeignKeyParentConflict (finding 1 above), where 18 accepts it. The PR description states the 14 to 17 versus 18 split well, but it lives only in the PR text and in code comments; the PR changes no docs. Because the step is not yet reachable from AttachPartitionOnline (attach_partition_flow.go#L457 still refuses a table that is not plain), the right moment is the PR that opens the flow: list which partitioned tables the online attach takes on each major, so a first-time user whose attach is refused on 17 and passes on 18 can find out why without reading source. A one-row-per-major table in the attach docs would do.

Checked, no finding

  • Public surface. Every changed signature is unexported (ensureAttachForeignKeys, ensureLeafForeignKey's gate, the new ensureAttachPartitionedFK), so no importer is broken and nothing new has to be supported. The tracker, runStep pair mirrors what the index and key steps already take, so the attach flow threads one reporting channel through all of its steps; callers that pass nil, 0 simply get no progress.
  • Typed errors. The refusals an importer would classify (ErrPartitionedForeignKeyViolation, ErrPartitionedForeignKeySubPartitioned, ErrPartitionedForeignKeyParentConflict, ErrInvariantViolation) are existing sentinels, wrapped with %w, and the new wraps keep errors.Is working through both layers (the integration tests assert ErrPartitionedForeignKeyViolation and ErrPartitionedForeignKeySubPartitioned through them). A host should still key on the sentinel and show a fixed line rather than render the wrapped text, which carries the OID-derived constraint name noted in finding 4 above.
  • Report shape. AttachPartitionStep for this step stays {foreign-key, <parent's foreign key name>, found|added|validated} for plain and partitioned tables alike, so a host's progress or audit view needs no new case. The action vocabulary matches what the leaf step already reports.
  • Reruns. Every path reads and decides again, so a host that retries a failed attach after fixing data (or after a lock timeout) resumes rather than starting over, on both routes.
  • Dependencies and scope. No new imports beyond pkg/progress in attach_foreign_key.go and pkg/preflight in the leaf file, both already used by the package.

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.

🤖 Approving with comments: 0 blocking, 6 non-blocking across the two review comments above.

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

@JashLal

JashLal commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

🤖 Static review of 7c8e368dc6e2a168e6f3d2144ca87dfd6f20505a.

P2 · Preserve the referenced table OID before enabling partitioned attach. The pre-18 branch gets the resolved fk.ref, then gives runPartitionedFK only the names in spec. The two proveAttachNode reads check the candidate’s identity. If concurrent DDL rebinds the referenced name, the build can still install a constraint on the candidate that points to the replacement. A later failed attach leaves that constraint installed, including its referential actions. Pass the resolved reference OID into the nested build and check it before any leaf changes. The current public attach flow still refuses a partitioned candidate, so this can be fixed before that flow is enabled. Build call

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