Skip to content

executor: give an attached table a foreign key with an ON DELETE column list - #643

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/partitioned-attach-fk-delete-cols
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/partitioned-attach-fk-delete-cols

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

Lets the online attach give a new partition a parent foreign key whose ON DELETE SET NULL (cols) or SET DEFAULT (cols) names a column list, which it refused until now.

Why

When pg-sprite attaches a table as a new partition online, it first gives the table every foreign key the parent has, checked while writes continue, so the attach itself scans nothing. From PostgreSQL 15 a foreign key can say that deleting a referenced row clears only some of its columns, for example ON DELETE SET NULL (account_id) on a key over (account_id, region). The attach refused any parent with such a foreign key, because the step that adds a partition's foreign key could not write the column list. That step learned to write it for the partitioned foreign key build, so the attach can now use it too.

What

  • The attach's foreign key step reads the parent's column list and passes it to the leaf step by column name, so it lands on the right columns when the table numbers its columns differently from the parent.
  • The check just before the ATTACH (pairAttachForeignKeys) now compares the list too, mapped into the table's column numbers by position in the foreign key. Before, it built the expected definition without a list, so it would have rejected the correct foreign key.
  • The refusal is gone, and so is its code attach-partition-foreign-key-unsupported, which nothing else produced and no release has shipped. Its rows in docs/execution-model.md and docs/schemabot-integration.md are removed.
  • Two parent foreign keys that differ only in their column list are still refused, as two of one definition: PostgreSQL ignores the list when it picks which foreign key to adopt. A table that already has a foreign key differing from the parent's only in its list is refused for the same reason.
  • Tests (PostgreSQL 15+):
    • a parent foreign key with a list, given to a table whose columns are in another order, and attached through the full online attach, which adopts it; a delete then clears only the listed column;
    • the two refusals above;
    • a unit case for the pre-attach comparison;
    • the "refuses before building an earlier one" test now uses a reference to a partitioned table as its refusal.

Before / after

Example: cards has FOREIGN KEY (account_id, region) REFERENCES accounts (id, region) ON DELETE SET NULL (account_id), and cards_2027 declares account_id as its first column, while the parent has it third.

ALTER TABLE app.cards ATTACH PARTITION app.cards_2027 FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')

Before
  foreign key step reads the parent's FK: it has an ON DELETE column list
    └─ refused before anything is added: attach-partition-foreign-key-unsupported
       the operator has to add the foreign key by hand, or run the blocking ATTACH

