Skip to content

executor: run a partitioned foreign key that references the primary key - #710

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd101-partitioned-fk-entry-spec
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd101-partitioned-fk-entry-spec

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

A foreign key added to a partitioned table that writes REFERENCES accounts without listing columns now runs online, using the referenced table's primary key, as PostgreSQL does.

Why

pg-sprite adds a foreign key to a partitioned table one partition at a time, so writes keep flowing. In PostgreSQL, REFERENCES accounts with no column list means "accounts' primary key", and it is a common way to write a foreign key. pg-sprite refused that form outright, so the user had to rewrite the statement with the columns spelled out before it would run.

What

  • New pkg/executor/partitioned_fk_reference.go: resolveFKTarget reads the referenced table's primary key columns, in key order, when the statement names none, and writes them into the spec. Every partition's statement and the parent's then name them.
  • A referenced table with no primary key, or one whose key has a different number of columns, is refused as partitioned-foreign-key-unsupported-shape before any partition is touched.
  • Both the build (under its table lock) and the dry run's catalog check resolve it.
  • The statement check no longer refuses an empty column list. The leaf step still treats a spec with no referenced columns as an invariant violation.
  • Also checked on main and already covered: an ON DELETE SET NULL (cols) column list (runs on 15+, refused typed on 14), and foreign-table or sub-partitioned partitions (refused typed before any step). A build-level test for the foreign-table refusal was added.
  • Docs: partitioned-foreign-key-design.md, execution-model.md, schemabot-integration.md, refusal-classes.md.
  • Tests on PostgreSQL 14 and 16:
    • A single-column key and a composite key declared (region, id) over columns created (id, region) both run online, and a rerun finds the work done.
    • migrate.Run executes the statement.
    • Both fail without the change.
    • The no-primary-key, wrong-length and foreign-table refusals leave the tree unchanged.

Before / after

cards is partitioned; accounts has PRIMARY KEY (id).

input: pg-sprite migrate --alter "ALTER TABLE cards ADD CONSTRAINT cards_account_fk
         FOREIGN KEY (account_id) REFERENCES accounts"

Before
  statement check ──▶ no referenced column list ──▶ refused
  result          ──▶ unsupported shape; nothing created

After
  resolve target  ──▶ accounts' primary key is (id)
  each partition  ──▶ ADD FOREIGN KEY (account_id) REFERENCES accounts (id)
  parent          ──▶ adopts the partitions' keys
  result          ──▶ executed; every key reads REFERENCES accounts(id)

REFERENCES accounts with no column list was refused before anything
ran, though an ordinary ADD FOREIGN KEY takes the referenced primary key.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 3, 2026 02:36
@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-03T02:36:36.587096Z
We couldn’t complete this review. Comment @codex review to try again.
971bab4 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 3, 2026

Copy link
Copy Markdown
Collaborator

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

Inspected the whole change at 971bab4e54dd48a516b6b0a07ee4c37ca017fdf9 (12 files, +322/-35): the new resolveFKTarget, its two callers (partitionedFKFlow.resolve and AdmitPartitionedForeignKey), the split of the spec check into validate and validateRequested (validate and validateRequested), and the shape check that no longer refuses an empty column list. I read them against every consumer of the resolved spec: checkParent, readLeafFKFacts, adoptLeafFKs, readBackParentFK, the attach path's parentFKSpec and the migrate and desired-state admission wrappers. CI at the time of posting: all 17 checks green, including test (PostgreSQL 14) through test (PostgreSQL 17), both PostgreSQL 18 legs, lint, the docs guards and Supabase compatibility.