After
  foreign key step: ADD ... ON DELETE SET NULL ("account_id") NOT VALID, then VALIDATE
                    (the list is written by name, so it lands on the table's column 1)
  pre-attach check: the table's FK clears column {1}, the parent's maps to {1}  → ready
  ATTACH adopts that foreign key; it scans and validates nothing
  DELETE FROM accounts ...  → cards_2027.account_id cleared, region kept

…mn list

The online attach now carries the parent's ON DELETE SET NULL/SET DEFAULT
column list onto the table by column name, and its pre-attach check reads
the list in the table's own column numbers. This retires the unreleased
attach-partition-foreign-key-unsupported code, which had no other source.
@Kiran01bm
Kiran01bm marked this pull request as ready for review November 30, 2026 05:50
@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

Copy link
Copy Markdown
Collaborator

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

Inspected the whole change at 16f4a7ebc063e5bcb7bd0270fd9a9543ffee5f0c: the parent-side read that now carries the ON DELETE column list by name (attach_foreign_key.go#L204-L237), the refusal that no longer fires on a list and now treats two foreign keys that differ only in the list as one definition (attach_foreign_key.go#L110-L136), the pre-ATTACH pairing that maps the list into the table's numbering (attach_partition_ready.go#L164-L217), the removed code and its three registry entries, the docs rows, and the tests. I also read the leaf step the change leans on: clause and quotedColumns (partitioned_fk_leaf.go#L182-L209), decideLeafForeignKey (partitioned_fk_catalog.go#L315-L348) and foreignKeysSQL (partitioned_fk_catalog.go#L126-L136).

The change does what the body says and I found nothing that blocks it.

  • Emitted DDL. The step renders ADD CONSTRAINT <derived> FOREIGN KEY (...) REFERENCES ... ON DELETE SET NULL ("account_id") NOT VALID, then the existing VALIDATE CONSTRAINT. The list is read from the parent's confdelsetcols as attribute numbers, turned into names against the parent (fkColumnNames, one pg_catalog-qualified lookup per number, attach_foreign_key.go#L239-L261), and rendered by name, so a table that numbers its columns differently gets the right ones. Each name goes through pgx.Identifier.Sanitize, so mixed case and embedded quotes are safe, and the list keeps the parent's order. validateDeleteSetColumns (partitioned_fk_leaf.go#L145-L163) still refuses a list on another action, a column outside the key, or a repeat, before any statement runs.
  • PostgreSQL 15 gate. The attach path never calls refuseDeleteSetColumns (only the build does, partitioned_fk_flow.go#L100 and partitioned_fk_admit.go#L46), and it does not need to: below 15 foreignKeysSQL substitutes an empty list for the missing confdelsetcols column, so no parent foreign key can carry a list and the statement never gains a column list a 14 server would reject. The new tests skip below 15.
  • Locks. The added statements are catalog reads in the same brief read transaction, and the ADD ... NOT VALID and VALIDATE are the statements the step already ran, with a different ON DELETE clause. A list changes neither the lock mode nor its order, so there is no lock regression (LK-2 holds).
  • Fail closed. A table foreign key that differs from the parent's only in its list is refused by the leaf step (ErrPartitionedForeignKeyConflict), and if one slipped through, pairAttachForeignKeys pairs it to 0 so requireReady returns errAttachForeignKeyNotReady before the ATTACH can take a scan under ACCESS EXCLUSIVE.
  • Removed code. CodeAttachPartitionForeignKeyUnsupported is in no release: no tag contains the commit that added it (latest tag v0.5.7), so deleting it from Codes(), Permanent() and sentinelCode, and from both docs tables, breaks no released importer. No reference to the code or to errAttachForeignKeyUnsupported remains in the tree.

CI (two red checks, one cause). all-green only aggregates; the one real failure is test (PostgreSQL 16). The failing test is TestRunRefusesAFinishOnlyTargetOnARowWhoseSwapDidNotCommit in pkg/schemachange, which fails inside finishWithRoom with save checkpoint for t_57753_20.orders: ERROR: canceling statement due to lock timeout (SQLSTATE 55P03) (read from gh run view --log-failed; I did not rerun anything). This PR touches no file under pkg/schemachange, and pkg/executor passed on that same job (ok ... pkg/executor 202.610s). The same job on main at ed1ba99 (run 46355586728) failed on a sibling test in the same file, TestRunRefusesAFinishOnlyTargetOnceTheRowIsDone, with a lock-timeout error as well, and the CI run for 6881313 on main has a red PostgreSQL 15 job. So this reads as a flake in the copy-and-swap tests under load, not something this change caused; I did not read the PostgreSQL 15 log. It deserves its own fix, and the PR can merge once a green run lands.

Invariants (docs/invariants.md): this upholds ST-7 (the step decides from the table's catalog before and after each statement; the added list is part of the compared definition, and no *Enforced:* line moves), upholds LK-2 (same statement, same locks), and upholds CO-9 (the new fkColumnNameSQL is pg_catalog-qualified, OPERATOR(pg_catalog.=) throughout).

Non-blocking

  1. A NOT VALID table foreign key that differs only in its list is not refused, and on PostgreSQL 18 the attach may take it. decideLeafForeignKey refuses a list-only difference only for a foreign key isAdoptable accepts, and that requires validated (partitioned_fk_catalog.go#L196-L198); the doc comment on the rule says it is the one PostgreSQL 14 to 17 apply and that 18 also adopts a NOT VALID one (partitioned_fk_catalog.go#L179-L188). The pre-ATTACH pairing skips such a key as well, because its list differs (attach_partition_ready.go#L205). If the 18 server picks that key over the step's validated one, it adopts it, validates it under ACCESS EXCLUSIVE, and the table clears the wrong columns on delete. I could not confirm which key 18 picks (that needs a PostgreSQL 18 container, which I do not run), and the same hole existed before this change for a parent with no list, so it is not a regression; but the new tests only build the list-only difference with a validated key (attach_foreign_key_integration_test.go#L496-L529). A second subtest with NOT VALID on the table's key, run on 18, would settle it either way. No test case block: I did not run it.

  2. tableDeleteSetColumns panics on a list column outside the key, where its twin returns the case to a validator. key[slices.Index(p.key, attnum)] (attach_partition_ready.go#L214) is key[-1] when attnum is not in p.key. PostgreSQL refuses such a list when the foreign key is created, so a real catalog cannot hold one, which is why this is latent. But pairAttachForeignKeys has no error return and runs on a safety path (the gate before the ATTACH), the sibling mapping deleteSetAttnums (partitioned_fk_leaf.go#L69-L78) is only safe because validateDeleteSetColumns runs first, and this one has no such guard. The two also duplicate the same position-mapping. Reusing one helper that returns an error, and having readAttachTableFacts surface it, keeps the gate failing closed with a message rather than crashing the run.

Test case: a list column outside the key must not panic
func TestTableDeleteSetColumnsOutsideTheKeyDoesNotPanic(t *testing.T) {
	p := catalogFK{key: []int16{3, 4}, deleteSetColumns: []int16{9}}
	assert.NotPanics(t, func() { tableDeleteSetColumns(p, []int16{2, 1}) })
}

--- FAIL: TestTableDeleteSetColumnsOutsideTheKeyDoesNotPanic (0.00s) on 16f4a7e (runtime error: index out of range [-1] at attach_partition_ready.go:214). Passes once the mapping returns an error or skips the column.

  1. The refusal of two parent foreign keys that differ only in their list, and the position mapping, are covered only by integration tests. refuseParentForeignKeys and sameParentFKDefinition (attach_foreign_key.go#L110-L136) decide from catalog rows alone and need no server, but the only test is the container subtest at attach_foreign_key_integration_test.go#L461-L494. Making sameParentFKDefinition compare the lists (mutant M4 below) leaves the PR's unit test TestPairAttachForeignKeys green. The unit case added at attach_partition_internal_test.go#L158-L168 covers one single-column list and one position map. Also, every attach test uses SET NULL; the SET DEFAULT (cols) form the PR body names goes through the same code but is not exercised end to end.
Test case: two parent foreign keys that differ only in their list are one definition
func TestRefuseParentForeignKeysTwoThatDifferOnlyInTheirList(t *testing.T) {
	base := catalogFK{refOID: 50, key: []int16{3, 4}, refKey: []int16{1, 2}, match: "s", onUpdate: "a", onDelete: "n", validated: true}
	a, b := base, base
	a.name, a.deleteSetColumns = "cards_account_fk", []int16{3}
	b.name, b.deleteSetColumns = "cards_region_fk", []int16{4}
	err := refuseParentForeignKeys([]parentForeignKey{
		{spec: partitionedFKSpec{name: a.name}, catalog: a},
		{spec: partitionedFKSpec{name: b.name}, catalog: b}})
	require.ErrorIs(t, err, ErrPartitionedForeignKeyConflict)
	assert.Contains(t, err.Error(), "cards_account_fk")
	assert.Contains(t, err.Error(), "cards_region_fk")
}

Passes on 16f4a7e; --- FAIL: TestRefuseParentForeignKeysTwoThatDifferOnlyInTheirList (0.00s) ("Expected error ... in chain but got nil") under mutant M4, while TestPairAttachForeignKeys stays green under M4.

Verified

  • Ran only anchored unit tests with -timeout 300s, after confirming there is no TestMain in pkg/executor and that TestPairAttachForeignKeys and my probe tests call no helper that opens a connection: TestPairAttachForeignKeys passes at 16f4a7e; go vet ./pkg/executor/ is clean. I did not run any of the integration tests (they start containers and I do not run those here): the new subtests, TestEnsureAttachForeignKeysGivesTheTableAnOnDeleteColumnList and the two refusal subtests, were read, not executed; CI shows pkg/executor green on PostgreSQL 16, and the PostgreSQL 14, 15, 17 and 18 jobs green.
  • Mutation table (each change applied alone, the tests named run, then git checkout):
Mutant (production change) Caught by
M1 attachMayAdopt drops the list comparison TestPairAttachForeignKeys (the new list subtest, expected 0, got 10)
M2 tableDeleteSetColumns returns the parent's numbers unmapped TestPairAttachForeignKeys (expected 10, got 0)
M3 tableDeleteSetColumns returns an empty list TestPairAttachForeignKeys (expected 10, got 0)
M4 sameParentFKDefinition also compares the lists survived TestPairAttachForeignKeys; killed by the probe in finding 3
M5 parentFKSpec leaves the list unset not run: only the container tests reach it
M6 control: no-op all pass

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

@aparajon

Copy link
Copy Markdown
Collaborator

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

Read the change from two seats: an importer that drives the online attach and routes on its outcome codes (SchemaBot is the obvious one), and an operator who meets only the error text and the guide. The addition fits the package: no new exported name, one fewer exported constant, and the same typed refusals (ErrPartitionedForeignKeyConflict, ErrPartitionedForeignKeyReferencedTable) the partitioned foreign key build already uses, so a host that routes on those keeps working. The removed executor.CodeAttachPartitionForeignKeyUnsupported was never in a tagged release (no tag contains the commit that added it; latest is v0.5.7), so dropping it from Codes() and the guide is a clean removal rather than a break, and the PR body says so.

Non-blocking

  1. The attach table's pointer for the foreign key step's own codes now leads to the wrong table. The last row of the attach outcomes table sends "the index and foreign key steps' own codes" to the partitioned index build table (schemabot-integration.md#L931). The foreign key step's codes (partitioned-foreign-key-conflict, partitioned-foreign-key-referenced-table, partitioned-foreign-key-name-taken, and data-fault with 23503) are documented in the partitioned foreign key build table (schemabot-integration.md#L872-L881), not the index one. Until now that gap was papered over by the one foreign key code that had its own attach row; this PR removes that row, and with it the only attach-specific mention of a foreign key refusal. After this change the two new refusals an attach can return for a list (two parent foreign keys that differ only in it, and a table key that differs only in it) both come back as partitioned-foreign-key-conflict, and an importer reading the attach section has nothing that says so. Changing the pointer to name both tables (index codes there, foreign key codes at the foreign key build table) settles it.

  2. The refusal text for two parent foreign keys that differ only in their list says they "have one definition", which an operator can see is not true. The message reads "the partitioned parent's foreign keys X and Y have one definition, and the attach adopts the table's foreign key for one of them only" (attach_foreign_key.go#L114-L115). For the case this PR adds, \d on the parent shows two keys with different ON DELETE SET NULL (...) lists, so the sentence reads as a bug in the tool rather than a limit of the server. The refusal is permanent and has no remedy in the text. Saying "apart from the ON DELETE column list, which the attach does not compare" in the message, and naming the way out (drop one of the two, or run the plain blocking ATTACH), would let the operator act without opening the source. The execution model row for the code (execution-model.md#L414) describes the table-side case but not this parent-side one.

What reads well for adopters

  • Both docs tables lose the removed code and their surrounding prose is updated to match, so the guide and Codes() agree; the code, its Permanent() entry, its sentinelCode branch and both registry tests are removed together.
  • The pairing check names the same column set the leaf step writes, by position in the key rather than by number, which is what an importer with a table whose columns are in another order needs, and the new integration test builds exactly that table.
  • The PR body's before/after example is concrete and checks out against the code: the step writes ON DELETE SET NULL ("account_id") by name, the pre-attach check maps the parent's list into the table's numbering, and the attach adopts the table's key and scans nothing.

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, 5 non-blocking (see the review comment(s) 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