What the change does: a FOREIGN KEY ... REFERENCES schema.table with no column list now reads the referenced table's primary key columns, in key order, under the build's lock, writes them into the spec, and from there every leaf statement and the parent's name them. A referenced table with no primary key, or one whose key has a different number of columns, is refused as partitioned-foreign-key-unsupported-shape before any leaf step. I could not find a defect. The pieces that carry the safety all hold:

  • Pairing order. The query orders by unnest(conkey) WITH ORDINALITY, so the columns come back in key order, not table order, and ref.attnums is set from the same rows in the same order. That is the order the server records in confkey, so sameDefinition (slices.Equal(k.refKey, ref.attnums)) holds for the keys the build creates and for the rerun's read of the finished parent. The (region, id) over (id, region) test pins it.
  • One resolution, every consumer. resolve stores the returned spec in f.fk, and every step that renders or compares (leafFKAddSQL, parentFKSQL, decideLeafForeignKey, judgeLeafFKRecorded, readBackParentFK) takes f.fk.spec. The two later reads of f.req.spec (checkParent's column attnums and name, the deadlock wrapper's name) use only fields the resolution does not change. The attach path builds its specs from confkey with explicit names, so validate never meets an empty list there.
  • Fail closed. validate now refuses an unresolved spec as ErrInvariantViolation, so a caller that reaches a step with no referenced columns stops before it renders REFERENCES t (). A PK read that errors, or finds none, or finds the wrong length, returns before the first leaf step.
  • Statement changes underneath. The parent's statement now names the key columns read at resolve time. If the primary key changes during the run, the leaf statements either still succeed against a unique index on those columns or fail at the server, and the parent step re-proves the referenced table by OID under its lock (lockAndProveReference) and reads back the definition by attnums. It cannot silently reference other columns.

Invariants (docs/invariants.md): upholds CO-9 (#L518; referencedPrimaryKeySQL qualifies every relation, function, operator and cast with pg_catalog), upholds LK-2 (#L842; the new read runs inside the existing resolve read, takes no new lock, and the statements it renders are the ones LK-2 already bounds), extends ST-6 (#L1671; the dry run and a desired plan read the new refusals through AdmitPartitionedForeignKey, see finding 1), and upholds ST-7 (#L1773); its text is the subject of finding 1 of comment 2/2.

Consistency with #702 (sub-partitioned partitions): the two compose. #702's sub-partitioned step copies f.fk and only renames the constraint (fk.spec.name = derivedPartitionIndexName(...)), so it carries the columns this change resolves, and its decideTree decides every partition from f.fk, not from f.req.spec. The two PRs edit the same files (partitioned_fk_flow.go, partitioned_fk.go, partitioned_fk_leaf.go, the executor's partitioned foreign key tests and the refusal tables in docs/), so whichever lands second may need a mechanical merge. Neither assumes the other's refusal list: this PR's new tests build a leaf-only tree, and #702 removes the sub-partitioned refusal this PR leaves alone.

Non-blocking

  1. The dry run's and the desired plan's reading of the two new refusals has no test, and a mutant that drops it survives. AdmitPartitionedForeignKey was changed to call resolveFKTarget so a dry run and AdmitPlanPartitionedForeignKeys learn the no-primary-key and wrong-length refusals before anything runs (the doc comment says so, and the PR body says "Both the build ... and the dry run's catalog check resolve it"). The new tests reach it only through AddPartitionedForeignKey and migrate.Run; none calls AdmitPartitionedForeignKey, AdmitPartitionedForeignKeyCatalog or AdmitPlanPartitionedForeignKeys with a statement that names no columns. Reverting line 103 to resolveFKReference (which, with no column list, resolves an empty attnum list and returns no error) keeps every test green, and then a dry run reports a no-primary-key statement as executable while the run refuses it, the divergence ST-6 exists to prevent. Reasoned from the code, not run (it needs a live PostgreSQL).
Test case (not run here: it needs a live PostgreSQL): the admission refuses a referenced table with no primary key
// With no referenced column list the foreign key references the primary key,
// so the catalog admission a dry run and a desired plan read refuses a
// referenced table without one, as the build does.
func TestAdmitPartitionedForeignKeyRefusesAReferencedTableWithoutAPrimaryKey(t *testing.T) {
	withPartitionedFKServer(t, func(t *testing.T, newFixture func(t *testing.T) partitionedFKFixture) {
		f := newFixture(t)
		f.exec(t, `
			CREATE TABLE %[1]s.accounts (id bigint NOT NULL UNIQUE);
			CREATE TABLE %[1]s.events (
			    id         bigint      NOT NULL,
			    account_id bigint,
			    created_at timestamptz NOT NULL
			) PARTITION BY RANGE (created_at);
			CREATE TABLE %[1]s.events_2026_01 PARTITION OF %[1]s.events
			    FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')`)

		err := AdmitPartitionedForeignKey(t.Context(), f.pool, fmt.Sprintf(`
			ALTER TABLE %[1]s.events
			    ADD CONSTRAINT events_account_fk
			    FOREIGN KEY (account_id) REFERENCES %[1]s.accounts`, f.schema))

		require.ErrorIs(t, err, ErrPartitionedForeignKeyUnsupportedShape)
	})
}

A second case with PRIMARY KEY (id, region) and a one-column foreign key pins the wrong-length refusal the same way.

  1. The no-primary-key branch of resolveFKTarget is unpinned beyond the sentinel, and validate's new guard has no direct test. With no primary key, len(columns) == 0 (#L63) is always followed by the length check at #L67, since spec.columns is never empty after validateRequested. Deleting the first branch therefore returns the same sentinel with the message "has 1 columns referencing the 0 columns of the primary key of app.accounts" instead of "names no referenced columns and app.accounts has no primary key; name the referenced columns". The new refusal subtests pass the sentinel and the code to refuse, so they cannot tell the two apart, and the first message is the one an operator reads. Likewise the len(s.refColumns) == 0 guard in validate is reached by no test: a mutant that deletes it would have the step render REFERENCES t () and fail at the server, a failed verdict instead of the typed invariant violation. Either assert the message of the no-primary-key case (assert.ErrorContains(t, err, "has no primary key")), and add a unit case to the leaf's spec tests for the unresolved spec, or drop the branch the length check already covers. Reasoned, not run.

  2. The wrong-length message names counts, not the key. The message at #L67-L70 (has %d columns referencing the %d columns of the primary key of %s) reads "1 columns" for a single column and names counts but not the primary key's columns, so an operator with a two-column key and a one-column foreign key has to look the key up to fix the statement. Listing the key ((id, region)) in the message would say what to write. The existing shape check words its counts the same way (%d columns referencing %d), so this is consistency with what is there; it is a wording improvement, not a defect.

  3. A foreign key written with no list on one run and with the explicit key on the next is the same foreign key, but only the first form is tested for the rerun. TestAddPartitionedForeignKeyReferencingThePrimaryKey reruns the same no-list statement and finds the parent's key done. The mixed rerun (first run no list, resume with (id), or the reverse) relies on requestedForeignKeys comparing attnums, which it does, so I expect it to hold; but a resumed run is the case an operator hits after a statement is edited to name the column, and ADD CONSTRAINT under the same name with the explicit list is the natural edit. One extra assertion in the single-column subtest, f.add with REFERENCES %[1]s.accounts (id) after the first run, pins it. Reasoned, not run.

Verified

  • Read the whole diff and the unchanged callers listed above. I ran no test: every new scenario starts a PostgreSQL container, and I did not build or run anything locally. CI at this head passed them on PostgreSQL 14 to 18.
  • Checked referencedPrimaryKeySQL against the catalog: contype 'p' is at most one row per table, conkey holds the key attnums in key order, and a primary key column cannot be dropped without dropping the constraint, so the join needs no attisdropped filter. The attnums scan as int16, the type catalogFK.refKey holds.
  • Mutation table (by reading; the scenarios need a live PostgreSQL):
Mutant Caught by
resolveFKTarget returns the spec without setting refColumns TestAddPartitionedForeignKeyReferencingThePrimaryKey, TestRunRoutesAPartitionedForeignKeyReferencingThePrimaryKeyToTheBuild: validate refuses the unresolved spec
ORDER BY k.ord replaced by ORDER BY a.attnum the composite subtest, whose key order (region, id) differs from its column order
the len(columns) != len(spec.columns) check removed the wrong-length refusal test: the step's validate then refuses the mismatch as an invariant violation, not the typed sentinel
the len(columns) == 0 branch removed survives: same sentinel from the length check (finding 2)
AdmitPartitionedForeignKey back to resolveFKReference survives: no test calls the admission with a no-list statement (finding 1)
validate's len(s.refColumns) == 0 guard removed survives: no test reaches a step with an unresolved spec (finding 2)
partitionedFKFlow.resolve stores f.req.spec instead of the resolved spec the single-column subtest: the first leaf step is refused as an invariant violation
unsupportedFKClauses refuses an empty list again TestAdmitPartitionedForeignKeyShape's new no-list case

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

@aparajon

aparajon commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

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

Read the change from two seats: a user of pg-sprite migrate --alter who writes REFERENCES accounts the way PostgreSQL's own documentation does and wants it to run online, and a host or downstream importer (a schema change orchestrator) that routes statements with AdmitPartitionedForeignKeyShape and AdmitPartitionedForeignKeyCatalog and reports the refusal to its own users. CI at the time of posting: all 17 checks green.

Non-blocking

  1. The capability pages still state the old accepted shape. The four docs the PR updates (execution-model.md, partitioned-foreign-key-design.md, refusal-classes.md, schemabot-integration.md) are consistent with each other. The three places an adopter reads first are not: docs/limitations.md#L19 describes the supported statement as ADD CONSTRAINT name FOREIGN KEY (columns) REFERENCES schema.table (columns), and docs/capabilities.md#L260 and its source pkg/capabilities/capabilities.yaml#L232 repeat it. None says that a statement with no column list runs, and none lists the two new refusals (a referenced table with no primary key, one whose key has another number of columns) beside the other unsupported-statement causes. The limitations row never listed "no referenced column list" as refused either, so a reader of that page could not have known the old form was refused, or that the new one is taken. One clause in each, "or, with no list, its primary key", and the two refusals added to the list, keeps the pages that describe what runs true to what runs. The docs guard job passes at this head, so nothing holds these three to the other four.

  2. Two descriptions of what the build admits predate the change. The exported doc comment of migrate.AdmitPartitionedForeignKeyCatalog lists the refusals a host learns from it ("a referenced table the build does not take ..., a sub-partitioned partition, and an ON DELETE column list on PostgreSQL 14"), and it is the page an importer reads to decide what to report. It now also refuses a no-list statement whose referenced table has no primary key or one of another length, which the executor's own AdmitPartitionedForeignKey doc comment was updated to say and this one was not. The ST-7 entry in the registry (docs/invariants.md#L1832-L1836) says the build "renders every statement from the admitted columns, referenced table and columns, and rules alone"; with this change the referenced columns can be the ones the build reads from the catalog under its lock. The entry is upheld (the statement still names the referenced table by a name the step re-proves by OID, and the read-back compares attnums), and the rule needs no change, but its Enforced: text is the sentence a reviewer checks a later change against, so one clause ("the referenced columns, read from the referenced table's primary key when the statement names none") keeps it true.

What reads well for adopters

  • The PR body shows the user's own statement before and after, with the refusal replaced by the executed result and what every key reads as (REFERENCES accounts(id)), which is what an adopter checks first.
  • The refusal text for a missing primary key is actionable and names the table and the constraint: "foreign key X names no referenced columns and app.accounts has no primary key; name the referenced columns".
  • The composite-key test is the right one for a host that generates statements: a key declared (region, id) over columns created (id, region) pairs by key order, as the server does, so the foreign key a host reads back from the catalog is the one it asked for.
  • A rerun of the same statement finds the finished parent's key done, so a host's retry after an unknown commit outcome is safe, as for the explicit form.
  • The failure codes are unchanged (partitioned-foreign-key-unsupported-shape, unsupported-statement, capability-boundary), so a host's routing table for the build's outcomes needs no new row; only the cause text widens, and the integration guide's two tables say so.
  • It composes with the open sub-partitioned PR (executor: add a partitioned table's foreign key through sub-partitioned partitions #702): that step reuses the resolved foreign key, so a no-list statement on a sub-partitioned tree takes the same primary key columns at every level.

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

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.

2 participants